loop.spec.ts 50 KB

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