agent.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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, { DEFAULT_MAX_PARALLEL_TOOL_CALLS, 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(
  51. ctx, SessionId('first-driver'), { provider: 'mock', model: 'mock' }, session, DEFAULT_MAX_PARALLEL_TOOL_CALLS,
  52. )
  53. expect(() => prepared.agent.ctx).toThrow('context is not bound')
  54. expect(() => prepareReactLoopAgent(
  55. ctx, SessionId('second-driver'), { provider: 'mock', model: 'mock' }, session, DEFAULT_MAX_PARALLEL_TOOL_CALLS,
  56. ))
  57. .toThrow('already has a concrete agent driver')
  58. await prepared.dispose()
  59. await ctx.fiber.dispose()
  60. })
  61. it('borrows caller options and binds its scoped context exactly once', async () => {
  62. const ctx = await harness(new MockAdapter([textResponse('unused')]))
  63. const options = { provider: 'mock', model: 'mock' }
  64. const agent = ctx.agentLoop.create(SessionId('owned-bindings'), options)
  65. expect(agent.options).toBe(options)
  66. expect(agent.id).toBe('owned-bindings')
  67. expect(agent.session.id).toBe(agent.id)
  68. expect(() => { bindReactLoopAgentContext(agent, new Context()) }).toThrow(/context is already bound/)
  69. await ctx.fiber.dispose()
  70. })
  71. it('send() throws after disposal', async () => {
  72. const adapter = new MockAdapter(['hang'])
  73. const ctx = await harness(adapter)
  74. let agent!: ReactLoopAgent
  75. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  76. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  77. }, { inject: ['agentLoop'] }))
  78. send(agent, 'go')
  79. await new Promise(r => setTimeout(r, 30))
  80. await fiber.dispose()
  81. await agent.done
  82. expect(() => { agent.send([{ type: 'text', text: 'too late' }]) }).toThrow('disposed')
  83. })
  84. it('steer() throws after disposal', async () => {
  85. const adapter = new MockAdapter(['hang'])
  86. const ctx = await harness(adapter)
  87. let agent!: ReactLoopAgent
  88. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  89. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  90. }, { inject: ['agentLoop'] }))
  91. send(agent, 'go')
  92. await new Promise(r => setTimeout(r, 30))
  93. await fiber.dispose()
  94. await agent.done
  95. expect(() => { agent.steer([{ type: 'text', text: 'too late' }]) }).toThrow('disposed')
  96. })
  97. it('inject() throws after disposal', async () => {
  98. const adapter = new MockAdapter(['hang'])
  99. const ctx = await harness(adapter)
  100. let agent!: ReactLoopAgent
  101. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  102. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  103. }, { inject: ['agentLoop'] }))
  104. send(agent, 'go')
  105. await new Promise(r => setTimeout(r, 30))
  106. await fiber.dispose()
  107. await agent.done
  108. expect(() => { agent.inject([{ type: 'text', text: 'too late' }]) }).toThrow('disposed')
  109. })
  110. it('inject() decides enclosure from the LOG (open turn), not agent status', async () => {
  111. const adapter = new MockAdapter([textResponse('ok')])
  112. const ctx = await harness(adapter)
  113. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  114. // Simulate an OPEN turn in the log while the agent is idle (status is not a
  115. // reliable open-turn signal). inject must append into that open turn, NOT
  116. // wrap a new one.
  117. agent.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  118. agent.inject([{ type: 'text', text: 'mid' }], { source: { kind: 'plugin', plugin: 'p' } })
  119. expect(agent.session.events.filter(e => e.type === 'turn/start')).toHaveLength(1)
  120. expect(agent.session.events.at(-1)!.type).toBe('context/message')
  121. // Close the turn; now inject must wrap its own one-shot injection turn.
  122. agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  123. agent.inject([{ type: 'text', text: 'after' }], { source: { kind: 'plugin', plugin: 'p' } })
  124. const starts = agent.session.events.filter(e => e.type === 'turn/start')
  125. expect(starts).toHaveLength(2)
  126. const last = starts[1]!
  127. expect(last.type === 'turn/start' && last.data.trigger.kind).toBe('injection')
  128. expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed
  129. })
  130. it('idle inject() contains a failing flush (logs, does not throw into the caller)', async () => {
  131. const adapter = new MockAdapter([textResponse('ok')])
  132. const ctx = await harness(adapter)
  133. // A persistence-like listener whose flush rejects.
  134. ctx.on('session/flush', () => { throw new Error('disk gone') })
  135. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  136. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  137. // inject() is synchronous and fires a fire-and-forget flush; a rejecting
  138. // flush must be contained (logged), never thrown into the caller.
  139. expect(() => { agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } }) }).not.toThrow()
  140. await new Promise(r => setTimeout(r, 20)) // let the contained flush settle
  141. expect(warn).toHaveBeenCalledWith(expect.stringContaining('flush after idle injection failed'))
  142. warn.mockRestore()
  143. })
  144. it('idle inject() closes its one-shot turn AND still checkpoints even if the append throws', async () => {
  145. const adapter = new MockAdapter([textResponse('ok')])
  146. const ctx = await harness(adapter)
  147. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  148. let flushes = 0
  149. ctx.on('session/flush', () => { flushes += 1 })
  150. // Invalid injected content throws after turn/start. `finally` must still append turn/end and
  151. // flush the balanced in-memory turn so a crash cannot lose it before the next checkpoint.
  152. expect(() => {
  153. agent.inject([{ type: 'text', text: 'x', bad: 1n } as never], { source: { kind: 'plugin', plugin: 'p' } })
  154. }).toThrow(/non-JSON-serializable/)
  155. const types = agent.session.events.map(e => e.type)
  156. expect(types).toEqual(['turn/start', 'turn/end']) // balanced, no open turn
  157. await new Promise(r => setTimeout(r, 10)) // let the fire-and-forget flush run
  158. expect(flushes).toBe(1) // checkpoint fired despite the throw
  159. })
  160. it('idle inject() still checkpoints when a listener throws on the synthetic turn/end', async () => {
  161. const adapter = new MockAdapter([textResponse('ok')])
  162. const ctx = await harness(adapter)
  163. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  164. let flushes = 0
  165. ctx.on('session/flush', () => { flushes += 1 })
  166. // Session contains a throwing post-commit turn/end observer. The accepted
  167. // boundary still triggers the idle injection's durability checkpoint.
  168. let threw = false
  169. ctx.on('session/event', (_s, event) => {
  170. if (!threw && event.type === 'turn/end') { threw = true; throw new Error('boom turn/end') }
  171. })
  172. expect(() => { agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } }) }).not.toThrow()
  173. const types = agent.session.events.map(e => e.type)
  174. expect(types).toEqual(['turn/start', 'context/message', 'turn/end']) // balanced
  175. await new Promise(r => setTimeout(r, 10))
  176. expect(flushes).toBe(1) // checkpoint fired despite the throwing turn/end listener
  177. })
  178. it('idle inject() reports a failing flush via agent/error (step 0) AND the logger', async () => {
  179. const adapter = new MockAdapter([textResponse('ok')])
  180. const ctx = await harness(adapter)
  181. // A non-Error rejection exercises the String() normalization branch.
  182. ctx.on('session/flush', () => { throw 'disk gone' })
  183. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  184. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  185. const errors: { turn: number; step: number; message: string }[] = []
  186. ctx.on('agent/error', (_a, turn, step, error) => void errors.push({ turn, step, message: error.message }))
  187. agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } })
  188. await new Promise(r => setTimeout(r, 20)) // let the contained flush settle
  189. // Reported via agent/error (step 0 — the idle-injection convention) so
  190. // plugins monitoring agent/error see idle-injection persistence failures,
  191. // mirroring the loop's post-turn/end flush path. A non-Error throw is
  192. // normalized to an Error.
  193. expect(errors).toEqual([{ turn: 1, step: 0, message: 'disk gone' }])
  194. expect(warn).toHaveBeenCalledWith(expect.stringContaining('flush after idle injection failed'))
  195. warn.mockRestore()
  196. })
  197. it('idle inject() with a non-serializable source opens no turn (nothing to close)', async () => {
  198. const adapter = new MockAdapter([textResponse('ok')])
  199. const ctx = await harness(adapter)
  200. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  201. // A non-serializable source makes the turn/start append throw BEFORE the
  202. // event is pushed (Session.append validates before push), so NO turn opens.
  203. // The finally's isTurnOpen() guard sees no open turn and appends nothing —
  204. // the log stays empty, not left with a dangling turn/start.
  205. expect(() => {
  206. agent.inject([{ type: 'text', text: 'x' }], { source: { kind: 'plugin', plugin: 'p', bad: 1n } as never })
  207. }).toThrow(/non-JSON-serializable/)
  208. expect(agent.session.events).toHaveLength(0)
  209. })
  210. it('steer() when idle falls through to send() and starts a turn', async () => {
  211. const adapter = new MockAdapter([textResponse('ok')])
  212. const ctx = await harness(adapter)
  213. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  214. // steer while idle delegates to send
  215. agent.steer([{ type: 'text', text: 'steer idle' }], { source: { kind: 'plugin', plugin: 'test' } })
  216. await waitForIdle(ctx, agent)
  217. // The message was recorded as a user-level message (send path)
  218. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  219. expect(adapter.requests).toHaveLength(1)
  220. })
  221. it('disposer is idempotent (double-stop)', async () => {
  222. // The internal start seam exposes one idle driver's disposer for repeated invocation.
  223. const ctx = new Context()
  224. await ctx.plugin(SessionStore)
  225. const session = ctx.sessions.create(SessionId('test'))
  226. const prepared = prepareReactLoopAgent(
  227. ctx, SessionId('bare'), { provider: 'mock', model: 'mock' }, session, DEFAULT_MAX_PARALLEL_TOOL_CALLS,
  228. )
  229. const { agent } = prepared
  230. prepared.markPublished()
  231. const dispose = prepared.startDriver()
  232. const firstDisposal = dispose()
  233. expect(agent.status).toBe('disposed')
  234. await firstDisposal
  235. await expect(dispose()).resolves.toBeUndefined()
  236. expect(agent.status).toBe('disposed')
  237. })
  238. it('a pre-start disposal makes a later driver-start attempt inert', async () => {
  239. const ctx = new Context()
  240. await ctx.plugin(SessionStore)
  241. const session = ctx.sessions.create(SessionId('pre-start-dispose'))
  242. const prepared = prepareReactLoopAgent(
  243. ctx, SessionId('pre-start-dispose'), { provider: 'mock', model: 'mock' }, session, DEFAULT_MAX_PARALLEL_TOOL_CALLS,
  244. )
  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'), { provider: 'mock', 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'), { provider: 'mock', 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'), { provider: 'mock', 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'), { provider: 'mock', model: 'mock' })
  296. const other = ctx.agentLoop.create(SessionId('a2'), { provider: 'mock', 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. // Queue the internal waiter while running, then dispose the bare driver. Its disposed branch
  316. // must chain the loop's `done` promise rather than resolve before exit.
  317. const ctx = new Context()
  318. await ctx.plugin(LlmService)
  319. await ctx.plugin(SessionStore)
  320. await ctx.plugin(SystemPrompt)
  321. await ctx.plugin(ToolRegistry)
  322. await ctx.plugin(AgentRegistry)
  323. const adapter = new MockAdapter(['hang'])
  324. ctx.llm.registerAdapter(['mock'], adapter)
  325. const session = ctx.sessions.create(SessionId('bare'))
  326. const prepared = prepareReactLoopAgent(
  327. ctx, SessionId('bare'), { provider: 'mock', model: 'mock' }, session, DEFAULT_MAX_PARALLEL_TOOL_CALLS,
  328. )
  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 agent-owned state, not an effect-scoped listener that owner disposal would
  343. // remove before the disposed transition. Fiber teardown must still settle it.
  344. const adapter = new MockAdapter(['hang'])
  345. const ctx = await harness(adapter)
  346. let agent!: ReactLoopAgent
  347. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  348. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  349. }, { inject: ['agentLoop'] }))
  350. send(agent, 'go')
  351. await new Promise(r => setTimeout(r, 30))
  352. expect(agent.status).toBe('running')
  353. const idle = agent.whenIdle() // queued while running
  354. await fiber.dispose() // tears the fiber down (drops agent listeners)
  355. await idle // must resolve, not hang
  356. expect(agent.status).toBe('disposed')
  357. })
  358. it('whenIdle() on a disposed agent awaits the loop exit (done), not just the status flip', async () => {
  359. // Disposed status is emitted before the driver unwinds. `whenIdle()` must chain `done` so it
  360. // resolves only after true loop exit.
  361. const adapter = new MockAdapter(['hang'])
  362. const ctx = await harness(adapter)
  363. let agent!: ReactLoopAgent
  364. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  365. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  366. }, { inject: ['agentLoop'] }))
  367. send(agent, 'go')
  368. await new Promise(r => setTimeout(r, 30))
  369. let doneResolved = false
  370. void agent.done.then(() => { doneResolved = true })
  371. await fiber.dispose() // sets status disposed, aborts, drains the loop
  372. expect(agent.status).toBe('disposed')
  373. // whenIdle() must not resolve before `done` has — chaining `done` is the
  374. // quiescence guarantee. By here dispose() awaited the loop, so done is
  375. // settled; whenIdle resolves and done is observed resolved.
  376. await agent.whenIdle()
  377. expect(doneResolved).toBe(true)
  378. })
  379. it('contains a throwing agent/status listener on the running transition', async () => {
  380. const adapter = new MockAdapter([textResponse('ok')])
  381. const ctx = await harness(adapter)
  382. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  383. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  384. ctx.on('agent/status', (_subject, status) => {
  385. if (status === 'running') throw new Error('bad running listener')
  386. })
  387. send(agent, 'go')
  388. await agent.whenIdle()
  389. expect(adapter.requests).toHaveLength(1)
  390. expect(agent.status).toBe('idle')
  391. expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent event "agent/status" listener threw'))
  392. warn.mockRestore()
  393. })
  394. it('contains a throwing agent/status listener on the idle transition', async () => {
  395. const adapter = new MockAdapter([textResponse('ok')])
  396. const ctx = await harness(adapter)
  397. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  398. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  399. ctx.on('agent/status', (_subject, status) => {
  400. if (status === 'idle') throw new Error('bad idle listener')
  401. })
  402. send(agent, 'go')
  403. await agent.whenIdle()
  404. expect(adapter.requests).toHaveLength(1)
  405. expect(agent.status).toBe('idle')
  406. expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent event "agent/status" listener threw'))
  407. warn.mockRestore()
  408. })
  409. })