tool-skill.spec.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. import { describe, expect, it } from 'vitest'
  2. import { mkdir, writeFile } from 'node:fs/promises'
  3. import { join } from 'node:path'
  4. import { tmpdir } from 'node:os'
  5. import { Context } from 'cordis'
  6. import { createUserMessage, CallId, type Message } from '@deepseek-ai/dsh-llm'
  7. import { createScope, type Scope } from '@deepseek-ai/dsh-scope'
  8. import { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  9. import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
  10. import ToolRegistry, { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  11. import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent'
  12. import SkillService from '@deepseek-ai/dsh-skill'
  13. import * as SkillLocal from '@deepseek-ai/dsh-skill-local'
  14. import * as toolSkill from '@deepseek-ai/dsh-tool-skill'
  15. const testToolSignal = new AbortController().signal
  16. async function tempDir(name: string): Promise<string> {
  17. return await import('node:fs/promises').then(fs => fs.mkdtemp(join(tmpdir(), `dsh-${name}-`)))
  18. }
  19. async function writeSkill(root: string, name: string, description: string, body: string): Promise<void> {
  20. const dir = join(root, name)
  21. await mkdir(dir, { recursive: true })
  22. await writeFile(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: ${description}\n---\n\n${body}\n`)
  23. }
  24. async function setup(home: string, config: toolSkill.Config = {}): Promise<Context> {
  25. const ctx = new Context()
  26. await ctx.plugin(SystemPrompt)
  27. await ctx.plugin(ToolRegistry)
  28. await ctx.plugin(AgentRegistry)
  29. await ctx.plugin(SkillService)
  30. await ctx.plugin(SkillLocal, { dshHome: join(home, '.dsh'), agentsHome: join(home, '.agents'), watch: false })
  31. await ctx.plugin(toolSkill, config)
  32. return ctx
  33. }
  34. function agentForCwd(cwd: string): Agent {
  35. const id = SessionId(`tool-skill-${cwd}`)
  36. const session = new Session(id, [], { version: 0, id, createdAt: 0, cwd })
  37. return {
  38. ctx: new Context(),
  39. id,
  40. options: {},
  41. session,
  42. status: 'idle',
  43. acceptsNextStep: false,
  44. send: () => {},
  45. updateInbox: () => 'not-found',
  46. followup: () => {},
  47. steer: () => {},
  48. inject(input) {
  49. session.append('user/message', input, { surfaceOp: 'append' })
  50. },
  51. cancel() {},
  52. whenIdle: () => Promise.resolve(),
  53. }
  54. }
  55. function sessionAgent(session: Session, id = 'tool-skill-agent'): Agent {
  56. return {
  57. id: SessionId(id),
  58. options: {},
  59. session,
  60. status: 'running',
  61. acceptsNextStep: false,
  62. ctx: new Context(),
  63. send: () => {},
  64. updateInbox: () => 'not-found',
  65. followup: () => {},
  66. steer: () => {},
  67. inject(input) {
  68. session.append('user/message', input, { surfaceOp: 'append' })
  69. },
  70. cancel() {},
  71. whenIdle: () => Promise.resolve(),
  72. }
  73. }
  74. function openMessageTurn(session: Session, turn = 1): void {
  75. session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
  76. session.append('user/message', createUserMessage({
  77. content: [{ type: 'text', text: `turn ${turn}` }],
  78. source: { kind: 'user' },
  79. }), { surfaceOp: 'append' })
  80. }
  81. async function fireStep(ctx: Context, agent: Agent, turn: number, step: number): Promise<void> {
  82. await agentEvents(ctx, agent).serial('agent/step', turn, step, new AbortController().signal)
  83. }
  84. function catalogMessages(session: Session): Extract<SessionEvent, { type: 'user/message' }>[] {
  85. return session.events.filter((event): event is Extract<SessionEvent, { type: 'user/message' }> => event.type === 'user/message'
  86. && event.data.source.kind === 'plugin'
  87. && event.data.source.plugin === 'dsh-tool-skill')
  88. }
  89. function catalogContent(entries: string[]): Message['content'] {
  90. return [{
  91. type: 'text',
  92. text: ['<system-reminder>', '<available_skills>', ...entries, '</available_skills>', '</system-reminder>'].join('\n'),
  93. }]
  94. }
  95. async function composePrefix(ctx: Context, cwd: string, signal = new AbortController().signal): Promise<Message[]> {
  96. return await composePrefixForAgent(ctx, agentForCwd(cwd), signal)
  97. }
  98. async function composePrefixForAgent(ctx: Context, agent: Agent, signal = new AbortController().signal): Promise<Message[]> {
  99. await agentEvents(ctx, agent).serial('agent/step', 1, 1, signal)
  100. return agent.session.deriveMessages()
  101. }
  102. async function mintAgentScope(ctx: Context, subject: string | Agent): Promise<{ agent: Agent; scope: Scope }> {
  103. const agent = typeof subject === 'string' ? agentForCwd(subject) : subject
  104. let scope!: Scope
  105. await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) }, {
  106. inject: ['tools'],
  107. }))
  108. return { agent, scope }
  109. }
  110. describe('dsh-tool-skill', () => {
  111. it('registers the skill tool schema and removes it on dispose', async () => {
  112. const ctx = new Context()
  113. await ctx.plugin(SystemPrompt)
  114. await ctx.plugin(ToolRegistry)
  115. await ctx.plugin(AgentRegistry)
  116. const home = await tempDir('tool-schema')
  117. await ctx.plugin(SkillService)
  118. await ctx.plugin(SkillLocal, { dshHome: join(home, '.dsh'), agentsHome: join(home, '.agents'), watch: false })
  119. ctx.skills.register({ name: 'lifecycle-skill', description: 'Lifecycle', source: 'runtime', content: 'body' })
  120. const fiber = await ctx.plugin(toolSkill)
  121. expect(ctx.tools.schemas().map(tool => tool.name)).toEqual(['skill'])
  122. expect(await composePrefix(ctx, '/workspace')).toHaveLength(1)
  123. expect(ctx.tools.get('skill')?.presentCall?.({ name: 'project-skill' })).toEqual({
  124. card: 'generic',
  125. title: 'Load skill project-skill',
  126. kind: 'read',
  127. rawInput: 'project-skill',
  128. })
  129. await fiber.dispose()
  130. expect(ctx.tools.schemas()).toEqual([])
  131. expect(await composePrefix(ctx, '/workspace')).toEqual([])
  132. toolSkill.apply(ctx)
  133. expect(ctx.tools.schemas().map(tool => tool.name)).toEqual(['skill'])
  134. })
  135. it('forwards the step abort signal to skill discovery', async () => {
  136. const home = await tempDir('tool-prefix-signal')
  137. const ctx = await setup(home)
  138. let seenSignal: AbortSignal | undefined
  139. ctx.skills.registerProvider(() => ({
  140. name: 'signal-probe',
  141. async list(options) {
  142. seenSignal = options.signal
  143. return []
  144. },
  145. async get() {
  146. return undefined
  147. },
  148. }))
  149. const controller = new AbortController()
  150. await composePrefix(ctx, '/workspace', controller.signal)
  151. expect(seenSignal).toBe(controller.signal)
  152. })
  153. it('injects a stable durable name-and-description catalog at the first step', async () => {
  154. const home = await tempDir('tool-catalog')
  155. const ctx = await setup(home, { catalogDescriptionMaxLength: 50 })
  156. ctx.skills.register({
  157. name: 'z-skill',
  158. description: 'Long description '.repeat(5),
  159. whenToUse: 'Never render this routing hint.',
  160. source: 'secret-source',
  161. provider: 'runtime',
  162. resourceBase: { kind: 'directory', path: '/secret/path' },
  163. content: 'Secret body.',
  164. })
  165. ctx.skills.register({
  166. name: 'a-skill',
  167. description: 'Use {{placeholder}} <safely> & carefully.',
  168. source: 'runtime',
  169. provider: 'runtime',
  170. content: 'A body.',
  171. })
  172. ctx.skills.register({
  173. name: 'model-only-skill',
  174. description: 'Model-only skill.',
  175. invocation: { modelInvocable: true, userInvocable: false },
  176. source: 'runtime',
  177. content: 'Model-only body.',
  178. })
  179. ctx.skills.register({
  180. name: 'user-only-skill',
  181. description: 'User-only skill.',
  182. invocation: { modelInvocable: false, userInvocable: true },
  183. source: 'runtime',
  184. content: 'User-only body.',
  185. })
  186. ctx.on('agent/step', (agent) => {
  187. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'later contribution' }], source: { kind: 'plugin', plugin: 'later-contribution' } }))
  188. })
  189. const prefix = await composePrefix(ctx, '/workspace')
  190. expect(prefix).toEqual([
  191. {
  192. id: expect.any(String) as unknown,
  193. role: 'user',
  194. source: { kind: 'plugin', plugin: 'dsh-tool-skill' },
  195. content: [{
  196. type: 'text',
  197. text: [
  198. '<system-reminder>',
  199. 'A skill is a reusable set of task-specific instructions. The following skills are available in this session:',
  200. '',
  201. '<available_skills>',
  202. '- `a-skill`: Use {{placeholder}} &lt;safely&gt; &amp; carefully.',
  203. '- `model-only-skill`: Model-only skill.',
  204. '- `z-skill`: Long description Long description Long descript...',
  205. '</available_skills>',
  206. '',
  207. "If the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.",
  208. '</system-reminder>',
  209. ].join('\n'),
  210. }],
  211. },
  212. {
  213. id: expect.any(String) as unknown,
  214. role: 'user',
  215. content: [{ type: 'text', text: 'later contribution' }],
  216. source: { kind: 'plugin', plugin: 'later-contribution' },
  217. },
  218. ])
  219. const rendered = JSON.stringify(prefix[0])
  220. expect(rendered).not.toContain('whenToUse')
  221. expect(rendered).not.toContain('secret-source')
  222. expect(rendered).not.toContain('/secret/path')
  223. expect(rendered).not.toContain('Secret body')
  224. expect(rendered).not.toContain('user-only-skill')
  225. expect(renderPrompt(await ctx.systemPrompt.assemble({ agent: agentForCwd('/workspace') }))).not.toContain('<available_skills>')
  226. })
  227. it('does not inject a catalog when no model-invocable skills are available', async () => {
  228. const home = await tempDir('tool-empty-catalog')
  229. const ctx = await setup(home)
  230. ctx.skills.register({
  231. name: 'user-only-skill',
  232. description: 'User-only skill',
  233. invocation: { modelInvocable: false, userInvocable: true },
  234. source: 'runtime',
  235. content: 'User-only body.',
  236. })
  237. const agent = agentForCwd('/workspace')
  238. expect(await composePrefixForAgent(ctx, agent)).toEqual([])
  239. expect(await composePrefixForAgent(ctx, agent)).toEqual([])
  240. })
  241. it('omits an incomplete initial catalog and retries on a later request boundary', async () => {
  242. const home = await tempDir('tool-incomplete-prefix')
  243. const ctx = await setup(home)
  244. let failing = true
  245. const provider = {
  246. name: 'recovering',
  247. async list() {
  248. if (failing) throw new Error('temporarily unavailable')
  249. return []
  250. },
  251. async get() {
  252. return undefined
  253. },
  254. }
  255. let invalidate = (): void => {}
  256. ctx.skills.registerProvider((control) => {
  257. invalidate = control.invalidate
  258. return provider
  259. })
  260. const session = new Session(SessionId('incomplete-prefix'))
  261. const agent = sessionAgent(session)
  262. openMessageTurn(session)
  263. await composePrefixForAgent(ctx, agent)
  264. expect(catalogMessages(session)).toEqual([])
  265. failing = false
  266. invalidate()
  267. await fireStep(ctx, agent, 1, 1)
  268. expect(catalogMessages(session)).toEqual([])
  269. })
  270. it('records an empty baseline across repeated step observations', async () => {
  271. const home = await tempDir('tool-empty-step')
  272. const ctx = await setup(home)
  273. const session = new Session(SessionId('empty-step'))
  274. const agent = sessionAgent(session)
  275. openMessageTurn(session)
  276. await fireStep(ctx, agent, 1, 1)
  277. await fireStep(ctx, agent, 1, 2)
  278. expect(catalogMessages(session)).toEqual([])
  279. })
  280. it('injects complete replacement catalogs for additions and an empty tombstone for removals', async () => {
  281. const home = await tempDir('tool-dynamic-catalog')
  282. const ctx = await setup(home)
  283. const disposeFirst = ctx.skills.register({
  284. name: 'first-skill',
  285. description: 'First skill',
  286. source: 'runtime',
  287. content: 'First body.',
  288. })
  289. const session = new Session(SessionId('dynamic-catalog'))
  290. const agent = sessionAgent(session)
  291. openMessageTurn(session)
  292. expect(JSON.stringify(await composePrefixForAgent(ctx, agent))).toContain('first-skill')
  293. await fireStep(ctx, agent, 1, 1)
  294. expect(catalogMessages(session)).toHaveLength(1)
  295. const disposeSecond = ctx.skills.register({
  296. name: 'second-skill',
  297. description: 'Second skill',
  298. source: 'runtime',
  299. content: 'Second body.',
  300. })
  301. await fireStep(ctx, agent, 1, 2)
  302. const addition = catalogMessages(session)[1]
  303. if (addition?.type !== 'user/message') throw new Error('expected catalog addition')
  304. expect(JSON.stringify(addition.data.content)).toContain('first-skill')
  305. expect(JSON.stringify(addition.data.content)).toContain('second-skill')
  306. disposeSecond()
  307. disposeFirst()
  308. await fireStep(ctx, agent, 1, 3)
  309. const removal = catalogMessages(session)[2]
  310. if (removal?.type !== 'user/message') throw new Error('expected catalog removal')
  311. expect(JSON.stringify(removal.data.content)).toContain('No skills are currently available')
  312. expect(JSON.stringify(removal.data.content)).not.toContain('first-skill')
  313. expect(JSON.stringify(removal.data.content)).not.toContain('second-skill')
  314. await fireStep(ctx, agent, 1, 4)
  315. expect(catalogMessages(session)).toHaveLength(3)
  316. })
  317. it('resumes from the latest valid visible catalog content', async () => {
  318. const home = await tempDir('tool-catalog-resume')
  319. const ctx = await setup(home)
  320. ctx.skills.register({
  321. name: 'resumed-skill',
  322. description: 'Resumed skill',
  323. source: 'runtime',
  324. content: 'Resumed body.',
  325. })
  326. const session = new Session(SessionId('catalog-resume'))
  327. const agent = sessionAgent(session)
  328. openMessageTurn(session)
  329. session.append('user/message', createUserMessage({
  330. content: catalogContent(['- `old-skill`: Old skill']),
  331. source: { kind: 'plugin', plugin: 'dsh-tool-skill' },
  332. }), { surfaceOp: 'append' })
  333. session.append('user/message', createUserMessage({
  334. content: [{ type: 'text', text: 'missing catalog markers' }],
  335. source: { kind: 'plugin', plugin: 'dsh-tool-skill' },
  336. }), { surfaceOp: 'append' })
  337. session.append('user/message', createUserMessage({
  338. content: [{ type: 'text', text: '<available_skills>\nmissing closing marker' }],
  339. source: { kind: 'plugin', plugin: 'dsh-tool-skill' },
  340. }), { surfaceOp: 'append' })
  341. session.append('user/message', createUserMessage({
  342. content: [{ type: 'text', text: 'first block' }, { type: 'text', text: 'second block' }],
  343. source: { kind: 'plugin', plugin: 'dsh-tool-skill' },
  344. }), { surfaceOp: 'append' })
  345. session.append('user/message', createUserMessage({
  346. content: [{ type: 'reasoning', text: 'not a user-role catalog block' }],
  347. source: { kind: 'plugin', plugin: 'dsh-tool-skill' },
  348. }), { surfaceOp: 'append' })
  349. await fireStep(ctx, agent, 1, 1)
  350. expect(catalogMessages(session)).toHaveLength(6)
  351. expect(JSON.stringify(catalogMessages(session).at(-1)?.data.content)).toContain('resumed-skill')
  352. })
  353. it('re-establishes the current catalog after compaction hides its durable message', async () => {
  354. const home = await tempDir('tool-catalog-compaction')
  355. const ctx = await setup(home)
  356. ctx.skills.register({
  357. name: 'first-skill',
  358. description: 'First skill',
  359. source: 'runtime',
  360. content: 'First body.',
  361. })
  362. const session = new Session(SessionId('catalog-compaction'))
  363. const agent = sessionAgent(session)
  364. openMessageTurn(session)
  365. expect(JSON.stringify(await composePrefixForAgent(ctx, agent))).toContain('first-skill')
  366. const initial = catalogMessages(session)[0]
  367. if (initial === undefined) throw new Error('expected initial catalog')
  368. session.append('user/message', createUserMessage({
  369. content: [{ type: 'text', text: 'compacted history' }],
  370. source: { kind: 'plugin', plugin: 'compact' },
  371. }), {
  372. surfaceOp: { op: 'replace', start: initial.seq, end: initial.seq },
  373. sourceEventSeqs: [initial.seq],
  374. })
  375. await fireStep(ctx, agent, 1, 1)
  376. expect(catalogMessages(session)).toHaveLength(2)
  377. expect(JSON.stringify(catalogMessages(session).at(-1)?.data.content)).toContain('first-skill')
  378. })
  379. it('keeps body-only edits out of the catalog and loads the latest body on demand', async () => {
  380. const home = await tempDir('tool-body-refresh')
  381. const root = join(home, '.dsh/skills')
  382. await writeSkill(root, 'body-skill', 'Stable description', 'First body.')
  383. const ctx = await setup(home)
  384. const session = new Session(SessionId('body-refresh'))
  385. const agent = sessionAgent(session)
  386. openMessageTurn(session)
  387. expect(JSON.stringify(await composePrefixForAgent(ctx, agent))).toContain('Stable description')
  388. await writeSkill(root, 'body-skill', 'Stable description', 'Second body.')
  389. await fireStep(ctx, agent, 1, 1)
  390. expect(catalogMessages(session)).toHaveLength(1)
  391. const result = await ctx.tools.execute({
  392. signal: testToolSignal,
  393. callId: CallId('body-refresh'),
  394. name: 'skill',
  395. arguments: { name: 'body-skill' },
  396. agent,
  397. })
  398. expect(result.isError).toBe(false)
  399. expect(JSON.stringify(result.content)).toContain('Second body.')
  400. expect(JSON.stringify(result.content)).not.toContain('First body.')
  401. })
  402. it('retains the last-good catalog while any provider discovery is incomplete', async () => {
  403. const home = await tempDir('tool-incomplete-catalog')
  404. const ctx = await setup(home)
  405. const disposeStable = ctx.skills.register({
  406. name: 'stable-skill',
  407. description: 'Stable skill',
  408. source: 'runtime',
  409. content: 'Stable body.',
  410. })
  411. const session = new Session(SessionId('incomplete-catalog'))
  412. const agent = sessionAgent(session)
  413. openMessageTurn(session)
  414. expect(JSON.stringify(await composePrefixForAgent(ctx, agent))).toContain('stable-skill')
  415. ctx.skills.registerProvider(() => ({
  416. name: 'failing',
  417. async list() {
  418. throw new Error('temporarily unavailable')
  419. },
  420. async get() {
  421. return undefined
  422. },
  423. }))
  424. disposeStable()
  425. await fireStep(ctx, agent, 1, 1)
  426. expect(catalogMessages(session)).toHaveLength(1)
  427. })
  428. it('omits catalog guidance when the calling agent restricts away the shipped skill tool', async () => {
  429. const home = await tempDir('tool-restricted-catalog')
  430. const ctx = await setup(home)
  431. ctx.skills.register({ name: 'listed-skill', description: 'Listed', source: 'runtime', content: 'body' })
  432. const session = new Session(SessionId('restricted-catalog'))
  433. const agent = sessionAgent(session)
  434. openMessageTurn(session)
  435. const { scope } = await mintAgentScope(ctx, agent)
  436. scope.ctx.tools.restrict({ deny: ['skill'] })
  437. expect(ctx.tools.get('skill', agent)).toBeUndefined()
  438. await composePrefixForAgent(ctx, agent)
  439. expect(catalogMessages(session)).toEqual([])
  440. await fireStep(ctx, agent, 1, 1)
  441. expect(catalogMessages(session)).toEqual([])
  442. expect(await composePrefix(ctx, '/workspace')).toHaveLength(1)
  443. await scope.dispose()
  444. })
  445. it('does not attach shipped catalog guidance to a scoped same-name tool shadow', async () => {
  446. const home = await tempDir('tool-shadowed-catalog')
  447. const ctx = await setup(home)
  448. ctx.skills.register({ name: 'listed-skill', description: 'Listed', source: 'runtime', content: 'body' })
  449. const { agent, scope } = await mintAgentScope(ctx, '/workspace')
  450. scope.ctx.tools.register(defineContentToolFixture({
  451. name: 'skill',
  452. description: 'A scoped tool with unrelated semantics.',
  453. parameters: {},
  454. execute() {
  455. return Promise.resolve([{ type: 'text', text: 'shadow' }])
  456. },
  457. }))
  458. expect(ctx.tools.get('skill', agent)).not.toBe(ctx.tools.get('skill'))
  459. expect(await composePrefixForAgent(ctx, agent)).toEqual([])
  460. expect(await composePrefix(ctx, '/workspace')).toHaveLength(1)
  461. await scope.dispose()
  462. })
  463. it('validates the catalog description cap', async () => {
  464. const home = await tempDir('tool-invalid-catalog-cap')
  465. const ctx = new Context()
  466. await ctx.plugin(SystemPrompt)
  467. await ctx.plugin(ToolRegistry)
  468. await ctx.plugin(AgentRegistry)
  469. await ctx.plugin(SkillService)
  470. await ctx.plugin(SkillLocal, { dshHome: join(home, '.dsh'), agentsHome: join(home, '.agents'), watch: false })
  471. await expect(ctx.plugin(toolSkill, { catalogDescriptionMaxLength: 2 })).rejects.toThrow('greater than or equal to 3')
  472. })
  473. it('loads a skill for the calling agent cwd', async () => {
  474. const home = await tempDir('tool-load')
  475. const project = await tempDir('tool-project')
  476. await mkdir(join(project, '.git'), { recursive: true })
  477. await writeSkill(join(project, '.dsh/skills'), 'project-skill', 'Project skill', 'Project instructions.')
  478. const ctx = await setup(home)
  479. const result = await ctx.tools.execute({
  480. signal: testToolSignal,
  481. callId: CallId('c1'),
  482. name: 'skill',
  483. arguments: { name: 'project-skill' },
  484. agent: { session: { header: { cwd: project } } } as never,
  485. })
  486. expect(result.isError).toBe(false)
  487. if (result.isError) throw new Error('expected skill success')
  488. expect(result.value).toEqual({
  489. name: 'project-skill',
  490. provider: 'local',
  491. resourceBase: { kind: 'directory', path: join(project, '.dsh/skills/project-skill') },
  492. content: 'Project instructions.',
  493. })
  494. const block = result.content[0]
  495. expect(block?.type).toBe('text')
  496. if (block?.type !== 'text') throw new Error('expected text skill result')
  497. expect(block.text).toBe([
  498. '<skill_content name="project-skill">',
  499. '<skill_resources>',
  500. `Base directory for this skill: ${join(project, '.dsh/skills/project-skill')}`,
  501. 'Resolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.',
  502. '</skill_resources>',
  503. '',
  504. '<skill_instructions>',
  505. 'Project instructions.',
  506. '</skill_instructions>',
  507. '</skill_content>',
  508. ].join('\n'))
  509. expect(block.text).not.toContain('# Skill:')
  510. })
  511. it('renders provider-managed resource hints for non-local skills', async () => {
  512. const home = await tempDir('tool-resource-hints')
  513. const ctx = await setup(home)
  514. ctx.skills.register({
  515. name: 'opaque-skill',
  516. description: 'Opaque skill',
  517. source: 'runtime',
  518. provider: 'runtime',
  519. resourceBase: { kind: 'opaque', description: 'runtime memory' },
  520. content: 'Opaque instructions.',
  521. })
  522. ctx.skills.register({
  523. name: 'url-skill',
  524. description: 'URL skill',
  525. source: 'runtime',
  526. provider: 'runtime',
  527. resourceBase: { kind: 'url', url: 'https://skills.example.test/url-skill' },
  528. content: 'URL instructions.',
  529. })
  530. ctx.skills.register({
  531. name: 'provider-skill',
  532. description: 'Provider skill',
  533. source: 'runtime',
  534. provider: 'runtime',
  535. content: 'Provider instructions.',
  536. })
  537. const opaque = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c2'), name: 'skill', arguments: { name: 'opaque-skill' } })
  538. const url = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c3'), name: 'skill', arguments: { name: 'url-skill' } })
  539. const provider = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c4'), name: 'skill', arguments: { name: 'provider-skill' } })
  540. if (opaque.content[0]?.type !== 'text' || url.content[0]?.type !== 'text' || provider.content[0]?.type !== 'text') {
  541. throw new Error('expected text tool results')
  542. }
  543. expect(opaque.content[0].text).toContain('<skill_resources>\nResources for this skill: runtime memory\nLoad referenced resources only as needed.\n</skill_resources>')
  544. expect(url.content[0].text).toContain('<skill_resources>\nBase URL for this skill: https://skills.example.test/url-skill\nResolve relative URLs mentioned by this skill against the base URL before using them. Load referenced resources only as needed.\n</skill_resources>')
  545. expect(provider.content[0].text).toContain('<skill_resources>\nResources for this skill are managed by provider "runtime".\nLoad referenced resources only as needed.\n</skill_resources>')
  546. })
  547. it('rejects an unknown resource-base kind at the canonical output boundary', async () => {
  548. const home = await tempDir('tool-resource-assert-never')
  549. const ctx = await setup(home)
  550. ctx.skills.register({
  551. name: 'rogue-resource-skill',
  552. description: 'Rogue resource skill',
  553. source: 'runtime',
  554. provider: 'runtime',
  555. resourceBase: { kind: 'future' } as never,
  556. content: 'Rogue instructions.',
  557. })
  558. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c5'), name: 'skill', arguments: { name: 'rogue-resource-skill' } })
  559. expect(result.isError).toBe(true)
  560. expect(result.error?.info?.code).toBe('INVALID_TOOL_OUTPUT')
  561. const block = result.content[0]
  562. if (block?.type !== 'text') throw new Error('expected text tool result')
  563. expect(block.text).toContain('value.resourceBase')
  564. })
  565. it('returns isError for unknown, invalid, and model-disabled skills', async () => {
  566. const home = await tempDir('tool-errors')
  567. await writeSkill(join(home, '.dsh/skills'), 'hidden-skill', 'Hidden skill', 'Hidden instructions.')
  568. await writeFile(join(home, '.dsh/skills/hidden-skill/SKILL.md'), '---\nname: hidden-skill\ndescription: Hidden skill\ndisable-model-invocation: true\n---\n\nHidden instructions.\n')
  569. const ctx = await setup(home)
  570. ctx.skills.register({
  571. name: 'model-only-skill',
  572. description: 'Model-only skill',
  573. invocation: { modelInvocable: true, userInvocable: false },
  574. source: 'runtime',
  575. content: 'Model-only instructions.',
  576. })
  577. const unknown = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'skill', arguments: { name: 'missing' } })
  578. const invalid = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c2'), name: 'skill', arguments: { name: 'Bad_Name' } })
  579. const disabled = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c3'), name: 'skill', arguments: { name: 'hidden-skill' } })
  580. const modelOnly = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c4'), name: 'skill', arguments: { name: 'model-only-skill' } })
  581. expect(unknown.isError).toBe(true)
  582. expect(invalid.isError).toBe(true)
  583. expect(disabled.isError).toBe(true)
  584. expect(modelOnly.isError).toBe(false)
  585. const unknownBlock = unknown.content[0]
  586. if (unknownBlock?.type !== 'text') throw new Error('expected text tool result')
  587. expect(unknownBlock.text).toContain('skill "missing" is unknown or no longer available')
  588. })
  589. it('checks model policy before provider loading and rechecks the loaded definition', async () => {
  590. const home = await tempDir('tool-policy-before-load')
  591. const ctx = await setup(home)
  592. const getCalls: string[] = []
  593. ctx.skills.registerProvider(() => ({
  594. name: 'policy-probe',
  595. async list() {
  596. return [
  597. {
  598. name: 'denied-skill',
  599. description: 'Denied skill',
  600. invocation: { modelInvocable: false, userInvocable: true },
  601. provider: 'policy-probe',
  602. source: 'test',
  603. rank: 1,
  604. locator: 'denied-skill',
  605. },
  606. {
  607. name: 'policy-race-skill',
  608. description: 'Policy race skill',
  609. invocation: { modelInvocable: true, userInvocable: true },
  610. provider: 'policy-probe',
  611. source: 'test',
  612. rank: 1,
  613. locator: 'policy-race-skill',
  614. },
  615. {
  616. name: 'vanishing-skill',
  617. description: 'Vanishing skill',
  618. invocation: { modelInvocable: true, userInvocable: true },
  619. provider: 'policy-probe',
  620. source: 'test',
  621. rank: 1,
  622. locator: 'vanishing-skill',
  623. },
  624. ]
  625. },
  626. async get(candidate) {
  627. getCalls.push(candidate.name)
  628. if (candidate.name === 'vanishing-skill') return undefined
  629. return {
  630. ...candidate,
  631. invocation: { modelInvocable: false, userInvocable: true },
  632. content: 'Instructions must not be disclosed.',
  633. }
  634. },
  635. }))
  636. const denied = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c6'), name: 'skill', arguments: { name: 'denied-skill' } })
  637. const raced = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c7'), name: 'skill', arguments: { name: 'policy-race-skill' } })
  638. const vanished = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c8'), name: 'skill', arguments: { name: 'vanishing-skill' } })
  639. expect(denied.isError).toBe(true)
  640. expect(raced.isError).toBe(true)
  641. expect(vanished.isError).toBe(true)
  642. expect(getCalls).toEqual(['policy-race-skill', 'vanishing-skill'])
  643. for (const result of [denied, raced]) {
  644. const block = result.content[0]
  645. if (block?.type !== 'text') throw new Error('expected text tool result')
  646. expect(block.text).toContain('is not available for model invocation')
  647. expect(block.text).not.toContain('Instructions must not be disclosed.')
  648. }
  649. const vanishedBlock = vanished.content[0]
  650. if (vanishedBlock?.type !== 'text') throw new Error('expected text tool result')
  651. expect(vanishedBlock.text).toContain('skill "vanishing-skill" is unknown or no longer available')
  652. })
  653. })