agent.spec.ts 20 KB

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