loop.spec.ts 59 KB

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