agent.spec.ts 21 KB

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