agent.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 } 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(
  54. ctx, SessionId('first-driver'), { provider: 'mock', model: 'mock' }, session,
  55. )
  56. expect(() => prepared.agent.ctx).toThrow('context is not bound')
  57. expect(() => prepareReactLoopAgent(
  58. ctx, SessionId('second-driver'), { provider: 'mock', model: 'mock' }, session,
  59. ))
  60. .toThrow('already has a concrete agent driver')
  61. await prepared.dispose()
  62. await ctx.fiber.dispose()
  63. })
  64. it('borrows caller options and binds its scoped context exactly once', async () => {
  65. const ctx = await harness(new MockAdapter([textResponse('unused')]))
  66. const options = { provider: 'mock', model: 'mock' }
  67. const agent = ctx.agentLoop.create(SessionId('owned-bindings'), options)
  68. expect(agent.options).toBe(options)
  69. expect(agent.id).toBe('owned-bindings')
  70. expect(agent.session.id).toBe(agent.id)
  71. expect(() => { bindReactLoopAgentContext(agent, new Context()) }).toThrow(/context is already bound/)
  72. await ctx.fiber.dispose()
  73. })
  74. it('idle inject() appends context without opening a turn or requesting a flush', async () => {
  75. const adapter = new MockAdapter([textResponse('ok')])
  76. const ctx = await harness(adapter)
  77. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  78. let flushes = 0
  79. ctx.on('session/flush', () => { flushes += 1 })
  80. agent.inject([{ type: 'text', text: 'context' }], { source: { kind: 'plugin', plugin: 'p' } })
  81. expect(agent.session.events.map(event => event.type)).toEqual(['user/message'])
  82. expect(agent.status).toBe('idle')
  83. expect(adapter.requests).toHaveLength(0)
  84. await agent.whenIdle()
  85. expect(flushes).toBe(0)
  86. })
  87. it('inject() defaults its source to an empty plugin, never user', async () => {
  88. const adapter = new MockAdapter([textResponse('ok')])
  89. const ctx = await harness(adapter)
  90. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  91. agent.inject([{ type: 'text', text: 'no explicit source' }])
  92. const injected = agent.session.events.at(-1)!
  93. expect(injected.type === 'user/message' && injected.data.source).toEqual({ kind: 'plugin', plugin: '' })
  94. await agent.whenIdle()
  95. })
  96. it('idle inject() rejects invalid input before append', async () => {
  97. const adapter = new MockAdapter([textResponse('ok')])
  98. const ctx = await harness(adapter)
  99. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  100. expect(() => {
  101. agent.inject([{ type: 'text', text: 'x', bad: 1n } as never], { source: { kind: 'plugin', plugin: 'p' } })
  102. }).toThrow(/non-JSON-serializable/)
  103. expect(agent.session.events).toHaveLength(0)
  104. })
  105. it('steer() when idle falls through to send() and starts a turn', async () => {
  106. const adapter = new MockAdapter([textResponse('ok')])
  107. const ctx = await harness(adapter)
  108. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  109. // steer while idle delegates to send
  110. agent.steer([{ type: 'text', text: 'steer idle' }], { source: { kind: 'plugin', plugin: 'test' } })
  111. await waitForIdle(ctx, agent)
  112. // The message was recorded as a user-level message (send path)
  113. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  114. expect(adapter.requests).toHaveLength(1)
  115. })
  116. it('disposer is idempotent (double-stop)', async () => {
  117. // Create a bare Agent and start it through the package-internal
  118. // test seam. Then call its disposer twice — the second call hits the
  119. // early-return branch.
  120. const ctx = new Context()
  121. await ctx.plugin(SessionStore)
  122. await ctx.plugin(AgentRegistry)
  123. const session = ctx.sessions.create(SessionId('test'))
  124. const prepared = prepareReactLoopAgent(
  125. ctx, SessionId('bare'), { provider: 'mock', model: 'mock' }, session,
  126. )
  127. const { agent } = prepared
  128. // Start the loop to get the disposer; the agent waits for messages
  129. // (idle, never-resolving cancel), so it will stay idle.
  130. prepared.markPublished()
  131. prepared.start()
  132. const dispose = prepared.dispose
  133. // First dispose
  134. const firstDisposal = dispose()
  135. expect(agent.status).toBe('disposed')
  136. await firstDisposal
  137. // Second dispose — idempotent, no throw
  138. await expect(dispose()).resolves.toBeUndefined()
  139. expect(agent.status).toBe('disposed')
  140. })
  141. it('a pre-start disposal makes a later driver-start attempt inert', async () => {
  142. const ctx = new Context()
  143. await ctx.plugin(SessionStore)
  144. const session = ctx.sessions.create(SessionId('pre-start-dispose'))
  145. const prepared = prepareReactLoopAgent(
  146. ctx, SessionId('pre-start-dispose'), { provider: 'mock', model: 'mock' }, session,
  147. )
  148. await prepared.dispose()
  149. expect(prepared.agent.status).toBe('disposed')
  150. prepared.start()
  151. const dispose = prepared.dispose
  152. await dispose()
  153. await expect(prepared.agent.done).resolves.toBeUndefined()
  154. expect(prepared.agent.session.events).toEqual([])
  155. await ctx.fiber.dispose()
  156. })
  157. it('setting the same status does not emit agent/status again', async () => {
  158. const adapter = new MockAdapter([textResponse('ok')])
  159. const ctx = await harness(adapter)
  160. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  161. const statuses: string[] = []
  162. ctx.on('agent/status', (subject, status) => {
  163. if (subject === agent) statuses.push(status)
  164. })
  165. send(agent, 'hi')
  166. await waitForIdle(ctx, agent)
  167. // After the turn, agent is idle. Send again to trigger another attempt
  168. // to go idle — but it's already idle, so no emission.
  169. const idleTransitionCount = statuses.filter(s => s === 'idle').length
  170. expect(idleTransitionCount).toBe(1) // only the final transition from running
  171. })
  172. it('whenIdle() resolves immediately when the agent is not running', async () => {
  173. const adapter = new MockAdapter([textResponse('ok')])
  174. const ctx = await harness(adapter)
  175. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  176. // Fresh agent is idle — whenIdle() takes the not-running fast path and
  177. // resolves without subscribing. await must not hang.
  178. await agent.whenIdle()
  179. expect(agent.status).not.toBe('running')
  180. })
  181. it('whenIdle() waits for queued work that has not flipped status yet', async () => {
  182. const adapter = new MockAdapter(['hang'])
  183. const ctx = await harness(adapter)
  184. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  185. send(agent, 'queued')
  186. let settled = false
  187. const idle = agent.whenIdle().then(() => { settled = true })
  188. await Promise.resolve()
  189. expect(settled).toBe(false)
  190. await waitForStatus(ctx, agent, 'running')
  191. agent.cancel({ kind: 'user' })
  192. await idle
  193. expect(settled).toBe(true)
  194. expect(agent.status).toBe('idle')
  195. })
  196. it('whenIdle() awaits the running→idle transition, ignoring other subjects/running events', async () => {
  197. const adapter = new MockAdapter([textResponse('ok'), textResponse('ok')])
  198. const ctx = await harness(adapter)
  199. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  200. const other = ctx.agentLoop.create(SessionId('a2'), { provider: 'mock', model: 'mock' })
  201. // Drive `agent` into `running`, then await whenIdle() — it subscribes to
  202. // agent/status and resolves on the first transition out of running.
  203. const running = new Promise<void>((resolve) => {
  204. const dispose = ctx.on('agent/status', (subject, status) => {
  205. if (subject === agent && status === 'running') { dispose(); resolve() }
  206. })
  207. })
  208. send(agent, 'go')
  209. await running
  210. expect(agent.status).toBe('running')
  211. // While `agent`'s whenIdle is pending, churn `other` through running→idle:
  212. // every status event it emits hits whenIdle's guard with `subject !== this`,
  213. // so the wait must ignore them and only resolve on `agent`'s own idle.
  214. send(other, 'go')
  215. await agent.whenIdle()
  216. expect(agent.status).toBe('idle')
  217. })
  218. it('whenIdle() subscribed while running resolves via done when the agent is then disposed', async () => {
  219. // Covers the waiter's disposed arm: whenIdle() queues an internal waiter
  220. // while running (not the fast path), then the disposer settles it and chains
  221. // `done` (loop exit), not an eager resolve. A bare Agent + direct
  222. // internal driver disposer keeps the emit synchronous.
  223. const ctx = new Context()
  224. await ctx.plugin(LlmService)
  225. await ctx.plugin(SessionStore)
  226. await ctx.plugin(SystemPrompt)
  227. await ctx.plugin(ToolRegistry)
  228. await ctx.plugin(AgentRegistry)
  229. const adapter = new MockAdapter(['hang'])
  230. ctx.llm.registerAdapter(['mock'], adapter)
  231. const session = ctx.sessions.create(SessionId('bare'))
  232. const prepared = prepareReactLoopAgent(
  233. ctx, SessionId('bare'), { provider: 'mock', model: 'mock' }, session,
  234. )
  235. const { agent } = prepared
  236. prepared.markPublished()
  237. prepared.start()
  238. const dispose = prepared.dispose
  239. agent.send([{ type: 'text', text: 'go' }])
  240. await new Promise(r => setTimeout(r, 30))
  241. expect(agent.status).toBe('running')
  242. const idle = agent.whenIdle() // queues an internal waiter (running)
  243. const disposal = dispose() // settles the waiter synchronously; whenIdle chains done
  244. await idle
  245. expect(agent.status).toBe('disposed')
  246. await disposal
  247. })
  248. it('whenIdle() subscribed while running survives a FIBER dispose (no hung promise)', async () => {
  249. // The waiter is internal agent state, NOT an effect-scoped ctx.on listener:
  250. // disposing the OWNING fiber runs the agent's listener disposers, which would
  251. // have dropped a ctx.on-based waiter before the 'disposed' transition and
  252. // hung the promise. With internal waiters, the fiber disposer still settles it.
  253. const adapter = new MockAdapter(['hang'])
  254. const ctx = await harness(adapter)
  255. let agent!: Agent
  256. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  257. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  258. }, { inject: ['agentLoop'] }))
  259. send(agent, 'go')
  260. await new Promise(r => setTimeout(r, 30))
  261. expect(agent.status).toBe('running')
  262. const idle = agent.whenIdle() // queued while running
  263. await fiber.dispose() // tears the fiber down (drops agent listeners)
  264. await idle // must resolve, not hang
  265. expect(agent.status).toBe('disposed')
  266. })
  267. it('whenIdle() on a disposed agent awaits the loop exit (done), not just the status flip', async () => {
  268. // The disposer emits agent/status('disposed') BEFORE the driver loop
  269. // unwinds, so whenIdle() must chain `done` (true quiescence) on the
  270. // disposed path. Dispose a running agent, then assert whenIdle() resolves
  271. // only after `done` — i.e. the loop has actually exited.
  272. const adapter = new MockAdapter(['hang'])
  273. const ctx = await harness(adapter)
  274. let agent!: Agent
  275. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  276. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  277. }, { inject: ['agentLoop'] }))
  278. send(agent, 'go')
  279. await new Promise(r => setTimeout(r, 30))
  280. let doneResolved = false
  281. void driverDone(agent).then(() => { doneResolved = true })
  282. await fiber.dispose() // sets status disposed, aborts, drains the loop
  283. expect(agent.status).toBe('disposed')
  284. // whenIdle() must not resolve before `done` has — chaining `done` is the
  285. // quiescence guarantee. By here dispose() awaited the loop, so done is
  286. // settled; whenIdle resolves and done is observed resolved.
  287. await agent.whenIdle()
  288. expect(doneResolved).toBe(true)
  289. })
  290. it('contains a throwing agent/status listener on the running transition', async () => {
  291. const adapter = new MockAdapter([textResponse('ok')])
  292. const ctx = await harness(adapter)
  293. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  294. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  295. ctx.on('agent/status', (_subject, status) => {
  296. if (status === 'running') throw new Error('bad running listener')
  297. })
  298. send(agent, 'go')
  299. await agent.whenIdle()
  300. expect(adapter.requests).toHaveLength(1)
  301. expect(agent.status).toBe('idle')
  302. expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent event "agent/status" listener threw'))
  303. warn.mockRestore()
  304. })
  305. it('contains a throwing agent/status listener on the idle transition', async () => {
  306. const adapter = new MockAdapter([textResponse('ok')])
  307. const ctx = await harness(adapter)
  308. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  309. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  310. ctx.on('agent/status', (_subject, status) => {
  311. if (status === 'idle') throw new Error('bad idle listener')
  312. })
  313. send(agent, 'go')
  314. await agent.whenIdle()
  315. expect(adapter.requests).toHaveLength(1)
  316. expect(agent.status).toBe('idle')
  317. expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent event "agent/status" listener threw'))
  318. warn.mockRestore()
  319. })
  320. })