loop.spec.ts 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  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.send(
  416. createUserMessage({ content: [{ type: 'text', text: 'change of plans' }], source: { kind: 'user' } }),
  417. { target: 'next-step', wakeup: true },
  418. )
  419. return [{ type: 'text', text: 'tool done' }]
  420. },
  421. }))
  422. send(agent, 'start')
  423. await waitForIdle(ctx, agent)
  424. const types = agent.session.events.map(e => e.type)
  425. expect(types).toContain('steering/message')
  426. // steering recorded before the second step's request derived its history
  427. const steeringSeq = agent.session.events.find(e => e.type === 'steering/message')!.seq
  428. const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1]
  429. expect(secondStepStart).toBeDefined()
  430. expect(steeringSeq).toBeLessThan(secondStepStart!.seq)
  431. // the second model request saw the steering content
  432. const secondRequest = adapter.requests[1]
  433. const flat = JSON.stringify(secondRequest!.messages)
  434. expect(flat).toContain('change of plans')
  435. })
  436. it('same-tick idle steering preserves one turn per send', async () => {
  437. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  438. const ctx = await harness(adapter)
  439. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  440. const idle = waitForIdle(ctx, agent)
  441. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'first idle steer' }], source: { kind: 'user' } }))
  442. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'second idle steer' }], source: { kind: 'user' } }))
  443. await idle
  444. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  445. expect(agent.session.events
  446. .filter(event => event.type === 'user/message')
  447. .map(event => event.data.content)).toEqual([
  448. [{ type: 'text', text: 'first idle steer' }],
  449. [{ type: 'text', text: 'second idle steer' }],
  450. ])
  451. expect(agent.session.events.filter(event => event.type === 'steering/message')).toEqual([])
  452. expect(adapter.requests).toHaveLength(2)
  453. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('first idle steer')
  454. expect(JSON.stringify(adapter.requests[0]?.messages)).not.toContain('second idle steer')
  455. expect(JSON.stringify(adapter.requests[1]?.messages)).toContain('second idle steer')
  456. })
  457. it('keeps steering staged after a failed step until the next admitted turn', async () => {
  458. const adapter = new MockAdapter([textResponse('recovered')])
  459. const ctx = await harness(adapter)
  460. const agent = ctx.agentLoop.create(SessionId('failed-steering'), { provider: 'mock', model: 'mock' })
  461. let fail = true
  462. ctx.on('agent/step', (subject) => {
  463. if (subject !== agent || !fail) return
  464. fail = false
  465. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'pending steering' }], source: { kind: 'user' } }))
  466. throw new Error('step failed')
  467. })
  468. send(agent, 'prompt')
  469. await waitForIdle(ctx, agent)
  470. expect(adapter.requests).toHaveLength(0)
  471. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  472. expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(false)
  473. send(agent, 'resume')
  474. await waitForIdle(ctx, agent)
  475. expect(adapter.requests).toHaveLength(1)
  476. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  477. expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(true)
  478. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('pending steering')
  479. })
  480. it('rejects failed steering commits while preserving later context', async () => {
  481. const adapter = new MockAdapter([textResponse('recovered')])
  482. const ctx = await harness(adapter)
  483. const agent = ctx.agentLoop.create(SessionId('failed-steering-commit'), { provider: 'mock', model: 'mock' })
  484. let receipt: ReturnType<Agent['steer']> | undefined
  485. ctx.on('agent/step', (subject) => {
  486. if (subject !== agent || receipt !== undefined) return
  487. receipt = subject.steer(createUserMessage({
  488. content: [{ type: 'text', text: 'rejected steering' }],
  489. source: { kind: 'user' },
  490. }))
  491. subject.inject(createUserMessage({
  492. content: [{ type: 'text', text: 'preserved context' }],
  493. source: { kind: 'plugin', plugin: 'loop-test' },
  494. }))
  495. })
  496. let rejected = false
  497. ctx.on('internal/dispatch', (_mode, name, args) => {
  498. if (name !== 'session/event') return
  499. const event = args[1] as { type: string }
  500. if (event.type === 'steering/message' && !rejected) {
  501. rejected = true
  502. throw new Error('reject steering commit')
  503. }
  504. })
  505. send(agent, 'first prompt')
  506. await waitForIdle(ctx, agent)
  507. expect(adapter.requests).toHaveLength(0)
  508. if (receipt === undefined) throw new Error('agent/step did not submit steering')
  509. expect(await receipt.outcome).toEqual({ status: 'rejected' })
  510. expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(false)
  511. send(agent, 'recover')
  512. await waitForIdle(ctx, agent)
  513. expect(adapter.requests).toHaveLength(1)
  514. const request = JSON.stringify(adapter.requests[0]?.messages)
  515. expect(request).toContain('preserved context')
  516. expect(request).not.toContain('rejected steering')
  517. })
  518. it('rejects committed steering when the step boundary fails', async () => {
  519. const adapter = new MockAdapter([])
  520. const ctx = await harness(adapter)
  521. const agent = ctx.agentLoop.create(SessionId('failed-step-boundary'), { provider: 'mock', model: 'mock' })
  522. let receipt: ReturnType<Agent['steer']> | undefined
  523. ctx.on('agent/step', (subject) => {
  524. if (subject !== agent || receipt !== undefined) return
  525. receipt = subject.steer(createUserMessage({
  526. content: [{ type: 'text', text: 'committed steering' }],
  527. source: { kind: 'user' },
  528. }))
  529. })
  530. ctx.on('internal/dispatch', (_mode, name, args) => {
  531. if (name !== 'session/event') return
  532. const event = args[1] as { type: string }
  533. if (event.type === 'step/start') throw new Error('reject step boundary')
  534. })
  535. send(agent, 'prompt')
  536. await waitForIdle(ctx, agent)
  537. if (receipt === undefined) throw new Error('agent/step did not submit steering')
  538. expect(await receipt.outcome).toEqual({ status: 'rejected' })
  539. expect(adapter.requests).toHaveLength(0)
  540. expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(true)
  541. expect(agent.session.events.some(event => event.type === 'step/start')).toBe(false)
  542. })
  543. it('retries context and steering after a context commit fails', async () => {
  544. const adapter = new MockAdapter([textResponse('recovered')])
  545. const ctx = await harness(adapter)
  546. const agent = ctx.agentLoop.create(SessionId('failed-context-commit'), { provider: 'mock', model: 'mock' })
  547. let receipt: ReturnType<Agent['steer']> | undefined
  548. ctx.on('agent/step', (subject) => {
  549. if (subject !== agent || receipt !== undefined) return
  550. subject.inject(createUserMessage({
  551. content: [{ type: 'text', text: 'preserved context' }],
  552. source: { kind: 'plugin', plugin: 'loop-test' },
  553. }))
  554. receipt = subject.steer(createUserMessage({
  555. content: [{ type: 'text', text: 'preserved steering' }],
  556. source: { kind: 'user' },
  557. }))
  558. })
  559. let rejected = false
  560. ctx.on('internal/dispatch', (_mode, name, args) => {
  561. if (name !== 'session/event') return
  562. const event = args[1] as { type: string; data?: { source?: { kind: string } } }
  563. if (event.type === 'user/message' && event.data?.source?.kind === 'plugin' && !rejected) {
  564. rejected = true
  565. throw new Error('reject context commit')
  566. }
  567. })
  568. send(agent, 'first prompt')
  569. await waitForIdle(ctx, agent)
  570. expect(adapter.requests).toHaveLength(0)
  571. expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(false)
  572. send(agent, 'recover')
  573. await waitForIdle(ctx, agent)
  574. if (receipt === undefined) throw new Error('agent/step did not submit steering')
  575. expect(await receipt.outcome).toEqual({ status: 'admitted', turn: 2, step: 1 })
  576. expect(adapter.requests).toHaveLength(1)
  577. const request = JSON.stringify(adapter.requests[0]?.messages)
  578. expect(request).toContain('preserved context')
  579. expect(request).toContain('preserved steering')
  580. })
  581. it('inject() while idle appends context without opening a turn', async () => {
  582. const adapter = new MockAdapter([textResponse('ok')])
  583. const ctx = await harness(adapter)
  584. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  585. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'file changed: a.ts' }], source: { kind: 'plugin', plugin: 'watcher' } }))
  586. expect(agent.status).toBe('idle')
  587. expect(adapter.requests).toHaveLength(0)
  588. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(0)
  589. expect(agent.session.events.at(-1)).toMatchObject({
  590. type: 'user/message',
  591. data: {
  592. role: 'user',
  593. content: [{ type: 'text', text: 'file changed: a.ts' }],
  594. source: { kind: 'plugin', plugin: 'watcher' },
  595. },
  596. })
  597. send(agent, 'go')
  598. await waitForIdle(ctx, agent)
  599. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  600. const flat = JSON.stringify(adapter.requests[0]!.messages)
  601. expect(flat).toContain('file changed: a.ts')
  602. expect(flat).not.toContain('<context source=')
  603. })
  604. it('inject() persists structured context content verbatim with durable source', async () => {
  605. const adapter = new MockAdapter([textResponse('ok')])
  606. const ctx = await harness(adapter)
  607. const agent = ctx.agentLoop.create(SessionId('raw-context'), { provider: 'mock', model: 'mock' })
  608. const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
  609. agent.inject(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'plugin', plugin: 'workspace-context' } }))
  610. send(agent, 'go')
  611. await waitForIdle(ctx, agent)
  612. const contextEvent = agent.session.events.find(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  613. expect(contextEvent?.type === 'user/message' && contextEvent.data.source)
  614. .toEqual({ kind: 'plugin', plugin: 'workspace-context' })
  615. const requestText = JSON.stringify(adapter.requests[0]!.messages)
  616. expect(requestText).toContain('Additional instructions from: pkg/AGENTS.md')
  617. expect(requestText).not.toContain('<context source=')
  618. })
  619. it('defers inject() during tool execution until after the tool result', async () => {
  620. const adapter = new MockAdapter([
  621. toolCallResponse('c1', 'noticer', {}, 'calling'),
  622. textResponse('done'),
  623. ])
  624. const ctx = await harness(adapter)
  625. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  626. let visibleDuringTool = false
  627. ctx.tools.register(defineContentToolFixture({
  628. name: 'noticer',
  629. description: 'injects a notice',
  630. parameters: {},
  631. async execute() {
  632. await Promise.resolve()
  633. const first = { type: 'text' as const, text: 'mid-turn notice' }
  634. agent.inject(createUserMessage({ content: [first], source: { kind: 'plugin', plugin: 'x' } }))
  635. first.text = 'mutated after inject'
  636. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'second notice' }], source: { kind: 'plugin', plugin: 'x' } }))
  637. visibleDuringTool = agent.session.events.some(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  638. return [{ type: 'text', text: 'ok' }]
  639. },
  640. }))
  641. send(agent, 'go')
  642. await waitForIdle(ctx, agent)
  643. expect(visibleDuringTool).toBe(false)
  644. // The injection stays in the open turn, but its user-role context cannot
  645. // split the assistant tool call from the provider's tool-result message.
  646. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  647. expect(turnStarts).toHaveLength(1)
  648. const ts0 = turnStarts[0]!
  649. expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
  650. const result = agent.session.events.find(e => e.type === 'tool/result')!
  651. const contexts = agent.session.events.filter(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  652. expect(contexts).toHaveLength(2)
  653. expect(result.seq).toBeLessThan(contexts[0]!.seq)
  654. expect(contexts.flatMap(event => event.type === 'user/message' ? event.data.content : []))
  655. .toEqual([
  656. { type: 'text', text: 'mid-turn notice' },
  657. { type: 'text', text: 'second notice' },
  658. ])
  659. const secondRequest = adapter.requests[1]!.messages
  660. const resultIndex = secondRequest.findIndex(message =>
  661. message.content.some(block => block.type === 'tool-result'))
  662. const contextIndexes = secondRequest.flatMap((message, index) =>
  663. message.content.some(block => block.type === 'text'
  664. && (block.text.includes('mid-turn notice') || block.text.includes('second notice')))
  665. ? [index]
  666. : [])
  667. expect(resultIndex).toBeGreaterThanOrEqual(0)
  668. expect(contextIndexes).toHaveLength(2)
  669. expect(contextIndexes.every(index => index > resultIndex)).toBe(true)
  670. })
  671. it('rejects non-JSON context before it enters the active tool-batch FIFO', async () => {
  672. const adapter = new MockAdapter([
  673. toolCallResponse('c1', 'invalid-injector', {}, 'calling'),
  674. textResponse('done'),
  675. ])
  676. const ctx = await harness(adapter)
  677. const agent = ctx.agentLoop.create(SessionId('invalid-context'), { provider: 'mock', model: 'mock' })
  678. ctx.tools.register(defineContentToolFixture({
  679. name: 'invalid-injector',
  680. description: 'attempts an invalid context injection',
  681. parameters: {},
  682. async execute() {
  683. expect(() => {
  684. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'invalid' }], source: { kind: 'plugin', plugin: 'test', bigint: 1n } as never }))
  685. }).toThrow('agent context must be losslessly JSON-serializable')
  686. return [{ type: 'text', text: 'rejected invalid context' }]
  687. },
  688. }))
  689. send(agent, 'go')
  690. await waitForIdle(ctx, agent)
  691. expect(agent.session.events.some(event => event.type === 'user/message' && event.data.source.kind === 'plugin')).toBe(false)
  692. })
  693. it('agent/turn-stopping can steer another step (/loop pattern)', async () => {
  694. const adapter = new MockAdapter([
  695. textResponse('step 1'),
  696. textResponse('step 2'),
  697. textResponse('step 3'),
  698. ])
  699. const ctx = await harness(adapter)
  700. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  701. let steps = 0
  702. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  703. ctx.on('agent/turn-stopping', (subject) => {
  704. if (steps < 3) {
  705. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'plugin', plugin: 'loop-test' } }))
  706. }
  707. })
  708. send(agent, 'go')
  709. await waitForIdle(ctx, agent)
  710. expect(steps).toBe(3)
  711. expect(adapter.requests).toHaveLength(3)
  712. })
  713. it('a tool can conclude the turn despite owing a follow-up request', async () => {
  714. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  715. const ctx = await harness(adapter)
  716. ctx.tools.register(defineContentToolFixture({
  717. name: 'echo',
  718. description: '',
  719. parameters: { text: { type: 'string' } },
  720. async execute(args, exec) {
  721. exec.concludeTurn()
  722. return [{ type: 'text', text: String(args.text) }]
  723. },
  724. }))
  725. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  726. send(agent, 'go')
  727. await waitForIdle(ctx, agent)
  728. // only one model call despite the tool call requesting a follow-up
  729. expect(adapter.requests).toHaveLength(1)
  730. // The tool still executes and durably records its result.
  731. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  732. })
  733. it('a concluding tool result beats steering that arrived during the same step', async () => {
  734. const adapter = new MockAdapter([
  735. toolCallResponse('c1', 'finalize', {}),
  736. textResponse('next turn reply'),
  737. ])
  738. const ctx = await harness(adapter)
  739. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  740. let receipt: ReturnType<Agent['steer']> | undefined
  741. let contextInjected = false
  742. ctx.on('session/event', (session, event) => {
  743. if (session !== agent.session || event.type !== 'step/end' || contextInjected) return
  744. contextInjected = true
  745. agent.inject(createUserMessage({
  746. content: [{ type: 'text', text: 'final context' }],
  747. source: { kind: 'plugin', plugin: 'finalize' },
  748. }))
  749. })
  750. ctx.tools.register(defineContentToolFixture({
  751. name: 'finalize',
  752. description: '',
  753. parameters: {},
  754. async execute(_args, exec) {
  755. // Steering lands while the concluding tool is still executing; the
  756. // step/end listener adds ordinary context after the normal result drain.
  757. receipt = agent.steer(createUserMessage({ content: [{ type: 'text', text: 'late steering' }], source: { kind: 'user' } }))
  758. exec.concludeTurn()
  759. return [{ type: 'text', text: 'final' }]
  760. },
  761. }))
  762. send(agent, 'go')
  763. await waitForIdle(ctx, agent)
  764. // The terminal result stands: no extra request reopens the concluded turn.
  765. expect(adapter.requests).toHaveLength(1)
  766. const events = agent.session.events.map(event => event.type)
  767. expect(events.filter(type => type === 'turn/end')).toHaveLength(1)
  768. if (receipt === undefined) throw new Error('concluding tool did not submit steering')
  769. expect(await receipt.outcome).toEqual({ status: 'rejected' })
  770. expect(events).not.toContain('steering/message')
  771. expect(agent.session.events.some(event => event.type === 'user/message'
  772. && event.data.source.kind === 'plugin'
  773. && event.data.content.some(block => block.type === 'text' && block.text === 'final context'))).toBe(true)
  774. send(agent, 'follow up')
  775. await waitForIdle(ctx, agent)
  776. expect(adapter.requests).toHaveLength(2)
  777. const texts = adapter.requests[1]!.messages
  778. .flatMap(message => message.content)
  779. .filter(block => block.type === 'text')
  780. .map(block => block.text)
  781. expect(texts).toContain('final context')
  782. expect(texts).not.toContain('late steering')
  783. })
  784. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  785. const adapter = new MockAdapter([textResponse('ok')])
  786. const ctx = await harness(adapter)
  787. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  788. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  789. const config = await next()
  790. // The seed is frozen — config is not a mutable per-call knob; a switch
  791. // is proposed by returning a replacement, and the loop logs it.
  792. expect(Object.isFrozen(config)).toBe(true)
  793. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  794. return { ...config, model: 'other-model' }
  795. })
  796. send(agent, 'hi')
  797. await waitForIdle(ctx, agent)
  798. expect(adapter.requests[0]!.model).toBe('other-model')
  799. // The header event records what the request ACTUALLY used — the switch is
  800. // a reconstructable fact, not silent drift.
  801. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  802. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  803. })
  804. it('agent/step fires once per step before the step is opened', async () => {
  805. const adapter = new MockAdapter([
  806. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  807. textResponse('done'),
  808. ])
  809. const ctx = await harness(adapter)
  810. ctx.tools.register(defineContentToolFixture({
  811. name: 'echo', description: 'echo', parameters: {},
  812. async execute() { return [{ type: 'text', text: 'echoed' }] },
  813. }))
  814. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  815. const fires: { turn: number; step: number; signal: AbortSignal }[] = []
  816. ctx.on('agent/step', (subject, turn, step, signal) => {
  817. if (subject === agent) fires.push({ turn, step, signal })
  818. })
  819. send(agent, 'go')
  820. await waitForIdle(ctx, agent)
  821. expect(fires.map(({ turn, step }) => ({ turn, step }))).toEqual([
  822. { turn: 1, step: 1 },
  823. { turn: 1, step: 2 },
  824. ])
  825. expect(fires.every(({ signal }) => signal instanceof AbortSignal)).toBe(true)
  826. })
  827. it('agent/step fires BEFORE the step it precedes opens (events land outside the step)', async () => {
  828. // The append lands before step/start, yet derive happens afterwards and the
  829. // same step's request must include it.
  830. const adapter = new MockAdapter([textResponse('ok')])
  831. const ctx = await harness(adapter)
  832. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  833. let injected = false
  834. ctx.on('agent/step', (subject) => {
  835. if (subject === agent && !injected) {
  836. injected = true
  837. subject.session.append('user/message', createUserMessage({
  838. content: [{ type: 'text', text: 'INJECTED-IN-PRE-STEP' }],
  839. source: { kind: 'plugin', plugin: 'test' },
  840. }), { surfaceOp: 'append' })
  841. }
  842. })
  843. send(agent, 'go')
  844. await waitForIdle(ctx, agent)
  845. // The adapter's request includes the node injected during pre-step (derive
  846. // reflects it).
  847. const text = JSON.stringify(adapter.requests[0]!.messages)
  848. expect(text).toContain('INJECTED-IN-PRE-STEP')
  849. // And the injected event sits BEFORE the first step/start in the log —
  850. // the seam fired outside the step.
  851. const events = agent.session.events
  852. const injectedSeq = events.find(e => e.type === 'user/message' && e.data.source.kind === 'plugin')!.seq
  853. const firstStepStartSeq = events.find(e => e.type === 'step/start')!.seq
  854. expect(injectedSeq).toBeLessThan(firstStepStartSeq)
  855. })
  856. it('a throwing agent/step listener ends the turn (error), not the loop', async () => {
  857. // Before step/start, a pre-step throw reaches the turn catch: no step needs
  858. // closing, the turn records error, and the loop remains available.
  859. const adapter = new MockAdapter([textResponse('second turn ok')])
  860. const ctx = await harness(adapter)
  861. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  862. let throwOnce = true
  863. ctx.on('agent/step', () => {
  864. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  865. })
  866. const errors: Error[] = []
  867. ctx.on('agent/error', (_a, _t, _s, error) => {
  868. if (error instanceof Error) errors.push(error)
  869. })
  870. send(agent, 'first')
  871. await waitForIdle(ctx, agent)
  872. // The first turn failed at step 1 (no model call happened), surfaced via
  873. // agent/error, with the durable failure on turn/end.reason.
  874. expect(errors).toHaveLength(1)
  875. expect(errors[0]!.message).toContain('boom in pre-step')
  876. expect(adapter.requests.length).toBe(0)
  877. const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
  878. expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  879. // The step opened-and-closed count stays balanced even though it never ran.
  880. const types = agent.session.events.map(e => e.type)
  881. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  882. // The loop survived: a second prompt runs a normal completed turn.
  883. send(agent, 'second')
  884. await waitForIdle(ctx, agent)
  885. expect(adapter.requests.length).toBe(1)
  886. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  887. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  888. })
  889. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  890. const adapter = new MockAdapter(['hang'])
  891. const ctx = await harness(adapter)
  892. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  893. const reasons: TurnEndReason[] = []
  894. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  895. send(agent, 'go')
  896. // wait until the stream is hanging, then cancel
  897. await new Promise(r => setTimeout(r, 30))
  898. expect(agent.status).toBe('running')
  899. agent.cancel({ kind: 'user' })
  900. await waitForIdle(ctx, agent)
  901. expect(reasons).toEqual([{ kind: 'aborted' }])
  902. })
  903. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  904. // A single step that ends with a max-tokens finish (no tool calls): the
  905. // turn stops by default and ends max-tokens, not completed.
  906. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  907. const ctx = await harness(adapter)
  908. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  909. const reasons: TurnEndReason[] = []
  910. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  911. send(agent, 'go')
  912. await waitForIdle(ctx, agent)
  913. expect(adapter.requests).toHaveLength(1)
  914. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  915. // Assert the durable row, not only the live listener.
  916. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  917. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  918. })
  919. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  920. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  921. // must be FORCED to reach step 2 which finishes normally (stop).
  922. const adapter = new MockAdapter([
  923. maxTokensResponse('first half'),
  924. textResponse('second half'),
  925. ])
  926. const ctx = await harness(adapter)
  927. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  928. let steps = 0
  929. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  930. // Force exactly one continuation (step 1 → step 2), then defer to default
  931. // (step 2 is a plain stop with no tool calls → stops).
  932. ctx.on('agent/turn-stopping', (subject) => {
  933. if (steps < 2) {
  934. subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue after truncation' }], source: { kind: 'plugin', plugin: 'max-tokens-test' } }))
  935. }
  936. })
  937. const reasons: TurnEndReason[] = []
  938. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  939. send(agent, 'go')
  940. await waitForIdle(ctx, agent)
  941. expect(steps).toBe(2)
  942. expect(adapter.requests).toHaveLength(2)
  943. expect(adapter.requests[1]!.messages).toEqual([
  944. {
  945. id: expect.any(String) as unknown,
  946. role: 'user',
  947. content: [{ type: 'text', text: 'go' }],
  948. source: { kind: 'user' },
  949. },
  950. {
  951. id: expect.any(String) as unknown,
  952. role: 'assistant',
  953. content: [{ type: 'text', text: 'first half' }],
  954. source: { kind: 'model', provider: 'mock', model: 'mock' },
  955. },
  956. {
  957. id: expect.any(String) as unknown,
  958. role: 'user',
  959. content: [{ type: 'text', text: 'continue after truncation' }],
  960. source: { kind: 'plugin', plugin: 'max-tokens-test' },
  961. },
  962. ])
  963. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  964. })
  965. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  966. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  967. // stop. The per-turn reason must be independent — turn 2 ends completed.
  968. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  969. const ctx = await harness(adapter)
  970. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  971. const reasons: TurnEndReason[] = []
  972. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  973. send(agent, 'first')
  974. await waitForIdle(ctx, agent)
  975. send(agent, 'second')
  976. await waitForIdle(ctx, agent)
  977. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  978. })
  979. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  980. const callId = CallId('c1')
  981. const adapter = new MockAdapter([[
  982. { type: 'block-start', index: 0, blockType: 'tool-call' },
  983. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  984. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  985. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  986. { type: 'finish', reason: { kind: 'max-tokens' } },
  987. ]])
  988. const ctx = await harness(adapter)
  989. let executions = 0
  990. ctx.tools.register(defineContentToolFixture({
  991. name: 'echo',
  992. description: '',
  993. parameters: { text: { type: 'string' } },
  994. async execute() {
  995. executions += 1
  996. return [{ type: 'text', text: 'should not run' }]
  997. },
  998. }))
  999. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1000. const reasons: TurnEndReason[] = []
  1001. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1002. send(agent, 'go')
  1003. await waitForIdle(ctx, agent)
  1004. expect(executions).toBe(0)
  1005. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  1006. expect(agent.session.deriveMessages()).toEqual([{
  1007. id: expect.any(String) as unknown,
  1008. role: 'user',
  1009. content: [{ type: 'text', text: 'go' }],
  1010. source: { kind: 'user' },
  1011. }])
  1012. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  1013. // Empty content still needs an assistant/message to carry usage; derivation
  1014. // skips that host so it does not create a spurious assistant turn.
  1015. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  1016. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  1017. turn: 1,
  1018. step: 1,
  1019. message: {
  1020. id: expect.any(String) as unknown,
  1021. role: 'assistant',
  1022. content: [],
  1023. source: { kind: 'model', provider: 'mock', model: 'mock' },
  1024. },
  1025. usage: { inputTokens: 10, outputTokens: 5 },
  1026. })
  1027. })
  1028. it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
  1029. // The truncated tool call is dropped from durable content, while the
  1030. // successful provider call still needs an exact replay anchor.
  1031. const callId = CallId('c1')
  1032. const adapter = new MockAdapter([[
  1033. { type: 'block-start', index: 0, blockType: 'tool-call' },
  1034. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  1035. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  1036. { type: 'finish', reason: { kind: 'max-tokens' } },
  1037. ]])
  1038. const ctx = await harness(adapter)
  1039. ctx.tools.register(defineContentToolFixture({
  1040. name: 'echo',
  1041. description: '',
  1042. parameters: { text: { type: 'string' } },
  1043. async execute() { return [{ type: 'text', text: 'should not run' }] },
  1044. }))
  1045. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1046. const reasons: TurnEndReason[] = []
  1047. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1048. send(agent, 'go')
  1049. await waitForIdle(ctx, agent)
  1050. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  1051. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  1052. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  1053. turn: 1,
  1054. step: 1,
  1055. message: {
  1056. id: expect.any(String) as unknown,
  1057. role: 'assistant',
  1058. content: [],
  1059. source: { kind: 'model', provider: 'mock', model: 'mock' },
  1060. },
  1061. })
  1062. expect(assistant.sourceEventSeqs?.length).toBeGreaterThan(0)
  1063. expect(agent.session.deriveMessages()).toEqual([{
  1064. id: expect.any(String) as unknown,
  1065. role: 'user',
  1066. content: [{ type: 'text', text: 'go' }],
  1067. source: { kind: 'user' },
  1068. }])
  1069. })
  1070. it('appends an empty completion anchor for a normal stop with no usage', async () => {
  1071. // A clean content-less call stays absent from derived messages but remains
  1072. // a durable successful-call boundary for replay consumers.
  1073. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  1074. const ctx = await harness(adapter)
  1075. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1076. const reasons: TurnEndReason[] = []
  1077. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1078. send(agent, 'go')
  1079. await waitForIdle(ctx, agent)
  1080. expect(reasons).toEqual([{ kind: 'completed' }])
  1081. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  1082. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  1083. turn: 1,
  1084. step: 1,
  1085. message: {
  1086. id: expect.any(String) as unknown,
  1087. role: 'assistant',
  1088. content: [],
  1089. source: { kind: 'model', provider: 'mock', model: 'mock' },
  1090. },
  1091. })
  1092. expect(assistant.sourceEventSeqs?.length).toBe(1)
  1093. expect(agent.session.deriveMessages()).toEqual([{
  1094. id: expect.any(String) as unknown,
  1095. role: 'user',
  1096. content: [{ type: 'text', text: 'go' }],
  1097. source: { kind: 'user' },
  1098. }])
  1099. })
  1100. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  1101. const callId = CallId('c1')
  1102. const adapter = new MockAdapter([[
  1103. { type: 'block-start', index: 0, blockType: 'text' },
  1104. { type: 'text-delta', index: 0, text: 'partial text' },
  1105. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  1106. { type: 'block-start', index: 1, blockType: 'tool-call' },
  1107. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  1108. { type: 'finish', reason: { kind: 'max-tokens' } },
  1109. ]])
  1110. const ctx = await harness(adapter)
  1111. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1112. send(agent, 'go')
  1113. await waitForIdle(ctx, agent)
  1114. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  1115. expect(agent.session.deriveMessages()).toEqual([
  1116. {
  1117. id: expect.any(String) as unknown,
  1118. role: 'user',
  1119. content: [{ type: 'text', text: 'go' }],
  1120. source: { kind: 'user' },
  1121. },
  1122. {
  1123. id: expect.any(String) as unknown,
  1124. role: 'assistant',
  1125. content: [{ type: 'text', text: 'partial text' }],
  1126. source: { kind: 'model', provider: 'mock', model: 'mock' },
  1127. },
  1128. ])
  1129. })
  1130. it('contains a step/end observer failure without changing continuation', async () => {
  1131. const adapter = new MockAdapter([
  1132. toolCallResponse('c1', 'echo', { text: 'x' }),
  1133. textResponse('continued after tool call'),
  1134. ])
  1135. const ctx = await harness(adapter)
  1136. ctx.tools.register(defineContentToolFixture({
  1137. name: 'echo',
  1138. description: '',
  1139. parameters: { text: { type: 'string' } },
  1140. async execute(args) {
  1141. return [{ type: 'text', text: String(args.text) }]
  1142. },
  1143. }))
  1144. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1145. let threw = false
  1146. // Post-commit session observers cannot control the loop. The tool call still
  1147. // drives the second model request, and the turn completes normally.
  1148. ctx.on('session/event', (_session, event) => {
  1149. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  1150. })
  1151. send(agent, 'go')
  1152. await waitForIdle(ctx, agent)
  1153. expect(adapter.requests).toHaveLength(2)
  1154. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  1155. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  1156. })
  1157. it('keeps a reentrant agent/inbox/enqueue send as the next independent turn', async () => {
  1158. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  1159. const ctx = await harness(adapter)
  1160. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1161. let nested = false
  1162. ctx.on('agent/inbox/enqueue', (subject) => {
  1163. if (subject !== agent || nested) return
  1164. nested = true
  1165. send(agent, 'queued listener message')
  1166. })
  1167. const idle = waitForIdle(ctx, agent)
  1168. send(agent, 'outer message')
  1169. await idle
  1170. const turns = agent.session.events.filter(event => event.type === 'turn/start')
  1171. const messages = agent.session.events
  1172. .filter(event => event.type === 'user/message')
  1173. .map(event => event.data.content)
  1174. expect(turns).toHaveLength(2)
  1175. expect(messages).toEqual([
  1176. [{ type: 'text', text: 'outer message' }],
  1177. [{ type: 'text', text: 'queued listener message' }],
  1178. ])
  1179. })
  1180. it('preserves independent turn sources across an adjacent microtask send', async () => {
  1181. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  1182. const ctx = await harness(adapter)
  1183. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1184. const idle = waitForIdle(ctx, agent)
  1185. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'user message' }], source: { kind: 'user' } }))
  1186. await Promise.resolve()
  1187. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'plugin message' }], source: { kind: 'plugin', plugin: 'test' } }))
  1188. await idle
  1189. const triggers = agent.session.events
  1190. .filter(event => event.type === 'turn/start')
  1191. .map(event => event.data.trigger)
  1192. const sources = agent.session.events
  1193. .filter(event => event.type === 'user/message')
  1194. .map(event => event.data.source)
  1195. expect(triggers).toEqual([
  1196. { kind: 'message', source: { kind: 'user' } },
  1197. { kind: 'message', source: { kind: 'plugin', plugin: 'test' } },
  1198. ])
  1199. expect(sources).toEqual([
  1200. { kind: 'user' },
  1201. { kind: 'plugin', plugin: 'test' },
  1202. ])
  1203. })
  1204. it('keeps a session-listener send after dequeue in the following turn', async () => {
  1205. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  1206. const ctx = await harness(adapter)
  1207. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1208. const turns: number[] = []
  1209. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  1210. // queue two messages while idle — first starts turn 1 immediately;
  1211. // queue the second during turn 1 when the first assistant chunk streams
  1212. let queued = false
  1213. ctx.on('session/event', (_s, event) => {
  1214. if (event.type === 'assistant/chunk' && !queued) {
  1215. queued = true
  1216. send(agent, 'second message')
  1217. }
  1218. })
  1219. send(agent, 'first message')
  1220. await waitForIdle(ctx, agent)
  1221. expect(turns).toEqual([1, 2])
  1222. expect(adapter.requests).toHaveLength(2)
  1223. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first')
  1224. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
  1225. })
  1226. it('keeps a model-adapter callback send in the following turn', async () => {
  1227. const agentRef: { current?: Agent } = {}
  1228. const adapter = new MockAdapter([
  1229. () => {
  1230. const agent = agentRef.current
  1231. if (agent === undefined) throw new Error('model callback ran before agent setup')
  1232. send(agent, 'model callback message')
  1233. return textResponse('first')
  1234. },
  1235. textResponse('second'),
  1236. ])
  1237. const ctx = await harness(adapter)
  1238. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1239. agentRef.current = agent
  1240. const idle = waitForIdle(ctx, agent)
  1241. send(agent, 'outer message')
  1242. await idle
  1243. const messages = agent.session.events
  1244. .filter(event => event.type === 'user/message')
  1245. .map(event => event.data.content)
  1246. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
  1247. expect(messages).toEqual([
  1248. [{ type: 'text', text: 'outer message' }],
  1249. [{ type: 'text', text: 'model callback message' }],
  1250. ])
  1251. })
  1252. it('errors from the model surface as agent/error and end the turn', async () => {
  1253. const adapter = new MockAdapter([]) // script exhausted → throws
  1254. const ctx = await harness(adapter)
  1255. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1256. const errors: Error[] = []
  1257. const reasons: TurnEndReason[] = []
  1258. ctx.on('agent/error', (_agent, _turn, _step, error) => {
  1259. if (error instanceof Error) errors.push(error)
  1260. })
  1261. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  1262. send(agent, 'hi')
  1263. await waitForIdle(ctx, agent)
  1264. expect(errors).toHaveLength(1)
  1265. expect(errors[0]!.message).toContain('script exhausted')
  1266. expect(reasons[0]).toMatchObject({ kind: 'error' })
  1267. // The durable failure lives entirely on turn/end.reason (with the failing
  1268. // step), not a standalone error event.
  1269. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  1270. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  1271. })
  1272. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  1273. const adapter = new MockAdapter(['hang'])
  1274. const ctx = await harness(adapter)
  1275. let agent!: Agent
  1276. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  1277. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  1278. }, { inject: ['agentLoop'] }))
  1279. expect(ctx.agents.get(SessionId('scoped'))).toBe(agent)
  1280. send(agent, 'go')
  1281. await new Promise(r => setTimeout(r, 30))
  1282. expect(agent.status).toBe('running')
  1283. await fiber.dispose()
  1284. await driverDone(agent)
  1285. expect(ctx.agents.get(SessionId('scoped'))).toBeUndefined()
  1286. })
  1287. it('creates agents from config on startup', async () => {
  1288. const adapter = new MockAdapter([textResponse('from config')])
  1289. const ctx = new Context()
  1290. await ctx.plugin(LlmService)
  1291. await ctx.plugin(SessionStore)
  1292. await ctx.plugin(SystemPrompt)
  1293. await ctx.plugin(ToolRegistry)
  1294. await ctx.plugin(AgentRegistry)
  1295. await ctx.plugin(AgentLoop, {
  1296. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock' }],
  1297. })
  1298. ctx.llm.registerAdapter(['mock'], adapter)
  1299. const agent = ctx.agents.list()[0]!
  1300. expect(agent).toBeDefined()
  1301. expect(agent.id).toBe(agent.session.id)
  1302. expect(agent.id).toMatch(/^config-agent-session-/)
  1303. expect(agent.options.model).toBe('mock')
  1304. // the agent is alive: send triggers a turn
  1305. send(agent, 'hi')
  1306. await waitForIdle(ctx, agent)
  1307. expect(adapter.requests).toHaveLength(1)
  1308. })
  1309. it('attaches config agent cwd to the fresh session header', async () => {
  1310. const ctx = new Context()
  1311. await ctx.plugin(LlmService)
  1312. await ctx.plugin(SessionStore)
  1313. await ctx.plugin(SystemPrompt)
  1314. await ctx.plugin(ToolRegistry)
  1315. await ctx.plugin(AgentRegistry)
  1316. await ctx.plugin(AgentLoop, {
  1317. agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
  1318. })
  1319. const agent = ctx.agents.list()[0]!
  1320. expect(agent.session.header.cwd).toBe('/work/project')
  1321. })
  1322. it('replays a session log into an identical derived history', async () => {
  1323. const adapter = new MockAdapter([
  1324. toolCallResponse('c1', 'echo', { text: 'x' }),
  1325. textResponse('done'),
  1326. ])
  1327. const ctx = await harness(adapter)
  1328. ctx.tools.register(defineContentToolFixture({
  1329. name: 'echo',
  1330. description: '',
  1331. parameters: { text: { type: 'string' } },
  1332. async execute(args) {
  1333. return [{ type: 'text', text: String(args.text) }]
  1334. },
  1335. }))
  1336. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  1337. send(agent, 'run')
  1338. await waitForIdle(ctx, agent)
  1339. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  1340. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  1341. // event-by-event identity of types over the inherited prefix
  1342. expect(replayed.events.slice(0, agent.session.seq).map(e => e.type)).toEqual(
  1343. agent.session.events.map(e => e.type))
  1344. expect(replayed.events.at(-1)?.type).toBe('session/end-seed')
  1345. })
  1346. })