loop.spec.ts 34 KB

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