agent.spec.ts 21 KB

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