File size: 10,654 Bytes
f0634fb | 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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createControlledPromise } from '@antfu/utils';
import { InMemorySkillCatalog } from '#/features/skill/catalog/registry';
import { summarizeSkill } from '#/features/skill/catalog/types';
import { IAgentSkillService } from '#/features/skill/skillService';
import type { LlmRequester } from '#human/llm/requester/requester';
import {
ISkillTool,
MAX_SKILL_QUERY_DEPTH,
NestedSkillTooDeepError,
SkillToolInputSchema,
} from '#/features/skill/tools/skill';
import { SkillTool } from '#/features/skill/tools/skillTool';
import { executeTool } from '../../tools/fixtures/execute-tool';
import { stubSkill } from './catalog/stubs';
import {
createTestAgent,
InMemoryWireRecordPersistence,
skillServices,
type TestAgentContext,
} from '../../harness';
type GenerateFn = LlmRequester;
const COMMIT_SKILL = stubSkill('commit', {
description: 'commit changes',
path: '/skills/commit/SKILL.md',
dir: '/skills/commit',
content: '# Commit',
metadata: {},
source: 'user',
});
function catalogWithCommit(): InMemorySkillCatalog {
const skills = new InMemorySkillCatalog();
skills.register(COMMIT_SKILL);
return skills;
}
describe('AgentSkillService', () => {
let ctx: TestAgentContext;
afterEach(async () => {
await ctx.dispose();
});
it('activate prompts with the rendered skill for a known skill', async () => {
ctx = createTestAgent(skillServices(catalogWithCommit()));
ctx.mockNextResponse({ type: 'text', text: 'done' });
const launched = await ctx.get(IAgentSkillService).activate({ name: 'commit' });
expect(launched.turn_id).toBe(0);
await ctx.untilTurnEnd();
const activation = ctx.context.get().find((m) => m.origin?.kind === 'skill_activation');
expect(activation?.role).toBe('user');
expect(activation?.origin).toMatchObject({
kind: 'skill_activation',
skillName: 'commit',
});
});
it('activate throws for an unknown skill', async () => {
ctx = createTestAgent(skillServices(catalogWithCommit()));
await expect(ctx.get(IAgentSkillService).activate({ name: 'missing' })).rejects.toThrow(
/not found/i,
);
});
it('activate waits for the catalog to be ready before resolving', async () => {
let resolveReady!: () => void;
const ready = new Promise<void>((resolve) => {
resolveReady = resolve;
});
const skills = catalogWithCommit();
ctx = createTestAgent(
skillServices({
_serviceBrand: undefined,
catalog: skills,
ready,
onDidChange: () => ({ dispose: () => {} }),
load: async () => {},
reload: async () => {},
list: async () => skills.listSkills().map(summarizeSkill),
}),
);
ctx.mockNextResponse({ type: 'text', text: 'done' });
let finished = false;
const activation = ctx
.get(IAgentSkillService)
.activate({ name: 'commit' })
.then(() => {
finished = true;
});
await Promise.resolve();
expect(finished).toBe(false);
resolveReady();
await activation;
expect(finished).toBe(true);
await ctx.untilTurnEnd();
expect(ctx.context.get().some((m) => m.origin?.kind === 'skill_activation')).toBe(true);
});
});
describe('SkillTool', () => {
let ctx: TestAgentContext;
let skills: InMemorySkillCatalog;
beforeEach(() => {
skills = catalogWithCommit();
ctx = createTestAgent(skillServices(skills));
});
afterEach(async () => {
await ctx.dispose();
});
function toolContext(args: { readonly skill: string; readonly args?: string }) {
return {
turnId: 0,
toolCallId: 'call_skill',
args,
signal: new AbortController().signal,
};
}
function makeTool(depth?: number): SkillTool {
const tool = ctx.get(ISkillTool) as SkillTool;
return depth === undefined ? tool : tool.withInitialQueryDepth(depth);
}
it('exposes metadata and schema for model-invoked skills', () => {
const tool = makeTool();
expect(tool.name).toBe('Skill');
expect(tool.parameters).toMatchObject({
type: 'object',
required: ['skill'],
additionalProperties: false,
properties: {
skill: { type: 'string' },
args: { type: 'string' },
},
});
expect(SkillToolInputSchema.safeParse({ skill: 'commit' }).success).toBe(true);
expect(SkillToolInputSchema.safeParse({ skill: 'commit', args: '-m fix' }).success).toBe(true);
expect(SkillToolInputSchema.safeParse({}).success).toBe(false);
});
it('returns a tool error when the skill is unknown', async () => {
const result = await executeTool(
makeTool(),
toolContext({ skill: 'missing' }),
);
expect(result).toMatchObject({
isError: true,
output: 'Skill "missing" not found in the current skill listing.',
});
});
it('rejects skills that disable model invocation', async () => {
skills.register(stubSkill('private', { metadata: { disableModelInvocation: true } }));
const result = await executeTool(
makeTool(),
toolContext({ skill: 'private' }),
);
expect(result).toMatchObject({
isError: true,
output: 'Skill "private" can only be triggered by the user (model invocation is disabled).',
});
});
it('rejects non-inline skill types in the current v1 runtime', async () => {
skills.register(stubSkill('flow-only', { metadata: { type: 'flow' } }));
const result = await executeTool(
makeTool(),
toolContext({ skill: 'flow-only' }),
);
expect(result).toMatchObject({
isError: true,
output: 'Skill "flow-only" is not an inline skill and cannot be invoked by the model in v1.',
});
});
it('loads inline skills through the model-tool wrapper without exposing the body in output', async () => {
const result = await executeTool(
makeTool(),
toolContext({ skill: 'commit', args: 'src/app.ts' }),
);
expect(result).toMatchObject({
output: 'Skill "commit" loaded inline. Follow its instructions.',
});
expect(result.output).not.toContain('# Commit');
expect(ctx.context.get()).toHaveLength(0);
expect(result.delivery?.kind).toBe('steer');
expect(result.delivery?.message.origin).toMatchObject({
kind: 'skill_activation',
skillName: 'commit',
trigger: 'model-tool',
});
expect(result.delivery?.message.content[0]).toMatchObject({
type: 'text',
text: expect.stringContaining(
'<skill-loaded name="commit" trigger="model-tool" source="user" dir="/skills/commit" args="src/app.ts">',
),
});
expect(result.delivery?.message.content[0]).toMatchObject({
type: 'text',
text: expect.stringContaining('ARGUMENTS: src/app.ts'),
});
});
it('honors initialQueryDepth as an alias for queryDepth', async () => {
const nested = await executeTool(
makeTool(2),
toolContext({ skill: 'commit' }),
);
const root = await executeTool(
makeTool(0),
toolContext({ skill: 'commit' }),
);
expect(ctx.context.get()).toHaveLength(0);
expect(nested.delivery?.message.origin).toMatchObject({
kind: 'skill_activation',
trigger: 'nested-skill',
});
expect(root.delivery?.message.origin).toMatchObject({
kind: 'skill_activation',
trigger: 'model-tool',
});
});
it('throws a structured recursion error when nested skill invocation is too deep', async () => {
await expect(
executeTool(
makeTool(MAX_SKILL_QUERY_DEPTH),
toolContext({ skill: 'commit' }),
),
).rejects.toBeInstanceOf(NestedSkillTooDeepError);
expect(ctx.context.get()).toHaveLength(0);
});
});
describe('AgentSkillService busy delivery (harness)', () => {
let ctx: TestAgentContext;
afterEach(async () => {
await ctx.dispose();
});
it('steers the activation into the running turn and launches a new one when idle', async () => {
const catalog = new InMemorySkillCatalog();
catalog.register(
stubSkill('tower', {
content: 'Tower mission: $ARGUMENTS',
metadata: {},
}),
);
const gate = createControlledPromise<void>();
let generateCalls = 0;
const generate: GenerateFn = {
generate: async (_config, _content, control) => {
generateCalls += 1;
const n = generateCalls;
control.onEvent?.({ type: 'llm.sent' });
if (n === 1) await gate;
control.signal.throwIfAborted();
const text = `response-${String(n)}`;
control.onEvent?.({ type: 'llm.streaming.part', part: { type: 'text', text } });
control.onEvent?.({
type: 'llm.streaming.usage',
usage: { inputOther: 1, output: 1, inputCacheRead: 0, inputCacheCreation: 0 },
});
control.onEvent?.({
type: 'llm.streaming.finish',
finish: { finishReason: 'completed', rawFinishReason: 'stop' },
});
control.onEvent?.({ type: 'llm.streaming.message_id', messageId: `mock-${String(n)}` });
control.onEvent?.({ type: 'llm.done' });
},
};
const persistence = new InMemoryWireRecordPersistence();
ctx = createTestAgent(skillServices(catalog), { generate, persistence });
const promptPromise = ctx.rpc.prompt({ input: [{ type: 'text', text: 'start' }] });
await vi.waitFor(() => {
expect(generateCalls).toBe(1);
});
const busyResult = await ctx.get(IAgentSkillService).activate({ name: 'tower', args: 'mission-1' });
expect(busyResult.turn_id).toBe(0);
expect(generateCalls).toBe(1);
gate.resolve();
await promptPromise;
await ctx.untilTurnEnd();
const idleResult = await ctx.get(IAgentSkillService).activate({ name: 'tower', args: 'mission-2' });
expect(idleResult.turn_id).toBe(2);
await ctx.untilTurnEnd();
expect(generateCalls).toBe(3);
const activations = ctx
.contextData()
.history.filter((m) => m.role === 'user' && m.origin?.kind === 'skill_activation');
expect(activations.map((m) => (m.origin?.kind === 'skill_activation' ? m.origin.skillArgs : ''))).toEqual([
'mission-1',
'mission-2',
]);
const types = persistence.records.map((record) => record.type);
expect(types.filter((type) => type === 'turn.prompt')).toHaveLength(2);
expect(types.filter((type) => type === 'turn.steer')).toHaveLength(1);
const steer = persistence.records.find((record) => record.type === 'turn.steer');
expect(steer).toMatchObject({ origin: { kind: 'skill_activation', skillArgs: 'mission-1' } });
});
});
|