loop.spec.ts 34 KB

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