loop.spec.ts 59 KB

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