agent.spec.ts 21 KB

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