loop.spec.ts 46 KB

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