agent.spec.ts 19 KB

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