loop.spec.ts 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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. // Durable inbox receipt and admission bracket 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).toEqual([])
  175. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  176. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('error')
  177. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error'
  178. ? turnEnd.data.reason.error
  179. : '').toContain('no value for this assembly')
  180. // The loop survived: a waterfall listener rescues {{cwd}} and the SAME
  181. // agent completes a real model turn.
  182. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  183. assembly.variables['cwd'] = '/rescued'
  184. return next()
  185. })
  186. send(agent, 'again')
  187. await waitForIdle(ctx, agent)
  188. expect(adapter.requests).toHaveLength(1)
  189. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nIn /rescued.')
  190. const turnEnds = agent.session.events.filter(e => e.type === 'turn/end')
  191. expect(turnEnds).toHaveLength(2)
  192. expect(turnEnds[1]?.type === 'turn/end' && turnEnds[1].data.reason.kind).toBe('completed')
  193. })
  194. it('supports the model-via-agent/request path with a {{model}} persona: the supplier states it via the assemble waterfall', async () => {
  195. // AgentOptions.model unset: the model arrives in the agent/request
  196. // waterfall (the loop's documented fallback — see runStep's no-model
  197. // error). {{model}} renders BEFORE that waterfall, so the SAME plugin
  198. // states the fact early on system-prompt/assemble — the owner of a
  199. // late-bound fact owns stating it wherever it is claimed.
  200. const adapter = new MockAdapter([textResponse('ok')])
  201. const ctx = await harness(adapter, 'You run on {{model}}.')
  202. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  203. assembly.variables['provider'] = 'mock'
  204. assembly.variables['model'] = 'mock'
  205. return next()
  206. })
  207. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  208. const config = await next()
  209. return { ...config, provider: 'mock', model: 'mock' }
  210. })
  211. const agent = ctx.agentLoop.create(SessionId('a-late-model'), {})
  212. send(agent, 'hi')
  213. await waitForIdle(ctx, agent)
  214. expect(adapter.requests).toHaveLength(1)
  215. expect(adapter.requests[0]!.model).toBe('mock')
  216. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou run on mock.')
  217. })
  218. it('omits the system field when a system-prompt/assemble veto empties the assembly', async () => {
  219. // The documented escape valve: a deployment that must drop the harness
  220. // openers short-circuits the assemble waterfall; the request then carries
  221. // NO system field at all (not an empty string).
  222. const adapter = new MockAdapter([textResponse('ok')])
  223. const ctx = await harness(adapter)
  224. ctx.on('system-prompt/assemble', async () => ({ sections: [], tools: [], variables: {} }))
  225. const agent = ctx.agentLoop.create(SessionId('a-no-system'), { provider: 'mock', model: 'mock' })
  226. send(agent, 'hi')
  227. await waitForIdle(ctx, agent)
  228. expect(adapter.requests).toHaveLength(1)
  229. expect('system' in adapter.requests[0]!).toBe(false)
  230. })
  231. it('records raw chunks for replay as assistant/chunk session events', async () => {
  232. const adapter = new MockAdapter([textResponse('abc')])
  233. const ctx = await harness(adapter)
  234. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  235. send(agent, 'hi')
  236. await waitForIdle(ctx, agent)
  237. const chunkEvents = agent.session.events.filter(e => e.type === 'assistant/chunk')
  238. // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7
  239. expect(chunkEvents).toHaveLength(7)
  240. // replay: chunk events alone re-assemble to the recorded assistant message
  241. const deltaText = chunkEvents
  242. .flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : [])
  243. .filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
  244. .map(c => c.text)
  245. .join('')
  246. expect(deltaText).toBe('abc')
  247. })
  248. it('injects steering between steps and continues the turn', async () => {
  249. const adapter = new MockAdapter([
  250. toolCallResponse('c1', 'slow', {}),
  251. textResponse('addressed the steering'),
  252. ])
  253. const ctx = await harness(adapter)
  254. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  255. ctx.tools.register(defineContentToolFixture({
  256. name: 'slow',
  257. description: '',
  258. parameters: {},
  259. async execute() {
  260. // steer while the turn is running (during tool execution)
  261. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'change of plans' }], source: { kind: 'user' } }))
  262. return [{ type: 'text', text: 'tool done' }]
  263. },
  264. }))
  265. send(agent, 'start')
  266. await waitForIdle(ctx, agent)
  267. const steering = agent.session.events.find(e =>
  268. e.type === 'user/message' && JSON.stringify(e.data.content).includes('change of plans'))
  269. expect(steering).toBeDefined()
  270. // Steering is admitted before the second step's request derives history.
  271. const steeringSeq = steering!.seq
  272. const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1]
  273. expect(secondStepStart).toBeDefined()
  274. expect(steeringSeq).toBeLessThan(secondStepStart!.seq)
  275. // the second model request saw the steering content
  276. const secondRequest = adapter.requests[1]
  277. const flat = JSON.stringify(secondRequest!.messages)
  278. expect(flat).toContain('change of plans')
  279. })
  280. it('coalesces same-tick idle steering into one turn', async () => {
  281. const adapter = new MockAdapter([textResponse('first')])
  282. const ctx = await harness(adapter)
  283. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  284. const idle = waitForIdle(ctx, agent)
  285. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'first idle steer' }], source: { kind: 'user' } }))
  286. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'second idle steer' }], source: { kind: 'user' } }))
  287. await idle
  288. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  289. expect(agent.session.events
  290. .filter(event => event.type === 'user/message')
  291. .map(event => event.data.content)).toEqual([
  292. [{ type: 'text', text: 'first idle steer' }],
  293. [{ type: 'text', text: 'second idle steer' }],
  294. ])
  295. expect(agent.session.events.filter(event => event.type === 'steering/message')).toEqual([])
  296. expect(adapter.requests).toHaveLength(1)
  297. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('first idle steer')
  298. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('second idle steer')
  299. })
  300. it('contains a throwing step observer and carries steering into a replacement turn', async () => {
  301. const adapter = new MockAdapter([textResponse('recovered')])
  302. const ctx = await harness(adapter)
  303. const agent = ctx.agentLoop.create(SessionId('failed-steering'), { provider: 'mock', model: 'mock' })
  304. let fail = true
  305. ctx.on('agent/step', (subject) => {
  306. if (subject !== agent || !fail) return
  307. fail = false
  308. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'pending steering' }], source: { kind: 'user' } }))
  309. throw new Error('step failed')
  310. })
  311. send(agent, 'prompt')
  312. await waitForIdle(ctx, agent)
  313. expect(adapter.requests).toHaveLength(1)
  314. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  315. expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(false)
  316. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('pending steering')
  317. })
  318. it('inject() while idle durably stages context without opening a turn', async () => {
  319. const adapter = new MockAdapter([textResponse('ok')])
  320. const ctx = await harness(adapter)
  321. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  322. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'file changed: a.ts' }], source: { kind: 'plugin', plugin: 'watcher' } }))
  323. expect(agent.status).toBe('idle')
  324. expect(adapter.requests).toHaveLength(0)
  325. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(0)
  326. expect(agent.session.events.at(-1)).toMatchObject({
  327. type: 'agent/inbox/spliced',
  328. data: {
  329. target: 'next-step',
  330. inserted: [{
  331. role: 'user',
  332. content: [{ type: 'text', text: 'file changed: a.ts' }],
  333. source: { kind: 'plugin', plugin: 'watcher' },
  334. }],
  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('continues for steering that arrived during a concluding tool 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. expect(adapter.requests).toHaveLength(2)
  492. const events = agent.session.events.map(event => event.type)
  493. expect(events.filter(type => type === 'turn/end')).toHaveLength(1)
  494. expect(JSON.stringify(adapter.requests[1]?.messages)).toContain('late steering')
  495. const texts = adapter.requests[1]!.messages
  496. .flatMap(message => message.content)
  497. .filter(block => block.type === 'text')
  498. .map(block => block.text)
  499. expect(texts).toContain('late steering')
  500. })
  501. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  502. const adapter = new MockAdapter([textResponse('ok')])
  503. const ctx = await harness(adapter)
  504. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  505. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  506. const config = await next()
  507. // The seed is frozen — config is not a mutable per-call knob; a switch
  508. // is proposed by returning a replacement, and the loop logs it.
  509. expect(Object.isFrozen(config)).toBe(true)
  510. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  511. return { ...config, model: 'other-model' }
  512. })
  513. send(agent, 'hi')
  514. await waitForIdle(ctx, agent)
  515. expect(adapter.requests[0]!.model).toBe('other-model')
  516. // The header event records what the request ACTUALLY used — the switch is
  517. // a reconstructable fact, not silent drift.
  518. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  519. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  520. })
  521. it('agent/step fires once per step before the step is opened', async () => {
  522. const adapter = new MockAdapter([
  523. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  524. textResponse('done'),
  525. ])
  526. const ctx = await harness(adapter)
  527. ctx.tools.register(defineContentToolFixture({
  528. name: 'echo', description: 'echo', parameters: {},
  529. async execute() { return [{ type: 'text', text: 'echoed' }] },
  530. }))
  531. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  532. const fires: { turn: number; step: number; signal: AbortSignal }[] = []
  533. ctx.on('agent/step', (subject, turn, step, signal) => {
  534. if (subject === agent) fires.push({ turn, step, signal })
  535. })
  536. send(agent, 'go')
  537. await waitForIdle(ctx, agent)
  538. expect(fires.map(({ turn, step }) => ({ turn, step }))).toEqual([
  539. { turn: 1, step: 1 },
  540. { turn: 1, step: 2 },
  541. ])
  542. expect(fires.every(({ signal }) => signal instanceof AbortSignal)).toBe(true)
  543. })
  544. it('agent/step fires after its step boundary opens and before the request', async () => {
  545. const adapter = new MockAdapter([textResponse('ok')])
  546. const ctx = await harness(adapter)
  547. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  548. let boundaryOpen = false
  549. ctx.on('agent/step', (subject) => {
  550. if (subject === agent) boundaryOpen = subject.session.events.at(-1)?.type === 'step/start'
  551. })
  552. send(agent, 'go')
  553. await waitForIdle(ctx, agent)
  554. expect(boundaryOpen).toBe(true)
  555. expect(adapter.requests).toHaveLength(1)
  556. })
  557. it('a throwing agent/step listener ends the turn (error), not the loop', async () => {
  558. // Before step/start, a pre-step throw reaches the turn catch: no step needs
  559. // closing, the turn records error, and the loop remains available.
  560. const adapter = new MockAdapter([textResponse('second turn ok')])
  561. const ctx = await harness(adapter)
  562. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  563. let throwOnce = true
  564. ctx.on('agent/step', () => {
  565. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  566. })
  567. const errors: Error[] = []
  568. ctx.on('agent/error', (_a, _t, _s, error) => {
  569. if (error instanceof Error) errors.push(error)
  570. })
  571. send(agent, 'first')
  572. await waitForIdle(ctx, agent)
  573. // The first turn failed at step 1 before a model call.
  574. expect(errors).toEqual([])
  575. expect(adapter.requests.length).toBe(0)
  576. const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
  577. expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error' })
  578. // The step opened-and-closed count stays balanced even though it never ran.
  579. const types = agent.session.events.map(e => e.type)
  580. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  581. // The loop survived: a second prompt runs a normal completed turn.
  582. send(agent, 'second')
  583. await waitForIdle(ctx, agent)
  584. expect(adapter.requests.length).toBe(1)
  585. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  586. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  587. })
  588. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  589. const adapter = new MockAdapter(['hang'])
  590. const ctx = await harness(adapter)
  591. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  592. const reasons: TurnEndReason[] = []
  593. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  594. send(agent, 'go')
  595. // wait until the stream is hanging, then cancel
  596. await new Promise(r => setTimeout(r, 30))
  597. expect(agent.status).toBe('running')
  598. agent.cancel({ kind: 'user' })
  599. await waitForIdle(ctx, agent)
  600. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  601. })
  602. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  603. // A single step that ends with a max-tokens finish (no tool calls): the
  604. // turn stops by default and ends max-tokens, not completed.
  605. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  606. const ctx = await harness(adapter)
  607. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  608. const reasons: TurnEndReason[] = []
  609. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  610. send(agent, 'go')
  611. await waitForIdle(ctx, agent)
  612. expect(adapter.requests).toHaveLength(1)
  613. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  614. // Assert the durable row, not only the live listener.
  615. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  616. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  617. })
  618. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  619. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  620. // must be FORCED to reach step 2 which finishes normally (stop).
  621. const adapter = new MockAdapter([
  622. maxTokensResponse('first half'),
  623. textResponse('second half'),
  624. ])
  625. const ctx = await harness(adapter)
  626. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  627. let steps = 0
  628. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  629. // Force exactly one continuation (step 1 → step 2), then defer to default
  630. // (step 2 is a plain stop with no tool calls → stops).
  631. ctx.on('agent/turn-stopping', (subject) => {
  632. if (steps < 2) {
  633. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue after truncation' }], source: { kind: 'plugin', plugin: 'max-tokens-test' } }))
  634. }
  635. })
  636. const reasons: TurnEndReason[] = []
  637. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  638. send(agent, 'go')
  639. await waitForIdle(ctx, agent)
  640. expect(steps).toBe(2)
  641. expect(adapter.requests).toHaveLength(2)
  642. expect(adapter.requests[1]!.messages).toEqual([
  643. {
  644. id: expect.any(String) as unknown,
  645. role: 'user',
  646. content: [{ type: 'text', text: 'go' }],
  647. source: { kind: 'user' },
  648. },
  649. {
  650. id: expect.any(String) as unknown,
  651. role: 'assistant',
  652. content: [{ type: 'text', text: 'first half' }],
  653. source: { kind: 'model', provider: 'mock', model: 'mock' },
  654. },
  655. {
  656. id: expect.any(String) as unknown,
  657. role: 'user',
  658. content: [{ type: 'text', text: 'continue after truncation' }],
  659. source: { kind: 'plugin', plugin: 'max-tokens-test' },
  660. },
  661. ])
  662. expect(reasons).toEqual([{ kind: 'completed' }])
  663. })
  664. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  665. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  666. // stop. The per-turn reason must be independent — turn 2 ends completed.
  667. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  668. const ctx = await harness(adapter)
  669. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  670. const reasons: TurnEndReason[] = []
  671. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  672. send(agent, 'first')
  673. await waitForIdle(ctx, agent)
  674. send(agent, 'second')
  675. await waitForIdle(ctx, agent)
  676. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  677. })
  678. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  679. const callId = CallId('c1')
  680. const adapter = new MockAdapter([[
  681. { type: 'block-start', index: 0, blockType: 'tool-call' },
  682. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  683. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  684. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  685. { type: 'finish', reason: { kind: 'max-tokens' } },
  686. ]])
  687. const ctx = await harness(adapter)
  688. let executions = 0
  689. ctx.tools.register(defineContentToolFixture({
  690. name: 'echo',
  691. description: '',
  692. parameters: { text: { type: 'string' } },
  693. async execute() {
  694. executions += 1
  695. return [{ type: 'text', text: 'should not run' }]
  696. },
  697. }))
  698. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  699. const reasons: TurnEndReason[] = []
  700. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  701. send(agent, 'go')
  702. await waitForIdle(ctx, agent)
  703. expect(executions).toBe(0)
  704. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  705. expect(agent.session.deriveMessages()).toEqual([{
  706. id: expect.any(String) as unknown,
  707. role: 'user',
  708. content: [{ type: 'text', text: 'go' }],
  709. source: { kind: 'user' },
  710. }])
  711. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  712. // Empty content still needs an assistant/message to carry usage; derivation
  713. // skips that host so it does not create a spurious assistant turn.
  714. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  715. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  716. turn: 1,
  717. step: 1,
  718. message: {
  719. id: expect.any(String) as unknown,
  720. role: 'assistant',
  721. content: [],
  722. source: { kind: 'model', provider: 'mock', model: 'mock' },
  723. },
  724. usage: { inputTokens: 10, outputTokens: 5 },
  725. })
  726. })
  727. it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
  728. // The truncated tool call is dropped from durable content, while the
  729. // successful provider call still needs an exact replay anchor.
  730. const callId = CallId('c1')
  731. const adapter = new MockAdapter([[
  732. { type: 'block-start', index: 0, blockType: 'tool-call' },
  733. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  734. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  735. { type: 'finish', reason: { kind: 'max-tokens' } },
  736. ]])
  737. const ctx = await harness(adapter)
  738. ctx.tools.register(defineContentToolFixture({
  739. name: 'echo',
  740. description: '',
  741. parameters: { text: { type: 'string' } },
  742. async execute() { return [{ type: 'text', text: 'should not run' }] },
  743. }))
  744. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  745. const reasons: TurnEndReason[] = []
  746. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  747. send(agent, 'go')
  748. await waitForIdle(ctx, agent)
  749. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  750. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  751. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  752. turn: 1,
  753. step: 1,
  754. message: {
  755. id: expect.any(String) as unknown,
  756. role: 'assistant',
  757. content: [],
  758. source: { kind: 'model', provider: 'mock', model: 'mock' },
  759. },
  760. })
  761. expect(assistant.sourceEventSeqs?.length).toBeGreaterThan(0)
  762. expect(agent.session.deriveMessages()).toEqual([{
  763. id: expect.any(String) as unknown,
  764. role: 'user',
  765. content: [{ type: 'text', text: 'go' }],
  766. source: { kind: 'user' },
  767. }])
  768. })
  769. it('appends an empty completion anchor for a normal stop with no usage', async () => {
  770. // A clean content-less call stays absent from derived messages but remains
  771. // a durable successful-call boundary for replay consumers.
  772. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  773. const ctx = await harness(adapter)
  774. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  775. const reasons: TurnEndReason[] = []
  776. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  777. send(agent, 'go')
  778. await waitForIdle(ctx, agent)
  779. expect(reasons).toEqual([{ kind: 'completed' }])
  780. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  781. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  782. turn: 1,
  783. step: 1,
  784. message: {
  785. id: expect.any(String) as unknown,
  786. role: 'assistant',
  787. content: [],
  788. source: { kind: 'model', provider: 'mock', model: 'mock' },
  789. },
  790. })
  791. expect(assistant.sourceEventSeqs?.length).toBe(1)
  792. expect(agent.session.deriveMessages()).toEqual([{
  793. id: expect.any(String) as unknown,
  794. role: 'user',
  795. content: [{ type: 'text', text: 'go' }],
  796. source: { kind: 'user' },
  797. }])
  798. })
  799. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  800. const callId = CallId('c1')
  801. const adapter = new MockAdapter([[
  802. { type: 'block-start', index: 0, blockType: 'text' },
  803. { type: 'text-delta', index: 0, text: 'partial text' },
  804. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  805. { type: 'block-start', index: 1, blockType: 'tool-call' },
  806. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  807. { type: 'finish', reason: { kind: 'max-tokens' } },
  808. ]])
  809. const ctx = await harness(adapter)
  810. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  811. send(agent, 'go')
  812. await waitForIdle(ctx, agent)
  813. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  814. expect(agent.session.deriveMessages()).toEqual([
  815. {
  816. id: expect.any(String) as unknown,
  817. role: 'user',
  818. content: [{ type: 'text', text: 'go' }],
  819. source: { kind: 'user' },
  820. },
  821. {
  822. id: expect.any(String) as unknown,
  823. role: 'assistant',
  824. content: [{ type: 'text', text: 'partial text' }],
  825. source: { kind: 'model', provider: 'mock', model: 'mock' },
  826. },
  827. ])
  828. })
  829. it('contains a step/end observer failure without changing continuation', async () => {
  830. const adapter = new MockAdapter([
  831. toolCallResponse('c1', 'echo', { text: 'x' }),
  832. textResponse('continued after tool call'),
  833. ])
  834. const ctx = await harness(adapter)
  835. ctx.tools.register(defineContentToolFixture({
  836. name: 'echo',
  837. description: '',
  838. parameters: { text: { type: 'string' } },
  839. async execute(args) {
  840. return [{ type: 'text', text: String(args.text) }]
  841. },
  842. }))
  843. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  844. let threw = false
  845. // Post-commit session observers cannot control the loop. The tool call still
  846. // drives the second model request, and the turn completes normally.
  847. ctx.on('session/event', (_session, event) => {
  848. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  849. })
  850. send(agent, 'go')
  851. await waitForIdle(ctx, agent)
  852. expect(adapter.requests).toHaveLength(2)
  853. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  854. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  855. })
  856. it('contains a reentrant send attempted during durable inbox publication', async () => {
  857. const adapter = new MockAdapter([textResponse('first')])
  858. const ctx = await harness(adapter)
  859. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  860. let nested = false
  861. ctx.on('session/event', (session, event) => {
  862. if (session !== agent.session || event.type !== 'agent/inbox/spliced'
  863. || event.data.inserted.length === 0 || nested) return
  864. nested = true
  865. send(agent, 'queued listener message')
  866. })
  867. const idle = waitForIdle(ctx, agent)
  868. send(agent, 'outer message')
  869. await idle
  870. const turns = agent.session.events.filter(event => event.type === 'turn/start')
  871. const messages = agent.session.events
  872. .filter(event => event.type === 'user/message')
  873. .map(event => event.data.content)
  874. expect(turns).toHaveLength(1)
  875. expect(messages).toEqual([[{ type: 'text', text: 'outer message' }]])
  876. })
  877. it('preserves independent turn sources across an adjacent microtask send', async () => {
  878. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  879. const ctx = await harness(adapter)
  880. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  881. const idle = waitForIdle(ctx, agent)
  882. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'user message' }], source: { kind: 'user' } }))
  883. await Promise.resolve()
  884. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'plugin message' }], source: { kind: 'plugin', plugin: 'test' } }))
  885. await idle
  886. const turns = agent.session.events.filter(event => event.type === 'turn/start')
  887. const sources = agent.session.events
  888. .filter(event => event.type === 'user/message')
  889. .map(event => event.data.source)
  890. expect(turns).toHaveLength(2)
  891. expect(sources).toEqual([
  892. { kind: 'user' },
  893. { kind: 'plugin', plugin: 'test' },
  894. ])
  895. })
  896. it('keeps a session-listener send after dequeue in the following turn', async () => {
  897. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  898. const ctx = await harness(adapter)
  899. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  900. const turns: number[] = []
  901. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  902. // queue two messages while idle — first starts turn 1 immediately;
  903. // queue the second during turn 1 when the first assistant chunk streams
  904. let queued = false
  905. ctx.on('session/event', (_s, event) => {
  906. if (event.type === 'assistant/chunk' && !queued) {
  907. queued = true
  908. queueMicrotask(() => { send(agent, 'second message') })
  909. }
  910. })
  911. send(agent, 'first message')
  912. await waitForIdle(ctx, agent)
  913. expect(turns).toEqual([1, 2])
  914. expect(adapter.requests).toHaveLength(2)
  915. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first')
  916. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  917. })
  918. it('keeps a model-adapter callback send in the following turn', async () => {
  919. const agentRef: { current?: Agent } = {}
  920. const adapter = new MockAdapter([
  921. () => {
  922. const agent = agentRef.current
  923. if (agent === undefined) throw new Error('model callback ran before agent setup')
  924. send(agent, 'model callback message')
  925. return textResponse('first')
  926. },
  927. textResponse('second'),
  928. ])
  929. const ctx = await harness(adapter)
  930. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  931. agentRef.current = agent
  932. const idle = waitForIdle(ctx, agent)
  933. send(agent, 'outer message')
  934. await idle
  935. const messages = agent.session.events
  936. .filter(event => event.type === 'user/message')
  937. .map(event => event.data.content)
  938. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  939. expect(messages).toEqual([
  940. [{ type: 'text', text: 'outer message' }],
  941. [{ type: 'text', text: 'model callback message' }],
  942. ])
  943. })
  944. it('records normalized model errors on the turn boundary', async () => {
  945. const adapter = new MockAdapter([]) // script exhausted → throws
  946. const ctx = await harness(adapter)
  947. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  948. const errors: Error[] = []
  949. const reasons: TurnEndReason[] = []
  950. ctx.on('agent/error', (_agent, _turn, _step, error) => {
  951. if (error instanceof Error) errors.push(error)
  952. })
  953. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  954. send(agent, 'hi')
  955. await waitForIdle(ctx, agent)
  956. expect(errors).toEqual([])
  957. expect(reasons[0]).toMatchObject({ kind: 'error' })
  958. // The durable failure lives entirely on turn/end.reason (with the failing
  959. // step), not a standalone error event.
  960. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  961. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error' })
  962. })
  963. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  964. const adapter = new MockAdapter(['hang'])
  965. const ctx = await harness(adapter)
  966. let agent!: Agent
  967. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  968. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  969. }, { inject: ['agentLoop'] }))
  970. expect(ctx.agents.get(SessionId('scoped'))).toBe(agent)
  971. send(agent, 'go')
  972. await new Promise(r => setTimeout(r, 30))
  973. expect(agent.status).toBe('running')
  974. await fiber.dispose()
  975. await driverDone(agent)
  976. expect(ctx.agents.get(SessionId('scoped'))).toBeUndefined()
  977. })
  978. it('creates agents from config on startup', async () => {
  979. const adapter = new MockAdapter([textResponse('from config')])
  980. const ctx = new Context()
  981. await ctx.plugin(LlmService)
  982. await ctx.plugin(SessionStore)
  983. await ctx.plugin(SystemPrompt)
  984. await ctx.plugin(ToolRegistry)
  985. await ctx.plugin(AgentRegistry)
  986. await ctx.plugin(AgentLoop, {
  987. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock' }],
  988. })
  989. ctx.llm.registerAdapter(['mock'], adapter)
  990. const agent = ctx.agents.list()[0]!
  991. expect(agent).toBeDefined()
  992. expect(agent.id).toBe(agent.session.id)
  993. expect(agent.id).toMatch(/^config-agent-session-/)
  994. expect(agent.options.model).toBe('mock')
  995. // the agent is alive: send triggers a turn
  996. send(agent, 'hi')
  997. await waitForIdle(ctx, agent)
  998. expect(adapter.requests).toHaveLength(1)
  999. })
  1000. it('attaches config agent cwd to the fresh session header', async () => {
  1001. const ctx = new Context()
  1002. await ctx.plugin(LlmService)
  1003. await ctx.plugin(SessionStore)
  1004. await ctx.plugin(SystemPrompt)
  1005. await ctx.plugin(ToolRegistry)
  1006. await ctx.plugin(AgentRegistry)
  1007. await ctx.plugin(AgentLoop, {
  1008. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
  1009. })
  1010. const agent = ctx.agents.list()[0]!
  1011. expect(agent.session.header.cwd).toBe('/work/project')
  1012. })
  1013. it('replays a session log into an identical derived history', async () => {
  1014. const adapter = new MockAdapter([
  1015. toolCallResponse('c1', 'echo', { text: 'x' }),
  1016. textResponse('done'),
  1017. ])
  1018. const ctx = await harness(adapter)
  1019. ctx.tools.register(defineContentToolFixture({
  1020. name: 'echo',
  1021. description: '',
  1022. parameters: { text: { type: 'string' } },
  1023. async execute(args) {
  1024. return [{ type: 'text', text: String(args.text) }]
  1025. },
  1026. }))
  1027. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1028. send(agent, 'run')
  1029. await waitForIdle(ctx, agent)
  1030. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  1031. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  1032. // event-by-event identity of types over the inherited prefix
  1033. expect(replayed.events.slice(0, agent.session.seq).map(e => e.type)).toEqual(
  1034. agent.session.events.map(e => e.type))
  1035. expect(replayed.events.at(-1)?.type).toBe('session/end-seed')
  1036. })
  1037. })