commands.spec.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { createScope } from '@deepseek-ai/dsh-scope'
  4. import type { Scope } from '@deepseek-ai/dsh-scope'
  5. import type { Agent } from '@deepseek-ai/dsh-agent'
  6. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  7. import CommandRuntime, { CommandDefinitionId, parseCommand, type CommandDefinition } from '@deepseek-ai/dsh-commands'
  8. import { AttachmentStore } from '@deepseek-ai/dsh-attachment'
  9. function command(name: string, text = `ran:${name}`): CommandDefinition {
  10. return {
  11. name,
  12. description: `command ${name}`,
  13. handler: () => ({ kind: 'success', text }),
  14. }
  15. }
  16. async function mount(): Promise<Context> {
  17. const ctx = new Context()
  18. await ctx.plugin(SessionStore)
  19. await ctx.plugin(CommandRuntime)
  20. return ctx
  21. }
  22. /** Mint a scope whose key is a live agent (real session: the executor logs lifecycle events on it). */
  23. async function mintAgentScope(ctx: Context, name: string): Promise<{ scope: Scope; agent: Agent }> {
  24. const session = ctx.sessions.create(SessionId(name))
  25. const agent = { id: session.id, session } as Agent
  26. let scope!: Scope
  27. await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) }, { inject: ['commands'] }))
  28. return { scope, agent }
  29. }
  30. /** The lifecycle slice of one agent's log (boundary markers stripped). */
  31. function lifecycleOf(agent: Agent): Array<{ type: string; data: unknown }> {
  32. return agent.session.snapshotEvents()
  33. .filter(event => event.type === 'command/run' || event.type === 'command/done')
  34. .map(event => ({ type: event.type, data: event.data }))
  35. }
  36. describe('parseCommand()', () => {
  37. it.each([
  38. ['/goal', { name: 'goal', rawInput: '' }],
  39. ['/goal create the thing', { name: 'goal', rawInput: ' create the thing' }],
  40. ['/goal\ncreate the thing', { name: 'goal', rawInput: '\ncreate the thing' }],
  41. ['/goal_name-2\t x ', { name: 'goal_name-2', rawInput: '\t x ' }],
  42. ] as const)('parses %j without normalizing trailing input', (line, expected) => {
  43. expect(parseCommand(line)).toEqual(expected)
  44. })
  45. it.each(['goal', ' /goal', '/', '/Goal', '/goal/path', '/goal🔥'])('rejects non-command boundary %j', (line) => {
  46. expect(parseCommand(line)).toBeUndefined()
  47. })
  48. })
  49. describe('CommandRuntime', () => {
  50. it('lists immutable global descriptors with input metadata', async () => {
  51. const ctx = await mount()
  52. const { agent } = await mintAgentScope(ctx, 'a')
  53. const definition: CommandDefinition = {
  54. definitionId: CommandDefinitionId('example/inspect'),
  55. name: 'inspect',
  56. description: 'Inspect state',
  57. input: { hint: '<target>' },
  58. handler: () => ({ kind: 'success' }),
  59. }
  60. ctx.commands.register(definition)
  61. const listed = ctx.commands.list(agent)
  62. expect(listed).toEqual([{
  63. definitionId: CommandDefinitionId('example/inspect'),
  64. name: 'inspect',
  65. description: 'Inspect state',
  66. input: { hint: '<target>' },
  67. }])
  68. expect(Object.isFrozen(listed)).toBe(true)
  69. expect(Object.isFrozen(listed[0])).toBe(true)
  70. expect(Object.isFrozen(listed[0]?.input)).toBe(true)
  71. expect(ctx.commands.find(agent, 'inspect')).toMatchObject({ name: 'inspect', definitionId: CommandDefinitionId('example/inspect') })
  72. expect(ctx.commands.find(agent, 'missing')).toBeUndefined()
  73. })
  74. it('sorts distinct effective command names', async () => {
  75. const ctx = await mount()
  76. const { agent } = await mintAgentScope(ctx, 'a')
  77. ctx.commands.register(command('zeta'))
  78. ctx.commands.register(command('alpha'))
  79. ctx.commands.register(command('middle'))
  80. expect(ctx.commands.list(agent).map(item => item.name)).toEqual(['alpha', 'middle', 'zeta'])
  81. })
  82. it('uses agent-scoped shadows and removes them with their scope', async () => {
  83. const ctx = await mount()
  84. const { scope, agent } = await mintAgentScope(ctx, 'a')
  85. const other = { id: 'other' as SessionId } as Agent
  86. ctx.commands.register({ ...command('shared', 'global'), definitionId: CommandDefinitionId('example/shared') })
  87. scope.ctx.commands.register(command('shared', 'scoped'))
  88. expect(ctx.commands.list(agent).map(item => item.name)).toEqual(['shared'])
  89. expect(ctx.commands.find(agent, 'shared')?.handler).toBeDefined()
  90. expect(ctx.commands.list(agent)[0]).not.toHaveProperty('definitionId')
  91. expect(ctx.commands.list(other).map(item => item.name)).toEqual(['shared'])
  92. expect((await ctx.commands.execute(agent, '/shared', [], new AbortController().signal))?.result)
  93. .toEqual({ kind: 'success', text: 'scoped' })
  94. await scope.dispose()
  95. expect(ctx.commands.list(agent)[0]?.definitionId).toBe('example/shared')
  96. expect((await ctx.commands.execute(agent, '/shared', [], new AbortController().signal))?.result.text).toBe('global')
  97. })
  98. it('removes a registration when its contributing plugin fiber is disposed', async () => {
  99. const ctx = await mount()
  100. const { agent } = await mintAgentScope(ctx, 'a')
  101. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  102. inner.commands.register(command('temporary'))
  103. }, { inject: ['commands'] }))
  104. expect(ctx.commands.find(agent, 'temporary')).toBeDefined()
  105. await fiber.dispose()
  106. expect(ctx.commands.find(agent, 'temporary')).toBeUndefined()
  107. })
  108. it('rejects duplicates within one layer while allowing a scoped shadow', async () => {
  109. const ctx = await mount()
  110. const { scope } = await mintAgentScope(ctx, 'a')
  111. ctx.commands.register(command('same'))
  112. expect(() => ctx.commands.register(command('same'))).toThrow(/agent\.ctx/)
  113. scope.ctx.commands.register(command('same'))
  114. expect(() => scope.ctx.commands.register(command('same'))).toThrow(/already registered in this scope/)
  115. })
  116. it('notifies on registration and disposal while containing broken observers', async () => {
  117. const ctx = await mount()
  118. const changed = vi.fn()
  119. ctx.on('commands/change', changed)
  120. const dispose = ctx.commands.register(command('live'))
  121. dispose()
  122. dispose()
  123. expect(changed).toHaveBeenCalledTimes(2)
  124. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  125. ctx.on('commands/change', () => { throw new Error('observer threw') })
  126. // oxlint-disable-next-line typescript/no-misused-promises -- exercises rejected-listener containment
  127. ctx.on('commands/change', () => Promise.reject(new Error('observer rejected')))
  128. const afterFailures = vi.fn()
  129. ctx.on('commands/change', afterFailures)
  130. const removeContained = ctx.commands.register(command('contained'))
  131. const { agent } = await mintAgentScope(ctx, 'a')
  132. expect(ctx.commands.find(agent, 'contained')).toBeDefined()
  133. expect(afterFailures).toHaveBeenCalledTimes(1)
  134. await vi.waitFor(() => {
  135. expect(warn).toHaveBeenCalledWith('commands/change listener threw: Error: observer threw')
  136. expect(warn).toHaveBeenCalledWith('commands/change listener rejected: Error: observer rejected')
  137. })
  138. removeContained()
  139. expect(ctx.commands.find(agent, 'contained')).toBeUndefined()
  140. expect(afterFailures).toHaveBeenCalledTimes(2)
  141. })
  142. it('rejects non-string descriptions and input hints with boundary diagnostics', async () => {
  143. const ctx = await mount()
  144. expect(() => ctx.commands.register({
  145. ...command('description-type'),
  146. description: undefined,
  147. } as unknown as CommandDefinition)).toThrow('command "description-type" description must be a string')
  148. expect(() => ctx.commands.register({
  149. ...command('hint-type'),
  150. input: { hint: 42 },
  151. } as unknown as CommandDefinition)).toThrow('command "hint-type" input hint must be a string')
  152. expect(() => ctx.commands.register({
  153. ...command('input-type'),
  154. input: null,
  155. } as unknown as CommandDefinition)).toThrow('command "input-type" input hint must be a string')
  156. })
  157. it('passes exact invocation context and detaches valid handler results', async () => {
  158. const ctx = await mount()
  159. const { agent } = await mintAgentScope(ctx, 'a')
  160. const seen = vi.fn(() => ({ kind: 'success' as const, text: 'ok' }))
  161. ctx.commands.register({ name: 'run', description: 'Run it', handler: seen })
  162. const controller = new AbortController()
  163. const execution = await ctx.commands.execute(agent, '/run untouched ', [], controller.signal)
  164. expect(execution?.result).toEqual({ kind: 'success', text: 'ok' })
  165. expect(execution?.commandId).toBeTruthy()
  166. expect(Object.isFrozen(execution)).toBe(true)
  167. expect(Object.isFrozen(execution?.result)).toBe(true)
  168. expect(seen).toHaveBeenCalledWith(expect.objectContaining({
  169. agent,
  170. rawInput: ' untouched ',
  171. signal: controller.signal,
  172. }))
  173. await expect(ctx.commands.execute(agent, 'run', [], controller.signal)).resolves.toBeUndefined()
  174. await expect(ctx.commands.execute(agent, '/missing', [], controller.signal)).resolves.toBeUndefined()
  175. })
  176. it('stops awaiting an aborted handler and handles an already-aborted signal', async () => {
  177. const ctx = await mount()
  178. const { agent } = await mintAgentScope(ctx, 'a')
  179. let release!: (result: { kind: 'success'; text: string }) => void
  180. ctx.commands.register({
  181. name: 'wait',
  182. description: 'Wait',
  183. handler: () => new Promise((resolve) => { release = resolve }),
  184. })
  185. const running = new AbortController()
  186. const promise = ctx.commands.execute(agent, '/wait', [], running.signal)
  187. running.abort('operator cancelled command')
  188. await expect(promise).rejects.toThrow('operator cancelled command')
  189. release({ kind: 'success', text: 'late' })
  190. const already = new AbortController()
  191. already.abort(new Error('already gone'))
  192. await expect(ctx.commands.execute(agent, '/wait', [], already.signal)).rejects.toThrow('already gone')
  193. const defaultReason = new AbortController()
  194. defaultReason.abort({ source: 'test' })
  195. await expect(ctx.commands.execute(agent, '/wait', [], defaultReason.signal)).rejects.toThrow('command aborted')
  196. })
  197. it('propagates an asynchronously rejected handler', async () => {
  198. const ctx = await mount()
  199. const { agent } = await mintAgentScope(ctx, 'a')
  200. ctx.commands.register({
  201. name: 'reject',
  202. description: 'Reject',
  203. handler: () => Promise.reject(new Error('handler rejected')),
  204. })
  205. await expect(ctx.commands.execute(agent, '/reject', [], new AbortController().signal))
  206. .rejects.toThrow('handler rejected')
  207. ctx.commands.register({
  208. name: 'reject-value',
  209. description: 'Reject a non-Error value',
  210. // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- exercise untyped plugin normalization
  211. handler: () => Promise.reject('not an Error'),
  212. })
  213. await expect(ctx.commands.execute(agent, '/reject-value', [], new AbortController().signal))
  214. .rejects.toThrow('command handler rejected with a non-Error value: not an Error')
  215. const hostile = { toString(): string { throw new Error('cannot render') } }
  216. ctx.commands.register({
  217. name: 'reject-hostile',
  218. description: 'Reject an unrenderable value',
  219. // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- exercise hostile plugin normalization
  220. handler: () => Promise.reject(hostile),
  221. })
  222. await expect(ctx.commands.execute(agent, '/reject-hostile', [], new AbortController().signal))
  223. .rejects.toMatchObject({
  224. message: 'command handler rejected with a non-Error value: <unrenderable thrown value>',
  225. cause: hostile,
  226. })
  227. })
  228. it('observes an abort triggered synchronously inside the handler', async () => {
  229. const ctx = await mount()
  230. const { agent } = await mintAgentScope(ctx, 'a')
  231. const controller = new AbortController()
  232. ctx.commands.register({
  233. name: 'self-abort',
  234. description: 'Abort before returning',
  235. handler: () => {
  236. controller.abort('aborted in handler')
  237. return { kind: 'success' }
  238. },
  239. })
  240. await expect(ctx.commands.execute(agent, '/self-abort', [], controller.signal))
  241. .rejects.toThrow('aborted in handler')
  242. })
  243. it('returns a detached expected-error result', async () => {
  244. const ctx = await mount()
  245. const { agent } = await mintAgentScope(ctx, 'a')
  246. ctx.commands.register({
  247. name: 'denied',
  248. description: 'Denied',
  249. handler: () => ({ kind: 'error', text: 'not now' }),
  250. })
  251. const execution = await ctx.commands.execute(agent, '/denied', [], new AbortController().signal)
  252. expect(execution?.result).toEqual({ kind: 'error', text: 'not now' })
  253. expect(Object.isFrozen(execution?.result)).toBe(true)
  254. ctx.commands.register({
  255. name: 'silent',
  256. description: 'No output',
  257. handler: () => ({ kind: 'success' }),
  258. })
  259. const silent = await ctx.commands.execute(agent, '/silent', [], new AbortController().signal)
  260. expect(silent?.result).toEqual({ kind: 'success' })
  261. expect(Object.isFrozen(silent?.result)).toBe(true)
  262. })
  263. it.each([
  264. [{ ...command('Bad') }, /command name/],
  265. [{ ...command('empty-description'), description: ' ' }, /description/],
  266. [{ ...command('empty-hint'), input: { hint: '' } }, /input hint/],
  267. [{ ...command('bad-handler'), handler: undefined }, /handler/],
  268. ] as const)('rejects invalid definition %#', async (definition, expected) => {
  269. const ctx = await mount()
  270. expect(() => ctx.commands.register(definition as unknown as CommandDefinition)).toThrow(expected)
  271. })
  272. it('logs a paired command/run + command/done around a successful handler', async () => {
  273. const ctx = await mount()
  274. const { agent } = await mintAgentScope(ctx, 'a')
  275. ctx.commands.register(command('deploy', 'deployed'))
  276. const execution = await ctx.commands.execute(agent, '/deploy now', [], new AbortController().signal)
  277. const lifecycle = lifecycleOf(agent)
  278. expect(lifecycle).toMatchObject([
  279. { type: 'command/run', data: { name: 'deploy', args: ' now', source: { kind: 'user' } } },
  280. { type: 'command/done', data: { kind: 'success', text: 'deployed' } },
  281. ])
  282. const ids = lifecycle.map(event => (event.data as { commandId: string }).commandId)
  283. expect(ids[0]).toBeTruthy()
  284. expect(ids[0]).toBe(ids[1])
  285. // The execution's pairing id is the logged one (RPC-level correlation).
  286. expect(execution?.commandId).toBe(ids[0])
  287. // Direct log-only appends: no turn is opened for the pair on an idle log.
  288. expect(agent.session.snapshotEvents().map(event => event.type)).toEqual([
  289. 'command/run', 'command/done',
  290. ])
  291. })
  292. it('preserves an earlier authoritative domain-event reference on successful settlement', async () => {
  293. const ctx = await mount()
  294. const { agent } = await mintAgentScope(ctx, 'a')
  295. const source = agent.session.append('turn/start', { turn: 1 })
  296. ctx.commands.register({
  297. name: 'linked',
  298. description: 'Link outcome',
  299. handler: () => ({ kind: 'success', text: 'linked', sourceEventSeq: source.seq }),
  300. })
  301. const execution = await ctx.commands.execute(agent, '/linked', [], new AbortController().signal)
  302. expect(execution?.result).toEqual({ kind: 'success', text: 'linked', sourceEventSeq: source.seq })
  303. expect(lifecycleOf(agent)).toMatchObject([
  304. { type: 'command/run', data: { name: 'linked' } },
  305. { type: 'command/done', data: { kind: 'success', text: 'linked', sourceEventSeq: source.seq } },
  306. ])
  307. })
  308. it('omits raw input from command/run when an authoritative domain event owns it', async () => {
  309. const ctx = await mount()
  310. const { agent } = await mintAgentScope(ctx, 'a')
  311. const seen = vi.fn(() => ({ kind: 'success' as const }))
  312. ctx.commands.register({
  313. name: 'private',
  314. description: 'Record privately',
  315. recordInput: false,
  316. handler: seen,
  317. })
  318. await ctx.commands.execute(agent, '/private keep this once', [], new AbortController().signal)
  319. expect(seen).toHaveBeenCalledWith(expect.objectContaining({ rawInput: ' keep this once' }))
  320. const run = agent.session.snapshotEvents().find(event => event.type === 'command/run')
  321. expect(run?.type).toBe('command/run')
  322. expect(run?.type === 'command/run' && Object.hasOwn(run.data, 'args')).toBe(false)
  323. })
  324. it('mints distinct monotonic commandIds across executions', async () => {
  325. const ctx = await mount()
  326. const { agent } = await mintAgentScope(ctx, 'a')
  327. ctx.commands.register(command('first'))
  328. ctx.commands.register(command('second'))
  329. await ctx.commands.execute(agent, '/first', [], new AbortController().signal)
  330. await ctx.commands.execute(agent, '/second', [], new AbortController().signal)
  331. const ids = lifecycleOf(agent)
  332. .filter(event => event.type === 'command/run')
  333. .map(event => (event.data as { commandId: string }).commandId)
  334. expect(new Set(ids).size).toBe(2)
  335. })
  336. it('logs command/done kind error for an expected error result', async () => {
  337. const ctx = await mount()
  338. const { agent } = await mintAgentScope(ctx, 'a')
  339. ctx.commands.register({ name: 'denied', description: 'Denied', handler: () => ({ kind: 'error', text: 'not now' }) })
  340. await ctx.commands.execute(agent, '/denied', [], new AbortController().signal)
  341. expect(lifecycleOf(agent)).toMatchObject([
  342. { type: 'command/run', data: { name: 'denied' } },
  343. { type: 'command/done', data: { kind: 'error', text: 'not now' } },
  344. ])
  345. })
  346. it('logs command/done kind error when the handler throws, and preserves the throw', async () => {
  347. const ctx = await mount()
  348. const { agent } = await mintAgentScope(ctx, 'a')
  349. ctx.commands.register({
  350. name: 'boom',
  351. description: 'Throw',
  352. handler: () => { throw new Error('handler exploded') },
  353. })
  354. await expect(ctx.commands.execute(agent, '/boom', [], new AbortController().signal))
  355. .rejects.toThrow('handler exploded')
  356. expect(lifecycleOf(agent)).toMatchObject([
  357. { type: 'command/run', data: { name: 'boom' } },
  358. { type: 'command/done', data: { kind: 'error', text: 'handler exploded' } },
  359. ])
  360. })
  361. it('logs command/done kind error when the signal aborts a hanging handler', async () => {
  362. const ctx = await mount()
  363. const { agent } = await mintAgentScope(ctx, 'a')
  364. ctx.commands.register({
  365. name: 'hang',
  366. description: 'Hang',
  367. handler: () => new Promise(() => undefined),
  368. })
  369. const controller = new AbortController()
  370. const pending = ctx.commands.execute(agent, '/hang', [], controller.signal)
  371. // The run append must land before the abort so the pair stays complete.
  372. await vi.waitFor(() => { expect(lifecycleOf(agent)).toHaveLength(1) })
  373. controller.abort('operator cancelled command')
  374. await expect(pending).rejects.toThrow('operator cancelled command')
  375. await vi.waitFor(() => {
  376. expect(lifecycleOf(agent)).toMatchObject([
  377. { type: 'command/run', data: { name: 'hang' } },
  378. { type: 'command/done', data: { kind: 'error', text: 'operator cancelled command' } },
  379. ])
  380. })
  381. })
  382. it('logs nothing for admission misses (syntax or unknown name)', async () => {
  383. const ctx = await mount()
  384. const { agent } = await mintAgentScope(ctx, 'a')
  385. ctx.commands.register(command('real'))
  386. const signal = new AbortController().signal
  387. await ctx.commands.execute(agent, 'not a command', [], signal)
  388. await ctx.commands.execute(agent, '/missing', [], signal)
  389. expect(agent.session.snapshotEvents()).toEqual([])
  390. })
  391. it('joins an open turn without wrapping the lifecycle pair in synthetic turns', async () => {
  392. const ctx = await mount()
  393. const { agent } = await mintAgentScope(ctx, 'a')
  394. ctx.commands.register(command('mid'))
  395. agent.session.append('turn/start', { turn: 1 })
  396. await ctx.commands.execute(agent, '/mid', [], new AbortController().signal)
  397. expect(agent.session.snapshotEvents().map(event => event.type)).toEqual([
  398. 'turn/start', 'command/run', 'command/done',
  399. ])
  400. })
  401. it.each([
  402. [undefined, /CommandResult/],
  403. [null, /CommandResult/],
  404. [{}, /CommandResult/],
  405. [{ kind: 'success', text: 1 }, /success text/],
  406. [{ kind: 'success', sourceEventSeq: -1 }, /sourceEventSeq/],
  407. [{ kind: 'success', sourceEventSeq: -0 }, /sourceEventSeq/],
  408. [{ kind: 'success', sourceEventSeq: 1.5 }, /sourceEventSeq/],
  409. [{ kind: 'success', sourceEventSeq: '1' }, /sourceEventSeq/],
  410. [{ kind: 'error', text: '' }, /error text/],
  411. [{ kind: 'error', text: 1 }, /error text/],
  412. [{ kind: 'future', text: 'x' }, /unknown result kind/],
  413. ] as const)('rejects malformed handler result %j', async (output, expected) => {
  414. const ctx = await mount()
  415. const { agent } = await mintAgentScope(ctx, 'a')
  416. ctx.commands.register({
  417. name: 'broken',
  418. description: 'Broken',
  419. handler: () => output as never,
  420. })
  421. await expect(ctx.commands.execute(agent, '/broken', [], new AbortController().signal)).rejects.toThrow(expected)
  422. })
  423. })
  424. describe('command attachments', () => {
  425. const PNG = 'AAAA'
  426. function storeOf() {
  427. let saved = 0
  428. const store = {
  429. imageLimits: {
  430. maxImageBytes: 1024, maxImagesPerMessage: 2, maxMessageImageBytes: 1024,
  431. maxImagePixels: 1_000_000, maxImageDimension: 2000, mediaTypes: ['image/png'],
  432. },
  433. validateImage: vi.fn(() => Promise.resolve()),
  434. saveImage: vi.fn((input: { mediaType: string; name?: string }) => {
  435. saved += 1
  436. return Promise.resolve({
  437. attachmentId: `att-${saved}`, mediaType: input.mediaType, bytes: 3, width: 1, height: 1,
  438. ...input.name === undefined ? {} : { name: input.name },
  439. })
  440. }),
  441. saveFile: vi.fn((input: { data: Uint8Array; name?: string }) => {
  442. saved += 1
  443. return Promise.resolve({
  444. attachmentId: `att-${saved}`, bytes: input.data.byteLength, name: input.name ?? 'attachment',
  445. })
  446. }),
  447. validateImageBatch(inputs: readonly unknown[]) {
  448. const validate = AttachmentStore.prototype as unknown as {
  449. validateImageBatch(this: unknown, batch: readonly unknown[]): void
  450. }
  451. validate.validateImageBatch.call(this, inputs)
  452. },
  453. // The real base-class batch method over this double's limits and members.
  454. saveImages(inputs: readonly unknown[]) {
  455. return (AttachmentStore.prototype.saveImages as (this: unknown, batch: readonly unknown[]) => Promise<unknown[]>).call(this, inputs)
  456. },
  457. }
  458. return store
  459. }
  460. function accepting(handler: CommandDefinition['handler']): CommandDefinition {
  461. return {
  462. name: 'vision',
  463. description: 'accepts attachments',
  464. input: { hint: '<objective>', attachments: true },
  465. handler,
  466. }
  467. }
  468. it('rejects a boolean-typed images flag violation at registration', async () => {
  469. const ctx = await mount()
  470. expect(() => ctx.commands.register({
  471. ...command('flag-type'),
  472. input: { hint: 'x', attachments: 'yes' },
  473. } as unknown as CommandDefinition)).toThrow('command "flag-type" input attachments flag must be a boolean')
  474. })
  475. it('lists attachment acceptance on the descriptor and omits a false flag', async () => {
  476. const ctx = await mount()
  477. const { agent } = await mintAgentScope(ctx, 'a')
  478. ctx.commands.register(accepting(() => ({ kind: 'success' })))
  479. ctx.commands.register({ ...command('plain-input'), input: { hint: 'x', attachments: false } })
  480. const byName = new Map(ctx.commands.list(agent).map(descriptor => [descriptor.name, descriptor]))
  481. expect(byName.get('vision')?.input).toEqual({ hint: '<objective>', attachments: true })
  482. expect(byName.get('plain-input')?.input).toEqual({ hint: 'x' })
  483. })
  484. it('settles attachments sent to a non-declaring command as a logged error before the handler', async () => {
  485. const ctx = await mount()
  486. const { agent } = await mintAgentScope(ctx, 'a')
  487. const handler = vi.fn(() => ({ kind: 'success' as const }))
  488. ctx.commands.register({ ...command('deploy'), handler })
  489. const execution = await ctx.commands.execute(
  490. agent, '/deploy now', [{ type: 'image', mediaType: 'image/png', data: PNG }], new AbortController().signal)
  491. expect(execution?.result).toEqual({ kind: 'error', text: '/deploy does not accept attachments' })
  492. expect(handler).not.toHaveBeenCalled()
  493. expect(lifecycleOf(agent)).toMatchObject([
  494. { type: 'command/run', data: { name: 'deploy' } },
  495. { type: 'command/done', data: { kind: 'error', text: '/deploy does not accept attachments' } },
  496. ])
  497. })
  498. it('settles a declaring command as a logged error when no attachment store is composed', async () => {
  499. const ctx = await mount()
  500. const { agent } = await mintAgentScope(ctx, 'a')
  501. ctx.commands.register(accepting(() => ({ kind: 'success' })))
  502. const execution = await ctx.commands.execute(
  503. agent, '/vision x', [{ type: 'image', mediaType: 'image/png', data: PNG }], new AbortController().signal)
  504. expect(execution?.result).toEqual({
  505. kind: 'error',
  506. text: '/vision: attachments are unavailable because no attachment store is composed',
  507. })
  508. })
  509. it('admits a mixed batch in selection order and keeps plain invocations empty', async () => {
  510. const ctx = await mount()
  511. ctx.provide('attachments', storeOf())
  512. const { agent } = await mintAgentScope(ctx, 'a')
  513. ctx.commands.registerFileReceiptResolver((_receivingAgent, receiptId) => receiptId === 'receipt-notes'
  514. ? { attachmentId: 'file-notes' as never, name: 'notes.txt', bytes: 5 }
  515. : undefined)
  516. const seen = vi.fn((invocation: { attachments: readonly unknown[] }) => {
  517. expect(Object.isFrozen(invocation.attachments)).toBe(true)
  518. return { kind: 'success' as const }
  519. })
  520. ctx.commands.register(accepting(seen))
  521. await ctx.commands.execute(agent, '/vision x', [
  522. { type: 'image', mediaType: 'image/png', data: PNG, name: 'a.png' },
  523. { type: 'file', receiptId: 'receipt-notes' },
  524. { type: 'image', mediaType: 'image/png', data: PNG, name: 'b.png' },
  525. ], new AbortController().signal)
  526. const invocation = seen.mock.calls[0]?.[0] as { attachments: ReadonlyArray<{ type: string; attachment: { name?: string } }> }
  527. expect(invocation.attachments.map(block => [block.type, block.attachment.name])).toEqual([
  528. ['image', 'a.png'], ['file', 'notes.txt'], ['image', 'b.png'],
  529. ])
  530. await ctx.commands.execute(agent, '/vision y', [], new AbortController().signal)
  531. expect((seen.mock.calls[1]?.[0] as { attachments: readonly unknown[] }).attachments).toEqual([])
  532. })
  533. it('requires a same-session file receipt resolver and keeps its registration single-owner', async () => {
  534. const ctx = await mount()
  535. const store = storeOf()
  536. ctx.provide('attachments', store)
  537. const { agent } = await mintAgentScope(ctx, 'a')
  538. const handler = vi.fn(() => ({ kind: 'success' as const }))
  539. ctx.commands.register(accepting(handler))
  540. const missing = await ctx.commands.execute(
  541. agent, '/vision x', [{ type: 'file', receiptId: 'missing' }], new AbortController().signal)
  542. expect(missing?.result).toEqual({
  543. kind: 'error', text: 'File upload receipt is unknown for this session.',
  544. })
  545. expect(handler).not.toHaveBeenCalled()
  546. const mixed = await ctx.commands.execute(agent, '/vision x', [
  547. { type: 'image', mediaType: 'image/png', data: PNG },
  548. { type: 'file', receiptId: 'missing' },
  549. ], new AbortController().signal)
  550. expect(mixed?.result).toEqual({
  551. kind: 'error', text: 'File upload receipt is unknown for this session.',
  552. })
  553. expect(store.saveImage).not.toHaveBeenCalled()
  554. const first = vi.fn(() => undefined)
  555. const disposeFirst = ctx.commands.registerFileReceiptResolver(first)
  556. expect(() => ctx.commands.registerFileReceiptResolver(() => undefined))
  557. .toThrow('commands: a file receipt resolver is already registered')
  558. disposeFirst()
  559. const disposeSecond = ctx.commands.registerFileReceiptResolver(() => undefined)
  560. disposeFirst()
  561. expect(() => ctx.commands.registerFileReceiptResolver(() => undefined))
  562. .toThrow('commands: a file receipt resolver is already registered')
  563. disposeSecond()
  564. })
  565. it('settles an admission limit failure as a logged error result', async () => {
  566. const ctx = await mount()
  567. ctx.provide('attachments', storeOf())
  568. const { agent } = await mintAgentScope(ctx, 'a')
  569. const handler = vi.fn(() => ({ kind: 'success' as const }))
  570. ctx.commands.register(accepting(handler))
  571. const three = [1, 2, 3].map(() => ({ type: 'image' as const, mediaType: 'image/png' as const, data: PNG }))
  572. const execution = await ctx.commands.execute(agent, '/vision x', three, new AbortController().signal)
  573. expect(execution?.result).toEqual({ kind: 'error', text: 'Image batch exceeds the configured image-count limit.' })
  574. expect(handler).not.toHaveBeenCalled()
  575. expect(lifecycleOf(agent).at(-1)).toMatchObject({ type: 'command/done', data: { kind: 'error' } })
  576. })
  577. it('honors a cancellation that lands during admission before entering the handler', async () => {
  578. const ctx = await mount()
  579. const controller = new AbortController()
  580. const store = storeOf()
  581. store.saveImage.mockImplementationOnce((input: { mediaType: string }) => {
  582. controller.abort('operator cancelled during admission')
  583. return Promise.resolve({
  584. attachmentId: 'att-late', mediaType: input.mediaType, bytes: 3, width: 1, height: 1,
  585. })
  586. })
  587. ctx.provide('attachments', store)
  588. const { agent } = await mintAgentScope(ctx, 'a')
  589. const handler = vi.fn(() => ({ kind: 'success' as const }))
  590. ctx.commands.register(accepting(handler))
  591. await expect(ctx.commands.execute(
  592. agent, '/vision x', [{ type: 'image', mediaType: 'image/png', data: PNG }], controller.signal,
  593. )).rejects.toThrow('operator cancelled during admission')
  594. expect(handler).not.toHaveBeenCalled()
  595. expect(lifecycleOf(agent).at(-1)).toMatchObject({
  596. type: 'command/done',
  597. data: { kind: 'error', text: 'operator cancelled during admission' },
  598. })
  599. })
  600. it('logs and rethrows a non-attachment admission failure', async () => {
  601. const ctx = await mount()
  602. const store = storeOf()
  603. store.saveImage.mockRejectedValueOnce(new Error('disk gone'))
  604. ctx.provide('attachments', store)
  605. const { agent } = await mintAgentScope(ctx, 'a')
  606. ctx.commands.register(accepting(() => ({ kind: 'success' })))
  607. await expect(ctx.commands.execute(
  608. agent, '/vision x', [{ type: 'image', mediaType: 'image/png', data: PNG }], new AbortController().signal,
  609. )).rejects.toThrow('disk gone')
  610. expect(lifecycleOf(agent).at(-1)).toMatchObject({
  611. type: 'command/done',
  612. data: { kind: 'error', text: 'disk gone' },
  613. })
  614. })
  615. })