loop.spec.ts 51 KB

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