command-goal.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import Loader from '@deepseek-ai/cordis-plugin-loader'
  4. import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
  5. import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent'
  6. import CommandRuntime from '@deepseek-ai/dsh-commands'
  7. import GoalService from '@deepseek-ai/dsh-goal'
  8. import type { GoalRef } from '@deepseek-ai/dsh-goal'
  9. import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session'
  10. import * as commandGoal from '@deepseek-ai/dsh-command-goal'
  11. interface Harness {
  12. readonly ctx: Context
  13. readonly agent: Agent
  14. readonly session: Session
  15. readonly plugin: Awaited<ReturnType<Context['plugin']>>
  16. }
  17. /** Build a live idle agent accepted by the exact-identity goal service. */
  18. function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } {
  19. // Store-created: the command executor durably logs lifecycle events on it.
  20. const session = ctx.sessions.create(SessionId(id))
  21. const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} })
  22. let status: AgentStatus = 'idle'
  23. const agent: Agent = {
  24. id: session.id,
  25. options: {},
  26. session,
  27. inbox,
  28. ctx: new Context(),
  29. get status() { return status },
  30. send: () => {},
  31. followup: () => {},
  32. steer: () => {},
  33. inject(input) { inbox.append('next-step', input) },
  34. cancel() { status = 'idle' },
  35. runMaintenance: task => task(new AbortController().signal),
  36. whenIdle() { return Promise.resolve() },
  37. }
  38. return { agent, session }
  39. }
  40. /** Mount the real command registry, goal domain, and producer. */
  41. async function harness(): Promise<Harness> {
  42. const ctx = new Context()
  43. await ctx.plugin(SessionStore)
  44. await ctx.plugin(CommandRuntime)
  45. await ctx.plugin(AgentRegistry)
  46. await ctx.plugin(GoalService)
  47. const plugin = await ctx.plugin(commandGoal)
  48. const { agent, session } = stubAgent(ctx, `command-goal-${Math.random()}`)
  49. ctx.agents.register(agent)
  50. return { ctx, agent, session, plugin }
  51. }
  52. /** The log with executor-owned command lifecycle bookkeeping stripped (goal assertions target domain events). */
  53. function domainEvents(session: Session): readonly Session['events'][number][] {
  54. const lifecycle = new Set<number>()
  55. for (const event of session.events) {
  56. if (event.type !== 'command/run' && event.type !== 'command/done') continue
  57. lifecycle.add(event.seq)
  58. // The zero-step wrap around a lifecycle event is bookkeeping too.
  59. const before = session.events[event.seq - 1]
  60. const after = session.events[event.seq + 1]
  61. if (before?.type === 'turn/start') lifecycle.add(before.seq)
  62. if (after?.type === 'turn/end') lifecycle.add(after.seq)
  63. }
  64. return session.events.filter(event => !lifecycle.has(event.seq))
  65. }
  66. /** Execute `/goal` through the same registry boundary as a UI adapter. */
  67. async function run(test: Harness, suffix = ''): Promise<NonNullable<Awaited<ReturnType<CommandRuntime['execute']>>>['result']> {
  68. const execution = await test.ctx.commands.execute(
  69. test.agent,
  70. `/goal${suffix}`,
  71. [],
  72. new AbortController().signal,
  73. )
  74. if (execution === undefined) throw new Error('goal command was not registered')
  75. return execution.result
  76. }
  77. /** Current exact compare-and-set ref. */
  78. function ref(goal: NonNullable<ReturnType<GoalService['get']>>): GoalRef {
  79. return { id: goal.id, revision: goal.revision }
  80. }
  81. describe('@deepseek-ai/dsh-command-goal registration', () => {
  82. it('registers one global command with Loader-safe exports and disposes it', async () => {
  83. const test = await harness()
  84. expect(commandGoal.name).toBe('command-goal')
  85. expect(commandGoal.inject).toEqual(['commands', 'goals'])
  86. expect('default' in commandGoal).toBe(false)
  87. const loader = Object.create(Loader.prototype) as Loader
  88. expect(loader.unwrapExports(commandGoal)).toBe(commandGoal)
  89. expect(test.ctx.commands.list(test.agent)).toContainEqual({
  90. name: 'goal',
  91. description: 'set or view the goal for a long-running task',
  92. input: { hint: '[<objective>|clear|edit <objective>|pause|resume]', images: true },
  93. })
  94. expect(test.ctx.commands.find(test.agent, 'goal')).toBeDefined()
  95. await test.plugin.dispose()
  96. expect(test.ctx.commands.find(test.agent, 'goal')).toBeUndefined()
  97. })
  98. })
  99. describe('/goal human command', () => {
  100. it('shows an empty status without mutating the session', async () => {
  101. const test = await harness()
  102. await expect(run(test)).resolves.toEqual({
  103. kind: 'success',
  104. text: 'No goal is currently set.\nUsage: /goal [<objective>|clear|edit <objective>|pause|resume]',
  105. })
  106. expect(domainEvents(test.session)).toEqual([])
  107. })
  108. it('creates a trimmed objective and refuses silent replacement of unfinished work', async () => {
  109. const test = await harness()
  110. const created = await run(test, '\n finish the release ')
  111. expect(created.kind).toBe('success')
  112. expect(created.text).toContain('Goal created\nStatus: active')
  113. expect(created.text).toContain('Objective: finish the release')
  114. expect(created.text).toContain('Rounds: 0/256')
  115. expect(created.text).toContain('Activation: armed')
  116. expect(test.ctx.goals.get(test.agent)?.objective).toBe('finish the release')
  117. expect(domainEvents(test.session).map(event => event.type)).toEqual(['goal/change'])
  118. const count = domainEvents(test.session).length
  119. await expect(run(test, ' replacement')).resolves.toEqual({
  120. kind: 'error',
  121. text: 'A goal is already active. Use /goal edit <objective> to change it or /goal clear before replacing it.',
  122. })
  123. expect(domainEvents(test.session)).toHaveLength(count)
  124. })
  125. it('treats only exact control words as controls', async () => {
  126. const test = await harness()
  127. await run(test, ' pause everything only after verification')
  128. expect(test.ctx.goals.get(test.agent)?.objective).toBe('pause everything only after verification')
  129. })
  130. it('edits inline, requires an objective, and starts a new goal when the old one is complete', async () => {
  131. const empty = await harness()
  132. const invalidEdit = await run(empty, ' edit')
  133. expect(invalidEdit.kind).toBe('error')
  134. expect(invalidEdit.text).toContain('requires a replacement objective')
  135. const missingEdit = await run(empty, ' edit replacement')
  136. expect(missingEdit.kind).toBe('error')
  137. expect(missingEdit.text).toContain('/goal edit requires one')
  138. const test = await harness()
  139. await run(test, ' first')
  140. const first = test.ctx.goals.get(test.agent)!
  141. const updated = await run(test, ' EDIT\n second ')
  142. expect(updated.kind).toBe('success')
  143. expect(updated.text).toContain('Goal updated')
  144. expect(test.ctx.goals.get(test.agent)).toMatchObject({ id: first.id, objective: 'second', revision: 2 })
  145. const current = test.ctx.goals.get(test.agent)!
  146. test.ctx.goals.complete(test.agent, ref(current))
  147. const replacement = await run(test, ' edit third')
  148. expect(replacement.kind).toBe('success')
  149. expect(replacement.text).toContain('Goal created')
  150. expect(test.ctx.goals.get(test.agent)).toMatchObject({ objective: 'third', revision: 1 })
  151. expect(test.ctx.goals.get(test.agent)?.id).not.toBe(first.id)
  152. })
  153. it('returns direct missing-state results for pause, resume, and clear', async () => {
  154. const test = await harness()
  155. const missingPause = await run(test, ' pause')
  156. expect(missingPause.kind).toBe('error')
  157. expect(missingPause.text).toContain('/goal pause requires one')
  158. const missingResume = await run(test, ' resume')
  159. expect(missingResume.kind).toBe('error')
  160. expect(missingResume.text).toContain('/goal resume requires one')
  161. await expect(run(test, ' clear')).resolves.toEqual({ kind: 'success', text: 'No goal to clear.' })
  162. })
  163. it('pauses, resumes, clears, and converts expected domain rejections to command errors', async () => {
  164. const test = await harness()
  165. await run(test, ' work')
  166. const redundantResume = await run(test, ' RESUME')
  167. expect(redundantResume).toEqual({
  168. kind: 'error',
  169. text: 'The goal command is not valid for the current state. Run /goal to view available commands.',
  170. })
  171. const paused = await run(test, ' PAUSE')
  172. expect(paused.kind).toBe('success')
  173. expect(paused.text).toContain('Goal paused')
  174. expect(test.ctx.goals.get(test.agent)).toMatchObject({ phase: 'paused', activation: 'disarmed' })
  175. const resumed = await run(test, ' resume')
  176. expect(resumed.kind).toBe('success')
  177. expect(resumed.text).toContain('Goal resumed')
  178. expect(test.ctx.goals.get(test.agent)).toMatchObject({ phase: 'active', activation: 'armed' })
  179. await expect(run(test, ' clear')).resolves.toEqual({ kind: 'success', text: 'Goal cleared.' })
  180. expect(test.ctx.goals.get(test.agent)).toBeUndefined()
  181. })
  182. it('shows every durable phase and distinguishes disarmed active state', async () => {
  183. const test = await harness()
  184. test.ctx.goals.create(test.agent, { objective: 'state matrix', maxGoalRounds: 1 })
  185. test.ctx.goals.disarm(test.agent)
  186. expect((await run(test)).text)
  187. .toContain('Status: active\nObjective: state matrix\nRounds: 0/1\nActivation: disarmed')
  188. expect((await run(test)).text).toContain('/goal resume')
  189. let goal = test.ctx.goals.get(test.agent)!
  190. goal = test.ctx.goals.resume(test.agent, ref(goal))
  191. goal = test.ctx.goals.pause(test.agent, ref(goal))
  192. expect((await run(test)).text).toContain('Status: paused')
  193. goal = test.ctx.goals.resume(test.agent, ref(goal))
  194. goal = test.ctx.goals.block(test.agent, ref(goal), {
  195. code: 'upstream-unavailable',
  196. message: 'Provider unavailable',
  197. })
  198. const blocked = await run(test)
  199. expect(blocked.text).toContain('Status: blocked')
  200. expect(blocked.text).toContain('Blocker: upstream-unavailable: Provider unavailable')
  201. goal = test.ctx.goals.resume(test.agent, ref(goal))
  202. test.ctx.goals.complete(test.agent, ref(goal))
  203. const complete = await run(test)
  204. expect(complete.text).toContain('Status: complete')
  205. expect(complete.text).toContain('Commands: /goal <objective>, /goal clear')
  206. })
  207. it('does not turn unexpected implementation failures into expected command results', async () => {
  208. const test = await harness()
  209. vi.spyOn(test.ctx.goals, 'get').mockImplementationOnce(() => { throw new Error('unexpected failure') })
  210. await expect(run(test)).rejects.toThrow('unexpected failure')
  211. })
  212. })
  213. describe('/goal image attachments', () => {
  214. const PNG = 'AAAA'
  215. /** Wire the fake store the executor admits through (once per harness). */
  216. function provideStore(test: Harness): void {
  217. let saved = 0
  218. const saveImage = (input: { mediaType: string; name?: string }) => {
  219. saved += 1
  220. return Promise.resolve({
  221. attachmentId: `att-${saved}`, mediaType: input.mediaType, bytes: 3, width: 1, height: 1,
  222. ...input.name === undefined ? {} : { name: input.name },
  223. })
  224. }
  225. test.ctx.provide('attachments', {
  226. imageLimits: {
  227. maxImageBytes: 1024, maxImagesPerMessage: 4, maxMessageImageBytes: 1024,
  228. maxImagePixels: 1_000_000, mediaTypes: ['image/png'],
  229. },
  230. validateImage: () => Promise.resolve(),
  231. saveImage,
  232. async saveImages(inputs: readonly { mediaType: string; name?: string }[]) {
  233. const refs = []
  234. for (const input of inputs) refs.push(await saveImage(input))
  235. return refs
  236. },
  237. })
  238. }
  239. /** Run /goal with `count` composer images through the executor boundary. */
  240. async function runWithImages(test: Harness, suffix: string, count: number) {
  241. const images = Array.from({ length: count }, (_, index) => ({
  242. mediaType: 'image/png' as const, data: PNG, name: `ref-${index + 1}.png`,
  243. }))
  244. const execution = await test.ctx.commands.execute(test.agent, `/goal${suffix}`, images, new AbortController().signal)
  245. if (execution === undefined) throw new Error('goal command was not registered')
  246. return execution.result
  247. }
  248. it('submits one user followup carrying the admitted images ahead of the round prompt', async () => {
  249. const test = await harness()
  250. provideStore(test)
  251. const followup = vi.fn()
  252. ;(test.agent as unknown as { followup: typeof followup }).followup = followup
  253. const result = await runWithImages(test, ' rebuild the cathedral', 2)
  254. expect(result.kind).toBe('success')
  255. expect(followup).toHaveBeenCalledTimes(1)
  256. const message = followup.mock.calls[0]?.[0] as {
  257. content: ReadonlyArray<Record<string, unknown>>
  258. source: { kind: string }
  259. }
  260. expect(message.source).toEqual({ kind: 'user' })
  261. expect(message.content.map(block => block.type)).toEqual(['image', 'image', 'text'])
  262. expect(message.content.at(-1)).toEqual({ type: 'text', text: 'Reference images for the goal objective.' })
  263. expect((message.content[0] as { attachment: { name: string } }).attachment.name).toBe('ref-1.png')
  264. })
  265. it('accompanies an edit and a post-complete recreate the same way', async () => {
  266. const test = await harness()
  267. provideStore(test)
  268. const followup = vi.fn()
  269. ;(test.agent as unknown as { followup: typeof followup }).followup = followup
  270. test.ctx.goals.create(test.agent, { objective: 'initial objective' })
  271. const result = await runWithImages(test, ' edit refined objective', 1)
  272. expect(result.kind).toBe('success')
  273. expect(followup).toHaveBeenCalledTimes(1)
  274. })
  275. it('rejects attachments on sub-commands that cannot use them, leaving the domain untouched', async () => {
  276. const test = await harness()
  277. provideStore(test)
  278. const followup = vi.fn()
  279. ;(test.agent as unknown as { followup: typeof followup }).followup = followup
  280. test.ctx.goals.create(test.agent, { objective: 'active objective' })
  281. for (const suffix of [' pause', '', ' clear']) {
  282. const result = await runWithImages(test, suffix, 1)
  283. expect(result).toEqual({
  284. kind: 'error',
  285. text: 'Image attachments only accompany a goal objective: /goal <objective> or /goal edit <objective>.',
  286. })
  287. }
  288. expect(followup).not.toHaveBeenCalled()
  289. expect(test.ctx.goals.get(test.agent)?.phase).toBe('active')
  290. })
  291. it('does not submit attachments when goal creation is refused', async () => {
  292. const test = await harness()
  293. provideStore(test)
  294. const followup = vi.fn()
  295. ;(test.agent as unknown as { followup: typeof followup }).followup = followup
  296. test.ctx.goals.create(test.agent, { objective: 'existing objective' })
  297. const result = await runWithImages(test, ' replacement objective', 1)
  298. expect(result.kind).toBe('error')
  299. expect(followup).not.toHaveBeenCalled()
  300. })
  301. })