File size: 9,950 Bytes
68d7816 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | import { randomUUID } from 'node:crypto';
import { createDecorator } from '#/_base/di/instantiation';
import type {
BundledSkillActivation,
PromptOrigin,
SkillActivationOrigin,
} from '#/agent/contextMemory/types';
import { IAgentLoopService, type PromptLaunchResult, type Turn } from '#/agent/loop/loop';
import { promptMetadataTextFromContentParts } from '#/agent/prompt/promptMetadataText';
import { IAgentScopeContext } from '#/agent/scopeContext/scopeContext';
import { IEventService } from '#/app/event/event';
import { ITelemetryService } from '#/app/telemetry/telemetry';
import { ErrorCodes, Error2 } from '#/errors';
import type { ContentPart } from '#human/llm/message';
import { MAIN_AGENT_ID } from '#/session/agentLifecycle/agentLifecycle';
import { ISessionContext } from '#/session/sessionContext/sessionContext';
import { ISessionMetadata } from '#/session/sessionMetadata/sessionMetadata';
import { applyPromptMetadataUpdate } from '#/session/sessionMetadata/promptMetadata';
import { IEventDispatcher } from '#/state/eventDispatcher';
import { isUserActivatableSkillType, type SkillDefinition } from './catalog/types';
import { promptMetadataTextFromSkill, renderUserSlashSkillPrompt } from './prompt';
import { ISessionSkillCatalog } from './session/skillCatalog';
import type {
PromptSkillActivation,
PromptWithSkillsInput,
PromptWithSkillsResult,
SkillActivationInput,
} from './skill';
import { SkillActivated } from './skillOps';
export interface IAgentSkillService {
readonly _serviceBrand: undefined;
activate(input: SkillActivationInput): Promise<PromptLaunchResult>;
promptWithSkills(input: PromptWithSkillsInput): Promise<PromptWithSkillsResult>;
recordModelToolActivation(origin: SkillActivationOrigin): void;
}
export const IAgentSkillService = createDecorator<IAgentSkillService>('agentSkillService');
export class AgentSkillService implements IAgentSkillService {
declare readonly _serviceBrand: undefined;
constructor(
@ISessionSkillCatalog private readonly catalog: ISessionSkillCatalog,
@IAgentLoopService private readonly loop: IAgentLoopService,
@ISessionMetadata private readonly metadata: ISessionMetadata,
@IEventService private readonly eventService: IEventService,
@ISessionContext private readonly sessionContext: ISessionContext,
@ITelemetryService private readonly telemetry: ITelemetryService,
@IEventDispatcher private readonly dispatcher: IEventDispatcher,
@IAgentScopeContext private readonly scopeContext: IAgentScopeContext,
) {}
async activate(input: SkillActivationInput): Promise<PromptLaunchResult> {
const catalog = this.catalog;
await catalog.ready;
const skill = catalog.catalog.getSkill(input.name);
if (skill === undefined) {
throw new Error2(ErrorCodes.SKILL_NOT_FOUND, `Skill "${input.name}" was not found`);
}
if (!isUserActivatableSkillType(skill.metadata.type)) {
throw new Error2(
ErrorCodes.SKILL_TYPE_UNSUPPORTED,
`Skill "${skill.name}" cannot be activated by the user`,
);
}
const skillArgs = input.args ?? '';
const skillContent = this.renderSkillPrompt(skill, skillArgs);
const content: ContentPart[] = [
{
type: 'text',
text: renderUserSlashSkillPrompt({
skillName: skill.name,
skillArgs,
skillContent,
skillSource: skill.source,
skillDir: skill.dir,
}),
},
...(input.content ?? []),
];
const turn = await this.recordActivation(
{
kind: 'skill_activation',
activationId: randomUUID(),
skillName: skill.name,
trigger: 'user-slash',
skillType: skill.metadata.type,
skillPath: skill.path,
skillSource: skill.source,
skillArgs: input.args,
attachments: input.attachments,
clientMetadata: input.clientMetadata,
},
content,
);
if (turn === undefined) {
throw new Error2(
ErrorCodes.TURN_AGENT_BUSY,
'Cannot activate skill while another turn is active',
);
}
await turn.ready.catch(() => undefined);
if (turn.id === undefined) {
throw new Error2(ErrorCodes.INTERNAL, 'Skill activation turn ended before it started');
}
if (this.scopeContext.agentContext.agentId === MAIN_AGENT_ID) {
await applyPromptMetadataUpdate(
{
metadata: this.metadata,
eventService: this.eventService,
sessionId: this.sessionContext.sessionId,
},
promptMetadataTextFromSkill(input),
);
}
return { turn_id: turn.id };
}
async promptWithSkills(input: PromptWithSkillsInput): Promise<PromptWithSkillsResult> {
if (input.input.length === 0) {
throw new Error2(ErrorCodes.REQUEST_INVALID, 'promptWithSkills requires a non-empty prompt');
}
if (input.skills.length === 0) {
throw new Error2(
ErrorCodes.REQUEST_INVALID,
'promptWithSkills requires at least one skill',
);
}
const catalog = this.catalog;
await catalog.ready;
const prepared = input.skills.map((skill) => this.prepareBundled(skill));
if (this.scopeContext.agentContext.agentId === MAIN_AGENT_ID) {
await applyPromptMetadataUpdate(
{
metadata: this.metadata,
eventService: this.eventService,
sessionId: this.sessionContext.sessionId,
},
promptMetadataTextFromContentParts(input.input, input.clientMetadata),
);
}
for (const activation of prepared) {
void this.recordActivation(activation.origin);
}
const status = this.loop.snapshot();
const { id } = this.loop.submit({
message: {
role: 'user',
content: [...prepared.map((activation) => activation.part), ...input.input],
},
meta: {
origin: {
kind: 'user',
skillActivations: prepared.map((activation) => activation.entry),
clientMetadata: input.clientMetadata,
attachments: input.attachments,
} as PromptOrigin,
tracked: true,
},
});
const handle = this.loop.promptHandle(id)!;
if (status.state === 'running' || status.paused || status.queue.length > 0) {
return { prompt_id: id, created_at: handle.createdAt, state: 'queued' };
}
await Promise.race([handle.launched, handle.completion]);
const turn = await handle.launched;
if (turn === undefined && handle.state !== 'blocked') {
throw new Error2(ErrorCodes.INTERNAL, 'promptWithSkills failed to launch a turn');
}
if (turn !== undefined) await turn.ready.catch(() => undefined);
return {
turn_id: turn?.id,
prompt_id: id,
created_at: handle.createdAt,
state: handle.state === 'blocked' ? 'blocked' : 'running',
};
}
recordModelToolActivation(origin: SkillActivationOrigin): void {
void this.recordActivation(origin);
}
private prepareBundled(input: PromptSkillActivation): {
readonly origin: SkillActivationOrigin;
readonly part: ContentPart;
readonly entry: BundledSkillActivation;
} {
const catalog = this.catalog;
const skill = catalog.catalog.getSkill(input.name);
if (skill === undefined) {
throw new Error2(ErrorCodes.SKILL_NOT_FOUND, `Skill "${input.name}" was not found`);
}
if (!isUserActivatableSkillType(skill.metadata.type)) {
throw new Error2(
ErrorCodes.SKILL_TYPE_UNSUPPORTED,
`Skill "${skill.name}" cannot be activated by the user`,
);
}
const skillArgs = input.args ?? '';
const skillContent = this.renderSkillPrompt(skill, skillArgs);
const origin: SkillActivationOrigin = {
kind: 'skill_activation',
activationId: randomUUID(),
skillName: skill.name,
trigger: 'user-slash',
skillType: skill.metadata.type,
skillPath: skill.path,
skillSource: skill.source,
skillArgs: input.args,
};
return {
origin,
part: {
type: 'text',
text: renderUserSlashSkillPrompt({
skillName: skill.name,
skillArgs,
skillContent,
skillSource: skill.source,
skillDir: skill.dir,
}),
},
entry: {
activationId: origin.activationId,
skillName: origin.skillName,
skillArgs: origin.skillArgs,
skillType: origin.skillType,
skillPath: origin.skillPath,
skillSource: origin.skillSource,
},
};
}
private async recordActivation(
origin: SkillActivationOrigin,
input?: readonly ContentPart[],
): Promise<Turn | undefined> {
await this.dispatcher.dispatch(
new SkillActivated({
agentId: this.scopeContext.agentContext.agentId,
activationId: origin.activationId,
skillName: origin.skillName,
trigger: origin.trigger,
skillArgs: origin.skillArgs,
skillPath: origin.skillPath,
skillSource: origin.skillSource,
}),
);
this.publishActivation(origin);
if (input === undefined) return undefined;
const steer = this.loop.snapshot().state === 'running';
const { id } = this.loop.submit(
{
message: { role: 'user', content: [...input] },
meta: { origin, tracked: !steer },
},
{ steerIfActive: steer },
);
return this.loop.promptHandle(id)!.launched;
}
private renderSkillPrompt(skill: SkillDefinition, rawArgs: string): string {
return this.catalog.catalog.renderSkillPrompt(skill, rawArgs, {
sessionId: this.sessionContext.sessionId,
});
}
private publishActivation(origin: SkillActivationOrigin): void {
this.telemetry.track2('skill_invoked', {
skill_name: origin.skillName,
trigger: origin.trigger,
});
if (origin.skillType === 'flow') {
this.telemetry.track2('flow_invoked', {
flow_name: origin.skillName,
});
}
}
}
|