loop.spec.ts 46 KB

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