loop.spec.ts 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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 steering joins the prompt already in admission', async () => {
  255. const adapter = new MockAdapter([textResponse('combined')])
  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(1)
  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. ])
  268. expect(agent.session.events
  269. .filter(event => event.type === 'steering/message')
  270. .map(event => event.data.content)).toEqual([
  271. [{ type: 'text', text: 'second idle steer' }],
  272. ])
  273. expect(adapter.requests).toHaveLength(1)
  274. const request = JSON.stringify(adapter.requests[0]?.messages)
  275. expect(request).toContain('first idle steer')
  276. expect(request).toContain('second idle steer')
  277. })
  278. it('keeps steering staged after a failed step until retry', async () => {
  279. const adapter = new MockAdapter([textResponse('recovered')])
  280. const ctx = await harness(adapter)
  281. const agent = ctx.agentLoop.create(SessionId('failed-steering'), { provider: 'mock', model: 'mock' })
  282. let fail = true
  283. ctx.on('agent/step', (subject) => {
  284. if (subject !== agent || !fail) return
  285. fail = false
  286. subject.steer({ content: [{ type: 'text', text: 'pending steering' }], source: { kind: 'user' } })
  287. throw new Error('step failed')
  288. })
  289. send(agent, 'prompt')
  290. await waitForIdle(ctx, agent)
  291. expect(adapter.requests).toHaveLength(0)
  292. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  293. expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(false)
  294. const idle = waitForIdle(ctx, agent)
  295. agent.retry()
  296. await idle
  297. expect(adapter.requests).toHaveLength(1)
  298. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  299. expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(true)
  300. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('pending steering')
  301. })
  302. it('inject() while idle appends context without opening a turn', async () => {
  303. const adapter = new MockAdapter([textResponse('ok')])
  304. const ctx = await harness(adapter)
  305. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  306. agent.inject({ content: [{ type: 'text', text: 'file changed: a.ts' }], source: { kind: 'plugin', plugin: 'watcher' } })
  307. expect(agent.status).toBe('idle')
  308. expect(adapter.requests).toHaveLength(0)
  309. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(0)
  310. expect(agent.session.events.at(-1)).toMatchObject({
  311. type: 'user/message',
  312. data: { source: { kind: 'plugin', plugin: 'watcher' } },
  313. })
  314. send(agent, 'go')
  315. await waitForIdle(ctx, agent)
  316. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  317. const flat = JSON.stringify(adapter.requests[0]!.messages)
  318. expect(flat).toContain('file changed: a.ts')
  319. expect(flat).not.toContain('<context source=')
  320. })
  321. it('inject() persists structured context content verbatim with durable source', async () => {
  322. const adapter = new MockAdapter([textResponse('ok')])
  323. const ctx = await harness(adapter)
  324. const agent = ctx.agentLoop.create(SessionId('raw-context'), { provider: 'mock', model: 'mock' })
  325. const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
  326. agent.inject({ content: [{ type: 'text', text }], source: { kind: 'plugin', plugin: 'workspace-context' } })
  327. send(agent, 'go')
  328. await waitForIdle(ctx, agent)
  329. const contextEvent = agent.session.events.find(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  330. expect(contextEvent?.type === 'user/message' && contextEvent.data.source)
  331. .toEqual({ kind: 'plugin', plugin: 'workspace-context' })
  332. const requestText = JSON.stringify(adapter.requests[0]!.messages)
  333. expect(requestText).toContain('Additional instructions from: pkg/AGENTS.md')
  334. expect(requestText).not.toContain('<context source=')
  335. })
  336. it('defers inject() during tool execution until after the tool result', async () => {
  337. const adapter = new MockAdapter([
  338. toolCallResponse('c1', 'noticer', {}, 'calling'),
  339. textResponse('done'),
  340. ])
  341. const ctx = await harness(adapter)
  342. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  343. let visibleDuringTool = false
  344. ctx.tools.register(defineContentToolFixture({
  345. name: 'noticer',
  346. description: 'injects a notice',
  347. parameters: {},
  348. async execute() {
  349. await Promise.resolve()
  350. const first = { type: 'text' as const, text: 'mid-turn notice' }
  351. agent.inject({ content: [first], source: { kind: 'plugin', plugin: 'x' } })
  352. first.text = 'mutated after inject'
  353. agent.inject({ content: [{ type: 'text', text: 'second notice' }], source: { kind: 'plugin', plugin: 'x' } })
  354. visibleDuringTool = agent.session.events.some(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  355. return [{ type: 'text', text: 'ok' }]
  356. },
  357. }))
  358. send(agent, 'go')
  359. await waitForIdle(ctx, agent)
  360. expect(visibleDuringTool).toBe(false)
  361. // The injection stays in the open turn, but its user-role context cannot
  362. // split the assistant tool call from the provider's tool-result message.
  363. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  364. expect(turnStarts).toHaveLength(1)
  365. const ts0 = turnStarts[0]!
  366. expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
  367. const result = agent.session.events.find(e => e.type === 'tool/result')!
  368. const contexts = agent.session.events.filter(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  369. expect(contexts).toHaveLength(2)
  370. expect(result.seq).toBeLessThan(contexts[0]!.seq)
  371. expect(contexts.flatMap(event => event.type === 'user/message' ? event.data.content : []))
  372. .toEqual([
  373. { type: 'text', text: 'mutated after inject' },
  374. { type: 'text', text: 'second notice' },
  375. ])
  376. const secondRequest = adapter.requests[1]!.messages
  377. const resultIndex = secondRequest.findIndex(message =>
  378. message.content.some(block => block.type === 'tool-result'))
  379. const contextIndexes = secondRequest.flatMap((message, index) =>
  380. message.content.some(block => block.type === 'text'
  381. && (block.text.includes('mid-turn notice') || block.text.includes('second notice')))
  382. ? [index]
  383. : [])
  384. expect(resultIndex).toBeGreaterThanOrEqual(0)
  385. expect(contextIndexes).toHaveLength(1)
  386. expect(contextIndexes.every(index => index > resultIndex)).toBe(true)
  387. })
  388. it('rejects non-JSON context before it enters the active tool-batch FIFO', async () => {
  389. const adapter = new MockAdapter([
  390. toolCallResponse('c1', 'invalid-injector', {}, 'calling'),
  391. textResponse('done'),
  392. ])
  393. const ctx = await harness(adapter)
  394. const agent = ctx.agentLoop.create(SessionId('invalid-context'), { provider: 'mock', model: 'mock' })
  395. ctx.tools.register(defineContentToolFixture({
  396. name: 'invalid-injector',
  397. description: 'attempts an invalid context injection',
  398. parameters: {},
  399. async execute() {
  400. expect(() => {
  401. agent.inject({ content: [{ type: 'text', text: 'invalid' }], source: { kind: 'plugin', plugin: 'test', bigint: 1n } as never })
  402. }).toThrow('agent context must be losslessly JSON-serializable')
  403. return [{ type: 'text', text: 'rejected invalid context' }]
  404. },
  405. }))
  406. send(agent, 'go')
  407. await waitForIdle(ctx, agent)
  408. expect(agent.session.events.some(event => event.type === 'user/message' && event.data.source.kind === 'plugin')).toBe(false)
  409. })
  410. it('agent/turn-stopping can steer another step (/loop pattern)', async () => {
  411. const adapter = new MockAdapter([
  412. textResponse('step 1'),
  413. textResponse('step 2'),
  414. textResponse('step 3'),
  415. ])
  416. const ctx = await harness(adapter)
  417. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  418. let steps = 0
  419. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  420. ctx.on('agent/turn-stopping', (subject) => {
  421. if (steps < 3) {
  422. subject.steer({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'plugin', plugin: 'loop-test' } })
  423. }
  424. })
  425. send(agent, 'go')
  426. await waitForIdle(ctx, agent)
  427. expect(steps).toBe(3)
  428. expect(adapter.requests).toHaveLength(3)
  429. })
  430. it('a tool can conclude the turn despite owing a follow-up request', async () => {
  431. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  432. const ctx = await harness(adapter)
  433. ctx.tools.register(defineContentToolFixture({
  434. name: 'echo',
  435. description: '',
  436. parameters: { text: { type: 'string' } },
  437. async execute(args, exec) {
  438. exec.concludeTurn()
  439. return [{ type: 'text', text: String(args.text) }]
  440. },
  441. }))
  442. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  443. send(agent, 'go')
  444. await waitForIdle(ctx, agent)
  445. // only one model call despite the tool call requesting a follow-up
  446. expect(adapter.requests).toHaveLength(1)
  447. // The tool still executes and durably records its result.
  448. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  449. })
  450. it('a concluding tool result beats steering that arrived during the same step', async () => {
  451. const adapter = new MockAdapter([
  452. toolCallResponse('c1', 'finalize', {}),
  453. textResponse('next turn reply'),
  454. ])
  455. const ctx = await harness(adapter)
  456. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  457. ctx.tools.register(defineContentToolFixture({
  458. name: 'finalize',
  459. description: '',
  460. parameters: {},
  461. async execute(_args, exec) {
  462. // Steering lands while the concluding tool is still executing.
  463. agent.steer({ content: [{ type: 'text', text: 'late steering' }], source: { kind: 'user' } })
  464. exec.concludeTurn()
  465. return [{ type: 'text', text: 'final' }]
  466. },
  467. }))
  468. send(agent, 'go')
  469. await waitForIdle(ctx, agent)
  470. // The terminal result stands: no extra request reopens the concluded turn.
  471. expect(adapter.requests).toHaveLength(1)
  472. const events = agent.session.events.map(event => event.type)
  473. expect(events.filter(type => type === 'turn/end')).toHaveLength(1)
  474. // The steering is durable inside the concluded turn and feeds the NEXT
  475. // turn's request instead of being dropped or re-queued.
  476. expect(events).toContain('steering/message')
  477. send(agent, 'follow up')
  478. await waitForIdle(ctx, agent)
  479. expect(adapter.requests).toHaveLength(2)
  480. const texts = adapter.requests[1]!.messages
  481. .flatMap(message => message.content)
  482. .filter(block => block.type === 'text')
  483. .map(block => block.text)
  484. expect(texts).toContain('late steering')
  485. })
  486. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  487. const adapter = new MockAdapter([textResponse('ok')])
  488. const ctx = await harness(adapter)
  489. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  490. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  491. const config = await next()
  492. // The seed is frozen — config is not a mutable per-call knob; a switch
  493. // is proposed by returning a replacement, and the loop logs it.
  494. expect(Object.isFrozen(config)).toBe(true)
  495. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  496. return { ...config, model: 'other-model' }
  497. })
  498. send(agent, 'hi')
  499. await waitForIdle(ctx, agent)
  500. expect(adapter.requests[0]!.model).toBe('other-model')
  501. // The header event records what the request ACTUALLY used — the switch is
  502. // a reconstructable fact, not silent drift.
  503. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  504. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  505. })
  506. it('agent/step fires once per step before the step is opened', async () => {
  507. const adapter = new MockAdapter([
  508. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  509. textResponse('done'),
  510. ])
  511. const ctx = await harness(adapter)
  512. ctx.tools.register(defineContentToolFixture({
  513. name: 'echo', description: 'echo', parameters: {},
  514. async execute() { return [{ type: 'text', text: 'echoed' }] },
  515. }))
  516. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  517. const fires: { turn: number; step: number; signal: AbortSignal }[] = []
  518. ctx.on('agent/step', (subject, turn, step, signal) => {
  519. if (subject === agent) fires.push({ turn, step, signal })
  520. })
  521. send(agent, 'go')
  522. await waitForIdle(ctx, agent)
  523. expect(fires.map(({ turn, step }) => ({ turn, step }))).toEqual([
  524. { turn: 1, step: 1 },
  525. { turn: 1, step: 2 },
  526. ])
  527. expect(fires.every(({ signal }) => signal instanceof AbortSignal)).toBe(true)
  528. })
  529. it('agent/step fires BEFORE the step it precedes opens (events land outside the step)', async () => {
  530. // The append lands before step/start, yet derive happens afterwards and the
  531. // same step's request must include it.
  532. const adapter = new MockAdapter([textResponse('ok')])
  533. const ctx = await harness(adapter)
  534. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  535. let injected = false
  536. ctx.on('agent/step', (subject) => {
  537. if (subject === agent && !injected) {
  538. injected = true
  539. subject.session.append('user/message', {
  540. content: [{ type: 'text', text: 'INJECTED-IN-PRE-STEP' }],
  541. source: { kind: 'plugin', plugin: 'test' },
  542. }, { surfaceOp: 'append' })
  543. }
  544. })
  545. send(agent, 'go')
  546. await waitForIdle(ctx, agent)
  547. // The adapter's request includes the node injected during pre-step (derive
  548. // reflects it).
  549. const text = JSON.stringify(adapter.requests[0]!.messages)
  550. expect(text).toContain('INJECTED-IN-PRE-STEP')
  551. // And the injected event sits BEFORE the first step/start in the log —
  552. // the seam fired outside the step.
  553. const events = agent.session.events
  554. const injectedSeq = events.find(e => e.type === 'user/message' && e.data.source.kind === 'plugin')!.seq
  555. const firstStepStartSeq = events.find(e => e.type === 'step/start')!.seq
  556. expect(injectedSeq).toBeLessThan(firstStepStartSeq)
  557. })
  558. it('a throwing agent/step listener ends the turn (error), not the loop', async () => {
  559. // Before step/start, a pre-step throw reaches the turn catch: no step needs
  560. // closing, the turn records error, and the loop remains available.
  561. const adapter = new MockAdapter([textResponse('second turn ok')])
  562. const ctx = await harness(adapter)
  563. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  564. let throwOnce = true
  565. ctx.on('agent/step', () => {
  566. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  567. })
  568. const errors: Error[] = []
  569. ctx.on('agent/error', (_a, _t, _s, error) => {
  570. if (error instanceof Error) errors.push(error)
  571. })
  572. send(agent, 'first')
  573. await waitForIdle(ctx, agent)
  574. // The first turn failed at step 1 (no model call happened), surfaced via
  575. // agent/error, with the durable failure on turn/end.reason.
  576. expect(errors).toHaveLength(1)
  577. expect(errors[0]!.message).toContain('boom in pre-step')
  578. expect(adapter.requests.length).toBe(0)
  579. const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
  580. expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  581. // The step opened-and-closed count stays balanced even though it never ran.
  582. const types = agent.session.events.map(e => e.type)
  583. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  584. // The loop survived: a second prompt runs a normal completed turn.
  585. send(agent, 'second')
  586. await waitForIdle(ctx, agent)
  587. expect(adapter.requests.length).toBe(1)
  588. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  589. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  590. })
  591. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  592. const adapter = new MockAdapter(['hang'])
  593. const ctx = await harness(adapter)
  594. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  595. const reasons: TurnEndReason[] = []
  596. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  597. send(agent, 'go')
  598. // wait until the stream is hanging, then cancel
  599. await new Promise(r => setTimeout(r, 30))
  600. expect(agent.status).toBe('running')
  601. agent.cancel({ kind: 'user' })
  602. await waitForIdle(ctx, agent)
  603. expect(reasons).toEqual([{ kind: 'aborted' }])
  604. })
  605. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  606. // A single step that ends with a max-tokens finish (no tool calls): the
  607. // turn stops by default and ends max-tokens, not completed.
  608. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  609. const ctx = await harness(adapter)
  610. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  611. const reasons: TurnEndReason[] = []
  612. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  613. send(agent, 'go')
  614. await waitForIdle(ctx, agent)
  615. expect(adapter.requests).toHaveLength(1)
  616. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  617. // Assert the durable row, not only the live listener.
  618. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  619. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  620. })
  621. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  622. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  623. // must be FORCED to reach step 2 which finishes normally (stop).
  624. const adapter = new MockAdapter([
  625. maxTokensResponse('first half'),
  626. textResponse('second half'),
  627. ])
  628. const ctx = await harness(adapter)
  629. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  630. let steps = 0
  631. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  632. // Force exactly one continuation (step 1 → step 2), then defer to default
  633. // (step 2 is a plain stop with no tool calls → stops).
  634. ctx.on('agent/turn-stopping', (subject) => {
  635. if (steps < 2) {
  636. subject.steer({ content: [{ type: 'text', text: 'continue after truncation' }], source: { kind: 'plugin', plugin: 'max-tokens-test' } })
  637. }
  638. })
  639. const reasons: TurnEndReason[] = []
  640. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  641. send(agent, 'go')
  642. await waitForIdle(ctx, agent)
  643. expect(steps).toBe(2)
  644. expect(adapter.requests).toHaveLength(2)
  645. expect(adapter.requests[1]!.messages).toEqual([
  646. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  647. { role: 'assistant', content: [{ type: 'text', text: 'first half' }], provenance: { provider: 'mock', model: 'mock' } },
  648. { role: 'user', content: [{ type: 'text', text: 'continue after truncation' }] },
  649. ])
  650. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  651. })
  652. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  653. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  654. // stop. The per-turn reason must be independent — turn 2 ends completed.
  655. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  656. const ctx = await harness(adapter)
  657. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  658. const reasons: TurnEndReason[] = []
  659. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  660. send(agent, 'first')
  661. await waitForIdle(ctx, agent)
  662. send(agent, 'second')
  663. await waitForIdle(ctx, agent)
  664. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  665. })
  666. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  667. const callId = CallId('c1')
  668. const adapter = new MockAdapter([[
  669. { type: 'block-start', index: 0, blockType: 'tool-call' },
  670. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  671. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  672. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  673. { type: 'finish', reason: { kind: 'max-tokens' } },
  674. ]])
  675. const ctx = await harness(adapter)
  676. let executions = 0
  677. ctx.tools.register(defineContentToolFixture({
  678. name: 'echo',
  679. description: '',
  680. parameters: { text: { type: 'string' } },
  681. async execute() {
  682. executions += 1
  683. return [{ type: 'text', text: 'should not run' }]
  684. },
  685. }))
  686. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  687. const reasons: TurnEndReason[] = []
  688. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  689. send(agent, 'go')
  690. await waitForIdle(ctx, agent)
  691. expect(executions).toBe(0)
  692. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  693. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  694. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  695. // Empty content still needs an assistant/message to carry usage; derivation
  696. // skips that host so it does not create a spurious assistant turn.
  697. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  698. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  699. turn: 1, step: 1, content: [], provenance: { provider: 'mock', model: 'mock' }, usage: { inputTokens: 10, outputTokens: 5 },
  700. })
  701. })
  702. it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
  703. // The truncated tool call is dropped from durable content, while the
  704. // successful provider call still needs an exact replay anchor.
  705. const callId = CallId('c1')
  706. const adapter = new MockAdapter([[
  707. { type: 'block-start', index: 0, blockType: 'tool-call' },
  708. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  709. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  710. { type: 'finish', reason: { kind: 'max-tokens' } },
  711. ]])
  712. const ctx = await harness(adapter)
  713. ctx.tools.register(defineContentToolFixture({
  714. name: 'echo',
  715. description: '',
  716. parameters: { text: { type: 'string' } },
  717. async execute() { return [{ type: 'text', text: 'should not run' }] },
  718. }))
  719. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  720. const reasons: TurnEndReason[] = []
  721. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  722. send(agent, 'go')
  723. await waitForIdle(ctx, agent)
  724. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  725. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  726. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  727. turn: 1,
  728. step: 1,
  729. content: [],
  730. provenance: { provider: 'mock', model: 'mock' },
  731. })
  732. expect(assistant.sourceEventSeqs?.length).toBeGreaterThan(0)
  733. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  734. })
  735. it('appends an empty completion anchor for a normal stop with no usage', async () => {
  736. // A clean content-less call stays absent from derived messages but remains
  737. // a durable successful-call boundary for replay consumers.
  738. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  739. const ctx = await harness(adapter)
  740. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  741. const reasons: TurnEndReason[] = []
  742. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  743. send(agent, 'go')
  744. await waitForIdle(ctx, agent)
  745. expect(reasons).toEqual([{ kind: 'completed' }])
  746. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  747. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  748. turn: 1,
  749. step: 1,
  750. content: [],
  751. provenance: { provider: 'mock', model: 'mock' },
  752. })
  753. expect(assistant.sourceEventSeqs?.length).toBe(1)
  754. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  755. })
  756. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  757. const callId = CallId('c1')
  758. const adapter = new MockAdapter([[
  759. { type: 'block-start', index: 0, blockType: 'text' },
  760. { type: 'text-delta', index: 0, text: 'partial text' },
  761. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  762. { type: 'block-start', index: 1, blockType: 'tool-call' },
  763. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  764. { type: 'finish', reason: { kind: 'max-tokens' } },
  765. ]])
  766. const ctx = await harness(adapter)
  767. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  768. send(agent, 'go')
  769. await waitForIdle(ctx, agent)
  770. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  771. expect(agent.session.deriveMessages()).toEqual([
  772. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  773. { role: 'assistant', content: [{ type: 'text', text: 'partial text' }], provenance: { provider: 'mock', model: 'mock' } },
  774. ])
  775. })
  776. it('contains a step/end observer failure without changing continuation', async () => {
  777. const adapter = new MockAdapter([
  778. toolCallResponse('c1', 'echo', { text: 'x' }),
  779. textResponse('continued after tool call'),
  780. ])
  781. const ctx = await harness(adapter)
  782. ctx.tools.register(defineContentToolFixture({
  783. name: 'echo',
  784. description: '',
  785. parameters: { text: { type: 'string' } },
  786. async execute(args) {
  787. return [{ type: 'text', text: String(args.text) }]
  788. },
  789. }))
  790. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  791. let threw = false
  792. // Post-commit session observers cannot control the loop. The tool call still
  793. // drives the second model request, and the turn completes normally.
  794. ctx.on('session/event', (_session, event) => {
  795. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  796. })
  797. send(agent, 'go')
  798. await waitForIdle(ctx, agent)
  799. expect(adapter.requests).toHaveLength(2)
  800. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  801. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  802. })
  803. it('keeps a reentrant agent/inbox/enqueue send as the next independent turn', async () => {
  804. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  805. const ctx = await harness(adapter)
  806. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  807. let nested = false
  808. ctx.on('agent/inbox/enqueue', (subject) => {
  809. if (subject !== agent || nested) return
  810. nested = true
  811. send(agent, 'queued listener message')
  812. })
  813. const idle = waitForIdle(ctx, agent)
  814. send(agent, 'outer message')
  815. await idle
  816. const turns = agent.session.events.filter(event => event.type === 'turn/start')
  817. const messages = agent.session.events
  818. .filter(event => event.type === 'user/message')
  819. .map(event => event.data.content)
  820. expect(turns).toHaveLength(2)
  821. expect(messages).toEqual([
  822. [{ type: 'text', text: 'outer message' }],
  823. [{ type: 'text', text: 'queued listener message' }],
  824. ])
  825. })
  826. it('preserves independent turn sources across an adjacent microtask send', async () => {
  827. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  828. const ctx = await harness(adapter)
  829. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  830. const idle = waitForIdle(ctx, agent)
  831. agent.followup({ content: [{ type: 'text', text: 'user message' }], source: { kind: 'user' } })
  832. await Promise.resolve()
  833. agent.followup({ content: [{ type: 'text', text: 'plugin message' }], source: { kind: 'plugin', plugin: 'test' } })
  834. await idle
  835. const triggers = agent.session.events
  836. .filter(event => event.type === 'turn/start')
  837. .map(event => event.data.trigger)
  838. const sources = agent.session.events
  839. .filter(event => event.type === 'user/message')
  840. .map(event => event.data.source)
  841. expect(triggers).toEqual([
  842. { kind: 'message', source: { kind: 'user' } },
  843. { kind: 'message', source: { kind: 'plugin', plugin: 'test' } },
  844. ])
  845. expect(sources).toEqual([
  846. { kind: 'user' },
  847. { kind: 'plugin', plugin: 'test' },
  848. ])
  849. })
  850. it('keeps a session-listener send after dequeue in the following turn', async () => {
  851. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  852. const ctx = await harness(adapter)
  853. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  854. const turns: number[] = []
  855. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  856. // queue two messages while idle — first starts turn 1 immediately;
  857. // queue the second during turn 1 when the first assistant chunk streams
  858. let queued = false
  859. ctx.on('session/event', (_s, event) => {
  860. if (event.type === 'assistant/chunk' && !queued) {
  861. queued = true
  862. send(agent, 'second message')
  863. }
  864. })
  865. send(agent, 'first message')
  866. await waitForIdle(ctx, agent)
  867. expect(turns).toEqual([1, 2])
  868. expect(adapter.requests).toHaveLength(2)
  869. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first')
  870. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  871. })
  872. it('keeps a model-adapter callback send in the following turn', async () => {
  873. const agentRef: { current?: Agent } = {}
  874. const adapter = new MockAdapter([
  875. () => {
  876. const agent = agentRef.current
  877. if (agent === undefined) throw new Error('model callback ran before agent setup')
  878. send(agent, 'model callback message')
  879. return textResponse('first')
  880. },
  881. textResponse('second'),
  882. ])
  883. const ctx = await harness(adapter)
  884. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  885. agentRef.current = agent
  886. const idle = waitForIdle(ctx, agent)
  887. send(agent, 'outer message')
  888. await idle
  889. const messages = agent.session.events
  890. .filter(event => event.type === 'user/message')
  891. .map(event => event.data.content)
  892. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  893. expect(messages).toEqual([
  894. [{ type: 'text', text: 'outer message' }],
  895. [{ type: 'text', text: 'model callback message' }],
  896. ])
  897. })
  898. it('errors from the model surface as agent/error and end the turn', async () => {
  899. const adapter = new MockAdapter([]) // script exhausted → throws
  900. const ctx = await harness(adapter)
  901. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  902. const errors: Error[] = []
  903. const reasons: TurnEndReason[] = []
  904. ctx.on('agent/error', (_agent, _turn, _step, error) => {
  905. if (error instanceof Error) errors.push(error)
  906. })
  907. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  908. send(agent, 'hi')
  909. await waitForIdle(ctx, agent)
  910. expect(errors).toHaveLength(1)
  911. expect(errors[0]!.message).toContain('script exhausted')
  912. expect(reasons[0]).toMatchObject({ kind: 'error' })
  913. // The durable failure lives entirely on turn/end.reason (with the failing
  914. // step), not a standalone error event.
  915. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  916. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  917. })
  918. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  919. const adapter = new MockAdapter(['hang'])
  920. const ctx = await harness(adapter)
  921. let agent!: Agent
  922. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  923. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  924. }, { inject: ['agentLoop'] }))
  925. expect(ctx.agents.get(SessionId('scoped'))).toBe(agent)
  926. send(agent, 'go')
  927. await new Promise(r => setTimeout(r, 30))
  928. expect(agent.status).toBe('running')
  929. await fiber.dispose()
  930. await driverDone(agent)
  931. expect(ctx.agents.get(SessionId('scoped'))).toBeUndefined()
  932. })
  933. it('creates agents from config on startup', async () => {
  934. const adapter = new MockAdapter([textResponse('from config')])
  935. const ctx = new Context()
  936. await ctx.plugin(LlmService)
  937. await ctx.plugin(SessionStore)
  938. await ctx.plugin(SystemPrompt)
  939. await ctx.plugin(ToolRegistry)
  940. await ctx.plugin(AgentRegistry)
  941. await ctx.plugin(AgentLoop, {
  942. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock' }],
  943. })
  944. ctx.llm.registerAdapter(['mock'], adapter)
  945. const agent = ctx.agents.list()[0]!
  946. expect(agent).toBeDefined()
  947. expect(agent.id).toBe(agent.session.id)
  948. expect(agent.id).toMatch(/^config-agent-session-/)
  949. expect(agent.options.model).toBe('mock')
  950. // the agent is alive: send triggers a turn
  951. send(agent, 'hi')
  952. await waitForIdle(ctx, agent)
  953. expect(adapter.requests).toHaveLength(1)
  954. })
  955. it('attaches config agent cwd to the fresh session header', async () => {
  956. const ctx = new Context()
  957. await ctx.plugin(LlmService)
  958. await ctx.plugin(SessionStore)
  959. await ctx.plugin(SystemPrompt)
  960. await ctx.plugin(ToolRegistry)
  961. await ctx.plugin(AgentRegistry)
  962. await ctx.plugin(AgentLoop, {
  963. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
  964. })
  965. const agent = ctx.agents.list()[0]!
  966. expect(agent.session.header.cwd).toBe('/work/project')
  967. })
  968. it('replays a session log into an identical derived history', async () => {
  969. const adapter = new MockAdapter([
  970. toolCallResponse('c1', 'echo', { text: 'x' }),
  971. textResponse('done'),
  972. ])
  973. const ctx = await harness(adapter)
  974. ctx.tools.register(defineContentToolFixture({
  975. name: 'echo',
  976. description: '',
  977. parameters: { text: { type: 'string' } },
  978. async execute(args) {
  979. return [{ type: 'text', text: String(args.text) }]
  980. },
  981. }))
  982. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  983. send(agent, 'run')
  984. await waitForIdle(ctx, agent)
  985. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  986. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  987. // event-by-event identity of types
  988. expect(replayed.events.map(e => e.type)).toEqual(
  989. agent.session.events.map(e => e.type))
  990. })
  991. })