loop.spec.ts 49 KB

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