loop.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { StreamChunk, ToolResultBlock } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { SessionEventType, TurnEndReason } from '@deepseek-ai/dsh-session'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry from '@deepseek-ai/dsh-agent'
  8. import AgentLoop, { LoopAgent } from '@deepseek-ai/dsh-agent-loop'
  9. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  10. async function harness(adapter: MockAdapter) {
  11. const ctx = new Context()
  12. await ctx.plugin(LlmService)
  13. await ctx.plugin(SessionStore)
  14. await ctx.plugin(SystemPrompt)
  15. await ctx.plugin(ToolRegistry)
  16. await ctx.plugin(AgentRegistry)
  17. await ctx.plugin(AgentLoop, { agents: [] })
  18. ctx.llm.registerAdapter(['mock'], adapter)
  19. return ctx
  20. }
  21. /**
  22. * Wait for the agent's NEXT transition to idle. Always event-based: callers
  23. * invoke this right after send(), when the loop hasn't woken yet (status is
  24. * still 'idle' synchronously), so polling the current status would lie.
  25. */
  26. function waitForIdle(ctx: Context, agent: LoopAgent): Promise<void> {
  27. return new Promise((resolve) => {
  28. const dispose = ctx.on('agent/status', (subject, status) => {
  29. if (subject === agent && status === 'idle') {
  30. dispose()
  31. resolve()
  32. }
  33. })
  34. })
  35. }
  36. function send(agent: LoopAgent, text: string) {
  37. agent.send([{ type: 'text', text }])
  38. }
  39. describe('agent loop', () => {
  40. it('runs a simple turn: queued message → model → idle, with ordered events', async () => {
  41. const adapter = new MockAdapter([textResponse('hello there')])
  42. const ctx = await harness(adapter)
  43. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  44. const order: string[] = []
  45. for (const name of ['agent/turn-start', 'agent/step-start', 'agent/step-end', 'agent/turn-end'] as const) {
  46. ctx.on(name, () => void order.push(name))
  47. }
  48. send(agent, 'hi')
  49. await waitForIdle(ctx, agent)
  50. expect(order).toEqual(['agent/turn-start', 'agent/step-start', 'agent/step-end', 'agent/turn-end'])
  51. const types = agent.session.events.map(e => e.type)
  52. // user message recorded before turn/start, assembled message + usage present
  53. expect(types[0]).toBe('user/message')
  54. expect(types[1]).toBe('turn/start')
  55. expect(types).toContain('assistant/message')
  56. expect(types).toContain('usage')
  57. expect(types.at(-1)).toBe('turn/end')
  58. // derived history: user + assistant
  59. const messages = agent.session.deriveMessages()
  60. expect(messages.map(m => m.role)).toEqual(['user', 'assistant'])
  61. expect(messages[1].content).toEqual([{ type: 'text', text: 'hello there' }])
  62. })
  63. it('round-trips tool calls: model requests tool → executes → result in next request', async () => {
  64. const adapter = new MockAdapter([
  65. toolCallResponse('c1', 'echo', { text: 'ping' }, 'calling echo'),
  66. textResponse('done'),
  67. ])
  68. const ctx = await harness(adapter)
  69. ctx.tools.register(defineTool({
  70. name: 'echo',
  71. description: 'echo back',
  72. parameters: { text: { type: 'string' } },
  73. async execute(args) {
  74. return [{ type: 'text', text: `echo: ${args.text}` }]
  75. },
  76. }))
  77. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  78. send(agent, 'use the tool')
  79. await waitForIdle(ctx, agent)
  80. // two model calls happened (tool-call step, then final step)
  81. expect(adapter.requests).toHaveLength(2)
  82. // the second request's derived history contains the tool result
  83. const secondMessages = adapter.requests[1].messages
  84. const toolResultMessage = secondMessages.find(m =>
  85. m.content.some(b => b.type === 'tool-result'))
  86. expect(toolResultMessage).toBeDefined()
  87. const block = toolResultMessage!.content.find(b => b.type === 'tool-result')!
  88. expect(block).toMatchObject({ toolCallId: 'c1', isError: false })
  89. expect((block as ToolResultBlock).content).toEqual([{ type: 'text', text: 'echo: ping' }])
  90. // session log records call + result
  91. const types = agent.session.events.map(e => e.type)
  92. expect(types).toContain('tool/call')
  93. expect(types).toContain('tool/result')
  94. })
  95. it('passes assembled system prompt and tool schemas into the request', async () => {
  96. const adapter = new MockAdapter([textResponse('ok')])
  97. const ctx = await harness(adapter)
  98. ctx.systemPrompt.section({ name: 'persona', order: 0, text: 'You are a test agent.' })
  99. ctx.tools.register(defineTool({
  100. name: 'noop',
  101. description: 'does nothing',
  102. parameters: {},
  103. async execute() {
  104. return []
  105. },
  106. }))
  107. const agent = ctx.agentLoop.create('a1', { model: 'mock', systemPrompt: 'Agent-specific suffix.' })
  108. send(agent, 'hi')
  109. await waitForIdle(ctx, agent)
  110. const request = adapter.requests[0]
  111. expect(request.system).toBe('You are a test agent.\n\nAgent-specific suffix.')
  112. expect(request.tools?.map(t => t.name)).toEqual(['noop'])
  113. })
  114. it('records raw chunks for replay and emits agent/stream-chunk', async () => {
  115. const adapter = new MockAdapter([textResponse('abc')])
  116. const ctx = await harness(adapter)
  117. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  118. const streamed: StreamChunk[] = []
  119. ctx.on('agent/stream-chunk', (_agent, _turn, _step, chunk) => void streamed.push(chunk))
  120. send(agent, 'hi')
  121. await waitForIdle(ctx, agent)
  122. const chunkEvents = agent.session.events.filter(e => e.type === 'assistant/chunk')
  123. // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7
  124. expect(chunkEvents).toHaveLength(7)
  125. expect(streamed).toHaveLength(7)
  126. // replay: chunk events alone re-assemble to the recorded assistant message
  127. const deltaText = chunkEvents
  128. .flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : [])
  129. .filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
  130. .map(c => c.text)
  131. .join('')
  132. expect(deltaText).toBe('abc')
  133. })
  134. it('injects steering between steps and continues the turn', async () => {
  135. const adapter = new MockAdapter([
  136. toolCallResponse('c1', 'slow', {}),
  137. textResponse('addressed the steering'),
  138. ])
  139. const ctx = await harness(adapter)
  140. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  141. ctx.tools.register(defineTool({
  142. name: 'slow',
  143. description: '',
  144. parameters: {},
  145. async execute() {
  146. // steer while the turn is running (during tool execution)
  147. agent.steer([{ type: 'text', text: 'change of plans' }])
  148. return [{ type: 'text', text: 'tool done' }]
  149. },
  150. }))
  151. send(agent, 'start')
  152. await waitForIdle(ctx, agent)
  153. const types = agent.session.events.map(e => e.type)
  154. expect(types).toContain('steering/message')
  155. // steering recorded before the second step's request derived its history
  156. const steeringSeq = agent.session.events.find(e => e.type === 'steering/message')!.seq
  157. const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1]
  158. expect(secondStepStart).toBeDefined()
  159. expect(steeringSeq).toBeLessThan(secondStepStart!.seq)
  160. // the second model request saw the steering content
  161. const secondRequest = adapter.requests[1]
  162. const flat = JSON.stringify(secondRequest.messages)
  163. expect(flat).toContain('change of plans')
  164. })
  165. it('steering while idle behaves like send (starts a turn)', async () => {
  166. const adapter = new MockAdapter([textResponse('ok')])
  167. const ctx = await harness(adapter)
  168. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  169. agent.steer([{ type: 'text', text: 'hello' }])
  170. await waitForIdle(ctx, agent)
  171. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  172. })
  173. it('inject() appends context visible to the next request without starting a turn', async () => {
  174. const adapter = new MockAdapter([textResponse('ok')])
  175. const ctx = await harness(adapter)
  176. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  177. agent.inject([{ type: 'text', text: 'file changed: a.ts' }], { source: { kind: 'plugin', plugin: 'watcher' } })
  178. // no turn started
  179. await new Promise(r => setTimeout(r, 20))
  180. expect(agent.status).toBe('idle')
  181. expect(adapter.requests).toHaveLength(0)
  182. send(agent, 'go')
  183. await waitForIdle(ctx, agent)
  184. const flat = JSON.stringify(adapter.requests[0].messages)
  185. expect(flat).toContain('file changed: a.ts')
  186. expect(flat).toContain('<context source=\\"plugin\\">')
  187. })
  188. it('agent/turn-continuation can force-continue (/loop pattern) and force-stop', async () => {
  189. // force-continue: model never calls tools, but a plugin forces 3 steps
  190. const adapter = new MockAdapter([
  191. textResponse('step 1'),
  192. textResponse('step 2'),
  193. textResponse('step 3'),
  194. ])
  195. const ctx = await harness(adapter)
  196. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  197. let steps = 0
  198. ctx.on('agent/step-end', () => void steps++)
  199. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  200. if (steps < 3) return true
  201. return next()
  202. })
  203. send(agent, 'go')
  204. await waitForIdle(ctx, agent)
  205. expect(steps).toBe(3)
  206. expect(adapter.requests).toHaveLength(3)
  207. })
  208. it('agent/turn-continuation can veto continuation despite tool calls (budget-guard pattern)', async () => {
  209. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  210. const ctx = await harness(adapter)
  211. ctx.tools.register(defineTool({
  212. name: 'echo',
  213. description: '',
  214. parameters: { text: { type: 'string' } },
  215. async execute(args) {
  216. return [{ type: 'text', text: String(args.text) }]
  217. },
  218. }))
  219. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  220. ctx.on('agent/turn-continuation', async () => false as const)
  221. send(agent, 'go')
  222. await waitForIdle(ctx, agent)
  223. // only one model call despite the tool call requesting a follow-up
  224. expect(adapter.requests).toHaveLength(1)
  225. // tool still executed before the decision
  226. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  227. })
  228. it('agent/request waterfall can rewrite the request (model-switch pattern)', async () => {
  229. const adapter = new MockAdapter([textResponse('ok')])
  230. const ctx = await harness(adapter)
  231. ctx.llm.registerAdapter(['other-model'], adapter)
  232. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  233. ctx.on('agent/request', async (_agent, _turn, _step, options, next) => {
  234. options.model = 'other-model'
  235. return next()
  236. })
  237. send(agent, 'hi')
  238. await waitForIdle(ctx, agent)
  239. expect(adapter.requests[0].model).toBe('other-model')
  240. })
  241. it('abort() mid-stream ends the turn with reason aborted', async () => {
  242. const adapter = new MockAdapter(['hang'])
  243. const ctx = await harness(adapter)
  244. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  245. const reasons: TurnEndReason[] = []
  246. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  247. send(agent, 'go')
  248. // wait until the stream is hanging, then abort
  249. await new Promise(r => setTimeout(r, 30))
  250. expect(agent.status).toBe('running')
  251. agent.abort('user interrupt')
  252. await waitForIdle(ctx, agent)
  253. expect(reasons).toEqual([{ kind: 'aborted', reason: 'user interrupt' }])
  254. })
  255. it('chains queued messages into consecutive turns', async () => {
  256. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  257. const ctx = await harness(adapter)
  258. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  259. const turns: number[] = []
  260. ctx.on('agent/turn-start', (_agent, turn) => void turns.push(turn))
  261. // queue two messages while idle — first starts turn 1 immediately;
  262. // queue the second during turn 1 via a stream-chunk hook
  263. let queued = false
  264. ctx.on('agent/stream-chunk', () => {
  265. if (!queued) {
  266. queued = true
  267. send(agent, 'second message')
  268. }
  269. })
  270. send(agent, 'first message')
  271. await waitForIdle(ctx, agent)
  272. expect(turns).toEqual([1, 2])
  273. expect(adapter.requests).toHaveLength(2)
  274. })
  275. it('awaits session/flush at turn end (persistence checkpoint)', async () => {
  276. const adapter = new MockAdapter([textResponse('ok')])
  277. const ctx = await harness(adapter)
  278. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  279. let flushed = 0
  280. let flushedBeforeIdle = false
  281. ctx.on('session/flush', async (session) => {
  282. await new Promise(r => setTimeout(r, 10))
  283. flushed++
  284. flushedBeforeIdle = agent.status !== 'idle'
  285. void session
  286. })
  287. send(agent, 'hi')
  288. await waitForIdle(ctx, agent)
  289. expect(flushed).toBe(1)
  290. expect(flushedBeforeIdle).toBe(true)
  291. })
  292. it('errors from the model surface as agent/error and end the turn', async () => {
  293. const adapter = new MockAdapter([]) // script exhausted → throws
  294. const ctx = await harness(adapter)
  295. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  296. const errors: Error[] = []
  297. const reasons: TurnEndReason[] = []
  298. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  299. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  300. send(agent, 'hi')
  301. await waitForIdle(ctx, agent)
  302. expect(errors).toHaveLength(1)
  303. expect(errors[0].message).toContain('script exhausted')
  304. expect(reasons[0]).toMatchObject({ kind: 'error' })
  305. expect(agent.session.events.some(e => e.type === 'error')).toBe(true)
  306. })
  307. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  308. const adapter = new MockAdapter(['hang'])
  309. const ctx = await harness(adapter)
  310. let agent!: LoopAgent
  311. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  312. agent = inner.agentLoop.create('scoped', { model: 'mock' })
  313. }, { inject: ['agentLoop'] }))
  314. expect(ctx.agents.get('scoped')).toBe(agent)
  315. send(agent, 'go')
  316. await new Promise(r => setTimeout(r, 30))
  317. expect(agent.status).toBe('running')
  318. await fiber.dispose()
  319. await agent.done
  320. expect(agent.status).toBe('disposed')
  321. expect(ctx.agents.get('scoped')).toBeUndefined()
  322. expect(() => send(agent, 'too late')).toThrow('disposed')
  323. })
  324. it('replays a session log into an identical derived history', async () => {
  325. const adapter = new MockAdapter([
  326. toolCallResponse('c1', 'echo', { text: 'x' }),
  327. textResponse('done'),
  328. ])
  329. const ctx = await harness(adapter)
  330. ctx.tools.register(defineTool({
  331. name: 'echo',
  332. description: '',
  333. parameters: { text: { type: 'string' } },
  334. async execute(args) {
  335. return [{ type: 'text', text: String(args.text) }]
  336. },
  337. }))
  338. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  339. send(agent, 'run')
  340. await waitForIdle(ctx, agent)
  341. const replayed = ctx.sessions.create('replayed', [...agent.session.events])
  342. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  343. // event-by-event identity of types
  344. expect(replayed.events.map(e => e.type)).toEqual(
  345. agent.session.events.map(e => e.type as SessionEventType))
  346. })
  347. })