loop.spec.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { CallId, StreamChunk } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { SessionId, 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, { AgentId } from '@deepseek-ai/dsh-agent'
  8. import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  9. import { MockAdapter, maxTokensResponse, 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: ReactLoopAgent): 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: ReactLoopAgent, 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(AgentId('a1'), { model: 'mock' })
  44. // Turn boundaries are live agent/* emits; step boundaries are durable
  45. // session events only (no agent/* mirror). Interleave both feeds in fire
  46. // order to assert the full boundary nesting.
  47. const order: string[] = []
  48. for (const name of ['agent/turn-start', 'agent/turn-end'] as const) {
  49. ctx.on(name, () => void order.push(name))
  50. }
  51. ctx.on('session/event', (_session, event) => {
  52. if (event.type === 'step/start' || event.type === 'step/end') order.push(event.type)
  53. })
  54. send(agent, 'hi')
  55. await waitForIdle(ctx, agent)
  56. expect(order).toEqual(['agent/turn-start', 'step/start', 'step/end', 'agent/turn-end'])
  57. const types = agent.session.events.map(e => e.type)
  58. // turn/start opens the turn, THEN the queued user message is recorded inside
  59. // it (every event is turn-enclosed), then the assembled message (carrying the
  60. // step's usage).
  61. expect(types[0]).toBe('turn/start')
  62. expect(types[1]).toBe('user/message')
  63. expect(types).toContain('assistant/message')
  64. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  65. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data.usage).toEqual({ inputTokens: 10, outputTokens: 'hello there'.length })
  66. expect(types.at(-1)).toBe('turn/end')
  67. // derived history: user + assistant
  68. const messages = agent.session.deriveMessages()
  69. expect(messages.map(m => m.role)).toEqual(['user', 'assistant'])
  70. expect(messages[1]!.content).toEqual([{ type: 'text', text: 'hello there' }])
  71. })
  72. it('round-trips tool calls: model requests tool → executes → result in next request', async () => {
  73. const adapter = new MockAdapter([
  74. toolCallResponse('c1', 'echo', { text: 'ping' }, 'calling echo'),
  75. textResponse('done'),
  76. ])
  77. const ctx = await harness(adapter)
  78. ctx.tools.register(defineTool({
  79. name: 'echo',
  80. description: 'echo back',
  81. parameters: { text: { type: 'string' } },
  82. async execute(args) {
  83. return [{ type: 'text', text: `echo: ${args.text}` }]
  84. },
  85. }))
  86. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  87. send(agent, 'use the tool')
  88. await waitForIdle(ctx, agent)
  89. // two model calls happened (tool-call step, then final step)
  90. expect(adapter.requests).toHaveLength(2)
  91. // the second request's derived history contains the tool result
  92. const secondMessages = adapter.requests[1]!.messages
  93. const toolResultMessage = secondMessages.find(m =>
  94. m.content.some(b => b.type === 'tool-result'))
  95. expect(toolResultMessage).toBeDefined()
  96. const block = toolResultMessage!.content.find(b => b.type === 'tool-result')!
  97. expect(block).toMatchObject({ toolCallId: 'c1', isError: false })
  98. expect((block).content).toEqual([{ type: 'text', text: 'echo: ping' }])
  99. // session log records call + result
  100. const types = agent.session.events.map(e => e.type)
  101. expect(types).toContain('tool/call')
  102. expect(types).toContain('tool/result')
  103. })
  104. it('passes assembled system prompt and tool schemas into the request', async () => {
  105. const adapter = new MockAdapter([textResponse('ok')])
  106. const ctx = await harness(adapter)
  107. ctx.systemPrompt.section({ name: 'persona', order: 0, text: 'You are a test agent.' })
  108. ctx.tools.register(defineTool({
  109. name: 'noop',
  110. description: 'does nothing',
  111. parameters: {},
  112. async execute() {
  113. return []
  114. },
  115. }))
  116. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock', systemPrompt: 'Agent-specific suffix.' })
  117. send(agent, 'hi')
  118. await waitForIdle(ctx, agent)
  119. const request = adapter.requests[0]
  120. expect(request!.system).toBe('You are a test agent.\n\nAgent-specific suffix.')
  121. expect(request!.tools?.map(t => t.name)).toEqual(['noop'])
  122. })
  123. it('records raw chunks for replay and emits agent/stream-chunk', async () => {
  124. const adapter = new MockAdapter([textResponse('abc')])
  125. const ctx = await harness(adapter)
  126. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  127. const streamed: StreamChunk[] = []
  128. ctx.on('agent/stream-chunk', (_agent, _turn, _step, chunk) => void streamed.push(chunk))
  129. send(agent, 'hi')
  130. await waitForIdle(ctx, agent)
  131. const chunkEvents = agent.session.events.filter(e => e.type === 'assistant/chunk')
  132. // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7
  133. expect(chunkEvents).toHaveLength(7)
  134. expect(streamed).toHaveLength(7)
  135. // replay: chunk events alone re-assemble to the recorded assistant message
  136. const deltaText = chunkEvents
  137. .flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : [])
  138. .filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
  139. .map(c => c.text)
  140. .join('')
  141. expect(deltaText).toBe('abc')
  142. })
  143. it('injects steering between steps and continues the turn', async () => {
  144. const adapter = new MockAdapter([
  145. toolCallResponse('c1', 'slow', {}),
  146. textResponse('addressed the steering'),
  147. ])
  148. const ctx = await harness(adapter)
  149. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  150. ctx.tools.register(defineTool({
  151. name: 'slow',
  152. description: '',
  153. parameters: {},
  154. async execute() {
  155. // steer while the turn is running (during tool execution)
  156. agent.steer([{ type: 'text', text: 'change of plans' }])
  157. return [{ type: 'text', text: 'tool done' }]
  158. },
  159. }))
  160. send(agent, 'start')
  161. await waitForIdle(ctx, agent)
  162. const types = agent.session.events.map(e => e.type)
  163. expect(types).toContain('steering/message')
  164. // steering recorded before the second step's request derived its history
  165. const steeringSeq = agent.session.events.find(e => e.type === 'steering/message')!.seq
  166. const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1]
  167. expect(secondStepStart).toBeDefined()
  168. expect(steeringSeq).toBeLessThan(secondStepStart!.seq)
  169. // the second model request saw the steering content
  170. const secondRequest = adapter.requests[1]
  171. const flat = JSON.stringify(secondRequest!.messages)
  172. expect(flat).toContain('change of plans')
  173. })
  174. it('steering while idle behaves like send (starts a turn)', async () => {
  175. const adapter = new MockAdapter([textResponse('ok')])
  176. const ctx = await harness(adapter)
  177. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  178. agent.steer([{ type: 'text', text: 'hello' }])
  179. await waitForIdle(ctx, agent)
  180. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  181. })
  182. it('inject() while idle wraps context in a one-shot turn, visible to the next request', async () => {
  183. const adapter = new MockAdapter([textResponse('ok')])
  184. const ctx = await harness(adapter)
  185. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  186. agent.inject([{ type: 'text', text: 'file changed: a.ts' }], { source: { kind: 'plugin', plugin: 'watcher' } })
  187. // The idle inject records a self-contained turn (turn/start → context/message
  188. // → turn/end) so the event stays turn-enclosed, but does NOT run the model.
  189. await new Promise(r => setTimeout(r, 20))
  190. expect(agent.status).toBe('idle')
  191. expect(adapter.requests).toHaveLength(0)
  192. const injectedTurn = agent.session.events.filter(e => e.type === 'turn/start')
  193. expect(injectedTurn).toHaveLength(1)
  194. const it0 = injectedTurn[0]!
  195. expect(it0.type === 'turn/start' && it0.data.trigger.kind).toBe('injection')
  196. expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed
  197. send(agent, 'go')
  198. await waitForIdle(ctx, agent)
  199. const flat = JSON.stringify(adapter.requests[0]!.messages)
  200. expect(flat).toContain('file changed: a.ts')
  201. expect(flat).toContain('<context source=\\"plugin\\">')
  202. })
  203. it('inject() while running appends into the open turn (no extra synthetic turn)', async () => {
  204. const adapter = new MockAdapter([
  205. toolCallResponse('c1', 'noticer', {}, 'calling'),
  206. textResponse('done'),
  207. ])
  208. const ctx = await harness(adapter)
  209. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  210. // A tool that injects mid-execution: at this point the agent is running, so
  211. // inject must append the context/message into the ALREADY-open turn rather
  212. // than wrap it in its own one-shot turn.
  213. ctx.tools.register(defineTool({
  214. name: 'noticer',
  215. description: 'injects a notice',
  216. parameters: {},
  217. async execute() {
  218. agent.inject([{ type: 'text', text: 'mid-turn notice' }], { source: { kind: 'plugin', plugin: 'x' } })
  219. return [{ type: 'text', text: 'ok' }]
  220. },
  221. }))
  222. send(agent, 'go')
  223. await waitForIdle(ctx, agent)
  224. // Exactly ONE turn ran (no synthetic injection turn), and the mid-turn
  225. // context/message sits inside it.
  226. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  227. expect(turnStarts).toHaveLength(1)
  228. const ts0 = turnStarts[0]!
  229. expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
  230. expect(agent.session.events.some(e => e.type === 'context/message')).toBe(true)
  231. })
  232. it('agent/turn-continuation can force-continue (/loop pattern) and force-stop', async () => {
  233. // force-continue: model never calls tools, but a plugin forces 3 steps
  234. const adapter = new MockAdapter([
  235. textResponse('step 1'),
  236. textResponse('step 2'),
  237. textResponse('step 3'),
  238. ])
  239. const ctx = await harness(adapter)
  240. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  241. let steps = 0
  242. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  243. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  244. if (steps < 3) return { action: 'continue' as const }
  245. return next()
  246. })
  247. send(agent, 'go')
  248. await waitForIdle(ctx, agent)
  249. expect(steps).toBe(3)
  250. expect(adapter.requests).toHaveLength(3)
  251. })
  252. it('agent/turn-continuation can veto continuation despite tool calls (budget-guard pattern)', async () => {
  253. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  254. const ctx = await harness(adapter)
  255. ctx.tools.register(defineTool({
  256. name: 'echo',
  257. description: '',
  258. parameters: { text: { type: 'string' } },
  259. async execute(args) {
  260. return [{ type: 'text', text: String(args.text) }]
  261. },
  262. }))
  263. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  264. ctx.on('agent/turn-continuation', async () => ({ action: 'stop' }) as const)
  265. send(agent, 'go')
  266. await waitForIdle(ctx, agent)
  267. // only one model call despite the tool call requesting a follow-up
  268. expect(adapter.requests).toHaveLength(1)
  269. // tool still executed before the decision
  270. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  271. })
  272. it('agent/request waterfall can rewrite the request (model-switch pattern)', async () => {
  273. const adapter = new MockAdapter([textResponse('ok')])
  274. const ctx = await harness(adapter)
  275. ctx.llm.registerAdapter(['other-model'], adapter)
  276. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  277. ctx.on('agent/request', async (_agent, _turn, _step, options, next) => {
  278. options.model = 'other-model'
  279. return next()
  280. })
  281. send(agent, 'hi')
  282. await waitForIdle(ctx, agent)
  283. expect(adapter.requests[0]!.model).toBe('other-model')
  284. })
  285. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  286. const adapter = new MockAdapter(['hang'])
  287. const ctx = await harness(adapter)
  288. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  289. const reasons: TurnEndReason[] = []
  290. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  291. send(agent, 'go')
  292. // wait until the stream is hanging, then cancel
  293. await new Promise(r => setTimeout(r, 30))
  294. expect(agent.status).toBe('running')
  295. agent.cancel('user interrupt')
  296. await waitForIdle(ctx, agent)
  297. expect(reasons).toEqual([{ kind: 'aborted', reason: 'user interrupt' }])
  298. })
  299. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  300. // A single step that ends with a max-tokens finish (no tool calls): the
  301. // turn stops by default and ends max-tokens, not completed.
  302. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  303. const ctx = await harness(adapter)
  304. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  305. const reasons: TurnEndReason[] = []
  306. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  307. send(agent, 'go')
  308. await waitForIdle(ctx, agent)
  309. expect(adapter.requests).toHaveLength(1)
  310. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  311. // and the reason is recorded in the log's turn/end event
  312. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  313. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  314. })
  315. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  316. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so
  317. // continuation must be FORCED to reach step 2 which finishes normally
  318. // (stop). The rule "any max-tokens step surfaces as max-tokens" means the
  319. // turn ends max-tokens even though the LAST step completed cleanly.
  320. const adapter = new MockAdapter([
  321. maxTokensResponse('first half'),
  322. textResponse('second half'),
  323. ])
  324. const ctx = await harness(adapter)
  325. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  326. let steps = 0
  327. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  328. // Force exactly one continuation (step 1 → step 2), then defer to default
  329. // (step 2 is a plain stop with no tool calls → stops).
  330. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  331. if (steps < 2) return { action: 'continue' as const }
  332. return next()
  333. })
  334. const reasons: TurnEndReason[] = []
  335. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  336. send(agent, 'go')
  337. await waitForIdle(ctx, agent)
  338. expect(steps).toBe(2)
  339. expect(adapter.requests).toHaveLength(2)
  340. expect(adapter.requests[1]!.messages).toEqual([
  341. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  342. { role: 'assistant', content: [{ type: 'text', text: 'first half' }] },
  343. ])
  344. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  345. })
  346. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  347. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  348. // stop. The per-turn reason must be independent — turn 2 ends completed.
  349. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  350. const ctx = await harness(adapter)
  351. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  352. const reasons: TurnEndReason[] = []
  353. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  354. send(agent, 'first')
  355. await waitForIdle(ctx, agent)
  356. send(agent, 'second')
  357. await waitForIdle(ctx, agent)
  358. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  359. })
  360. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  361. const callId = CallId('c1')
  362. const adapter = new MockAdapter([[
  363. { type: 'block-start', index: 0, blockType: 'tool-call' },
  364. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  365. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  366. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  367. { type: 'finish', reason: { kind: 'max-tokens' } },
  368. ]])
  369. const ctx = await harness(adapter)
  370. let executions = 0
  371. ctx.tools.register(defineTool({
  372. name: 'echo',
  373. description: '',
  374. parameters: { text: { type: 'string' } },
  375. async execute() {
  376. executions += 1
  377. return [{ type: 'text', text: 'should not run' }]
  378. },
  379. }))
  380. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  381. const reasons: TurnEndReason[] = []
  382. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  383. send(agent, 'go')
  384. await waitForIdle(ctx, agent)
  385. expect(executions).toBe(0)
  386. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  387. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  388. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  389. // No-data-loss: a max-tokens step whose only content was a dropped tool call
  390. // has EMPTY assistant content, but its usage must still be represented. It
  391. // rides on an (empty-content) assistant/message — there is no standalone
  392. // usage event — and that empty message is skipped by deriveMessages(), so
  393. // the derived history above is NOT corrupted by a spurious assistant turn.
  394. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  395. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  396. turn: 1, step: 1, content: [], usage: { inputTokens: 10, outputTokens: 5 },
  397. })
  398. })
  399. it('appends no assistant/message for a max-tokens step with empty content and no usage', async () => {
  400. // A max-tokens step truncated to a dropped tool call AND with no usage chunk
  401. // has nothing to record: empty content and no accounting → no assistant/message
  402. // (the empty-content host exists only to carry usage). The turn still ends
  403. // max-tokens.
  404. const callId = CallId('c1')
  405. const adapter = new MockAdapter([[
  406. { type: 'block-start', index: 0, blockType: 'tool-call' },
  407. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  408. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  409. { type: 'finish', reason: { kind: 'max-tokens' } },
  410. ]])
  411. const ctx = await harness(adapter)
  412. ctx.tools.register(defineTool({
  413. name: 'echo',
  414. description: '',
  415. parameters: { text: { type: 'string' } },
  416. async execute() { return [{ type: 'text', text: 'should not run' }] },
  417. }))
  418. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  419. const reasons: TurnEndReason[] = []
  420. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  421. send(agent, 'go')
  422. await waitForIdle(ctx, agent)
  423. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  424. expect(agent.session.events.some(e => e.type === 'assistant/message')).toBe(false)
  425. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  426. })
  427. it('appends no assistant/message for a normal stop finish with empty content and no usage', async () => {
  428. // A clean `stop` finish that streamed nothing assembled (no blocks) and
  429. // carried no usage chunk has nothing to record: the content-or-usage guard
  430. // on the normal step path suppresses a pure trace-only empty assistant/message.
  431. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  432. const ctx = await harness(adapter)
  433. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  434. const reasons: TurnEndReason[] = []
  435. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  436. send(agent, 'go')
  437. await waitForIdle(ctx, agent)
  438. expect(reasons).toEqual([{ kind: 'completed' }])
  439. expect(agent.session.events.some(e => e.type === 'assistant/message')).toBe(false)
  440. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  441. })
  442. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  443. const callId = CallId('c1')
  444. const adapter = new MockAdapter([[
  445. { type: 'block-start', index: 0, blockType: 'text' },
  446. { type: 'text-delta', index: 0, text: 'partial text' },
  447. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  448. { type: 'block-start', index: 1, blockType: 'tool-call' },
  449. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  450. { type: 'finish', reason: { kind: 'max-tokens' } },
  451. ]])
  452. const ctx = await harness(adapter)
  453. let stepResults = 0
  454. ctx.on('agent/step-result', async (_agent, _turn, _step, message, next) => {
  455. stepResults += 1
  456. expect(message.content).toEqual([{ type: 'text', text: 'partial text' }])
  457. return next()
  458. })
  459. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  460. send(agent, 'go')
  461. await waitForIdle(ctx, agent)
  462. expect(stepResults).toBe(1)
  463. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  464. expect(agent.session.deriveMessages()).toEqual([
  465. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  466. { role: 'assistant', content: [{ type: 'text', text: 'partial text' }] },
  467. ])
  468. })
  469. it('stops the turn when a step/end session-event listener failure has recorded an error', async () => {
  470. const adapter = new MockAdapter([
  471. toolCallResponse('c1', 'echo', { text: 'x' }),
  472. textResponse('should not run'),
  473. ])
  474. const ctx = await harness(adapter)
  475. ctx.tools.register(defineTool({
  476. name: 'echo',
  477. description: '',
  478. parameters: { text: { type: 'string' } },
  479. async execute(args) {
  480. return [{ type: 'text', text: String(args.text) }]
  481. },
  482. }))
  483. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  484. let threw = false
  485. // A throwing step/end session-event listener is the surviving boundary-listener
  486. // failure path (step boundaries have no agent/* mirror): closeStep contains it
  487. // and surfaces it as a turn error rather than stranding the turn open.
  488. ctx.on('session/event', (_session, event) => {
  489. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  490. })
  491. send(agent, 'go')
  492. await waitForIdle(ctx, agent)
  493. expect(adapter.requests).toHaveLength(1)
  494. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  495. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('error')
  496. })
  497. it('chains queued messages into consecutive turns', async () => {
  498. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  499. const ctx = await harness(adapter)
  500. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  501. const turns: number[] = []
  502. ctx.on('agent/turn-start', (_agent, turn) => void turns.push(turn))
  503. // queue two messages while idle — first starts turn 1 immediately;
  504. // queue the second during turn 1 via a stream-chunk hook
  505. let queued = false
  506. ctx.on('agent/stream-chunk', () => {
  507. if (!queued) {
  508. queued = true
  509. send(agent, 'second message')
  510. }
  511. })
  512. send(agent, 'first message')
  513. await waitForIdle(ctx, agent)
  514. expect(turns).toEqual([1, 2])
  515. expect(adapter.requests).toHaveLength(2)
  516. })
  517. it('awaits session/flush at turn end (persistence checkpoint)', async () => {
  518. const adapter = new MockAdapter([textResponse('ok')])
  519. const ctx = await harness(adapter)
  520. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  521. let flushed = 0
  522. let flushedBeforeIdle = false
  523. ctx.on('session/flush', async (session) => {
  524. await new Promise(r => setTimeout(r, 10))
  525. flushed++
  526. flushedBeforeIdle = agent.status !== 'idle'
  527. void session
  528. })
  529. send(agent, 'hi')
  530. await waitForIdle(ctx, agent)
  531. expect(flushed).toBe(1)
  532. expect(flushedBeforeIdle).toBe(true)
  533. })
  534. it('errors from the model surface as agent/error and end the turn', async () => {
  535. const adapter = new MockAdapter([]) // script exhausted → throws
  536. const ctx = await harness(adapter)
  537. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  538. const errors: Error[] = []
  539. const reasons: TurnEndReason[] = []
  540. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  541. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  542. send(agent, 'hi')
  543. await waitForIdle(ctx, agent)
  544. expect(errors).toHaveLength(1)
  545. expect(errors[0]!.message).toContain('script exhausted')
  546. expect(reasons[0]).toMatchObject({ kind: 'error' })
  547. // The durable failure lives entirely on turn/end.reason (with the failing
  548. // step), not a standalone error event.
  549. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  550. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  551. })
  552. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  553. const adapter = new MockAdapter(['hang'])
  554. const ctx = await harness(adapter)
  555. let agent!: ReactLoopAgent
  556. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  557. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  558. }, { inject: ['agentLoop'] }))
  559. expect(ctx.agents.get(AgentId('scoped'))).toBe(agent)
  560. send(agent, 'go')
  561. await new Promise(r => setTimeout(r, 30))
  562. expect(agent.status).toBe('running')
  563. await fiber.dispose()
  564. await agent.done
  565. expect(agent.status).toBe('disposed')
  566. expect(ctx.agents.get(AgentId('scoped'))).toBeUndefined()
  567. expect(() => { send(agent, 'too late') }).toThrow('disposed')
  568. })
  569. it('creates agents from config on startup', async () => {
  570. const adapter = new MockAdapter([textResponse('from config')])
  571. const ctx = new Context()
  572. await ctx.plugin(LlmService)
  573. await ctx.plugin(SessionStore)
  574. await ctx.plugin(SystemPrompt)
  575. await ctx.plugin(ToolRegistry)
  576. await ctx.plugin(AgentRegistry)
  577. await ctx.plugin(AgentLoop, {
  578. agents: [{ id: AgentId('config-agent'), model: 'mock', systemPrompt: 'Config prompt' }],
  579. })
  580. ctx.llm.registerAdapter(['mock'], adapter)
  581. const agent = ctx.agents.get(AgentId('config-agent'))! as ReactLoopAgent
  582. expect(agent).toBeDefined()
  583. expect(agent.id).toBe('config-agent')
  584. expect(agent.options.model).toBe('mock')
  585. // the agent is alive: send triggers a turn
  586. send(agent, 'hi')
  587. await waitForIdle(ctx, agent)
  588. expect(adapter.requests).toHaveLength(1)
  589. })
  590. it('replays a session log into an identical derived history', async () => {
  591. const adapter = new MockAdapter([
  592. toolCallResponse('c1', 'echo', { text: 'x' }),
  593. textResponse('done'),
  594. ])
  595. const ctx = await harness(adapter)
  596. ctx.tools.register(defineTool({
  597. name: 'echo',
  598. description: '',
  599. parameters: { text: { type: 'string' } },
  600. async execute(args) {
  601. return [{ type: 'text', text: String(args.text) }]
  602. },
  603. }))
  604. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  605. send(agent, 'run')
  606. await waitForIdle(ctx, agent)
  607. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  608. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  609. // event-by-event identity of types
  610. expect(replayed.events.map(e => e.type)).toEqual(
  611. agent.session.events.map(e => e.type))
  612. })
  613. })