agent.spec.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. // Invalid injected content throws after turn/start. `finally` must still append turn/end and
  147. // flush the balanced in-memory turn so a crash cannot lose it before the next checkpoint.
  148. expect(() => {
  149. agent.inject([{ type: 'text', text: 'x', bad: 1n } as never], { source: { kind: 'plugin', plugin: 'p' } })
  150. }).toThrow(/non-JSON-serializable/)
  151. const types = agent.session.events.map(e => e.type)
  152. expect(types).toEqual(['turn/start', 'turn/end']) // balanced, no open turn
  153. await new Promise(r => setTimeout(r, 10)) // let the fire-and-forget flush run
  154. expect(flushes).toBe(1) // checkpoint fired despite the throw
  155. })
  156. it('idle inject() still checkpoints when a listener throws on the synthetic turn/end', async () => {
  157. const adapter = new MockAdapter([textResponse('ok')])
  158. const ctx = await harness(adapter)
  159. const agent = ctx.agentLoop.create(SessionId('a1'), { model: 'mock' })
  160. let flushes = 0
  161. ctx.on('session/flush', () => { flushes += 1 })
  162. // Session contains a throwing post-commit turn/end observer. The accepted
  163. // boundary still triggers the idle injection's durability checkpoint.
  164. let threw = false
  165. ctx.on('session/event', (_s, event) => {
  166. if (!threw && event.type === 'turn/end') { threw = true; throw new Error('boom turn/end') }
  167. })
  168. expect(() => { agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } }) }).not.toThrow()
  169. const types = agent.session.events.map(e => e.type)
  170. expect(types).toEqual(['turn/start', 'context/message', 'turn/end']) // balanced
  171. await new Promise(r => setTimeout(r, 10))
  172. expect(flushes).toBe(1) // checkpoint fired despite the throwing turn/end listener
  173. })
  174. it('idle inject() reports a failing flush via agent/error (step 0) AND the logger', async () => {
  175. const adapter = new MockAdapter([textResponse('ok')])
  176. const ctx = await harness(adapter)
  177. // A non-Error rejection exercises the String() normalization branch.
  178. ctx.on('session/flush', () => { throw 'disk gone' })
  179. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  180. const agent = ctx.agentLoop.create(SessionId('a1'), { model: 'mock' })
  181. const errors: { turn: number; step: number; message: string }[] = []
  182. ctx.on('agent/error', (_a, turn, step, error) => void errors.push({ turn, step, message: error.message }))
  183. agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } })
  184. await new Promise(r => setTimeout(r, 20)) // let the contained flush settle
  185. // Reported via agent/error (step 0 — the idle-injection convention) so
  186. // plugins monitoring agent/error see idle-injection persistence failures,
  187. // mirroring the loop's post-turn/end flush path. A non-Error throw is
  188. // normalized to an Error.
  189. expect(errors).toEqual([{ turn: 1, step: 0, message: 'disk gone' }])
  190. expect(warn).toHaveBeenCalledWith(expect.stringContaining('flush after idle injection failed'))
  191. warn.mockRestore()
  192. })
  193. it('idle inject() with a non-serializable source opens no turn (nothing to close)', async () => {
  194. const adapter = new MockAdapter([textResponse('ok')])
  195. const ctx = await harness(adapter)
  196. const agent = ctx.agentLoop.create(SessionId('a1'), { model: 'mock' })
  197. // A non-serializable source makes the turn/start append throw BEFORE the
  198. // event is pushed (Session.append validates before push), so NO turn opens.
  199. // The finally's isTurnOpen() guard sees no open turn and appends nothing —
  200. // the log stays empty, not left with a dangling turn/start.
  201. expect(() => {
  202. agent.inject([{ type: 'text', text: 'x' }], { source: { kind: 'plugin', plugin: 'p', bad: 1n } as never })
  203. }).toThrow(/non-JSON-serializable/)
  204. expect(agent.session.events).toHaveLength(0)
  205. })
  206. it('steer() when idle falls through to send() and starts a turn', async () => {
  207. const adapter = new MockAdapter([textResponse('ok')])
  208. const ctx = await harness(adapter)
  209. const agent = ctx.agentLoop.create(SessionId('a1'), { model: 'mock' })
  210. // steer while idle delegates to send
  211. agent.steer([{ type: 'text', text: 'steer idle' }], { source: { kind: 'plugin', plugin: 'test' } })
  212. await waitForIdle(ctx, agent)
  213. // The message was recorded as a user-level message (send path)
  214. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  215. expect(adapter.requests).toHaveLength(1)
  216. })
  217. it('disposer is idempotent (double-stop)', async () => {
  218. // The internal start seam exposes one idle driver's disposer for repeated invocation.
  219. const ctx = new Context()
  220. await ctx.plugin(SessionStore)
  221. const session = ctx.sessions.create(SessionId('test'))
  222. const prepared = prepareReactLoopAgent(ctx, SessionId('bare'), { model: 'mock' }, session)
  223. const { agent } = prepared
  224. prepared.markPublished()
  225. const dispose = prepared.startDriver()
  226. const firstDisposal = dispose()
  227. expect(agent.status).toBe('disposed')
  228. await firstDisposal
  229. await expect(dispose()).resolves.toBeUndefined()
  230. expect(agent.status).toBe('disposed')
  231. })
  232. it('a pre-start disposal makes a later driver-start attempt inert', async () => {
  233. const ctx = new Context()
  234. await ctx.plugin(SessionStore)
  235. const session = ctx.sessions.create(SessionId('pre-start-dispose'))
  236. const prepared = prepareReactLoopAgent(ctx, SessionId('pre-start-dispose'), { model: 'mock' }, session)
  237. await prepared.dispose()
  238. expect(prepared.agent.status).toBe('disposed')
  239. const dispose = prepared.startDriver()
  240. await dispose()
  241. await expect(prepared.agent.done).resolves.toBeUndefined()
  242. expect(prepared.agent.session.events).toEqual([])
  243. await ctx.fiber.dispose()
  244. })
  245. it('setting the same status does not emit agent/status again', async () => {
  246. const adapter = new MockAdapter([textResponse('ok')])
  247. const ctx = await harness(adapter)
  248. const agent = ctx.agentLoop.create(SessionId('a1'), { model: 'mock' })
  249. const statuses: string[] = []
  250. ctx.on('agent/status', (subject, status) => {
  251. if (subject === agent) statuses.push(status)
  252. })
  253. send(agent, 'hi')
  254. await waitForIdle(ctx, agent)
  255. // After the turn, agent is idle. Send again to trigger another attempt
  256. // to go idle — but it's already idle, so no emission.
  257. const idleTransitionCount = statuses.filter(s => s === 'idle').length
  258. expect(idleTransitionCount).toBe(1) // only the final transition from running
  259. })
  260. it('whenIdle() resolves immediately when the agent is not running', async () => {
  261. const adapter = new MockAdapter([textResponse('ok')])
  262. const ctx = await harness(adapter)
  263. const agent = ctx.agentLoop.create(SessionId('a1'), { model: 'mock' })
  264. // Fresh agent is idle — whenIdle() takes the not-running fast path and
  265. // resolves without subscribing. await must not hang.
  266. await agent.whenIdle()
  267. expect(agent.status).not.toBe('running')
  268. })
  269. it('whenIdle() waits for queued work that has not flipped status yet', async () => {
  270. const adapter = new MockAdapter(['hang'])
  271. const ctx = await harness(adapter)
  272. const agent = ctx.agentLoop.create(SessionId('a1'), { model: 'mock' })
  273. send(agent, 'queued')
  274. let settled = false
  275. const idle = agent.whenIdle().then(() => { settled = true })
  276. await Promise.resolve()
  277. expect(settled).toBe(false)
  278. await waitForStatus(ctx, agent, 'running')
  279. agent.cancel('done')
  280. await idle
  281. expect(settled).toBe(true)
  282. expect(agent.status).toBe('idle')
  283. })
  284. it('whenIdle() awaits the running→idle transition, ignoring other subjects/running events', async () => {
  285. const adapter = new MockAdapter([textResponse('ok'), textResponse('ok')])
  286. const ctx = await harness(adapter)
  287. const agent = ctx.agentLoop.create(SessionId('a1'), { model: 'mock' })
  288. const other = ctx.agentLoop.create(SessionId('a2'), { model: 'mock' })
  289. // Drive `agent` into `running`, then await whenIdle() — it subscribes to
  290. // agent/status and resolves on the first transition out of running.
  291. const running = new Promise<void>((resolve) => {
  292. const dispose = ctx.on('agent/status', (subject, status) => {
  293. if (subject === agent && status === 'running') { dispose(); resolve() }
  294. })
  295. })
  296. send(agent, 'go')
  297. await running
  298. expect(agent.status).toBe('running')
  299. // While `agent`'s whenIdle is pending, churn `other` through running→idle:
  300. // every status event it emits hits whenIdle's guard with `subject !== this`,
  301. // so the wait must ignore them and only resolve on `agent`'s own idle.
  302. send(other, 'go')
  303. await agent.whenIdle()
  304. expect(agent.status).toBe('idle')
  305. })
  306. it('whenIdle() subscribed while running resolves via done when the agent is then disposed', async () => {
  307. // Queue the internal waiter while running, then dispose the bare driver. Its disposed branch
  308. // must chain the loop's `done` promise rather than resolve before exit.
  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, SessionId('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 agent-owned state, not an effect-scoped listener that owner disposal would
  333. // remove before the disposed transition. Fiber teardown must still settle it.
  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(SessionId('scoped'), { model: 'mock' })
  339. }, { inject: ['agentLoop'] }))
  340. send(agent, 'go')
  341. await new Promise(r => setTimeout(r, 30))
  342. expect(agent.status).toBe('running')
  343. const idle = agent.whenIdle() // queued while running
  344. await fiber.dispose() // tears the fiber down (drops agent listeners)
  345. await idle // must resolve, not hang
  346. expect(agent.status).toBe('disposed')
  347. })
  348. it('whenIdle() on a disposed agent awaits the loop exit (done), not just the status flip', async () => {
  349. // Disposed status is emitted before the driver unwinds. `whenIdle()` must chain `done` so it
  350. // resolves only after true loop exit.
  351. const adapter = new MockAdapter(['hang'])
  352. const ctx = await harness(adapter)
  353. let agent!: ReactLoopAgent
  354. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  355. agent = inner.agentLoop.create(SessionId('scoped'), { model: 'mock' })
  356. }, { inject: ['agentLoop'] }))
  357. send(agent, 'go')
  358. await new Promise(r => setTimeout(r, 30))
  359. let doneResolved = false
  360. void agent.done.then(() => { doneResolved = true })
  361. await fiber.dispose() // sets status disposed, aborts, drains the loop
  362. expect(agent.status).toBe('disposed')
  363. // whenIdle() must not resolve before `done` has — chaining `done` is the
  364. // quiescence guarantee. By here dispose() awaited the loop, so done is
  365. // settled; whenIdle resolves and done is observed resolved.
  366. await agent.whenIdle()
  367. expect(doneResolved).toBe(true)
  368. })
  369. it('contains a throwing agent/status listener on the running transition', async () => {
  370. const adapter = new MockAdapter([textResponse('ok')])
  371. const ctx = await harness(adapter)
  372. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  373. const agent = ctx.agentLoop.create(SessionId('a1'), { model: 'mock' })
  374. ctx.on('agent/status', (_subject, status) => {
  375. if (status === 'running') throw new Error('bad running listener')
  376. })
  377. send(agent, 'go')
  378. await agent.whenIdle()
  379. expect(adapter.requests).toHaveLength(1)
  380. expect(agent.status).toBe('idle')
  381. expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent event "agent/status" listener threw'))
  382. warn.mockRestore()
  383. })
  384. it('contains a throwing agent/status listener on the idle 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 === 'idle') throw new Error('bad idle 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. })