loop.spec.ts 38 KB

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