tool-skill.spec.ts 29 KB

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