loop.spec.ts 51 KB

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