loop.spec.ts 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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, persona = '') {
  11. const ctx = new Context()
  12. await ctx.plugin(LlmService)
  13. await ctx.plugin(SessionStore)
  14. await ctx.plugin(SystemPrompt, { persona })
  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. // The persona is a TEMPLATE: {{model}} is the loop-registered variable
  129. // projecting this agent's configured model, so the model knows its own name.
  130. const ctx = await harness(adapter, 'You are a test agent on {{model}}.')
  131. ctx.systemPrompt.section({ name: 'tool:noop', order: 100, text: 'Use the noop tool wisely.' })
  132. ctx.tools.register(defineTool({
  133. name: 'noop',
  134. description: 'does nothing',
  135. parameters: {},
  136. async execute() {
  137. return []
  138. },
  139. }))
  140. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  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, 'Working in {{cwd}}.')
  150. const handle = await ctx.agents.create({
  151. agentId: AgentId('a-cwd'),
  152. sessionId: SessionId('s-cwd'),
  153. meta: { cwd: '/work/space' },
  154. agentOptions: { model: 'mock' },
  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 missing cwd variable must fail one turn without preventing a later valid turn.
  163. const adapter = new MockAdapter([textResponse('ok after rescue')])
  164. const ctx = await harness(adapter, 'In {{cwd}}.')
  165. const errors: Error[] = []
  166. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  167. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  168. send(agent, 'hi')
  169. await waitForIdle(ctx, agent)
  170. expect(adapter.requests).toHaveLength(0) // the request was never sent
  171. expect(errors.some(e => e.message.includes('no value for this assembly'))).toBe(true)
  172. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  173. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('error')
  174. // The loop survived: a waterfall listener rescues {{cwd}} and the SAME
  175. // agent completes a real model turn.
  176. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  177. assembly.variables['cwd'] = '/rescued'
  178. return next()
  179. })
  180. send(agent, 'again')
  181. await waitForIdle(ctx, agent)
  182. expect(adapter.requests).toHaveLength(1)
  183. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nIn /rescued.')
  184. const turnEnds = agent.session.events.filter(e => e.type === 'turn/end')
  185. expect(turnEnds).toHaveLength(2)
  186. expect(turnEnds[1]?.type === 'turn/end' && turnEnds[1].data.reason.kind).toBe('completed')
  187. })
  188. it('supports the model-via-agent/request path with a {{model}} persona: the supplier states it via the assemble waterfall', async () => {
  189. // AgentOptions.model unset: the model arrives in the agent/request
  190. // waterfall (the loop's documented fallback — see runStep's no-model
  191. // error). {{model}} renders BEFORE that waterfall, so the SAME plugin
  192. // states the fact early on system-prompt/assemble — the owner of a
  193. // late-bound fact owns stating it wherever it is claimed.
  194. const adapter = new MockAdapter([textResponse('ok')])
  195. const ctx = await harness(adapter, 'You run on {{model}}.')
  196. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  197. assembly.variables['model'] = 'mock'
  198. return next()
  199. })
  200. ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => {
  201. return { ...config, model: 'mock' }
  202. })
  203. const agent = ctx.agentLoop.create(AgentId('a-late-model'), {})
  204. send(agent, 'hi')
  205. await waitForIdle(ctx, agent)
  206. expect(adapter.requests).toHaveLength(1)
  207. expect(adapter.requests[0]!.model).toBe('mock')
  208. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou run on mock.')
  209. })
  210. it.each([
  211. ['BigInt', { n: 1n }],
  212. ['Map', new Map([['key', 'value']])],
  213. ['class instance', new (class ResultMeta { x = 1 })()],
  214. ])('normalizes non-JSON tool meta (%s) before the durable result commit', async (_kind, meta) => {
  215. const adapter = new MockAdapter([
  216. toolCallResponse('bad-meta-call', 'bad-meta', {}, 'calling'),
  217. textResponse('recovered'),
  218. ])
  219. const ctx = await harness(adapter)
  220. ctx.tools.register(defineTool({
  221. name: 'bad-meta',
  222. description: 'returns invalid durable metadata',
  223. parameters: {},
  224. execute: () => Promise.resolve({ content: [{ type: 'text' as const, text: 'apparent success' }], meta }),
  225. }))
  226. const agent = ctx.agentLoop.create(AgentId('bad-meta-agent'), { model: 'mock' })
  227. send(agent, 'use the tool')
  228. await waitForIdle(ctx, agent)
  229. const result = agent.session.events.find(event => event.type === 'tool/result')
  230. expect(result?.type).toBe('tool/result')
  231. if (result?.type === 'tool/result') {
  232. expect(result.data.callId).toBe('bad-meta-call')
  233. expect(result.data.isError).toBe(true)
  234. expect(result.data.meta).toBeUndefined()
  235. expect(result.data.content).toEqual([{
  236. type: 'text',
  237. text: 'Error: tool result must be losslessly JSON-serializable',
  238. }])
  239. }
  240. // The normalized failure was durably logged and fed back to the model; the
  241. // turn continued normally instead of failing after an apparent success.
  242. expect(adapter.requests).toHaveLength(2)
  243. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('losslessly JSON-serializable')
  244. })
  245. it('omits the system field when a system-prompt/assemble veto empties the assembly', async () => {
  246. // The documented escape valve: a deployment that must drop the harness
  247. // openers short-circuits the assemble waterfall; the request then carries
  248. // NO system field at all (not an empty string).
  249. const adapter = new MockAdapter([textResponse('ok')])
  250. const ctx = await harness(adapter)
  251. ctx.on('system-prompt/assemble', async () => ({ sections: [], tools: [], variables: {} }))
  252. const agent = ctx.agentLoop.create(AgentId('a-no-system'), { model: 'mock' })
  253. send(agent, 'hi')
  254. await waitForIdle(ctx, agent)
  255. expect(adapter.requests).toHaveLength(1)
  256. expect('system' in adapter.requests[0]!).toBe(false)
  257. })
  258. it('records raw chunks for replay as assistant/chunk session events', async () => {
  259. const adapter = new MockAdapter([textResponse('abc')])
  260. const ctx = await harness(adapter)
  261. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  262. send(agent, 'hi')
  263. await waitForIdle(ctx, agent)
  264. const chunkEvents = agent.session.events.filter(e => e.type === 'assistant/chunk')
  265. // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7
  266. expect(chunkEvents).toHaveLength(7)
  267. // replay: chunk events alone re-assemble to the recorded assistant message
  268. const deltaText = chunkEvents
  269. .flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : [])
  270. .filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
  271. .map(c => c.text)
  272. .join('')
  273. expect(deltaText).toBe('abc')
  274. })
  275. it('injects steering between steps and continues the turn', async () => {
  276. const adapter = new MockAdapter([
  277. toolCallResponse('c1', 'slow', {}),
  278. textResponse('addressed the steering'),
  279. ])
  280. const ctx = await harness(adapter)
  281. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  282. ctx.tools.register(defineTool({
  283. name: 'slow',
  284. description: '',
  285. parameters: {},
  286. async execute() {
  287. // steer while the turn is running (during tool execution)
  288. agent.steer([{ type: 'text', text: 'change of plans' }])
  289. return [{ type: 'text', text: 'tool done' }]
  290. },
  291. }))
  292. send(agent, 'start')
  293. await waitForIdle(ctx, agent)
  294. const types = agent.session.events.map(e => e.type)
  295. expect(types).toContain('steering/message')
  296. // steering recorded before the second step's request derived its history
  297. const steeringSeq = agent.session.events.find(e => e.type === 'steering/message')!.seq
  298. const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1]
  299. expect(secondStepStart).toBeDefined()
  300. expect(steeringSeq).toBeLessThan(secondStepStart!.seq)
  301. // the second model request saw the steering content
  302. const secondRequest = adapter.requests[1]
  303. const flat = JSON.stringify(secondRequest!.messages)
  304. expect(flat).toContain('change of plans')
  305. })
  306. it('steering while idle behaves like send (starts a turn)', async () => {
  307. const adapter = new MockAdapter([textResponse('ok')])
  308. const ctx = await harness(adapter)
  309. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  310. agent.steer([{ type: 'text', text: 'hello' }])
  311. await waitForIdle(ctx, agent)
  312. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  313. })
  314. it('inject() while idle wraps context in a one-shot turn, visible to the next request', async () => {
  315. const adapter = new MockAdapter([textResponse('ok')])
  316. const ctx = await harness(adapter)
  317. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  318. agent.inject([{ type: 'text', text: 'file changed: a.ts' }], { source: { kind: 'plugin', plugin: 'watcher' } })
  319. // The idle inject records a self-contained turn (turn/start → context/message
  320. // → turn/end) so the event stays turn-enclosed, but does NOT run the model.
  321. await new Promise(r => setTimeout(r, 20))
  322. expect(agent.status).toBe('idle')
  323. expect(adapter.requests).toHaveLength(0)
  324. const injectedTurn = agent.session.events.filter(e => e.type === 'turn/start')
  325. expect(injectedTurn).toHaveLength(1)
  326. const it0 = injectedTurn[0]!
  327. expect(it0.type === 'turn/start' && it0.data.trigger.kind).toBe('injection')
  328. expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed
  329. send(agent, 'go')
  330. await waitForIdle(ctx, agent)
  331. const flat = JSON.stringify(adapter.requests[0]!.messages)
  332. expect(flat).toContain('file changed: a.ts')
  333. expect(flat).toContain('<context source=\\"plugin\\">')
  334. })
  335. it('inject() can persist raw structured context without the generic context envelope', async () => {
  336. const adapter = new MockAdapter([textResponse('ok')])
  337. const ctx = await harness(adapter)
  338. const agent = ctx.agentLoop.create(AgentId('raw-context'), { model: 'mock' })
  339. const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
  340. const meta = {
  341. kind: 'workspace-instructions',
  342. version: 1,
  343. changes: [{ action: 'set', scope: 'pkg', path: 'pkg/AGENTS.md', digest: 'abc123' }],
  344. }
  345. agent.inject([{ type: 'text', text }], {
  346. source: { kind: 'plugin', plugin: 'workspace-context' },
  347. envelope: 'raw',
  348. meta,
  349. })
  350. send(agent, 'go')
  351. await waitForIdle(ctx, agent)
  352. const contextEvent = agent.session.events.find(event => event.type === 'context/message')
  353. expect(contextEvent?.type === 'context/message' && contextEvent.data).toMatchObject({ envelope: 'raw', meta })
  354. const requestText = JSON.stringify(adapter.requests[0]!.messages)
  355. expect(requestText).toContain('Additional instructions from: pkg/AGENTS.md')
  356. expect(requestText).not.toContain('<context source=')
  357. })
  358. it('inject() while running appends into the open turn (no extra synthetic turn)', async () => {
  359. const adapter = new MockAdapter([
  360. toolCallResponse('c1', 'noticer', {}, 'calling'),
  361. textResponse('done'),
  362. ])
  363. const ctx = await harness(adapter)
  364. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  365. // A tool that injects mid-execution: at this point the agent is running, so
  366. // inject must append the context/message into the ALREADY-open turn rather
  367. // than wrap it in its own one-shot turn.
  368. ctx.tools.register(defineTool({
  369. name: 'noticer',
  370. description: 'injects a notice',
  371. parameters: {},
  372. async execute() {
  373. agent.inject([{ type: 'text', text: 'mid-turn notice' }], { source: { kind: 'plugin', plugin: 'x' } })
  374. return [{ type: 'text', text: 'ok' }]
  375. },
  376. }))
  377. send(agent, 'go')
  378. await waitForIdle(ctx, agent)
  379. // Exactly ONE turn ran (no synthetic injection turn), and the mid-turn
  380. // context/message sits inside it.
  381. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  382. expect(turnStarts).toHaveLength(1)
  383. const ts0 = turnStarts[0]!
  384. expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
  385. expect(agent.session.events.some(e => e.type === 'context/message')).toBe(true)
  386. })
  387. it('agent/turn-continuation can force-continue (/loop pattern) and force-stop', async () => {
  388. // force-continue: model never calls tools, but a plugin forces 3 steps
  389. const adapter = new MockAdapter([
  390. textResponse('step 1'),
  391. textResponse('step 2'),
  392. textResponse('step 3'),
  393. ])
  394. const ctx = await harness(adapter)
  395. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  396. let steps = 0
  397. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  398. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  399. if (steps < 3) return { action: 'continue' as const }
  400. return next()
  401. })
  402. send(agent, 'go')
  403. await waitForIdle(ctx, agent)
  404. expect(steps).toBe(3)
  405. expect(adapter.requests).toHaveLength(3)
  406. })
  407. it('agent/turn-continuation can veto continuation despite tool calls (budget-guard pattern)', async () => {
  408. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  409. const ctx = await harness(adapter)
  410. ctx.tools.register(defineTool({
  411. name: 'echo',
  412. description: '',
  413. parameters: { text: { type: 'string' } },
  414. async execute(args) {
  415. return [{ type: 'text', text: String(args.text) }]
  416. },
  417. }))
  418. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  419. ctx.on('agent/turn-continuation', async () => ({ action: 'stop' }) as const)
  420. send(agent, 'go')
  421. await waitForIdle(ctx, agent)
  422. // only one model call despite the tool call requesting a follow-up
  423. expect(adapter.requests).toHaveLength(1)
  424. // tool still executed before the decision
  425. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  426. })
  427. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  428. const adapter = new MockAdapter([textResponse('ok')])
  429. const ctx = await harness(adapter)
  430. ctx.llm.registerAdapter(['other-model'], adapter)
  431. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  432. ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => {
  433. // The seed is frozen — config is not a mutable per-call knob; a switch
  434. // is proposed by returning a replacement, and the loop logs it.
  435. expect(Object.isFrozen(config)).toBe(true)
  436. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  437. return { ...config, model: 'other-model' }
  438. })
  439. send(agent, 'hi')
  440. await waitForIdle(ctx, agent)
  441. expect(adapter.requests[0]!.model).toBe('other-model')
  442. // The header event records what the request ACTUALLY used — the switch is
  443. // a reconstructable fact, not silent drift.
  444. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  445. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  446. })
  447. it('agent/pre-step fires once per step before the step is opened', async () => {
  448. // Two steps (a tool call, then a final text turn) → two model calls → two
  449. // pre-step fires, each carrying the assembled full system prompt, BEFORE
  450. // the step is opened and its request is derived (the request the adapter
  451. // sees reflects any surface state at fire time).
  452. const adapter = new MockAdapter([
  453. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  454. textResponse('done'),
  455. ])
  456. const ctx = await harness(adapter)
  457. ctx.tools.register(defineTool({
  458. name: 'echo', description: 'echo', parameters: {},
  459. async execute() { return [{ type: 'text', text: 'echoed' }] },
  460. }))
  461. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  462. const fires: { turn: number; step: number; fullSystemPrompt: string }[] = []
  463. ctx.on('agent/pre-step', (subject, turn, step, fullSystemPrompt) => {
  464. if (subject === agent) fires.push({ turn, step, fullSystemPrompt })
  465. })
  466. send(agent, 'go')
  467. await waitForIdle(ctx, agent)
  468. // One fire per step, in order, each with the assembled system prompt
  469. // (here just the loop's own harness-identity section — no persona set).
  470. const HARNESS = 'You are an AI agent powered by the DeepSeek Harness SDK.'
  471. expect(fires).toEqual([
  472. { turn: 1, step: 1, fullSystemPrompt: HARNESS },
  473. { turn: 1, step: 2, fullSystemPrompt: HARNESS },
  474. ])
  475. })
  476. it('agent/pre-step fires BEFORE the step it precedes opens (events land outside the step)', async () => {
  477. // The append lands before step/start, yet derive happens afterwards and the
  478. // same step's request must include it.
  479. const adapter = new MockAdapter([textResponse('ok')])
  480. const ctx = await harness(adapter)
  481. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  482. let injected = false
  483. ctx.on('agent/pre-step', (subject) => {
  484. if (subject === agent && !injected) {
  485. injected = true
  486. subject.session.append('context/message', {
  487. content: [{ type: 'text', text: 'INJECTED-IN-PRE-STEP' }],
  488. source: { kind: 'plugin', plugin: 'test' },
  489. }, { surfaceOp: 'append' })
  490. }
  491. })
  492. send(agent, 'go')
  493. await waitForIdle(ctx, agent)
  494. // The adapter's request includes the node injected during pre-step (derive
  495. // reflects it).
  496. const text = JSON.stringify(adapter.requests[0]!.messages)
  497. expect(text).toContain('INJECTED-IN-PRE-STEP')
  498. // And the injected event sits BEFORE the first step/start in the log —
  499. // the seam fired outside the step.
  500. const events = agent.session.events
  501. const injectedSeq = events.find(e => e.type === 'context/message')!.seq
  502. const firstStepStartSeq = events.find(e => e.type === 'step/start')!.seq
  503. expect(injectedSeq).toBeLessThan(firstStepStartSeq)
  504. })
  505. it('a throwing agent/pre-step listener ends the turn (error), not the loop', async () => {
  506. // Before step/start, a pre-step throw reaches the turn catch: no step needs
  507. // closing, the turn records error, and the loop remains available.
  508. const adapter = new MockAdapter([textResponse('second turn ok')])
  509. const ctx = await harness(adapter)
  510. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  511. let throwOnce = true
  512. ctx.on('agent/pre-step', () => {
  513. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  514. })
  515. const errors: Error[] = []
  516. ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
  517. send(agent, 'first')
  518. await waitForIdle(ctx, agent)
  519. // The first turn failed at step 1 (no model call happened), surfaced via
  520. // agent/error, with the durable failure on turn/end.reason.
  521. expect(errors).toHaveLength(1)
  522. expect(errors[0]!.message).toContain('boom in pre-step')
  523. expect(adapter.requests.length).toBe(0)
  524. const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
  525. expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  526. // The step opened-and-closed count stays balanced even though it never ran.
  527. const types = agent.session.events.map(e => e.type)
  528. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  529. // The loop survived: a second prompt runs a normal completed turn.
  530. send(agent, 'second')
  531. await waitForIdle(ctx, agent)
  532. expect(adapter.requests.length).toBe(1)
  533. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  534. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  535. })
  536. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  537. const adapter = new MockAdapter(['hang'])
  538. const ctx = await harness(adapter)
  539. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  540. const reasons: TurnEndReason[] = []
  541. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  542. send(agent, 'go')
  543. // wait until the stream is hanging, then cancel
  544. await new Promise(r => setTimeout(r, 30))
  545. expect(agent.status).toBe('running')
  546. agent.cancel('user interrupt')
  547. await waitForIdle(ctx, agent)
  548. expect(reasons).toEqual([{ kind: 'aborted', reason: 'user interrupt' }])
  549. })
  550. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  551. // A single step that ends with a max-tokens finish (no tool calls): the
  552. // turn stops by default and ends max-tokens, not completed.
  553. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  554. const ctx = await harness(adapter)
  555. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  556. const reasons: TurnEndReason[] = []
  557. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  558. send(agent, 'go')
  559. await waitForIdle(ctx, agent)
  560. expect(adapter.requests).toHaveLength(1)
  561. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  562. // Assert the durable row, not only the live listener.
  563. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  564. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  565. })
  566. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  567. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  568. // must be FORCED to reach step 2 which finishes normally (stop).
  569. const adapter = new MockAdapter([
  570. maxTokensResponse('first half'),
  571. textResponse('second half'),
  572. ])
  573. const ctx = await harness(adapter)
  574. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  575. let steps = 0
  576. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  577. // Force exactly one continuation (step 1 → step 2), then defer to default
  578. // (step 2 is a plain stop with no tool calls → stops).
  579. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  580. if (steps < 2) return { action: 'continue' as const }
  581. return next()
  582. })
  583. const reasons: TurnEndReason[] = []
  584. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  585. send(agent, 'go')
  586. await waitForIdle(ctx, agent)
  587. expect(steps).toBe(2)
  588. expect(adapter.requests).toHaveLength(2)
  589. expect(adapter.requests[1]!.messages).toEqual([
  590. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  591. { role: 'assistant', content: [{ type: 'text', text: 'first half' }] },
  592. ])
  593. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  594. })
  595. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  596. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  597. // stop. The per-turn reason must be independent — turn 2 ends completed.
  598. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  599. const ctx = await harness(adapter)
  600. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  601. const reasons: TurnEndReason[] = []
  602. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  603. send(agent, 'first')
  604. await waitForIdle(ctx, agent)
  605. send(agent, 'second')
  606. await waitForIdle(ctx, agent)
  607. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  608. })
  609. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  610. const callId = CallId('c1')
  611. const adapter = new MockAdapter([[
  612. { type: 'block-start', index: 0, blockType: 'tool-call' },
  613. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  614. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  615. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  616. { type: 'finish', reason: { kind: 'max-tokens' } },
  617. ]])
  618. const ctx = await harness(adapter)
  619. let executions = 0
  620. ctx.tools.register(defineTool({
  621. name: 'echo',
  622. description: '',
  623. parameters: { text: { type: 'string' } },
  624. async execute() {
  625. executions += 1
  626. return [{ type: 'text', text: 'should not run' }]
  627. },
  628. }))
  629. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  630. const reasons: TurnEndReason[] = []
  631. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  632. send(agent, 'go')
  633. await waitForIdle(ctx, agent)
  634. expect(executions).toBe(0)
  635. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  636. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  637. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  638. // Empty content still needs an assistant/message to carry usage; derivation
  639. // skips that host so it does not create a spurious assistant turn.
  640. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  641. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  642. turn: 1, step: 1, content: [], usage: { inputTokens: 10, outputTokens: 5 },
  643. })
  644. })
  645. it('appends no assistant/message for a max-tokens step with empty content and no usage', async () => {
  646. // A max-tokens step truncated to a dropped tool call AND with no usage chunk has nothing to
  647. // record: empty content and no accounting → no assistant/message (the empty-content host
  648. // exists only to carry usage).
  649. const callId = CallId('c1')
  650. const adapter = new MockAdapter([[
  651. { type: 'block-start', index: 0, blockType: 'tool-call' },
  652. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  653. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  654. { type: 'finish', reason: { kind: 'max-tokens' } },
  655. ]])
  656. const ctx = await harness(adapter)
  657. ctx.tools.register(defineTool({
  658. name: 'echo',
  659. description: '',
  660. parameters: { text: { type: 'string' } },
  661. async execute() { return [{ type: 'text', text: 'should not run' }] },
  662. }))
  663. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  664. const reasons: TurnEndReason[] = []
  665. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  666. send(agent, 'go')
  667. await waitForIdle(ctx, agent)
  668. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  669. expect(agent.session.events.some(e => e.type === 'assistant/message')).toBe(false)
  670. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  671. })
  672. it('appends no assistant/message for a normal stop finish with empty content and no usage', async () => {
  673. // A clean `stop` finish that streamed nothing assembled (no blocks) and
  674. // carried no usage chunk has nothing to record: the content-or-usage guard
  675. // on the normal step path suppresses a pure trace-only empty assistant/message.
  676. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  677. const ctx = await harness(adapter)
  678. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  679. const reasons: TurnEndReason[] = []
  680. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  681. send(agent, 'go')
  682. await waitForIdle(ctx, agent)
  683. expect(reasons).toEqual([{ kind: 'completed' }])
  684. expect(agent.session.events.some(e => e.type === 'assistant/message')).toBe(false)
  685. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  686. })
  687. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  688. const callId = CallId('c1')
  689. const adapter = new MockAdapter([[
  690. { type: 'block-start', index: 0, blockType: 'text' },
  691. { type: 'text-delta', index: 0, text: 'partial text' },
  692. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  693. { type: 'block-start', index: 1, blockType: 'tool-call' },
  694. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  695. { type: 'finish', reason: { kind: 'max-tokens' } },
  696. ]])
  697. const ctx = await harness(adapter)
  698. let stepResults = 0
  699. ctx.on('agent/step-result', async (_agent, _turn, _step, message, next) => {
  700. stepResults += 1
  701. expect(message.content).toEqual([{ type: 'text', text: 'partial text' }])
  702. return next()
  703. })
  704. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  705. send(agent, 'go')
  706. await waitForIdle(ctx, agent)
  707. expect(stepResults).toBe(1)
  708. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  709. expect(agent.session.deriveMessages()).toEqual([
  710. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  711. { role: 'assistant', content: [{ type: 'text', text: 'partial text' }] },
  712. ])
  713. })
  714. it('contains a step/end observer failure without changing continuation', async () => {
  715. const adapter = new MockAdapter([
  716. toolCallResponse('c1', 'echo', { text: 'x' }),
  717. textResponse('continued after tool call'),
  718. ])
  719. const ctx = await harness(adapter)
  720. ctx.tools.register(defineTool({
  721. name: 'echo',
  722. description: '',
  723. parameters: { text: { type: 'string' } },
  724. async execute(args) {
  725. return [{ type: 'text', text: String(args.text) }]
  726. },
  727. }))
  728. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  729. let threw = false
  730. // Post-commit session observers cannot control the loop. The tool call still
  731. // drives the second model request, and the turn completes normally.
  732. ctx.on('session/event', (_session, event) => {
  733. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  734. })
  735. send(agent, 'go')
  736. await waitForIdle(ctx, agent)
  737. expect(adapter.requests).toHaveLength(2)
  738. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  739. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  740. })
  741. it('keeps same-tick sends in separate turns and checkpoints before the next starts', async () => {
  742. const adapter = new MockAdapter([textResponse('first answer'), textResponse('second answer')])
  743. const ctx = await harness(adapter)
  744. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  745. const firstFlush = Promise.withResolvers<undefined>()
  746. const releaseFirstFlush = Promise.withResolvers<undefined>()
  747. let flushes = 0
  748. ctx.on('session/flush', async (session) => {
  749. if (session !== agent.session) return
  750. flushes += 1
  751. if (flushes === 1) {
  752. firstFlush.resolve(undefined)
  753. await releaseFirstFlush.promise
  754. }
  755. })
  756. const turns: number[] = []
  757. ctx.on('session/event', (session, event) => {
  758. if (session === agent.session && event.type === 'turn/start') turns.push(event.data.turn)
  759. })
  760. const idle = waitForIdle(ctx, agent)
  761. send(agent, 'first message')
  762. send(agent, 'second message')
  763. await firstFlush.promise
  764. expect(turns).toEqual([1])
  765. expect(adapter.requests).toHaveLength(1)
  766. releaseFirstFlush.resolve(undefined)
  767. await idle
  768. expect(turns).toEqual([1, 2])
  769. expect(flushes).toBe(2)
  770. expect(adapter.requests).toHaveLength(2)
  771. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first answer')
  772. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  773. })
  774. it('keeps a reentrant agent/queued send as the next independent turn', async () => {
  775. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  776. const ctx = await harness(adapter)
  777. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  778. let nested = false
  779. ctx.on('agent/queued', (subject) => {
  780. if (subject !== agent || nested) return
  781. nested = true
  782. send(agent, 'queued listener message')
  783. })
  784. const idle = waitForIdle(ctx, agent)
  785. send(agent, 'outer message')
  786. await idle
  787. const turns = agent.session.events.filter(event => event.type === 'turn/start')
  788. const messages = agent.session.events
  789. .filter(event => event.type === 'user/message')
  790. .map(event => event.data.content)
  791. expect(turns).toHaveLength(2)
  792. expect(messages).toEqual([
  793. [{ type: 'text', text: 'outer message' }],
  794. [{ type: 'text', text: 'queued listener message' }],
  795. ])
  796. })
  797. it('preserves independent turn sources across an adjacent microtask send', async () => {
  798. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  799. const ctx = await harness(adapter)
  800. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  801. const idle = waitForIdle(ctx, agent)
  802. agent.send([{ type: 'text', text: 'user message' }])
  803. await Promise.resolve()
  804. agent.send(
  805. [{ type: 'text', text: 'plugin message' }],
  806. { source: { kind: 'plugin', plugin: 'test' } },
  807. )
  808. await idle
  809. const triggers = agent.session.events
  810. .filter(event => event.type === 'turn/start')
  811. .map(event => event.data.trigger)
  812. const sources = agent.session.events
  813. .filter(event => event.type === 'user/message')
  814. .map(event => event.data.source)
  815. expect(triggers).toEqual([
  816. { kind: 'message', source: { kind: 'user' } },
  817. { kind: 'message', source: { kind: 'plugin', plugin: 'test' } },
  818. ])
  819. expect(sources).toEqual([
  820. { kind: 'user' },
  821. { kind: 'plugin', plugin: 'test' },
  822. ])
  823. })
  824. it('keeps a session-listener send after dequeue in the following turn', async () => {
  825. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  826. const ctx = await harness(adapter)
  827. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  828. const turns: number[] = []
  829. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  830. // queue two messages while idle — first starts turn 1 immediately;
  831. // queue the second during turn 1 when the first assistant chunk streams
  832. let queued = false
  833. ctx.on('session/event', (_s, event) => {
  834. if (event.type === 'assistant/chunk' && !queued) {
  835. queued = true
  836. send(agent, 'second message')
  837. }
  838. })
  839. send(agent, 'first message')
  840. await waitForIdle(ctx, agent)
  841. expect(turns).toEqual([1, 2])
  842. expect(adapter.requests).toHaveLength(2)
  843. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first')
  844. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  845. })
  846. it('keeps a model-adapter callback send in the following turn', async () => {
  847. const agentRef: { current?: ReactLoopAgent } = {}
  848. const adapter = new MockAdapter([
  849. () => {
  850. const agent = agentRef.current
  851. if (agent === undefined) throw new Error('model callback ran before agent setup')
  852. send(agent, 'model callback message')
  853. return textResponse('first')
  854. },
  855. textResponse('second'),
  856. ])
  857. const ctx = await harness(adapter)
  858. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  859. agentRef.current = agent
  860. const idle = waitForIdle(ctx, agent)
  861. send(agent, 'outer message')
  862. await idle
  863. const messages = agent.session.events
  864. .filter(event => event.type === 'user/message')
  865. .map(event => event.data.content)
  866. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  867. expect(messages).toEqual([
  868. [{ type: 'text', text: 'outer message' }],
  869. [{ type: 'text', text: 'model callback message' }],
  870. ])
  871. })
  872. it('awaits session/flush at turn end (persistence checkpoint)', async () => {
  873. const adapter = new MockAdapter([textResponse('ok')])
  874. const ctx = await harness(adapter)
  875. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  876. let flushed = 0
  877. let flushedBeforeIdle = false
  878. ctx.on('session/flush', async (session) => {
  879. await new Promise(r => setTimeout(r, 10))
  880. flushed++
  881. flushedBeforeIdle = agent.status !== 'idle'
  882. void session
  883. })
  884. send(agent, 'hi')
  885. await waitForIdle(ctx, agent)
  886. expect(flushed).toBe(1)
  887. expect(flushedBeforeIdle).toBe(true)
  888. })
  889. it('errors from the model surface as agent/error and end the turn', async () => {
  890. const adapter = new MockAdapter([]) // script exhausted → throws
  891. const ctx = await harness(adapter)
  892. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  893. const errors: Error[] = []
  894. const reasons: TurnEndReason[] = []
  895. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  896. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  897. send(agent, 'hi')
  898. await waitForIdle(ctx, agent)
  899. expect(errors).toHaveLength(1)
  900. expect(errors[0]!.message).toContain('script exhausted')
  901. expect(reasons[0]).toMatchObject({ kind: 'error' })
  902. // The durable failure lives entirely on turn/end.reason (with the failing
  903. // step), not a standalone error event.
  904. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  905. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  906. })
  907. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  908. const adapter = new MockAdapter(['hang'])
  909. const ctx = await harness(adapter)
  910. let agent!: ReactLoopAgent
  911. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  912. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  913. }, { inject: ['agentLoop'] }))
  914. expect(ctx.agents.get(AgentId('scoped'))).toBe(agent)
  915. send(agent, 'go')
  916. await new Promise(r => setTimeout(r, 30))
  917. expect(agent.status).toBe('running')
  918. await fiber.dispose()
  919. await agent.done
  920. expect(agent.status).toBe('disposed')
  921. expect(ctx.agents.get(AgentId('scoped'))).toBeUndefined()
  922. expect(() => { send(agent, 'too late') }).toThrow('disposed')
  923. })
  924. it('creates agents from config on startup', async () => {
  925. const adapter = new MockAdapter([textResponse('from config')])
  926. const ctx = new Context()
  927. await ctx.plugin(LlmService)
  928. await ctx.plugin(SessionStore)
  929. await ctx.plugin(SystemPrompt)
  930. await ctx.plugin(ToolRegistry)
  931. await ctx.plugin(AgentRegistry)
  932. await ctx.plugin(AgentLoop, {
  933. agents: [{ id: AgentId('config-agent'), model: 'mock' }],
  934. })
  935. ctx.llm.registerAdapter(['mock'], adapter)
  936. const agent = ctx.agents.get(AgentId('config-agent'))! as ReactLoopAgent
  937. expect(agent).toBeDefined()
  938. expect(agent.id).toBe('config-agent')
  939. expect(agent.options.model).toBe('mock')
  940. // the agent is alive: send triggers a turn
  941. send(agent, 'hi')
  942. await waitForIdle(ctx, agent)
  943. expect(adapter.requests).toHaveLength(1)
  944. })
  945. it('attaches config agent cwd to the fresh session header', async () => {
  946. const ctx = new Context()
  947. await ctx.plugin(LlmService)
  948. await ctx.plugin(SessionStore)
  949. await ctx.plugin(SystemPrompt)
  950. await ctx.plugin(ToolRegistry)
  951. await ctx.plugin(AgentRegistry)
  952. await ctx.plugin(AgentLoop, {
  953. agents: [{ id: AgentId('config-agent'), model: 'mock', cwd: '/work/project' }],
  954. })
  955. const agent = ctx.agents.get(AgentId('config-agent'))! as ReactLoopAgent
  956. expect(agent.session.header.cwd).toBe('/work/project')
  957. })
  958. it('replays a session log into an identical derived history', async () => {
  959. const adapter = new MockAdapter([
  960. toolCallResponse('c1', 'echo', { text: 'x' }),
  961. textResponse('done'),
  962. ])
  963. const ctx = await harness(adapter)
  964. ctx.tools.register(defineTool({
  965. name: 'echo',
  966. description: '',
  967. parameters: { text: { type: 'string' } },
  968. async execute(args) {
  969. return [{ type: 'text', text: String(args.text) }]
  970. },
  971. }))
  972. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  973. send(agent, 'run')
  974. await waitForIdle(ctx, agent)
  975. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  976. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  977. // event-by-event identity of types
  978. expect(replayed.events.map(e => e.type)).toEqual(
  979. agent.session.events.map(e => e.type))
  980. })
  981. })