loop.spec.ts 28 KB

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