agent.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { AgentId } from '@deepseek-ai/dsh-agent'
  4. import LlmService from '@deepseek-ai/dsh-llm'
  5. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  6. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  7. import ToolRegistry from '@deepseek-ai/dsh-tools'
  8. import AgentRegistry from '@deepseek-ai/dsh-agent'
  9. import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  10. import { MockAdapter, textResponse } from './mock-adapter.ts'
  11. async function harness(adapter: MockAdapter) {
  12. const ctx = new Context()
  13. await ctx.plugin(LlmService)
  14. await ctx.plugin(SessionStore)
  15. await ctx.plugin(SystemPrompt)
  16. await ctx.plugin(ToolRegistry)
  17. await ctx.plugin(AgentRegistry)
  18. await ctx.plugin(AgentLoop, { agents: [] })
  19. ctx.llm.registerAdapter(['mock'], adapter)
  20. return ctx
  21. }
  22. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  23. return new Promise((resolve) => {
  24. const dispose = ctx.on('agent/status', (subject, status) => {
  25. if (subject === agent && status === 'idle') {
  26. dispose()
  27. resolve()
  28. }
  29. })
  30. })
  31. }
  32. function waitForStatus(ctx: Context, agent: ReactLoopAgent, expected: ReactLoopAgent['status']): Promise<void> {
  33. return new Promise((resolve) => {
  34. const dispose = ctx.on('agent/status', (subject, status) => {
  35. if (subject === agent && status === expected) {
  36. dispose()
  37. resolve()
  38. }
  39. })
  40. })
  41. }
  42. function send(agent: ReactLoopAgent, text: string) {
  43. agent.send([{ type: 'text', text }])
  44. }
  45. describe('ReactLoopAgent', () => {
  46. it('send() throws after disposal', async () => {
  47. const adapter = new MockAdapter(['hang'])
  48. const ctx = await harness(adapter)
  49. let agent!: ReactLoopAgent
  50. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  51. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  52. }, { inject: ['agentLoop'] }))
  53. send(agent, 'go')
  54. await new Promise(r => setTimeout(r, 30))
  55. await fiber.dispose()
  56. await agent.done
  57. expect(() => { agent.send([{ type: 'text', text: 'too late' }]) }).toThrow('disposed')
  58. })
  59. it('steer() throws after disposal', async () => {
  60. const adapter = new MockAdapter(['hang'])
  61. const ctx = await harness(adapter)
  62. let agent!: ReactLoopAgent
  63. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  64. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  65. }, { inject: ['agentLoop'] }))
  66. send(agent, 'go')
  67. await new Promise(r => setTimeout(r, 30))
  68. await fiber.dispose()
  69. await agent.done
  70. expect(() => { agent.steer([{ type: 'text', text: 'too late' }]) }).toThrow('disposed')
  71. })
  72. it('inject() throws after disposal', async () => {
  73. const adapter = new MockAdapter(['hang'])
  74. const ctx = await harness(adapter)
  75. let agent!: ReactLoopAgent
  76. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  77. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  78. }, { inject: ['agentLoop'] }))
  79. send(agent, 'go')
  80. await new Promise(r => setTimeout(r, 30))
  81. await fiber.dispose()
  82. await agent.done
  83. expect(() => { agent.inject([{ type: 'text', text: 'too late' }]) }).toThrow('disposed')
  84. })
  85. it('inject() decides enclosure from the LOG (open turn), not agent status', async () => {
  86. const adapter = new MockAdapter([textResponse('ok')])
  87. const ctx = await harness(adapter)
  88. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  89. // Simulate an OPEN turn in the log while the agent is idle (status is not a
  90. // reliable open-turn signal). inject must append into that open turn, NOT
  91. // wrap a new one.
  92. agent.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  93. agent.inject([{ type: 'text', text: 'mid' }], { source: { kind: 'plugin', plugin: 'p' } })
  94. expect(agent.session.events.filter(e => e.type === 'turn/start')).toHaveLength(1)
  95. expect(agent.session.events.at(-1)!.type).toBe('context/message')
  96. // Close the turn; now inject must wrap its own one-shot injection turn.
  97. agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  98. agent.inject([{ type: 'text', text: 'after' }], { source: { kind: 'plugin', plugin: 'p' } })
  99. const starts = agent.session.events.filter(e => e.type === 'turn/start')
  100. expect(starts).toHaveLength(2)
  101. const last = starts[1]!
  102. expect(last.type === 'turn/start' && last.data.trigger.kind).toBe('injection')
  103. expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed
  104. })
  105. it('idle inject() contains a failing flush (logs, does not throw into the caller)', async () => {
  106. const adapter = new MockAdapter([textResponse('ok')])
  107. const ctx = await harness(adapter)
  108. // A persistence-like listener whose flush rejects.
  109. ctx.on('session/flush', () => { throw new Error('disk gone') })
  110. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  111. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  112. // inject() is synchronous and fires a fire-and-forget flush; a rejecting
  113. // flush must be contained (logged), never thrown into the caller.
  114. expect(() => { agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } }) }).not.toThrow()
  115. await new Promise(r => setTimeout(r, 20)) // let the contained flush settle
  116. expect(warn).toHaveBeenCalledWith(expect.stringContaining('flush after idle injection failed'))
  117. warn.mockRestore()
  118. })
  119. it('idle inject() closes its one-shot turn AND still checkpoints even if the append throws', async () => {
  120. const adapter = new MockAdapter([textResponse('ok')])
  121. const ctx = await harness(adapter)
  122. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  123. let flushes = 0
  124. ctx.on('session/flush', () => { flushes += 1 })
  125. // Non-serializable injected content makes Session.append throw AFTER
  126. // turn/start was recorded. The turn/end must still be appended (finally),
  127. // AND the durability checkpoint must still fire — the balanced turn is in
  128. // memory and a crash before the next turn/dispose would otherwise lose it.
  129. expect(() => {
  130. agent.inject([{ type: 'text', text: 'x', bad: 1n } as never], { source: { kind: 'plugin', plugin: 'p' } })
  131. }).toThrow(/non-JSON-serializable/)
  132. const types = agent.session.events.map(e => e.type)
  133. expect(types).toEqual(['turn/start', 'turn/end']) // balanced, no open turn
  134. await new Promise(r => setTimeout(r, 10)) // let the fire-and-forget flush run
  135. expect(flushes).toBe(1) // checkpoint fired despite the throw
  136. })
  137. it('idle inject() still checkpoints when a listener throws on the synthetic turn/end', async () => {
  138. const adapter = new MockAdapter([textResponse('ok')])
  139. const ctx = await harness(adapter)
  140. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  141. let flushes = 0
  142. ctx.on('session/flush', () => { flushes += 1 })
  143. // A session/event listener that throws on the synthetic turn/end. Append
  144. // pushes before notifying, so turn/end is in the log (turn balanced) but the
  145. // throw must NOT skip the durability checkpoint — the flush decision is made
  146. // from the log, not a flag set after the (throwing) append.
  147. let threw = false
  148. ctx.on('session/event', (_s, event) => {
  149. if (!threw && event.type === 'turn/end') { threw = true; throw new Error('boom turn/end') }
  150. })
  151. expect(() => { agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } }) }).not.toThrow()
  152. const types = agent.session.events.map(e => e.type)
  153. expect(types).toEqual(['turn/start', 'context/message', 'turn/end']) // balanced
  154. await new Promise(r => setTimeout(r, 10))
  155. expect(flushes).toBe(1) // checkpoint fired despite the throwing turn/end listener
  156. })
  157. it('idle inject() reports a failing flush via agent/error (step 0) AND the logger', async () => {
  158. const adapter = new MockAdapter([textResponse('ok')])
  159. const ctx = await harness(adapter)
  160. // A non-Error rejection exercises the String() normalization branch.
  161. ctx.on('session/flush', () => { throw 'disk gone' })
  162. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  163. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  164. const errors: { turn: number; step: number; message: string }[] = []
  165. ctx.on('agent/error', (_a, turn, step, error) => void errors.push({ turn, step, message: error.message }))
  166. agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } })
  167. await new Promise(r => setTimeout(r, 20)) // let the contained flush settle
  168. // Reported via agent/error (step 0 — the idle-injection convention) so
  169. // plugins monitoring agent/error see idle-injection persistence failures,
  170. // mirroring the loop's post-turn/end flush path. A non-Error throw is
  171. // normalized to an Error.
  172. expect(errors).toEqual([{ turn: 1, step: 0, message: 'disk gone' }])
  173. expect(warn).toHaveBeenCalledWith(expect.stringContaining('flush after idle injection failed'))
  174. warn.mockRestore()
  175. })
  176. it('idle inject() with a non-serializable source opens no turn (nothing to close)', async () => {
  177. const adapter = new MockAdapter([textResponse('ok')])
  178. const ctx = await harness(adapter)
  179. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  180. // A non-serializable source makes the turn/start append throw BEFORE the
  181. // event is pushed (Session.append validates before push), so NO turn opens.
  182. // The finally's isTurnOpen() guard sees no open turn and appends nothing —
  183. // the log stays empty, not left with a dangling turn/start.
  184. expect(() => {
  185. agent.inject([{ type: 'text', text: 'x' }], { source: { kind: 'plugin', plugin: 'p', bad: 1n } as never })
  186. }).toThrow(/non-JSON-serializable/)
  187. expect(agent.session.events).toHaveLength(0)
  188. })
  189. it('steer() when idle falls through to send() and starts a turn', async () => {
  190. const adapter = new MockAdapter([textResponse('ok')])
  191. const ctx = await harness(adapter)
  192. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  193. // steer while idle delegates to send
  194. agent.steer([{ type: 'text', text: 'steer idle' }], { source: { kind: 'plugin', plugin: 'test' } })
  195. await waitForIdle(ctx, agent)
  196. // The message was recorded as a user-level message (send path)
  197. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  198. expect(adapter.requests).toHaveLength(1)
  199. })
  200. it('disposer is idempotent (double-stop)', async () => {
  201. // Create a bare ReactLoopAgent and call start() directly to get the disposer.
  202. // Then call it twice — the second call hits the early-return branch.
  203. const ctx = new Context()
  204. await ctx.plugin(SessionStore)
  205. const session = ctx.sessions.create(SessionId('test'))
  206. const agent = new ReactLoopAgent(ctx, AgentId('bare'), { model: 'mock' }, session)
  207. // Start the loop to get the disposer; the agent waits for messages
  208. // (idle, never-resolving cancel), so it will stay idle.
  209. const dispose = agent.start()
  210. // First dispose
  211. dispose()
  212. expect(agent.status).toBe('disposed')
  213. // Second dispose — idempotent, no throw
  214. expect(() => { dispose() }).not.toThrow()
  215. expect(agent.status).toBe('disposed')
  216. })
  217. it('setting the same status does not emit agent/status again', async () => {
  218. const adapter = new MockAdapter([textResponse('ok')])
  219. const ctx = await harness(adapter)
  220. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  221. const statuses: string[] = []
  222. ctx.on('agent/status', (subject, status) => {
  223. if (subject === agent) statuses.push(status)
  224. })
  225. send(agent, 'hi')
  226. await waitForIdle(ctx, agent)
  227. // After the turn, agent is idle. Send again to trigger another attempt
  228. // to go idle — but it's already idle, so no emission.
  229. const idleTransitionCount = statuses.filter(s => s === 'idle').length
  230. expect(idleTransitionCount).toBe(1) // only the final transition from running
  231. })
  232. it('whenIdle() resolves immediately when the agent is not running', async () => {
  233. const adapter = new MockAdapter([textResponse('ok')])
  234. const ctx = await harness(adapter)
  235. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  236. // Fresh agent is idle — whenIdle() takes the not-running fast path and
  237. // resolves without subscribing. await must not hang.
  238. await agent.whenIdle()
  239. expect(agent.status).not.toBe('running')
  240. })
  241. it('whenIdle() waits for queued work that has not flipped status yet', async () => {
  242. const adapter = new MockAdapter(['hang'])
  243. const ctx = await harness(adapter)
  244. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  245. send(agent, 'queued')
  246. let settled = false
  247. const idle = agent.whenIdle().then(() => { settled = true })
  248. await Promise.resolve()
  249. expect(settled).toBe(false)
  250. await waitForStatus(ctx, agent, 'running')
  251. agent.cancel('done')
  252. await idle
  253. expect(settled).toBe(true)
  254. expect(agent.status).toBe('idle')
  255. })
  256. it('whenIdle() awaits the running→idle transition, ignoring other subjects/running events', async () => {
  257. const adapter = new MockAdapter([textResponse('ok'), textResponse('ok')])
  258. const ctx = await harness(adapter)
  259. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  260. const other = ctx.agentLoop.create(AgentId('a2'), { model: 'mock' })
  261. // Drive `agent` into `running`, then await whenIdle() — it subscribes to
  262. // agent/status and resolves on the first transition out of running.
  263. const running = new Promise<void>((resolve) => {
  264. const dispose = ctx.on('agent/status', (subject, status) => {
  265. if (subject === agent && status === 'running') { dispose(); resolve() }
  266. })
  267. })
  268. send(agent, 'go')
  269. await running
  270. expect(agent.status).toBe('running')
  271. // While `agent`'s whenIdle is pending, churn `other` through running→idle:
  272. // every status event it emits hits whenIdle's guard with `subject !== this`,
  273. // so the wait must ignore them and only resolve on `agent`'s own idle.
  274. send(other, 'go')
  275. await agent.whenIdle()
  276. expect(agent.status).toBe('idle')
  277. })
  278. it('whenIdle() subscribed while running resolves via done when the agent is then disposed', async () => {
  279. // Covers the waiter's disposed arm: whenIdle() queues an internal waiter
  280. // while running (not the fast path), then the disposer settles it and chains
  281. // `done` (loop exit), not an eager resolve. A bare ReactLoopAgent + direct
  282. // start() disposer keeps the emit synchronous.
  283. const ctx = new Context()
  284. await ctx.plugin(LlmService)
  285. await ctx.plugin(SessionStore)
  286. await ctx.plugin(SystemPrompt)
  287. await ctx.plugin(ToolRegistry)
  288. await ctx.plugin(AgentRegistry)
  289. const adapter = new MockAdapter(['hang'])
  290. ctx.llm.registerAdapter(['mock'], adapter)
  291. const session = ctx.sessions.create(SessionId('bare'))
  292. const agent = new ReactLoopAgent(ctx, AgentId('bare'), { model: 'mock' }, session)
  293. const dispose = agent.start()
  294. agent.send([{ type: 'text', text: 'go' }])
  295. await new Promise(r => setTimeout(r, 30))
  296. expect(agent.status).toBe('running')
  297. const idle = agent.whenIdle() // queues an internal waiter (running)
  298. dispose() // settles the waiter synchronously; whenIdle chains done
  299. await idle
  300. expect(agent.status).toBe('disposed')
  301. await agent.done
  302. })
  303. it('whenIdle() subscribed while running survives a FIBER dispose (no hung promise)', async () => {
  304. // The waiter is internal agent state, NOT an effect-scoped ctx.on listener:
  305. // disposing the OWNING fiber runs the agent's listener disposers, which would
  306. // have dropped a ctx.on-based waiter before the 'disposed' transition and
  307. // hung the promise. With internal waiters, the fiber disposer still settles
  308. // it. Regression for the round-3 whenIdle finding.
  309. const adapter = new MockAdapter(['hang'])
  310. const ctx = await harness(adapter)
  311. let agent!: ReactLoopAgent
  312. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  313. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  314. }, { inject: ['agentLoop'] }))
  315. send(agent, 'go')
  316. await new Promise(r => setTimeout(r, 30))
  317. expect(agent.status).toBe('running')
  318. const idle = agent.whenIdle() // queued while running
  319. await fiber.dispose() // tears the fiber down (drops agent listeners)
  320. await idle // must resolve, not hang
  321. expect(agent.status).toBe('disposed')
  322. })
  323. it('whenIdle() on a disposed agent awaits the loop exit (done), not just the status flip', async () => {
  324. // The disposer emits agent/status('disposed') BEFORE the driver loop
  325. // unwinds, so whenIdle() must chain `done` (true quiescence) on the
  326. // disposed path. Dispose a running agent, then assert whenIdle() resolves
  327. // only after `done` — i.e. the loop has actually exited.
  328. const adapter = new MockAdapter(['hang'])
  329. const ctx = await harness(adapter)
  330. let agent!: ReactLoopAgent
  331. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  332. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  333. }, { inject: ['agentLoop'] }))
  334. send(agent, 'go')
  335. await new Promise(r => setTimeout(r, 30))
  336. let doneResolved = false
  337. void agent.done.then(() => { doneResolved = true })
  338. await fiber.dispose() // sets status disposed, aborts, drains the loop
  339. expect(agent.status).toBe('disposed')
  340. // whenIdle() must not resolve before `done` has — chaining `done` is the
  341. // quiescence guarantee. By here dispose() awaited the loop, so done is
  342. // settled; whenIdle resolves and done is observed resolved.
  343. await agent.whenIdle()
  344. expect(doneResolved).toBe(true)
  345. })
  346. it('contains a throwing agent/status listener on the running transition', async () => {
  347. const adapter = new MockAdapter([textResponse('ok')])
  348. const ctx = await harness(adapter)
  349. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  350. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  351. ctx.on('agent/status', (_subject, status) => {
  352. if (status === 'running') throw new Error('bad running listener')
  353. })
  354. send(agent, 'go')
  355. await agent.whenIdle()
  356. expect(adapter.requests).toHaveLength(1)
  357. expect(agent.status).toBe('idle')
  358. expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent/status listener threw on running'))
  359. warn.mockRestore()
  360. })
  361. it('contains a throwing agent/status listener on the idle transition', async () => {
  362. const adapter = new MockAdapter([textResponse('ok')])
  363. const ctx = await harness(adapter)
  364. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  365. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  366. ctx.on('agent/status', (_subject, status) => {
  367. if (status === 'idle') throw new Error('bad idle listener')
  368. })
  369. send(agent, 'go')
  370. await agent.whenIdle()
  371. expect(adapter.requests).toHaveLength(1)
  372. expect(agent.status).toBe('idle')
  373. expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent/status listener threw on idle'))
  374. warn.mockRestore()
  375. })
  376. })