loop.spec.ts 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { createUserMessage, 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, { defineContentToolFixture } 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.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
  41. }
  42. describe('agent loop', () => {
  43. it.each([0, -1, 1.5, Number.NaN, Number.MAX_SAFE_INTEGER + 1])(
  44. 'rejects invalid AgentOptions.maxTokens %s before publication',
  45. async (maxTokens) => {
  46. const ctx = await harness(new MockAdapter([]))
  47. expect(() => ctx.agentLoop.create(
  48. SessionId('invalid-max-tokens'),
  49. { provider: 'mock', model: 'mock', maxTokens },
  50. )).toThrow('agent maxTokens must be a positive safe integer')
  51. expect(ctx.agents.list()).toEqual([])
  52. expect(ctx.sessions.list()).toEqual([])
  53. },
  54. )
  55. it('seeds a valid AgentOptions.maxTokens into the first model request', async () => {
  56. const adapter = new MockAdapter([textResponse('bounded')])
  57. const ctx = await harness(adapter)
  58. const agent = ctx.agentLoop.create(
  59. SessionId('valid-max-tokens'),
  60. { provider: 'mock', model: 'mock', maxTokens: 256 },
  61. )
  62. send(agent, 'use the configured output limit')
  63. await waitForIdle(ctx, agent)
  64. expect(adapter.requests[0]?.maxTokens).toBe(256)
  65. })
  66. it('runs a simple turn: queued message → model → idle, with ordered events', async () => {
  67. const adapter = new MockAdapter([textResponse('hello there')])
  68. const ctx = await harness(adapter)
  69. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  70. // All boundaries — turn and step — are durable session events on the
  71. // session/event feed (no agent/* mirror). Record them in fire order to
  72. // assert the full boundary nesting.
  73. const order: string[] = []
  74. ctx.on('session/event', (_session, event) => {
  75. if (event.type === 'turn/start' || event.type === 'step/start' || event.type === 'step/end' || event.type === 'turn/end') {
  76. order.push(event.type)
  77. }
  78. })
  79. send(agent, 'hi')
  80. await waitForIdle(ctx, agent)
  81. expect(order).toEqual(['turn/start', 'step/start', 'step/end', 'turn/end'])
  82. const types = agent.session.events.map(e => e.type)
  83. // turn/start opens the turn, THEN the queued user message is recorded inside
  84. // it (every event is turn-enclosed), then the assembled message (carrying the
  85. // step's usage).
  86. expect(types[0]).toBe('turn/start')
  87. expect(types[1]).toBe('user/message')
  88. expect(types).toContain('assistant/message')
  89. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  90. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data.usage).toEqual({ inputTokens: 10, outputTokens: 'hello there'.length })
  91. expect(types.at(-1)).toBe('turn/end')
  92. // derived history: user + assistant
  93. const messages = agent.session.deriveMessages()
  94. expect(messages.map(m => m.role)).toEqual(['user', 'assistant'])
  95. expect(messages[1]!.content).toEqual([{ type: 'text', text: 'hello there' }])
  96. })
  97. it('round-trips tool calls: model requests tool → executes → result in next request', async () => {
  98. const adapter = new MockAdapter([
  99. toolCallResponse('c1', 'echo', { text: 'ping' }, 'calling echo'),
  100. textResponse('done'),
  101. ])
  102. const ctx = await harness(adapter)
  103. ctx.tools.register(defineContentToolFixture({
  104. name: 'echo',
  105. description: 'echo back',
  106. parameters: { text: { type: 'string' } },
  107. async execute(args) {
  108. return [{ type: 'text', text: `echo: ${args.text}` }]
  109. },
  110. }))
  111. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  112. send(agent, 'use the tool')
  113. await waitForIdle(ctx, agent)
  114. // two model calls happened (tool-call step, then final step)
  115. expect(adapter.requests).toHaveLength(2)
  116. // the second request's derived history contains the tool result
  117. const secondMessages = adapter.requests[1]!.messages
  118. const toolResultMessage = secondMessages.find(m =>
  119. m.content.some(b => b.type === 'tool-result'))
  120. expect(toolResultMessage).toBeDefined()
  121. const block = toolResultMessage!.content.find(b => b.type === 'tool-result')!
  122. expect(block).toMatchObject({ toolCallId: 'c1', isError: false })
  123. expect((block).content).toEqual([{ type: 'text', text: 'echo: ping' }])
  124. // session log records call + result
  125. const types = agent.session.events.map(e => e.type)
  126. expect(types).toContain('tool/call')
  127. expect(types).toContain('tool/result')
  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(defineContentToolFixture({
  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) => {
  169. if (error instanceof Error) errors.push(error)
  170. })
  171. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  172. send(agent, 'hi')
  173. await waitForIdle(ctx, agent)
  174. expect(adapter.requests).toHaveLength(0) // the request was never sent
  175. expect(errors.some(e => e.message.includes('no value for this assembly'))).toBe(true)
  176. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  177. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('error')
  178. // The loop survived: a waterfall listener rescues {{cwd}} and the SAME
  179. // agent completes a real model turn.
  180. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  181. assembly.variables['cwd'] = '/rescued'
  182. return next()
  183. })
  184. send(agent, 'again')
  185. await waitForIdle(ctx, agent)
  186. expect(adapter.requests).toHaveLength(1)
  187. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nIn /rescued.')
  188. const turnEnds = agent.session.events.filter(e => e.type === 'turn/end')
  189. expect(turnEnds).toHaveLength(2)
  190. expect(turnEnds[1]?.type === 'turn/end' && turnEnds[1].data.reason.kind).toBe('completed')
  191. })
  192. it('supports the model-via-agent/request path with a {{model}} persona: the supplier states it via the assemble waterfall', async () => {
  193. // AgentOptions.model unset: the model arrives in the agent/request
  194. // waterfall (the loop's documented fallback — see runStep's no-model
  195. // error). {{model}} renders BEFORE that waterfall, so the SAME plugin
  196. // states the fact early on system-prompt/assemble — the owner of a
  197. // late-bound fact owns stating it wherever it is claimed.
  198. const adapter = new MockAdapter([textResponse('ok')])
  199. const ctx = await harness(adapter, 'You run on {{model}}.')
  200. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  201. assembly.variables['provider'] = 'mock'
  202. assembly.variables['model'] = 'mock'
  203. return next()
  204. })
  205. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  206. const config = await next()
  207. return { ...config, provider: 'mock', model: 'mock' }
  208. })
  209. const agent = ctx.agentLoop.create(SessionId('a-late-model'), {})
  210. send(agent, 'hi')
  211. await waitForIdle(ctx, agent)
  212. expect(adapter.requests).toHaveLength(1)
  213. expect(adapter.requests[0]!.model).toBe('mock')
  214. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou run on mock.')
  215. })
  216. it('omits the system field when a system-prompt/assemble veto empties the assembly', async () => {
  217. // The documented escape valve: a deployment that must drop the harness
  218. // openers short-circuits the assemble waterfall; the request then carries
  219. // NO system field at all (not an empty string).
  220. const adapter = new MockAdapter([textResponse('ok')])
  221. const ctx = await harness(adapter)
  222. ctx.on('system-prompt/assemble', async () => ({ sections: [], tools: [], variables: {} }))
  223. const agent = ctx.agentLoop.create(SessionId('a-no-system'), { provider: 'mock', model: 'mock' })
  224. send(agent, 'hi')
  225. await waitForIdle(ctx, agent)
  226. expect(adapter.requests).toHaveLength(1)
  227. expect('system' in adapter.requests[0]!).toBe(false)
  228. })
  229. it('records raw chunks for replay as assistant/chunk session events', async () => {
  230. const adapter = new MockAdapter([textResponse('abc')])
  231. const ctx = await harness(adapter)
  232. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  233. send(agent, 'hi')
  234. await waitForIdle(ctx, agent)
  235. const chunkEvents = agent.session.events.filter(e => e.type === 'assistant/chunk')
  236. // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7
  237. expect(chunkEvents).toHaveLength(7)
  238. // replay: chunk events alone re-assemble to the recorded assistant message
  239. const deltaText = chunkEvents
  240. .flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : [])
  241. .filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
  242. .map(c => c.text)
  243. .join('')
  244. expect(deltaText).toBe('abc')
  245. })
  246. it('injects steering between steps and continues the turn', async () => {
  247. const adapter = new MockAdapter([
  248. toolCallResponse('c1', 'slow', {}),
  249. textResponse('addressed the steering'),
  250. ])
  251. const ctx = await harness(adapter)
  252. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  253. ctx.tools.register(defineContentToolFixture({
  254. name: 'slow',
  255. description: '',
  256. parameters: {},
  257. async execute() {
  258. // steer while the turn is running (during tool execution)
  259. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'change of plans' }], source: { kind: 'user' } }))
  260. return [{ type: 'text', text: 'tool done' }]
  261. },
  262. }))
  263. send(agent, 'start')
  264. await waitForIdle(ctx, agent)
  265. const types = agent.session.events.map(e => e.type)
  266. expect(types).toContain('steering/message')
  267. // steering recorded before the second step's request derived its history
  268. const steeringSeq = agent.session.events.find(e => e.type === 'steering/message')!.seq
  269. const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1]
  270. expect(secondStepStart).toBeDefined()
  271. expect(steeringSeq).toBeLessThan(secondStepStart!.seq)
  272. // the second model request saw the steering content
  273. const secondRequest = adapter.requests[1]
  274. const flat = JSON.stringify(secondRequest!.messages)
  275. expect(flat).toContain('change of plans')
  276. })
  277. it('same-tick idle steering preserves one turn per send', async () => {
  278. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  279. const ctx = await harness(adapter)
  280. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  281. const idle = waitForIdle(ctx, agent)
  282. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'first idle steer' }], source: { kind: 'user' } }))
  283. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'second idle steer' }], source: { kind: 'user' } }))
  284. await idle
  285. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  286. expect(agent.session.events
  287. .filter(event => event.type === 'user/message')
  288. .map(event => event.data.content)).toEqual([
  289. [{ type: 'text', text: 'first idle steer' }],
  290. [{ type: 'text', text: 'second idle steer' }],
  291. ])
  292. expect(agent.session.events.filter(event => event.type === 'steering/message')).toEqual([])
  293. expect(adapter.requests).toHaveLength(2)
  294. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('first idle steer')
  295. expect(JSON.stringify(adapter.requests[0]?.messages)).not.toContain('second idle steer')
  296. expect(JSON.stringify(adapter.requests[1]?.messages)).toContain('second idle steer')
  297. })
  298. it('keeps steering staged after a failed step until the next admitted turn', async () => {
  299. const adapter = new MockAdapter([textResponse('recovered')])
  300. const ctx = await harness(adapter)
  301. const agent = ctx.agentLoop.create(SessionId('failed-steering'), { provider: 'mock', model: 'mock' })
  302. let fail = true
  303. ctx.on('agent/step', (subject) => {
  304. if (subject !== agent || !fail) return
  305. fail = false
  306. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'pending steering' }], source: { kind: 'user' } }))
  307. throw new Error('step failed')
  308. })
  309. send(agent, 'prompt')
  310. await waitForIdle(ctx, agent)
  311. expect(adapter.requests).toHaveLength(0)
  312. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  313. expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(false)
  314. send(agent, 'resume')
  315. await waitForIdle(ctx, agent)
  316. expect(adapter.requests).toHaveLength(1)
  317. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  318. expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(true)
  319. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('pending steering')
  320. })
  321. it('inject() while idle appends context without opening a turn', async () => {
  322. const adapter = new MockAdapter([textResponse('ok')])
  323. const ctx = await harness(adapter)
  324. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  325. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'file changed: a.ts' }], source: { kind: 'plugin', plugin: 'watcher' } }))
  326. expect(agent.status).toBe('idle')
  327. expect(adapter.requests).toHaveLength(0)
  328. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(0)
  329. expect(agent.session.events.at(-1)).toMatchObject({
  330. type: 'user/message',
  331. data: {
  332. role: 'user',
  333. content: [{ type: 'text', text: 'file changed: a.ts' }],
  334. source: { kind: 'plugin', plugin: 'watcher' },
  335. },
  336. })
  337. send(agent, 'go')
  338. await waitForIdle(ctx, agent)
  339. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  340. const flat = JSON.stringify(adapter.requests[0]!.messages)
  341. expect(flat).toContain('file changed: a.ts')
  342. expect(flat).not.toContain('<context source=')
  343. })
  344. it('inject() persists structured context content verbatim with durable source', async () => {
  345. const adapter = new MockAdapter([textResponse('ok')])
  346. const ctx = await harness(adapter)
  347. const agent = ctx.agentLoop.create(SessionId('raw-context'), { provider: 'mock', model: 'mock' })
  348. const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
  349. agent.inject(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'plugin', plugin: 'workspace-context' } }))
  350. send(agent, 'go')
  351. await waitForIdle(ctx, agent)
  352. const contextEvent = agent.session.events.find(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  353. expect(contextEvent?.type === 'user/message' && contextEvent.data.source)
  354. .toEqual({ kind: 'plugin', plugin: 'workspace-context' })
  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(SessionId('a1'), { provider: 'mock', model: 'mock' })
  366. let visibleDuringTool = false
  367. ctx.tools.register(defineContentToolFixture({
  368. name: 'noticer',
  369. description: 'injects a notice',
  370. parameters: {},
  371. async execute() {
  372. await Promise.resolve()
  373. const first = { type: 'text' as const, text: 'mid-turn notice' }
  374. agent.inject(createUserMessage({ content: [first], source: { kind: 'plugin', plugin: 'x' } }))
  375. first.text = 'mutated after inject'
  376. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'second notice' }], source: { kind: 'plugin', plugin: 'x' } }))
  377. visibleDuringTool = agent.session.events.some(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  378. return [{ type: 'text', text: 'ok' }]
  379. },
  380. }))
  381. send(agent, 'go')
  382. await waitForIdle(ctx, agent)
  383. expect(visibleDuringTool).toBe(false)
  384. // The injection stays in the open turn, but its user-role context cannot
  385. // split the assistant tool call from the provider's tool-result message.
  386. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  387. expect(turnStarts).toHaveLength(1)
  388. const ts0 = turnStarts[0]!
  389. expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
  390. const result = agent.session.events.find(e => e.type === 'tool/result')!
  391. const contexts = agent.session.events.filter(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  392. expect(contexts).toHaveLength(2)
  393. expect(result.seq).toBeLessThan(contexts[0]!.seq)
  394. expect(contexts.flatMap(event => event.type === 'user/message' ? event.data.content : []))
  395. .toEqual([
  396. { type: 'text', text: 'mid-turn notice' },
  397. { type: 'text', text: 'second notice' },
  398. ])
  399. const secondRequest = adapter.requests[1]!.messages
  400. const resultIndex = secondRequest.findIndex(message =>
  401. message.content.some(block => block.type === 'tool-result'))
  402. const contextIndexes = secondRequest.flatMap((message, index) =>
  403. message.content.some(block => block.type === 'text'
  404. && (block.text.includes('mid-turn notice') || block.text.includes('second notice')))
  405. ? [index]
  406. : [])
  407. expect(resultIndex).toBeGreaterThanOrEqual(0)
  408. expect(contextIndexes).toHaveLength(2)
  409. expect(contextIndexes.every(index => index > resultIndex)).toBe(true)
  410. })
  411. it('rejects non-JSON context before it enters the active tool-batch FIFO', async () => {
  412. const adapter = new MockAdapter([
  413. toolCallResponse('c1', 'invalid-injector', {}, 'calling'),
  414. textResponse('done'),
  415. ])
  416. const ctx = await harness(adapter)
  417. const agent = ctx.agentLoop.create(SessionId('invalid-context'), { provider: 'mock', model: 'mock' })
  418. ctx.tools.register(defineContentToolFixture({
  419. name: 'invalid-injector',
  420. description: 'attempts an invalid context injection',
  421. parameters: {},
  422. async execute() {
  423. expect(() => {
  424. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'invalid' }], source: { kind: 'plugin', plugin: 'test', bigint: 1n } as never }))
  425. }).toThrow('agent context must be losslessly JSON-serializable')
  426. return [{ type: 'text', text: 'rejected invalid context' }]
  427. },
  428. }))
  429. send(agent, 'go')
  430. await waitForIdle(ctx, agent)
  431. expect(agent.session.events.some(event => event.type === 'user/message' && event.data.source.kind === 'plugin')).toBe(false)
  432. })
  433. it('agent/turn-stopping can steer another step (/loop pattern)', async () => {
  434. const adapter = new MockAdapter([
  435. textResponse('step 1'),
  436. textResponse('step 2'),
  437. textResponse('step 3'),
  438. ])
  439. const ctx = await harness(adapter)
  440. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  441. let steps = 0
  442. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  443. ctx.on('agent/turn-stopping', (subject) => {
  444. if (steps < 3) {
  445. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'plugin', plugin: 'loop-test' } }))
  446. }
  447. })
  448. send(agent, 'go')
  449. await waitForIdle(ctx, agent)
  450. expect(steps).toBe(3)
  451. expect(adapter.requests).toHaveLength(3)
  452. })
  453. it('a tool can conclude the turn despite owing a follow-up request', async () => {
  454. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  455. const ctx = await harness(adapter)
  456. ctx.tools.register(defineContentToolFixture({
  457. name: 'echo',
  458. description: '',
  459. parameters: { text: { type: 'string' } },
  460. async execute(args, exec) {
  461. exec.concludeTurn()
  462. return [{ type: 'text', text: String(args.text) }]
  463. },
  464. }))
  465. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  466. send(agent, 'go')
  467. await waitForIdle(ctx, agent)
  468. // only one model call despite the tool call requesting a follow-up
  469. expect(adapter.requests).toHaveLength(1)
  470. // The tool still executes and durably records its result.
  471. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  472. })
  473. it('a concluding tool result beats steering that arrived during the same step', async () => {
  474. const adapter = new MockAdapter([
  475. toolCallResponse('c1', 'finalize', {}),
  476. textResponse('next turn reply'),
  477. ])
  478. const ctx = await harness(adapter)
  479. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  480. ctx.tools.register(defineContentToolFixture({
  481. name: 'finalize',
  482. description: '',
  483. parameters: {},
  484. async execute(_args, exec) {
  485. // Steering lands while the concluding tool is still executing.
  486. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'late steering' }], source: { kind: 'user' } }))
  487. exec.concludeTurn()
  488. return [{ type: 'text', text: 'final' }]
  489. },
  490. }))
  491. send(agent, 'go')
  492. await waitForIdle(ctx, agent)
  493. // The terminal result stands: no extra request reopens the concluded turn.
  494. expect(adapter.requests).toHaveLength(1)
  495. const events = agent.session.events.map(event => event.type)
  496. expect(events.filter(type => type === 'turn/end')).toHaveLength(1)
  497. // The steering is durable inside the concluded turn and feeds the NEXT
  498. // turn's request instead of being dropped or re-queued.
  499. expect(events).toContain('steering/message')
  500. send(agent, 'follow up')
  501. await waitForIdle(ctx, agent)
  502. expect(adapter.requests).toHaveLength(2)
  503. const texts = adapter.requests[1]!.messages
  504. .flatMap(message => message.content)
  505. .filter(block => block.type === 'text')
  506. .map(block => block.text)
  507. expect(texts).toContain('late steering')
  508. })
  509. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  510. const adapter = new MockAdapter([textResponse('ok')])
  511. const ctx = await harness(adapter)
  512. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  513. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  514. const config = await next()
  515. // The seed is frozen — config is not a mutable per-call knob; a switch
  516. // is proposed by returning a replacement, and the loop logs it.
  517. expect(Object.isFrozen(config)).toBe(true)
  518. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  519. return { ...config, model: 'other-model' }
  520. })
  521. send(agent, 'hi')
  522. await waitForIdle(ctx, agent)
  523. expect(adapter.requests[0]!.model).toBe('other-model')
  524. // The header event records what the request ACTUALLY used — the switch is
  525. // a reconstructable fact, not silent drift.
  526. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  527. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  528. })
  529. it('agent/step fires once per step before the step is opened', async () => {
  530. const adapter = new MockAdapter([
  531. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  532. textResponse('done'),
  533. ])
  534. const ctx = await harness(adapter)
  535. ctx.tools.register(defineContentToolFixture({
  536. name: 'echo', description: 'echo', parameters: {},
  537. async execute() { return [{ type: 'text', text: 'echoed' }] },
  538. }))
  539. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  540. const fires: { turn: number; step: number; signal: AbortSignal }[] = []
  541. ctx.on('agent/step', (subject, turn, step, signal) => {
  542. if (subject === agent) fires.push({ turn, step, signal })
  543. })
  544. send(agent, 'go')
  545. await waitForIdle(ctx, agent)
  546. expect(fires.map(({ turn, step }) => ({ turn, step }))).toEqual([
  547. { turn: 1, step: 1 },
  548. { turn: 1, step: 2 },
  549. ])
  550. expect(fires.every(({ signal }) => signal instanceof AbortSignal)).toBe(true)
  551. })
  552. it('agent/step fires BEFORE the step it precedes opens (events land outside the step)', async () => {
  553. // The append lands before step/start, yet derive happens afterwards and the
  554. // same step's request must include it.
  555. const adapter = new MockAdapter([textResponse('ok')])
  556. const ctx = await harness(adapter)
  557. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  558. let injected = false
  559. ctx.on('agent/step', (subject) => {
  560. if (subject === agent && !injected) {
  561. injected = true
  562. subject.session.append('user/message', createUserMessage({
  563. content: [{ type: 'text', text: 'INJECTED-IN-PRE-STEP' }],
  564. source: { kind: 'plugin', plugin: 'test' },
  565. }), { surfaceOp: 'append' })
  566. }
  567. })
  568. send(agent, 'go')
  569. await waitForIdle(ctx, agent)
  570. // The adapter's request includes the node injected during pre-step (derive
  571. // reflects it).
  572. const text = JSON.stringify(adapter.requests[0]!.messages)
  573. expect(text).toContain('INJECTED-IN-PRE-STEP')
  574. // And the injected event sits BEFORE the first step/start in the log —
  575. // the seam fired outside the step.
  576. const events = agent.session.events
  577. const injectedSeq = events.find(e => e.type === 'user/message' && e.data.source.kind === 'plugin')!.seq
  578. const firstStepStartSeq = events.find(e => e.type === 'step/start')!.seq
  579. expect(injectedSeq).toBeLessThan(firstStepStartSeq)
  580. })
  581. it('a throwing agent/step listener ends the turn (error), not the loop', async () => {
  582. // Before step/start, a pre-step throw reaches the turn catch: no step needs
  583. // closing, the turn records error, and the loop remains available.
  584. const adapter = new MockAdapter([textResponse('second turn ok')])
  585. const ctx = await harness(adapter)
  586. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  587. let throwOnce = true
  588. ctx.on('agent/step', () => {
  589. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  590. })
  591. const errors: Error[] = []
  592. ctx.on('agent/error', (_a, _t, _s, error) => {
  593. if (error instanceof Error) errors.push(error)
  594. })
  595. send(agent, 'first')
  596. await waitForIdle(ctx, agent)
  597. // The first turn failed at step 1 (no model call happened), surfaced via
  598. // agent/error, with the durable failure on turn/end.reason.
  599. expect(errors).toHaveLength(1)
  600. expect(errors[0]!.message).toContain('boom in pre-step')
  601. expect(adapter.requests.length).toBe(0)
  602. const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
  603. expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  604. // The step opened-and-closed count stays balanced even though it never ran.
  605. const types = agent.session.events.map(e => e.type)
  606. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  607. // The loop survived: a second prompt runs a normal completed turn.
  608. send(agent, 'second')
  609. await waitForIdle(ctx, agent)
  610. expect(adapter.requests.length).toBe(1)
  611. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  612. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  613. })
  614. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  615. const adapter = new MockAdapter(['hang'])
  616. const ctx = await harness(adapter)
  617. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  618. const reasons: TurnEndReason[] = []
  619. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  620. send(agent, 'go')
  621. // wait until the stream is hanging, then cancel
  622. await new Promise(r => setTimeout(r, 30))
  623. expect(agent.status).toBe('running')
  624. agent.cancel({ kind: 'user' })
  625. await waitForIdle(ctx, agent)
  626. expect(reasons).toEqual([{ kind: 'aborted' }])
  627. })
  628. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  629. // A single step that ends with a max-tokens finish (no tool calls): the
  630. // turn stops by default and ends max-tokens, not completed.
  631. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  632. const ctx = await harness(adapter)
  633. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  634. const reasons: TurnEndReason[] = []
  635. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  636. send(agent, 'go')
  637. await waitForIdle(ctx, agent)
  638. expect(adapter.requests).toHaveLength(1)
  639. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  640. // Assert the durable row, not only the live listener.
  641. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  642. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  643. })
  644. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  645. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  646. // must be FORCED to reach step 2 which finishes normally (stop).
  647. const adapter = new MockAdapter([
  648. maxTokensResponse('first half'),
  649. textResponse('second half'),
  650. ])
  651. const ctx = await harness(adapter)
  652. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  653. let steps = 0
  654. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  655. // Force exactly one continuation (step 1 → step 2), then defer to default
  656. // (step 2 is a plain stop with no tool calls → stops).
  657. ctx.on('agent/turn-stopping', (subject) => {
  658. if (steps < 2) {
  659. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue after truncation' }], source: { kind: 'plugin', plugin: 'max-tokens-test' } }))
  660. }
  661. })
  662. const reasons: TurnEndReason[] = []
  663. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  664. send(agent, 'go')
  665. await waitForIdle(ctx, agent)
  666. expect(steps).toBe(2)
  667. expect(adapter.requests).toHaveLength(2)
  668. expect(adapter.requests[1]!.messages).toEqual([
  669. {
  670. id: expect.any(String) as unknown,
  671. role: 'user',
  672. content: [{ type: 'text', text: 'go' }],
  673. source: { kind: 'user' },
  674. },
  675. {
  676. id: expect.any(String) as unknown,
  677. role: 'assistant',
  678. content: [{ type: 'text', text: 'first half' }],
  679. source: { kind: 'model', provider: 'mock', model: 'mock' },
  680. },
  681. {
  682. id: expect.any(String) as unknown,
  683. role: 'user',
  684. content: [{ type: 'text', text: 'continue after truncation' }],
  685. source: { kind: 'plugin', plugin: 'max-tokens-test' },
  686. },
  687. ])
  688. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  689. })
  690. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  691. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  692. // stop. The per-turn reason must be independent — turn 2 ends completed.
  693. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  694. const ctx = await harness(adapter)
  695. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  696. const reasons: TurnEndReason[] = []
  697. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  698. send(agent, 'first')
  699. await waitForIdle(ctx, agent)
  700. send(agent, 'second')
  701. await waitForIdle(ctx, agent)
  702. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  703. })
  704. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  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: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  711. { type: 'finish', reason: { kind: 'max-tokens' } },
  712. ]])
  713. const ctx = await harness(adapter)
  714. let executions = 0
  715. ctx.tools.register(defineContentToolFixture({
  716. name: 'echo',
  717. description: '',
  718. parameters: { text: { type: 'string' } },
  719. async execute() {
  720. executions += 1
  721. return [{ type: 'text', text: 'should not run' }]
  722. },
  723. }))
  724. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  725. const reasons: TurnEndReason[] = []
  726. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  727. send(agent, 'go')
  728. await waitForIdle(ctx, agent)
  729. expect(executions).toBe(0)
  730. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  731. expect(agent.session.deriveMessages()).toEqual([{
  732. id: expect.any(String) as unknown,
  733. role: 'user',
  734. content: [{ type: 'text', text: 'go' }],
  735. source: { kind: 'user' },
  736. }])
  737. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  738. // Empty content still needs an assistant/message to carry usage; derivation
  739. // skips that host so it does not create a spurious assistant turn.
  740. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  741. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  742. turn: 1,
  743. step: 1,
  744. message: {
  745. id: expect.any(String) as unknown,
  746. role: 'assistant',
  747. content: [],
  748. source: { kind: 'model', provider: 'mock', model: 'mock' },
  749. },
  750. usage: { inputTokens: 10, outputTokens: 5 },
  751. })
  752. })
  753. it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
  754. // The truncated tool call is dropped from durable content, while the
  755. // successful provider call still needs an exact replay anchor.
  756. const callId = CallId('c1')
  757. const adapter = new MockAdapter([[
  758. { type: 'block-start', index: 0, blockType: 'tool-call' },
  759. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  760. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  761. { type: 'finish', reason: { kind: 'max-tokens' } },
  762. ]])
  763. const ctx = await harness(adapter)
  764. ctx.tools.register(defineContentToolFixture({
  765. name: 'echo',
  766. description: '',
  767. parameters: { text: { type: 'string' } },
  768. async execute() { return [{ type: 'text', text: 'should not run' }] },
  769. }))
  770. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  771. const reasons: TurnEndReason[] = []
  772. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  773. send(agent, 'go')
  774. await waitForIdle(ctx, agent)
  775. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  776. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  777. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  778. turn: 1,
  779. step: 1,
  780. message: {
  781. id: expect.any(String) as unknown,
  782. role: 'assistant',
  783. content: [],
  784. source: { kind: 'model', provider: 'mock', model: 'mock' },
  785. },
  786. })
  787. expect(assistant.sourceEventSeqs?.length).toBeGreaterThan(0)
  788. expect(agent.session.deriveMessages()).toEqual([{
  789. id: expect.any(String) as unknown,
  790. role: 'user',
  791. content: [{ type: 'text', text: 'go' }],
  792. source: { kind: 'user' },
  793. }])
  794. })
  795. it('appends an empty completion anchor for a normal stop with no usage', async () => {
  796. // A clean content-less call stays absent from derived messages but remains
  797. // a durable successful-call boundary for replay consumers.
  798. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  799. const ctx = await harness(adapter)
  800. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  801. const reasons: TurnEndReason[] = []
  802. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  803. send(agent, 'go')
  804. await waitForIdle(ctx, agent)
  805. expect(reasons).toEqual([{ kind: 'completed' }])
  806. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  807. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  808. turn: 1,
  809. step: 1,
  810. message: {
  811. id: expect.any(String) as unknown,
  812. role: 'assistant',
  813. content: [],
  814. source: { kind: 'model', provider: 'mock', model: 'mock' },
  815. },
  816. })
  817. expect(assistant.sourceEventSeqs?.length).toBe(1)
  818. expect(agent.session.deriveMessages()).toEqual([{
  819. id: expect.any(String) as unknown,
  820. role: 'user',
  821. content: [{ type: 'text', text: 'go' }],
  822. source: { kind: 'user' },
  823. }])
  824. })
  825. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  826. const callId = CallId('c1')
  827. const adapter = new MockAdapter([[
  828. { type: 'block-start', index: 0, blockType: 'text' },
  829. { type: 'text-delta', index: 0, text: 'partial text' },
  830. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  831. { type: 'block-start', index: 1, blockType: 'tool-call' },
  832. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  833. { type: 'finish', reason: { kind: 'max-tokens' } },
  834. ]])
  835. const ctx = await harness(adapter)
  836. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  837. send(agent, 'go')
  838. await waitForIdle(ctx, agent)
  839. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  840. expect(agent.session.deriveMessages()).toEqual([
  841. {
  842. id: expect.any(String) as unknown,
  843. role: 'user',
  844. content: [{ type: 'text', text: 'go' }],
  845. source: { kind: 'user' },
  846. },
  847. {
  848. id: expect.any(String) as unknown,
  849. role: 'assistant',
  850. content: [{ type: 'text', text: 'partial text' }],
  851. source: { kind: 'model', provider: 'mock', model: 'mock' },
  852. },
  853. ])
  854. })
  855. it('contains a step/end observer failure without changing continuation', async () => {
  856. const adapter = new MockAdapter([
  857. toolCallResponse('c1', 'echo', { text: 'x' }),
  858. textResponse('continued after tool call'),
  859. ])
  860. const ctx = await harness(adapter)
  861. ctx.tools.register(defineContentToolFixture({
  862. name: 'echo',
  863. description: '',
  864. parameters: { text: { type: 'string' } },
  865. async execute(args) {
  866. return [{ type: 'text', text: String(args.text) }]
  867. },
  868. }))
  869. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  870. let threw = false
  871. // Post-commit session observers cannot control the loop. The tool call still
  872. // drives the second model request, and the turn completes normally.
  873. ctx.on('session/event', (_session, event) => {
  874. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  875. })
  876. send(agent, 'go')
  877. await waitForIdle(ctx, agent)
  878. expect(adapter.requests).toHaveLength(2)
  879. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  880. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  881. })
  882. it('keeps a reentrant agent/inbox/enqueue send as the next independent turn', async () => {
  883. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  884. const ctx = await harness(adapter)
  885. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  886. let nested = false
  887. ctx.on('agent/inbox/enqueue', (subject) => {
  888. if (subject !== agent || nested) return
  889. nested = true
  890. send(agent, 'queued listener message')
  891. })
  892. const idle = waitForIdle(ctx, agent)
  893. send(agent, 'outer message')
  894. await idle
  895. const turns = agent.session.events.filter(event => event.type === 'turn/start')
  896. const messages = agent.session.events
  897. .filter(event => event.type === 'user/message')
  898. .map(event => event.data.content)
  899. expect(turns).toHaveLength(2)
  900. expect(messages).toEqual([
  901. [{ type: 'text', text: 'outer message' }],
  902. [{ type: 'text', text: 'queued listener message' }],
  903. ])
  904. })
  905. it('preserves independent turn sources across an adjacent microtask send', async () => {
  906. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  907. const ctx = await harness(adapter)
  908. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  909. const idle = waitForIdle(ctx, agent)
  910. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'user message' }], source: { kind: 'user' } }))
  911. await Promise.resolve()
  912. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'plugin message' }], source: { kind: 'plugin', plugin: 'test' } }))
  913. await idle
  914. const triggers = agent.session.events
  915. .filter(event => event.type === 'turn/start')
  916. .map(event => event.data.trigger)
  917. const sources = agent.session.events
  918. .filter(event => event.type === 'user/message')
  919. .map(event => event.data.source)
  920. expect(triggers).toEqual([
  921. { kind: 'message', source: { kind: 'user' } },
  922. { kind: 'message', source: { kind: 'plugin', plugin: 'test' } },
  923. ])
  924. expect(sources).toEqual([
  925. { kind: 'user' },
  926. { kind: 'plugin', plugin: 'test' },
  927. ])
  928. })
  929. it('keeps a session-listener send after dequeue in the following turn', async () => {
  930. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  931. const ctx = await harness(adapter)
  932. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  933. const turns: number[] = []
  934. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  935. // queue two messages while idle — first starts turn 1 immediately;
  936. // queue the second during turn 1 when the first assistant chunk streams
  937. let queued = false
  938. ctx.on('session/event', (_s, event) => {
  939. if (event.type === 'assistant/chunk' && !queued) {
  940. queued = true
  941. send(agent, 'second message')
  942. }
  943. })
  944. send(agent, 'first message')
  945. await waitForIdle(ctx, agent)
  946. expect(turns).toEqual([1, 2])
  947. expect(adapter.requests).toHaveLength(2)
  948. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first')
  949. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  950. })
  951. it('keeps a model-adapter callback send in the following turn', async () => {
  952. const agentRef: { current?: Agent } = {}
  953. const adapter = new MockAdapter([
  954. () => {
  955. const agent = agentRef.current
  956. if (agent === undefined) throw new Error('model callback ran before agent setup')
  957. send(agent, 'model callback message')
  958. return textResponse('first')
  959. },
  960. textResponse('second'),
  961. ])
  962. const ctx = await harness(adapter)
  963. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  964. agentRef.current = agent
  965. const idle = waitForIdle(ctx, agent)
  966. send(agent, 'outer message')
  967. await idle
  968. const messages = agent.session.events
  969. .filter(event => event.type === 'user/message')
  970. .map(event => event.data.content)
  971. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  972. expect(messages).toEqual([
  973. [{ type: 'text', text: 'outer message' }],
  974. [{ type: 'text', text: 'model callback message' }],
  975. ])
  976. })
  977. it('errors from the model surface as agent/error and end the turn', async () => {
  978. const adapter = new MockAdapter([]) // script exhausted → throws
  979. const ctx = await harness(adapter)
  980. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  981. const errors: Error[] = []
  982. const reasons: TurnEndReason[] = []
  983. ctx.on('agent/error', (_agent, _turn, _step, error) => {
  984. if (error instanceof Error) errors.push(error)
  985. })
  986. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  987. send(agent, 'hi')
  988. await waitForIdle(ctx, agent)
  989. expect(errors).toHaveLength(1)
  990. expect(errors[0]!.message).toContain('script exhausted')
  991. expect(reasons[0]).toMatchObject({ kind: 'error' })
  992. // The durable failure lives entirely on turn/end.reason (with the failing
  993. // step), not a standalone error event.
  994. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  995. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  996. })
  997. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  998. const adapter = new MockAdapter(['hang'])
  999. const ctx = await harness(adapter)
  1000. let agent!: Agent
  1001. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  1002. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  1003. }, { inject: ['agentLoop'] }))
  1004. expect(ctx.agents.get(SessionId('scoped'))).toBe(agent)
  1005. send(agent, 'go')
  1006. await new Promise(r => setTimeout(r, 30))
  1007. expect(agent.status).toBe('running')
  1008. await fiber.dispose()
  1009. await driverDone(agent)
  1010. expect(ctx.agents.get(SessionId('scoped'))).toBeUndefined()
  1011. })
  1012. it('creates agents from config on startup', async () => {
  1013. const adapter = new MockAdapter([textResponse('from config')])
  1014. const ctx = new Context()
  1015. await ctx.plugin(LlmService)
  1016. await ctx.plugin(SessionStore)
  1017. await ctx.plugin(SystemPrompt)
  1018. await ctx.plugin(ToolRegistry)
  1019. await ctx.plugin(AgentRegistry)
  1020. await ctx.plugin(AgentLoop, {
  1021. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock' }],
  1022. })
  1023. ctx.llm.registerAdapter(['mock'], adapter)
  1024. const agent = ctx.agents.list()[0]!
  1025. expect(agent).toBeDefined()
  1026. expect(agent.id).toBe(agent.session.id)
  1027. expect(agent.id).toMatch(/^config-agent-session-/)
  1028. expect(agent.options.model).toBe('mock')
  1029. // the agent is alive: send triggers a turn
  1030. send(agent, 'hi')
  1031. await waitForIdle(ctx, agent)
  1032. expect(adapter.requests).toHaveLength(1)
  1033. })
  1034. it('attaches config agent cwd to the fresh session header', async () => {
  1035. const ctx = new Context()
  1036. await ctx.plugin(LlmService)
  1037. await ctx.plugin(SessionStore)
  1038. await ctx.plugin(SystemPrompt)
  1039. await ctx.plugin(ToolRegistry)
  1040. await ctx.plugin(AgentRegistry)
  1041. await ctx.plugin(AgentLoop, {
  1042. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
  1043. })
  1044. const agent = ctx.agents.list()[0]!
  1045. expect(agent.session.header.cwd).toBe('/work/project')
  1046. })
  1047. it('replays a session log into an identical derived history', async () => {
  1048. const adapter = new MockAdapter([
  1049. toolCallResponse('c1', 'echo', { text: 'x' }),
  1050. textResponse('done'),
  1051. ])
  1052. const ctx = await harness(adapter)
  1053. ctx.tools.register(defineContentToolFixture({
  1054. name: 'echo',
  1055. description: '',
  1056. parameters: { text: { type: 'string' } },
  1057. async execute(args) {
  1058. return [{ type: 'text', text: String(args.text) }]
  1059. },
  1060. }))
  1061. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1062. send(agent, 'run')
  1063. await waitForIdle(ctx, agent)
  1064. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  1065. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  1066. // event-by-event identity of types over the inherited prefix
  1067. expect(replayed.events.slice(0, agent.session.seq).map(e => e.type)).toEqual(
  1068. agent.session.events.map(e => e.type))
  1069. expect(replayed.events.at(-1)?.type).toBe('session/end-seed')
  1070. })
  1071. })