tool-skill.spec.ts 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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 '@deepseek-ai/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, type UserMessage } from '@deepseek-ai/dsh-session'
  9. import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
  10. import ToolRuntime, { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  11. import AgentRegistry, { agentEvents, Inbox, type Agent, type PreStepDecision } from '@deepseek-ai/dsh-agent'
  12. import SkillRegistry from '@deepseek-ai/dsh-skill'
  13. import * as SkillFileSystem from '@deepseek-ai/dsh-skill-filesystem'
  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(ToolRuntime)
  28. await ctx.plugin(AgentRegistry)
  29. await ctx.plugin(SkillRegistry)
  30. await ctx.plugin(SkillFileSystem, { 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. inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }),
  43. status: 'idle',
  44. send: () => {},
  45. followup: () => {},
  46. steer: () => {},
  47. inject: () => { throw new Error('step-boundary catalog must not use agent.inject()') },
  48. cancel() {},
  49. runMaintenance: task => task(new AbortController().signal),
  50. whenIdle: () => Promise.resolve(),
  51. }
  52. }
  53. function sessionAgent(session: Session, id = 'tool-skill-agent'): Agent {
  54. return {
  55. id: SessionId(id),
  56. options: {},
  57. session,
  58. inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }),
  59. status: 'running',
  60. ctx: new Context(),
  61. send: () => {},
  62. followup: () => {},
  63. steer: () => {},
  64. inject: () => { throw new Error('step-boundary catalog must not use agent.inject()') },
  65. cancel() {},
  66. runMaintenance: task => task(new AbortController().signal),
  67. whenIdle: () => Promise.resolve(),
  68. }
  69. }
  70. function openMessageTurn(session: Session, turn = 1): void {
  71. session.append('turn/start', { turn })
  72. session.append('user/message', createUserMessage({
  73. content: [{ type: 'text', text: `turn ${turn}` }],
  74. source: { kind: 'user' },
  75. }), { surfaceOp: 'append' })
  76. }
  77. async function fireStep(ctx: Context, agent: Agent, turn: number, step: number): Promise<void> {
  78. const signal = new AbortController().signal
  79. const decision = await agentEvents(ctx, agent).waterfall(
  80. 'agent/pre-step',
  81. { messages: [], turn, step, signal },
  82. () => Promise.resolve({ kind: 'enter' as const, messages: [] }),
  83. )
  84. if (decision.kind === 'enter') {
  85. for (const message of decision.messages) {
  86. agent.session.append('user/message', message, { surfaceOp: 'append' })
  87. }
  88. }
  89. }
  90. async function proposeStep(
  91. ctx: Context,
  92. agent: Agent,
  93. messages: UserMessage[],
  94. ): Promise<PreStepDecision> {
  95. const signal = new AbortController().signal
  96. return await agentEvents(ctx, agent).waterfall(
  97. 'agent/pre-step',
  98. { messages, turn: 1, step: 1, signal },
  99. () => Promise.resolve({ kind: 'enter' as const, messages }),
  100. )
  101. }
  102. function catalogMessages(session: Session): Extract<SessionEvent, { type: 'user/message' }>[] {
  103. return session.events.filter((event): event is Extract<SessionEvent, { type: 'user/message' }> => event.type === 'user/message'
  104. && event.data.source.kind === 'skill-catalog')
  105. }
  106. function readableCatalog(event: Extract<SessionEvent, { type: 'user/message' }>): boolean {
  107. const entries = (event.data.source as { entries?: unknown }).entries
  108. return Array.isArray(entries)
  109. && entries.every(entry => typeof entry === 'object' && entry !== null
  110. && typeof (entry as { name?: unknown }).name === 'string'
  111. && typeof (entry as { description?: unknown }).description === 'string')
  112. }
  113. function catalogContent(entries: string[]): Message['content'] {
  114. return [{
  115. type: 'text',
  116. text: ['<system-reminder>', '<available_skills>', ...entries, '</available_skills>', '</system-reminder>'].join('\n'),
  117. }]
  118. }
  119. async function composePrefix(ctx: Context, cwd: string, signal = new AbortController().signal): Promise<Message[]> {
  120. return await composePrefixForAgent(ctx, agentForCwd(cwd), signal)
  121. }
  122. async function composePrefixForAgent(ctx: Context, agent: Agent, signal = new AbortController().signal): Promise<Message[]> {
  123. const decision = await agentEvents(ctx, agent).waterfall(
  124. 'agent/pre-step',
  125. { messages: [], turn: 1, step: 1, signal },
  126. () => Promise.resolve({ kind: 'enter' as const, messages: [] }),
  127. )
  128. if (decision.kind === 'enter') {
  129. for (const message of decision.messages) {
  130. agent.session.append('user/message', message, { surfaceOp: 'append' })
  131. }
  132. }
  133. return agent.session.deriveMessages()
  134. }
  135. async function mintAgentScope(ctx: Context, subject: string | Agent): Promise<{ agent: Agent; scope: Scope }> {
  136. const agent = typeof subject === 'string' ? agentForCwd(subject) : subject
  137. let scope!: Scope
  138. await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) }, {
  139. inject: ['tools'],
  140. }))
  141. return { agent, scope }
  142. }
  143. describe('dsh-tool-skill', () => {
  144. it('registers the skill tool schema and removes it on dispose', async () => {
  145. const ctx = new Context()
  146. await ctx.plugin(SystemPrompt)
  147. await ctx.plugin(ToolRuntime)
  148. await ctx.plugin(AgentRegistry)
  149. const home = await tempDir('tool-schema')
  150. await ctx.plugin(SkillRegistry)
  151. await ctx.plugin(SkillFileSystem, { dshHome: join(home, '.dsh'), agentsHome: join(home, '.agents'), watch: false })
  152. ctx.skills.register({ name: 'lifecycle-skill', description: 'Lifecycle', source: 'runtime', content: 'body' })
  153. const fiber = await ctx.plugin(toolSkill)
  154. expect(ctx.tools.schemas().map(tool => tool.name)).toEqual(['skill'])
  155. expect(await composePrefix(ctx, '/workspace')).toHaveLength(1)
  156. expect(ctx.tools.get('skill')?.presentCall?.({ name: 'project-skill' })).toEqual({
  157. card: 'generic',
  158. title: 'Load skill project-skill',
  159. kind: 'read',
  160. rawInput: 'project-skill',
  161. })
  162. await fiber.dispose()
  163. expect(ctx.tools.schemas()).toEqual([])
  164. expect(await composePrefix(ctx, '/workspace')).toEqual([])
  165. toolSkill.apply(ctx)
  166. expect(ctx.tools.schemas().map(tool => tool.name)).toEqual(['skill'])
  167. })
  168. it('forwards the step abort signal to skill discovery', async () => {
  169. const home = await tempDir('tool-prefix-signal')
  170. const ctx = await setup(home)
  171. let seenSignal: AbortSignal | undefined
  172. ctx.skills.registerProvider(() => ({
  173. name: 'signal-probe',
  174. async list(options) {
  175. seenSignal = options.signal
  176. return []
  177. },
  178. async get() {
  179. return undefined
  180. },
  181. }))
  182. const controller = new AbortController()
  183. await composePrefix(ctx, '/workspace', controller.signal)
  184. expect(seenSignal).toBe(controller.signal)
  185. })
  186. it('injects a stable durable name-and-description catalog at the first step', async () => {
  187. const home = await tempDir('tool-catalog')
  188. const ctx = await setup(home, { catalogDescriptionMaxLength: 50 })
  189. ctx.skills.register({
  190. name: 'z-skill',
  191. description: 'Long description '.repeat(5),
  192. whenToUse: 'Never render this routing hint.',
  193. source: 'secret-source',
  194. provider: 'runtime',
  195. resourceBase: { kind: 'directory', path: '/secret/path' },
  196. content: 'Secret body.',
  197. })
  198. ctx.skills.register({
  199. name: 'a-skill',
  200. description: 'Use {{placeholder}} <safely> & carefully.',
  201. source: 'runtime',
  202. provider: 'runtime',
  203. content: 'A body.',
  204. })
  205. ctx.skills.register({
  206. name: 'model-only-skill',
  207. description: 'Model-only skill.',
  208. invocation: { modelInvocable: true, userInvocable: false },
  209. source: 'runtime',
  210. content: 'Model-only body.',
  211. })
  212. ctx.skills.register({
  213. name: 'user-only-skill',
  214. description: 'User-only skill.',
  215. invocation: { modelInvocable: false, userInvocable: true },
  216. source: 'runtime',
  217. content: 'User-only body.',
  218. })
  219. ctx.on('agent/pre-step', async (_payload, next) => {
  220. const decision = await next()
  221. if (decision.kind === 'reject') return decision
  222. return {
  223. ...decision,
  224. messages: [
  225. ...decision.messages,
  226. createUserMessage({
  227. content: [{ type: 'text', text: 'later contribution' }],
  228. source: { kind: 'plugin', plugin: 'later-contribution' },
  229. }),
  230. ],
  231. }
  232. })
  233. const prefix = await composePrefix(ctx, '/workspace')
  234. expect(prefix).toEqual([
  235. {
  236. id: expect.any(String) as unknown,
  237. role: 'user',
  238. content: [{ type: 'text', text: 'later contribution' }],
  239. source: { kind: 'plugin', plugin: 'later-contribution' },
  240. },
  241. {
  242. id: expect.any(String) as unknown,
  243. role: 'user',
  244. source: {
  245. kind: 'skill-catalog',
  246. form: 'catalog',
  247. entries: [
  248. { name: 'a-skill', description: 'Use {{placeholder}} <safely> & carefully.' },
  249. { name: 'model-only-skill', description: 'Model-only skill.' },
  250. { name: 'z-skill', description: 'Long description Long description Long descript...' },
  251. ],
  252. },
  253. content: [{
  254. type: 'text',
  255. text: [
  256. '<system-reminder>',
  257. 'A skill is a reusable set of task-specific instructions. The following skills are available in this session:',
  258. '',
  259. '<available_skills>',
  260. '- `a-skill`: Use {{placeholder}} &lt;safely&gt; &amp; carefully.',
  261. '- `model-only-skill`: Model-only skill.',
  262. '- `z-skill`: Long description Long description Long descript...',
  263. '</available_skills>',
  264. '',
  265. "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.",
  266. 'A user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.',
  267. '</system-reminder>',
  268. ].join('\n'),
  269. }],
  270. },
  271. ])
  272. const rendered = JSON.stringify(prefix[1])
  273. expect(rendered).not.toContain('whenToUse')
  274. expect(rendered).not.toContain('secret-source')
  275. expect(rendered).not.toContain('/secret/path')
  276. expect(rendered).not.toContain('Secret body')
  277. expect(rendered).not.toContain('user-only-skill')
  278. expect(renderPrompt(await ctx.systemPrompt.assemble({ agent: agentForCwd('/workspace') }))).not.toContain('<available_skills>')
  279. })
  280. it('does not inject a catalog when no model-invocable skills are available', async () => {
  281. const home = await tempDir('tool-empty-catalog')
  282. const ctx = await setup(home)
  283. ctx.skills.register({
  284. name: 'user-only-skill',
  285. description: 'User-only skill',
  286. invocation: { modelInvocable: false, userInvocable: true },
  287. source: 'runtime',
  288. content: 'User-only body.',
  289. })
  290. const agent = agentForCwd('/workspace')
  291. expect(await composePrefixForAgent(ctx, agent)).toEqual([])
  292. expect(await composePrefixForAgent(ctx, agent)).toEqual([])
  293. })
  294. it('omits an incomplete initial catalog and retries on a later request boundary', async () => {
  295. const home = await tempDir('tool-incomplete-prefix')
  296. const ctx = await setup(home)
  297. let failing = true
  298. const provider = {
  299. name: 'recovering',
  300. async list() {
  301. if (failing) throw new Error('temporarily unavailable')
  302. return []
  303. },
  304. async get() {
  305. return undefined
  306. },
  307. }
  308. let invalidate = (): void => {}
  309. ctx.skills.registerProvider((control) => {
  310. invalidate = control.invalidate
  311. return provider
  312. })
  313. const session = Session.create(SessionId('incomplete-prefix'))
  314. const agent = sessionAgent(session)
  315. openMessageTurn(session)
  316. await composePrefixForAgent(ctx, agent)
  317. expect(catalogMessages(session)).toEqual([])
  318. failing = false
  319. invalidate()
  320. await fireStep(ctx, agent, 1, 1)
  321. expect(catalogMessages(session)).toEqual([])
  322. })
  323. it('records an empty baseline across repeated step observations', async () => {
  324. const home = await tempDir('tool-empty-step')
  325. const ctx = await setup(home)
  326. const session = Session.create(SessionId('empty-step'))
  327. const agent = sessionAgent(session)
  328. openMessageTurn(session)
  329. await fireStep(ctx, agent, 1, 1)
  330. await fireStep(ctx, agent, 1, 2)
  331. expect(catalogMessages(session)).toEqual([])
  332. })
  333. it('deduplicates or replaces a catalog already proposed for the same step', async () => {
  334. const home = await tempDir('tool-proposed-catalog')
  335. const ctx = await setup(home)
  336. const disposeFirst = ctx.skills.register({
  337. name: 'first-skill',
  338. description: 'First skill',
  339. source: 'runtime',
  340. content: 'First body.',
  341. })
  342. const session = Session.create(SessionId('proposed-catalog'))
  343. const agent = sessionAgent(session)
  344. openMessageTurn(session)
  345. await fireStep(ctx, agent, 1, 1)
  346. const initial = catalogMessages(session)[0]?.data
  347. if (initial === undefined) throw new Error('expected initial catalog')
  348. const duplicate = await proposeStep(ctx, agent, [initial])
  349. expect(duplicate).toEqual({ kind: 'enter', messages: [] })
  350. ctx.skills.register({
  351. name: 'second-skill',
  352. description: 'Second skill',
  353. source: 'runtime',
  354. content: 'Second body.',
  355. })
  356. const companion = createUserMessage({
  357. content: [{ type: 'text', text: 'keep this message' }],
  358. source: { kind: 'user' },
  359. })
  360. const replaced = await proposeStep(ctx, agent, [companion, initial])
  361. expect(replaced.kind).toBe('enter')
  362. if (replaced.kind === 'reject') throw new Error('expected catalog replacement')
  363. expect(replaced.messages).toHaveLength(2)
  364. expect(replaced.messages[0]).toBe(companion)
  365. expect(replaced.messages[1]?.id).not.toBe(initial.id)
  366. expect(JSON.stringify(replaced.messages[1]?.content)).toContain('second-skill')
  367. disposeFirst()
  368. })
  369. it('removes a stale proposed catalog before the first empty baseline', async () => {
  370. const home = await tempDir('tool-proposed-empty-catalog')
  371. const ctx = await setup(home)
  372. const session = Session.create(SessionId('proposed-empty-catalog'))
  373. const malformed = createUserMessage({
  374. content: [{ type: 'text', text: 'preserve unreadable claimed context' }],
  375. source: { kind: 'skill-catalog', form: 'catalog' } as never,
  376. })
  377. const stale = createUserMessage({
  378. content: catalogContent(['- `stale-skill`: Stale skill']),
  379. source: {
  380. kind: 'skill-catalog',
  381. form: 'catalog',
  382. entries: [{ name: 'stale-skill', description: 'Stale skill' }],
  383. },
  384. })
  385. const decision = await proposeStep(ctx, sessionAgent(session), [malformed, stale])
  386. expect(decision).toEqual({ kind: 'enter', messages: [malformed] })
  387. })
  388. it('keeps a proposed catalog that already matches the current snapshot', async () => {
  389. const home = await tempDir('tool-matching-proposal')
  390. const ctx = await setup(home)
  391. ctx.skills.register({
  392. name: 'first-skill',
  393. description: 'First skill',
  394. source: 'runtime',
  395. content: 'First body.',
  396. })
  397. const session = Session.create(SessionId('matching-proposal'))
  398. const proposed = createUserMessage({
  399. content: catalogContent(['- `first-skill`: First skill']),
  400. source: {
  401. kind: 'skill-catalog',
  402. form: 'catalog',
  403. entries: [{ name: 'first-skill', description: 'First skill' }],
  404. },
  405. })
  406. const decision = await proposeStep(ctx, sessionAgent(session), [proposed])
  407. expect(decision).toEqual({ kind: 'enter', messages: [proposed] })
  408. })
  409. it('injects complete replacement catalogs for additions and an empty tombstone for removals', async () => {
  410. const home = await tempDir('tool-dynamic-catalog')
  411. const ctx = await setup(home)
  412. const disposeFirst = ctx.skills.register({
  413. name: 'first-skill',
  414. description: 'First skill',
  415. source: 'runtime',
  416. content: 'First body.',
  417. })
  418. const session = Session.create(SessionId('dynamic-catalog'))
  419. const agent = sessionAgent(session)
  420. openMessageTurn(session)
  421. expect(JSON.stringify(await composePrefixForAgent(ctx, agent))).toContain('first-skill')
  422. await fireStep(ctx, agent, 1, 1)
  423. expect(catalogMessages(session)).toHaveLength(1)
  424. const disposeSecond = ctx.skills.register({
  425. name: 'second-skill',
  426. description: 'Second skill',
  427. source: 'runtime',
  428. content: 'Second body.',
  429. })
  430. await fireStep(ctx, agent, 1, 2)
  431. const addition = catalogMessages(session)[1]
  432. if (addition?.type !== 'user/message') throw new Error('expected catalog addition')
  433. expect(JSON.stringify(addition.data.content)).toContain('first-skill')
  434. expect(JSON.stringify(addition.data.content)).toContain('second-skill')
  435. disposeSecond()
  436. disposeFirst()
  437. await fireStep(ctx, agent, 1, 3)
  438. const removal = catalogMessages(session)[2]
  439. if (removal?.type !== 'user/message') throw new Error('expected catalog removal')
  440. expect(JSON.stringify(removal.data.content)).toContain('No skills are currently available')
  441. expect(JSON.stringify(removal.data.content)).not.toContain('first-skill')
  442. expect(JSON.stringify(removal.data.content)).not.toContain('second-skill')
  443. await fireStep(ctx, agent, 1, 4)
  444. expect(catalogMessages(session)).toHaveLength(3)
  445. })
  446. it('resumes from the durable entries of the latest visible catalog', async () => {
  447. // Catalog identity lives on `source.entries`: the model-facing prose does
  448. // not decide whether a republish is needed, so a seeded message is
  449. // recognized by its source alone and malformed prose cannot hide (or fake)
  450. // a published catalog. A foreign-sourced message is not this plugin's
  451. // catalog at all.
  452. const home = await tempDir('tool-catalog-resume')
  453. const ctx = await setup(home)
  454. ctx.skills.register({
  455. name: 'resumed-skill',
  456. description: 'Resumed skill',
  457. source: 'runtime',
  458. content: 'Resumed body.',
  459. })
  460. const session = Session.create(SessionId('catalog-resume'))
  461. const agent = sessionAgent(session)
  462. openMessageTurn(session)
  463. session.append('user/message', createUserMessage({
  464. content: [{ type: 'text', text: 'prose a reader cannot rely on' }],
  465. source: {
  466. kind: 'skill-catalog',
  467. form: 'catalog',
  468. entries: [{ name: 'old-skill', description: 'Old skill' }],
  469. },
  470. }), { surfaceOp: 'append' })
  471. session.append('user/message', createUserMessage({
  472. content: catalogContent(['- `resumed-skill`: Resumed skill']),
  473. source: { kind: 'plugin', plugin: 'dsh-tool-skill' },
  474. }), { surfaceOp: 'append' })
  475. await fireStep(ctx, agent, 1, 1)
  476. // The seeded entries differ from the live snapshot, so one replacement
  477. // lands; the foreign-sourced lookalike neither counts as published nor
  478. // suppresses it.
  479. expect(catalogMessages(session)).toHaveLength(2)
  480. const latest = catalogMessages(session).at(-1)
  481. expect(latest?.data.source).toMatchObject({
  482. kind: 'skill-catalog',
  483. form: 'catalog',
  484. update: true,
  485. entries: [{ name: 'resumed-skill', description: 'Resumed skill' }],
  486. })
  487. expect(JSON.stringify(latest?.data.content)).toContain('resumed-skill')
  488. // A second step over unchanged entries republishes nothing.
  489. await fireStep(ctx, agent, 1, 2)
  490. expect(catalogMessages(session)).toHaveLength(2)
  491. })
  492. it('treats a malformed durable catalog as unrecognizable instead of failing the step', async () => {
  493. // Seeds reach `agent.session.events` from JSONL/SQLite on resume or fork,
  494. // and seed validation only guarantees a source object with a non-empty
  495. // `kind`. A catalog whose entries are missing or wrongly shaped must be
  496. // skipped like any foreign record; throwing here would fail every later
  497. // step of that session at the latest possible point.
  498. const home = await tempDir('tool-catalog-malformed')
  499. const ctx = await setup(home)
  500. ctx.skills.register({
  501. name: 'live-skill',
  502. description: 'Live skill',
  503. source: 'runtime',
  504. content: 'Live body.',
  505. })
  506. const session = Session.create(SessionId('catalog-malformed'))
  507. const agent = sessionAgent(session)
  508. openMessageTurn(session)
  509. for (const source of [
  510. { kind: 'skill-catalog', form: 'catalog' },
  511. { kind: 'skill-catalog', form: 'catalog', entries: null },
  512. { kind: 'skill-catalog', form: 'catalog', entries: 'not-an-array' },
  513. { kind: 'skill-catalog', form: 'catalog', entries: [null] },
  514. { kind: 'skill-catalog', form: 'catalog', entries: [{ name: 'x' }] },
  515. { kind: 'skill-catalog', form: 'catalog', entries: [{ description: 'no name' }] },
  516. ]) {
  517. session.append('user/message', createUserMessage({
  518. content: [{ type: 'text', text: 'unreadable catalog' }],
  519. source: source as never,
  520. }), { surfaceOp: 'append' })
  521. }
  522. await expect(fireStep(ctx, agent, 1, 1)).resolves.toBeUndefined()
  523. // None of the six counted as published, so the live catalog lands as a
  524. // first publication rather than a replacement.
  525. const published = catalogMessages(session).filter(event => readableCatalog(event))
  526. expect(published).toHaveLength(1)
  527. expect(published[0]?.data.source).toMatchObject({ kind: 'skill-catalog', form: 'catalog' })
  528. expect(published[0]?.data.source).not.toHaveProperty('update')
  529. expect(JSON.stringify(published[0]?.data.content)).toContain('live-skill')
  530. })
  531. it('re-establishes the current catalog after compaction hides its durable message', async () => {
  532. const home = await tempDir('tool-catalog-compaction')
  533. const ctx = await setup(home)
  534. ctx.skills.register({
  535. name: 'first-skill',
  536. description: 'First skill',
  537. source: 'runtime',
  538. content: 'First body.',
  539. })
  540. const session = Session.create(SessionId('catalog-compaction'))
  541. const agent = sessionAgent(session)
  542. openMessageTurn(session)
  543. expect(JSON.stringify(await composePrefixForAgent(ctx, agent))).toContain('first-skill')
  544. const initial = catalogMessages(session)[0]
  545. if (initial === undefined) throw new Error('expected initial catalog')
  546. session.append('user/message', createUserMessage({
  547. content: [{ type: 'text', text: 'compacted history' }],
  548. source: { kind: 'plugin', plugin: 'compact' },
  549. }), {
  550. surfaceOp: { op: 'replace', start: initial.seq, end: initial.seq },
  551. sourceEventSeqs: [initial.seq],
  552. })
  553. await fireStep(ctx, agent, 1, 1)
  554. expect(catalogMessages(session)).toHaveLength(2)
  555. expect(JSON.stringify(catalogMessages(session).at(-1)?.data.content)).toContain('first-skill')
  556. })
  557. it('keeps body-only edits out of the catalog and loads the latest body on demand', async () => {
  558. const home = await tempDir('tool-body-refresh')
  559. const root = join(home, '.dsh/skills')
  560. await writeSkill(root, 'body-skill', 'Stable description', 'First body.')
  561. const ctx = await setup(home)
  562. const session = Session.create(SessionId('body-refresh'))
  563. const agent = sessionAgent(session)
  564. openMessageTurn(session)
  565. expect(JSON.stringify(await composePrefixForAgent(ctx, agent))).toContain('Stable description')
  566. await writeSkill(root, 'body-skill', 'Stable description', 'Second body.')
  567. await fireStep(ctx, agent, 1, 1)
  568. expect(catalogMessages(session)).toHaveLength(1)
  569. const result = await ctx.tools.execute({
  570. signal: testToolSignal,
  571. callId: CallId('body-refresh'),
  572. name: 'skill',
  573. arguments: { name: 'body-skill' },
  574. agent,
  575. })
  576. expect(result.isError).toBe(false)
  577. expect(JSON.stringify(result.content)).toContain('Second body.')
  578. expect(JSON.stringify(result.content)).not.toContain('First body.')
  579. })
  580. it('resolves the layered registry as the calling agent sees it', async () => {
  581. const home = await tempDir('tool-scoped-layer')
  582. const ctx = await setup(home)
  583. const { agent, scope } = await mintAgentScope(ctx, '/workspace/scoped')
  584. const scopedSkills = scope.ctx.get('skills')
  585. if (scopedSkills === undefined) throw new Error('skills service missing')
  586. scopedSkills.register({
  587. name: 'preset-only-skill',
  588. description: 'Visible to the scoped agent alone',
  589. source: 'preset',
  590. content: 'Preset-only body.',
  591. })
  592. expect(JSON.stringify(await composePrefixForAgent(ctx, agent))).toContain('preset-only-skill')
  593. expect(JSON.stringify(await composePrefix(ctx, '/workspace/other'))).not.toContain('preset-only-skill')
  594. const scoped = await ctx.tools.execute({
  595. signal: testToolSignal,
  596. callId: CallId('scoped-load'),
  597. name: 'skill',
  598. arguments: { name: 'preset-only-skill' },
  599. agent,
  600. })
  601. expect(scoped.isError).toBe(false)
  602. expect(JSON.stringify(scoped.content)).toContain('Preset-only body.')
  603. const foreign = await ctx.tools.execute({
  604. signal: testToolSignal,
  605. callId: CallId('foreign-load'),
  606. name: 'skill',
  607. arguments: { name: 'preset-only-skill' },
  608. agent: agentForCwd('/workspace/other'),
  609. })
  610. expect(foreign.isError).toBe(true)
  611. await scope.dispose()
  612. })
  613. it('retains the last-good catalog while any provider discovery is incomplete', async () => {
  614. const home = await tempDir('tool-incomplete-catalog')
  615. const ctx = await setup(home)
  616. const disposeStable = ctx.skills.register({
  617. name: 'stable-skill',
  618. description: 'Stable skill',
  619. source: 'runtime',
  620. content: 'Stable body.',
  621. })
  622. const session = Session.create(SessionId('incomplete-catalog'))
  623. const agent = sessionAgent(session)
  624. openMessageTurn(session)
  625. expect(JSON.stringify(await composePrefixForAgent(ctx, agent))).toContain('stable-skill')
  626. ctx.skills.registerProvider(() => ({
  627. name: 'failing',
  628. async list() {
  629. throw new Error('temporarily unavailable')
  630. },
  631. async get() {
  632. return undefined
  633. },
  634. }))
  635. disposeStable()
  636. await fireStep(ctx, agent, 1, 1)
  637. expect(catalogMessages(session)).toHaveLength(1)
  638. })
  639. it('omits catalog guidance when the calling agent restricts away the shipped skill tool', async () => {
  640. const home = await tempDir('tool-restricted-catalog')
  641. const ctx = await setup(home)
  642. ctx.skills.register({ name: 'listed-skill', description: 'Listed', source: 'runtime', content: 'body' })
  643. const session = Session.create(SessionId('restricted-catalog'))
  644. const agent = sessionAgent(session)
  645. openMessageTurn(session)
  646. const { scope } = await mintAgentScope(ctx, agent)
  647. scope.ctx.tools.restrict({ deny: ['skill'] })
  648. expect(ctx.tools.get('skill', agent)).toBeUndefined()
  649. await composePrefixForAgent(ctx, agent)
  650. expect(catalogMessages(session)).toEqual([])
  651. await fireStep(ctx, agent, 1, 1)
  652. expect(catalogMessages(session)).toEqual([])
  653. expect(await composePrefix(ctx, '/workspace')).toHaveLength(1)
  654. await scope.dispose()
  655. })
  656. it('does not attach shipped catalog guidance to a scoped same-name tool shadow', async () => {
  657. const home = await tempDir('tool-shadowed-catalog')
  658. const ctx = await setup(home)
  659. ctx.skills.register({ name: 'listed-skill', description: 'Listed', source: 'runtime', content: 'body' })
  660. const { agent, scope } = await mintAgentScope(ctx, '/workspace')
  661. scope.ctx.tools.register(defineContentToolFixture({
  662. name: 'skill',
  663. description: 'A scoped tool with unrelated semantics.',
  664. parameters: {},
  665. execute() {
  666. return Promise.resolve([{ type: 'text', text: 'shadow' }])
  667. },
  668. }))
  669. expect(ctx.tools.get('skill', agent)).not.toBe(ctx.tools.get('skill'))
  670. expect(await composePrefixForAgent(ctx, agent)).toEqual([])
  671. expect(await composePrefix(ctx, '/workspace')).toHaveLength(1)
  672. await scope.dispose()
  673. })
  674. it('validates the catalog description cap', async () => {
  675. const home = await tempDir('tool-invalid-catalog-cap')
  676. const ctx = new Context()
  677. await ctx.plugin(SystemPrompt)
  678. await ctx.plugin(ToolRuntime)
  679. await ctx.plugin(AgentRegistry)
  680. await ctx.plugin(SkillRegistry)
  681. await ctx.plugin(SkillFileSystem, { dshHome: join(home, '.dsh'), agentsHome: join(home, '.agents'), watch: false })
  682. await expect(ctx.plugin(toolSkill, { catalogDescriptionMaxLength: 2 })).rejects.toThrow('greater than or equal to 3')
  683. })
  684. it('loads a skill for the calling agent cwd', async () => {
  685. const home = await tempDir('tool-load')
  686. const project = await tempDir('tool-project')
  687. await mkdir(join(project, '.git'), { recursive: true })
  688. await writeSkill(join(project, '.dsh/skills'), 'project-skill', 'Project skill', 'Project instructions.')
  689. const ctx = await setup(home)
  690. const result = await ctx.tools.execute({
  691. signal: testToolSignal,
  692. callId: CallId('c1'),
  693. name: 'skill',
  694. arguments: { name: 'project-skill' },
  695. agent: { session: { header: { cwd: project } } } as never,
  696. })
  697. expect(result.isError).toBe(false)
  698. if (result.isError) throw new Error('expected skill success')
  699. expect(result.value).toEqual({
  700. name: 'project-skill',
  701. provider: 'filesystem',
  702. resourceBase: { kind: 'directory', path: join(project, '.dsh/skills/project-skill') },
  703. content: 'Project instructions.',
  704. })
  705. const block = result.content[0]
  706. expect(block?.type).toBe('text')
  707. if (block?.type !== 'text') throw new Error('expected text skill result')
  708. expect(block.text).toBe([
  709. '<skill_content name="project-skill">',
  710. '<skill_resources>',
  711. `Base directory for this skill: ${join(project, '.dsh/skills/project-skill')}`,
  712. 'Resolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.',
  713. '</skill_resources>',
  714. '',
  715. '<skill_instructions>',
  716. 'Project instructions.',
  717. '</skill_instructions>',
  718. '</skill_content>',
  719. ].join('\n'))
  720. expect(block.text).not.toContain('# Skill:')
  721. })
  722. it('renders provider-managed resource hints for non-local skills', async () => {
  723. const home = await tempDir('tool-resource-hints')
  724. const ctx = await setup(home)
  725. ctx.skills.register({
  726. name: 'opaque-skill',
  727. description: 'Opaque skill',
  728. source: 'runtime',
  729. provider: 'runtime',
  730. resourceBase: { kind: 'opaque', description: 'runtime memory' },
  731. content: 'Opaque instructions.',
  732. })
  733. ctx.skills.register({
  734. name: 'url-skill',
  735. description: 'URL skill',
  736. source: 'runtime',
  737. provider: 'runtime',
  738. resourceBase: { kind: 'url', url: 'https://skills.example.test/url-skill' },
  739. content: 'URL instructions.',
  740. })
  741. ctx.skills.register({
  742. name: 'provider-skill',
  743. description: 'Provider skill',
  744. source: 'runtime',
  745. provider: 'runtime',
  746. content: 'Provider instructions.',
  747. })
  748. const opaque = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c2'), name: 'skill', arguments: { name: 'opaque-skill' } })
  749. const url = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c3'), name: 'skill', arguments: { name: 'url-skill' } })
  750. const provider = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c4'), name: 'skill', arguments: { name: 'provider-skill' } })
  751. if (opaque.content[0]?.type !== 'text' || url.content[0]?.type !== 'text' || provider.content[0]?.type !== 'text') {
  752. throw new Error('expected text tool results')
  753. }
  754. expect(opaque.content[0].text).toContain('<skill_resources>\nResources for this skill: runtime memory\nLoad referenced resources only as needed.\n</skill_resources>')
  755. 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>')
  756. 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>')
  757. })
  758. it('rejects an unknown resource-base kind at the canonical output boundary', async () => {
  759. const home = await tempDir('tool-resource-assert-never')
  760. const ctx = await setup(home)
  761. ctx.skills.register({
  762. name: 'rogue-resource-skill',
  763. description: 'Rogue resource skill',
  764. source: 'runtime',
  765. provider: 'runtime',
  766. resourceBase: { kind: 'future' } as never,
  767. content: 'Rogue instructions.',
  768. })
  769. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c5'), name: 'skill', arguments: { name: 'rogue-resource-skill' } })
  770. expect(result.isError).toBe(true)
  771. expect(result.error?.info?.code).toBe('INVALID_TOOL_OUTPUT')
  772. const block = result.content[0]
  773. if (block?.type !== 'text') throw new Error('expected text tool result')
  774. expect(block.text).toContain('value.resourceBase')
  775. })
  776. it('returns isError for unknown, invalid, and model-disabled skills', async () => {
  777. const home = await tempDir('tool-errors')
  778. await writeSkill(join(home, '.dsh/skills'), 'hidden-skill', 'Hidden skill', 'Hidden instructions.')
  779. 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')
  780. const ctx = await setup(home)
  781. ctx.skills.register({
  782. name: 'model-only-skill',
  783. description: 'Model-only skill',
  784. invocation: { modelInvocable: true, userInvocable: false },
  785. source: 'runtime',
  786. content: 'Model-only instructions.',
  787. })
  788. const unknown = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'skill', arguments: { name: 'missing' } })
  789. const invalid = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c2'), name: 'skill', arguments: { name: 'Bad_Name' } })
  790. const disabled = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c3'), name: 'skill', arguments: { name: 'hidden-skill' } })
  791. const modelOnly = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c4'), name: 'skill', arguments: { name: 'model-only-skill' } })
  792. expect(unknown.isError).toBe(true)
  793. expect(invalid.isError).toBe(true)
  794. expect(disabled.isError).toBe(true)
  795. expect(modelOnly.isError).toBe(false)
  796. const unknownBlock = unknown.content[0]
  797. if (unknownBlock?.type !== 'text') throw new Error('expected text tool result')
  798. expect(unknownBlock.text).toContain('skill "missing" is unknown or no longer available')
  799. })
  800. it('checks model policy before provider loading and rechecks the loaded definition', async () => {
  801. const home = await tempDir('tool-policy-before-load')
  802. const ctx = await setup(home)
  803. const getCalls: string[] = []
  804. ctx.skills.registerProvider(() => ({
  805. name: 'policy-probe',
  806. async list() {
  807. return [
  808. {
  809. name: 'denied-skill',
  810. description: 'Denied skill',
  811. invocation: { modelInvocable: false, userInvocable: true },
  812. provider: 'policy-probe',
  813. source: 'test',
  814. rank: 1,
  815. locator: 'denied-skill',
  816. },
  817. {
  818. name: 'policy-race-skill',
  819. description: 'Policy race skill',
  820. invocation: { modelInvocable: true, userInvocable: true },
  821. provider: 'policy-probe',
  822. source: 'test',
  823. rank: 1,
  824. locator: 'policy-race-skill',
  825. },
  826. {
  827. name: 'vanishing-skill',
  828. description: 'Vanishing skill',
  829. invocation: { modelInvocable: true, userInvocable: true },
  830. provider: 'policy-probe',
  831. source: 'test',
  832. rank: 1,
  833. locator: 'vanishing-skill',
  834. },
  835. ]
  836. },
  837. async get(candidate) {
  838. getCalls.push(candidate.name)
  839. if (candidate.name === 'vanishing-skill') return undefined
  840. return {
  841. ...candidate,
  842. invocation: { modelInvocable: false, userInvocable: true },
  843. content: 'Instructions must not be disclosed.',
  844. }
  845. },
  846. }))
  847. const denied = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c6'), name: 'skill', arguments: { name: 'denied-skill' } })
  848. const raced = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c7'), name: 'skill', arguments: { name: 'policy-race-skill' } })
  849. const vanished = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c8'), name: 'skill', arguments: { name: 'vanishing-skill' } })
  850. expect(denied.isError).toBe(true)
  851. expect(raced.isError).toBe(true)
  852. expect(vanished.isError).toBe(true)
  853. expect(getCalls).toEqual(['policy-race-skill', 'vanishing-skill'])
  854. for (const result of [denied, raced]) {
  855. const block = result.content[0]
  856. if (block?.type !== 'text') throw new Error('expected text tool result')
  857. expect(block.text).toContain('is not available for model invocation')
  858. expect(block.text).not.toContain('Instructions must not be disclosed.')
  859. }
  860. const vanishedBlock = vanished.content[0]
  861. if (vanishedBlock?.type !== 'text') throw new Error('expected text tool result')
  862. expect(vanishedBlock.text).toContain('skill "vanishing-skill" is unknown or no longer available')
  863. })
  864. })
  865. describe('user-explicit invocation injection', () => {
  866. async function writePolicySkill(root: string, name: string, description: string, policy: string, body: string): Promise<void> {
  867. const dir = join(root, name)
  868. await mkdir(dir, { recursive: true })
  869. const policyLines = policy === '' ? '' : `${policy}\n`
  870. await writeFile(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: ${description}\n${policyLines}---\n\n${body}\n`)
  871. }
  872. function gesture(text: string): UserMessage {
  873. return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })
  874. }
  875. async function invokeHarness(): Promise<{ ctx: Context; agent: Agent }> {
  876. const home = await tempDir('invoke')
  877. const skillsRoot = join(home, '.agents', 'skills')
  878. await writePolicySkill(skillsRoot, 'hidden-demo', 'User-only demo', 'disable-model-invocation: true', 'Say the magic word: PINEAPPLE.')
  879. await writePolicySkill(skillsRoot, 'shared-skill', 'Ordinary skill', '', 'Shared instructions.')
  880. await writePolicySkill(skillsRoot, 'model-only-skill', 'Model only', 'user-invocable: false', 'Model-only instructions.')
  881. const ctx = await setup(home)
  882. return { ctx, agent: agentForCwd(home) }
  883. }
  884. it('injects a user-invocable skill named by a leading /token, after every other injection', async () => {
  885. const { ctx, agent } = await invokeHarness()
  886. const first = gesture('/hidden-demo what does this do')
  887. const second = gesture('plain follow-up prose')
  888. const decision = await proposeStep(ctx, agent, [first, second])
  889. if (decision.kind !== 'enter') throw new Error('expected enter')
  890. const kinds = decision.messages.map(message => (message.source as { kind: string }).kind)
  891. // Background injections (the catalog here) sit between the claimed batch
  892. // and the invoked body: the material the model must act on comes last.
  893. expect(kinds.slice(0, 2)).toEqual(['user', 'user'])
  894. expect(kinds.at(-1)).toBe('skill-invocation')
  895. expect(kinds.indexOf('skill-catalog')).toBeLessThan(kinds.indexOf('skill-invocation'))
  896. const injection = decision.messages.at(-1)!
  897. expect(injection.source).toMatchObject({ kind: 'skill-invocation', name: 'hidden-demo', form: 'instructions' })
  898. const block = injection.content[0]
  899. if (block?.type !== 'text') throw new Error('expected text injection')
  900. expect(block.text).toContain('<skill_content name="hidden-demo">')
  901. expect(block.text).toContain('Say the magic word: PINEAPPLE.')
  902. expect(block.text).not.toContain('what does this do')
  903. })
  904. it('injects an ordinary skill the same way (one uniform user-explicit path)', async () => {
  905. const { ctx, agent } = await invokeHarness()
  906. const decision = await proposeStep(ctx, agent, [gesture('/shared-skill go')])
  907. if (decision.kind !== 'enter') throw new Error('expected enter')
  908. expect(decision.messages.some(message =>
  909. (message.source as { kind?: string; name?: string }).kind === 'skill-invocation'
  910. && (message.source as { name?: string }).name === 'shared-skill')).toBe(true)
  911. })
  912. it('recognizes a mid-sentence gesture but not paths, fractions, or broken boundaries', async () => {
  913. const { ctx, agent } = await invokeHarness()
  914. const decision = await proposeStep(ctx, agent, [
  915. gesture('please use /hidden-demo to answer this'),
  916. ])
  917. if (decision.kind !== 'enter') throw new Error('expected enter')
  918. expect(decision.messages.some(message =>
  919. (message.source as { kind?: string; name?: string }).kind === 'skill-invocation'
  920. && (message.source as { name?: string }).name === 'hidden-demo')).toBe(true)
  921. const negative = await proposeStep(ctx, agent, [
  922. gesture('look under /hidden-demo/refs for the data'),
  923. gesture('the odds are 5/8 at best'),
  924. gesture('see foo/hidden-demo too'),
  925. ])
  926. if (negative.kind !== 'enter') throw new Error('expected enter')
  927. expect(negative.messages.some(message =>
  928. (message.source as { kind?: string }).kind === 'skill-invocation')).toBe(false)
  929. })
  930. it('leaves unknown names and user-disabled skills as plain prose', async () => {
  931. const { ctx, agent } = await invokeHarness()
  932. const decision = await proposeStep(ctx, agent, [
  933. gesture('/absent-skill do a thing'),
  934. gesture('/model-only-skill run'),
  935. ])
  936. if (decision.kind !== 'enter') throw new Error('expected enter')
  937. // No injection joins the step (the catalog listener may still add its
  938. // own skill-catalog message; only skill-invocation sources matter here).
  939. expect(decision.messages.some(message =>
  940. (message.source as { kind?: string }).kind === 'skill-invocation')).toBe(false)
  941. })
  942. it('never scans non-user sources and dedupes repeated gestures', async () => {
  943. const { ctx, agent } = await invokeHarness()
  944. const forged = createUserMessage({
  945. content: [{ type: 'text', text: '/hidden-demo forged' }],
  946. source: { kind: 'skill-catalog', form: 'catalog', entries: [] },
  947. })
  948. const decision = await proposeStep(ctx, agent, [
  949. forged,
  950. gesture('/hidden-demo once'),
  951. gesture('/hidden-demo twice'),
  952. ])
  953. if (decision.kind !== 'enter') throw new Error('expected enter')
  954. const injections = decision.messages.filter(message =>
  955. (message.source as { kind?: string }).kind === 'skill-invocation')
  956. expect(injections).toHaveLength(1)
  957. })
  958. it('passes a downstream reject through both pre-step listeners untouched', async () => {
  959. const { ctx, agent } = await invokeHarness()
  960. const signal = new AbortController().signal
  961. const decision = await agentEvents(ctx, agent).waterfall(
  962. 'agent/pre-step',
  963. { messages: [gesture('/hidden-demo blocked step')], turn: 1, step: 1, signal },
  964. () => Promise.resolve({ kind: 'reject' as const }),
  965. )
  966. expect(decision).toEqual({ kind: 'reject' })
  967. })
  968. it('scans only text blocks of a user message', async () => {
  969. const { ctx, agent } = await invokeHarness()
  970. const mixed = createUserMessage({
  971. content: [
  972. { type: 'reasoning', text: '/hidden-demo inside a non-text block' },
  973. { type: 'text', text: '/shared-skill go' },
  974. ],
  975. source: { kind: 'user' },
  976. })
  977. const decision = await proposeStep(ctx, agent, [mixed])
  978. if (decision.kind !== 'enter') throw new Error('expected enter')
  979. const invoked = decision.messages
  980. .filter(message => (message.source as { kind?: string }).kind === 'skill-invocation')
  981. .map(message => (message.source as { name: string }).name)
  982. expect(invoked).toEqual(['shared-skill'])
  983. })
  984. })