loop.spec.ts 50 KB

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