loop.spec.ts 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { 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, { defineTool } from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
  8. import AgentExecutionProvider from '@deepseek-ai/dsh-agent-execution'
  9. import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  10. import { MockAdapter, maxTokensResponse, textResponse, toolCallResponse } from './mock-adapter.ts'
  11. async function harness(adapter: MockAdapter, persona = '') {
  12. const ctx = new Context()
  13. await ctx.plugin(LlmService)
  14. await ctx.plugin(SessionStore)
  15. await ctx.plugin(SystemPrompt, { persona })
  16. await ctx.plugin(ToolRegistry)
  17. await ctx.plugin(AgentRegistry)
  18. await ctx.plugin(AgentExecutionProvider)
  19. await ctx.plugin(AgentLoop, { agents: [] })
  20. ctx.llm.registerAdapter(['mock'], adapter)
  21. return ctx
  22. }
  23. /**
  24. * Wait for the agent's NEXT transition to idle. Always event-based: callers
  25. * invoke this right after send(), when the loop hasn't woken yet (status is
  26. * still 'idle' synchronously), so polling the current status would lie.
  27. */
  28. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  29. return new Promise((resolve) => {
  30. const dispose = ctx.on('agent/status', (subject, status) => {
  31. if (subject === agent && status === 'idle') {
  32. dispose()
  33. resolve()
  34. }
  35. })
  36. })
  37. }
  38. function send(agent: ReactLoopAgent, text: string) {
  39. agent.send([{ type: 'text', text }])
  40. }
  41. describe('agent loop', () => {
  42. it('runs a simple turn: queued message → model → idle, with ordered events', async () => {
  43. const adapter = new MockAdapter([textResponse('hello there')])
  44. const ctx = await harness(adapter)
  45. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  46. // All boundaries — turn and step — are durable session events on the
  47. // session/event feed (no agent/* mirror). Record them in fire order to
  48. // assert the full boundary nesting.
  49. const order: string[] = []
  50. ctx.on('session/event', (_session, event) => {
  51. if (event.type === 'turn/start' || event.type === 'step/start' || event.type === 'step/end' || event.type === 'turn/end') {
  52. order.push(event.type)
  53. }
  54. })
  55. send(agent, 'hi')
  56. await waitForIdle(ctx, agent)
  57. expect(order).toEqual(['turn/start', 'step/start', 'step/end', 'turn/end'])
  58. const types = agent.session.events.map(e => e.type)
  59. // turn/start opens the turn, THEN the queued user message is recorded inside
  60. // it (every event is turn-enclosed), then the assembled message (carrying the
  61. // step's usage).
  62. expect(types[0]).toBe('turn/start')
  63. expect(types[1]).toBe('user/message')
  64. expect(types).toContain('assistant/message')
  65. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  66. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data.usage).toEqual({ inputTokens: 10, outputTokens: 'hello there'.length })
  67. expect(types.at(-1)).toBe('turn/end')
  68. // derived history: user + assistant
  69. const messages = agent.session.deriveMessages()
  70. expect(messages.map(m => m.role)).toEqual(['user', 'assistant'])
  71. expect(messages[1]!.content).toEqual([{ type: 'text', text: 'hello there' }])
  72. })
  73. it('round-trips tool calls: model requests tool → executes → result in next request', async () => {
  74. const adapter = new MockAdapter([
  75. toolCallResponse('c1', 'echo', { text: 'ping' }, 'calling echo'),
  76. textResponse('done'),
  77. ])
  78. const ctx = await harness(adapter)
  79. ctx.tools.register(defineTool({
  80. name: 'echo',
  81. description: 'echo back',
  82. parameters: { text: { type: 'string' } },
  83. async execute(args) {
  84. return [{ type: 'text', text: `echo: ${args.text}` }]
  85. },
  86. }))
  87. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  88. send(agent, 'use the tool')
  89. await waitForIdle(ctx, agent)
  90. // two model calls happened (tool-call step, then final step)
  91. expect(adapter.requests).toHaveLength(2)
  92. // the second request's derived history contains the tool result
  93. const secondMessages = adapter.requests[1]!.messages
  94. const toolResultMessage = secondMessages.find(m =>
  95. m.content.some(b => b.type === 'tool-result'))
  96. expect(toolResultMessage).toBeDefined()
  97. const block = toolResultMessage!.content.find(b => b.type === 'tool-result')!
  98. expect(block).toMatchObject({ toolCallId: 'c1', isError: false })
  99. expect((block).content).toEqual([{ type: 'text', text: 'echo: ping' }])
  100. // session log records call + result
  101. const types = agent.session.events.map(e => e.type)
  102. expect(types).toContain('tool/call')
  103. expect(types).toContain('tool/result')
  104. })
  105. it('threads a tool-attached meta (execute object return) onto the tool/result event', async () => {
  106. const adapter = new MockAdapter([
  107. toolCallResponse('c1', 'writer', { path: 'a.txt' }, 'writing'),
  108. textResponse('done'),
  109. ])
  110. const ctx = await harness(adapter)
  111. // A tool that returns the { content, meta } object form: the loop must
  112. // persist `meta` on the tool/result event so a UI reproduces the card on replay.
  113. ctx.tools.register(defineTool({
  114. name: 'writer',
  115. description: 'writes a file',
  116. parameters: { path: { type: 'string' } },
  117. async execute() {
  118. return { content: [{ type: 'text', text: 'ok' }], meta: { diffs: [{ path: 'a.txt', oldText: null, newText: 'x' }] } }
  119. },
  120. }))
  121. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  122. send(agent, 'use the tool')
  123. await waitForIdle(ctx, agent)
  124. const toolResult = agent.session.events.find(e => e.type === 'tool/result')
  125. expect(toolResult?.type === 'tool/result' && toolResult.data.meta)
  126. .toEqual({ diffs: [{ path: 'a.txt', oldText: null, newText: 'x' }] })
  127. })
  128. it('renders harness identity, then the persona, then tool guidance — with {{variables}} resolved', async () => {
  129. const adapter = new MockAdapter([textResponse('ok')])
  130. // The persona is a TEMPLATE: {{model}} is the loop-registered variable
  131. // projecting this agent's configured model, so the model knows its own name.
  132. const ctx = await harness(adapter, 'You are a test agent on {{model}}.')
  133. ctx.systemPrompt.section({ name: 'tool:noop', order: 100, text: 'Use the noop tool wisely.' })
  134. ctx.tools.register(defineTool({
  135. name: 'noop',
  136. description: 'does nothing',
  137. parameters: {},
  138. async execute() {
  139. return []
  140. },
  141. }))
  142. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  143. send(agent, 'hi')
  144. await waitForIdle(ctx, agent)
  145. const request = adapter.requests[0]
  146. expect(request!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou are a test agent on mock.\n\nUse the noop tool wisely.')
  147. expect(request!.tools?.map(t => t.name)).toEqual(['noop'])
  148. })
  149. it('resolves {{cwd}} from the agent session workspace (factory create with meta.cwd)', async () => {
  150. const adapter = new MockAdapter([textResponse('ok')])
  151. const ctx = await harness(adapter, 'Working in {{cwd}}.')
  152. const handle = await ctx.agents.create({
  153. agentId: AgentId('a-cwd'),
  154. sessionId: SessionId('s-cwd'),
  155. meta: { cwd: '/work/space' },
  156. agentOptions: { provider: 'mock', model: 'mock' },
  157. })
  158. const agent = handle.agent as ReactLoopAgent
  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) => void errors.push(error))
  169. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  170. send(agent, 'hi')
  171. await waitForIdle(ctx, agent)
  172. expect(adapter.requests).toHaveLength(0) // the request was never sent
  173. expect(errors.some(e => e.message.includes('no value for this assembly'))).toBe(true)
  174. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  175. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('error')
  176. // The loop survived: a waterfall listener rescues {{cwd}} and the SAME
  177. // agent completes a real model turn.
  178. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  179. assembly.variables['cwd'] = '/rescued'
  180. return next()
  181. })
  182. send(agent, 'again')
  183. await waitForIdle(ctx, agent)
  184. expect(adapter.requests).toHaveLength(1)
  185. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nIn /rescued.')
  186. const turnEnds = agent.session.events.filter(e => e.type === 'turn/end')
  187. expect(turnEnds).toHaveLength(2)
  188. expect(turnEnds[1]?.type === 'turn/end' && turnEnds[1].data.reason.kind).toBe('completed')
  189. })
  190. it('supports the model-via-agent/request path with a {{model}} persona: the supplier states it via the assemble waterfall', async () => {
  191. // AgentOptions.model unset: the model arrives in the agent/request
  192. // waterfall (the loop's documented fallback — see runStep's no-model
  193. // error). {{model}} renders BEFORE that waterfall, so the SAME plugin
  194. // states the fact early on system-prompt/assemble — the owner of a
  195. // late-bound fact owns stating it wherever it is claimed.
  196. const adapter = new MockAdapter([textResponse('ok')])
  197. const ctx = await harness(adapter, 'You run on {{model}}.')
  198. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  199. assembly.variables['provider'] = 'mock'
  200. assembly.variables['model'] = 'mock'
  201. return next()
  202. })
  203. ctx.on('agent/request', async (_agent, _turn, _step, config, _signal, _next) => {
  204. return { ...config, provider: 'mock', model: 'mock' }
  205. })
  206. const agent = ctx.agentLoop.create(AgentId('a-late-model'), {})
  207. send(agent, 'hi')
  208. await waitForIdle(ctx, agent)
  209. expect(adapter.requests).toHaveLength(1)
  210. expect(adapter.requests[0]!.model).toBe('mock')
  211. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou run on mock.')
  212. })
  213. it.each([
  214. ['BigInt', { n: 1n }],
  215. ['Map', new Map([['key', 'value']])],
  216. ['class instance', new (class ResultMeta { x = 1 })()],
  217. ])('normalizes non-JSON tool meta (%s) before the durable result commit', async (_kind, meta) => {
  218. const adapter = new MockAdapter([
  219. toolCallResponse('bad-meta-call', 'bad-meta', {}, 'calling'),
  220. textResponse('recovered'),
  221. ])
  222. const ctx = await harness(adapter)
  223. ctx.tools.register(defineTool({
  224. name: 'bad-meta',
  225. description: 'returns invalid durable metadata',
  226. parameters: {},
  227. execute: () => Promise.resolve({ content: [{ type: 'text' as const, text: 'apparent success' }], meta }),
  228. }))
  229. const agent = ctx.agentLoop.create(AgentId('bad-meta-agent'), { provider: 'mock', model: 'mock' })
  230. send(agent, 'use the tool')
  231. await waitForIdle(ctx, agent)
  232. const result = agent.session.events.find(event => event.type === 'tool/result')
  233. expect(result?.type).toBe('tool/result')
  234. if (result?.type === 'tool/result') {
  235. expect(result.data.callId).toBe('bad-meta-call')
  236. expect(result.data.isError).toBe(true)
  237. expect(result.data.meta).toBeUndefined()
  238. expect(result.data.content).toEqual([{
  239. type: 'text',
  240. text: 'Error: tool result must be losslessly JSON-serializable',
  241. }])
  242. }
  243. // The normalized failure was durably logged and fed back to the model; the
  244. // turn continued normally instead of failing after an apparent success.
  245. expect(adapter.requests).toHaveLength(2)
  246. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('losslessly JSON-serializable')
  247. })
  248. it('omits the system field when a system-prompt/assemble veto empties the assembly', async () => {
  249. // The documented escape valve: a deployment that must drop the harness
  250. // openers short-circuits the assemble waterfall; the request then carries
  251. // NO system field at all (not an empty string).
  252. const adapter = new MockAdapter([textResponse('ok')])
  253. const ctx = await harness(adapter)
  254. ctx.on('system-prompt/assemble', async () => ({ sections: [], tools: [], variables: {} }))
  255. const agent = ctx.agentLoop.create(AgentId('a-no-system'), { provider: 'mock', model: 'mock' })
  256. send(agent, 'hi')
  257. await waitForIdle(ctx, agent)
  258. expect(adapter.requests).toHaveLength(1)
  259. expect('system' in adapter.requests[0]!).toBe(false)
  260. })
  261. it('records raw chunks for replay as assistant/chunk session events', async () => {
  262. const adapter = new MockAdapter([textResponse('abc')])
  263. const ctx = await harness(adapter)
  264. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  265. send(agent, 'hi')
  266. await waitForIdle(ctx, agent)
  267. const chunkEvents = agent.session.events.filter(e => e.type === 'assistant/chunk')
  268. // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7
  269. expect(chunkEvents).toHaveLength(7)
  270. // replay: chunk events alone re-assemble to the recorded assistant message
  271. const deltaText = chunkEvents
  272. .flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : [])
  273. .filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
  274. .map(c => c.text)
  275. .join('')
  276. expect(deltaText).toBe('abc')
  277. })
  278. it('injects steering between steps and continues the turn', async () => {
  279. const adapter = new MockAdapter([
  280. toolCallResponse('c1', 'slow', {}),
  281. textResponse('addressed the steering'),
  282. ])
  283. const ctx = await harness(adapter)
  284. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  285. ctx.tools.register(defineTool({
  286. name: 'slow',
  287. description: '',
  288. parameters: {},
  289. async execute() {
  290. // steer while the turn is running (during tool execution)
  291. agent.steer([{ type: 'text', text: 'change of plans' }])
  292. return [{ type: 'text', text: 'tool done' }]
  293. },
  294. }))
  295. send(agent, 'start')
  296. await waitForIdle(ctx, agent)
  297. const types = agent.session.events.map(e => e.type)
  298. expect(types).toContain('steering/message')
  299. // steering recorded before the second step's request derived its history
  300. const steeringSeq = agent.session.events.find(e => e.type === 'steering/message')!.seq
  301. const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1]
  302. expect(secondStepStart).toBeDefined()
  303. expect(steeringSeq).toBeLessThan(secondStepStart!.seq)
  304. // the second model request saw the steering content
  305. const secondRequest = adapter.requests[1]
  306. const flat = JSON.stringify(secondRequest!.messages)
  307. expect(flat).toContain('change of plans')
  308. })
  309. it('steering while idle behaves like send (starts a turn)', async () => {
  310. const adapter = new MockAdapter([textResponse('ok')])
  311. const ctx = await harness(adapter)
  312. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  313. agent.steer([{ type: 'text', text: 'hello' }])
  314. await waitForIdle(ctx, agent)
  315. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  316. })
  317. it('inject() while idle wraps context in a one-shot turn, visible to the next request', async () => {
  318. const adapter = new MockAdapter([textResponse('ok')])
  319. const ctx = await harness(adapter)
  320. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  321. agent.inject([{ type: 'text', text: 'file changed: a.ts' }], { source: { kind: 'plugin', plugin: 'watcher' } })
  322. // The idle inject records a self-contained turn (turn/start → context/message
  323. // → turn/end) so the event stays turn-enclosed, but does NOT run the model.
  324. await new Promise(r => setTimeout(r, 20))
  325. expect(agent.status).toBe('idle')
  326. expect(adapter.requests).toHaveLength(0)
  327. const injectedTurn = agent.session.events.filter(e => e.type === 'turn/start')
  328. expect(injectedTurn).toHaveLength(1)
  329. const it0 = injectedTurn[0]!
  330. expect(it0.type === 'turn/start' && it0.data.trigger.kind).toBe('injection')
  331. expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed
  332. send(agent, 'go')
  333. await waitForIdle(ctx, agent)
  334. const flat = JSON.stringify(adapter.requests[0]!.messages)
  335. expect(flat).toContain('file changed: a.ts')
  336. expect(flat).toContain('<context source=\\"plugin\\">')
  337. })
  338. it('inject() can persist raw structured context without the generic context envelope', async () => {
  339. const adapter = new MockAdapter([textResponse('ok')])
  340. const ctx = await harness(adapter)
  341. const agent = ctx.agentLoop.create(AgentId('raw-context'), { provider: 'mock', model: 'mock' })
  342. const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
  343. const meta = {
  344. kind: 'workspace-instructions',
  345. version: 1,
  346. changes: [{ action: 'set', scope: 'pkg', path: 'pkg/AGENTS.md', digest: 'abc123' }],
  347. }
  348. agent.inject([{ type: 'text', text }], {
  349. source: { kind: 'plugin', plugin: 'workspace-context' },
  350. envelope: 'raw',
  351. meta,
  352. })
  353. send(agent, 'go')
  354. await waitForIdle(ctx, agent)
  355. const contextEvent = agent.session.events.find(event => event.type === 'context/message')
  356. expect(contextEvent?.type === 'context/message' && contextEvent.data).toMatchObject({ envelope: 'raw', meta })
  357. const requestText = JSON.stringify(adapter.requests[0]!.messages)
  358. expect(requestText).toContain('Additional instructions from: pkg/AGENTS.md')
  359. expect(requestText).not.toContain('<context source=')
  360. })
  361. it('inject() while running appends into the open turn (no extra synthetic turn)', async () => {
  362. const adapter = new MockAdapter([
  363. toolCallResponse('c1', 'noticer', {}, 'calling'),
  364. textResponse('done'),
  365. ])
  366. const ctx = await harness(adapter)
  367. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  368. // A tool that injects mid-execution: at this point the agent is running, so
  369. // inject must append the context/message into the ALREADY-open turn rather
  370. // than wrap it in its own one-shot turn.
  371. ctx.tools.register(defineTool({
  372. name: 'noticer',
  373. description: 'injects a notice',
  374. parameters: {},
  375. async execute() {
  376. agent.inject([{ type: 'text', text: 'mid-turn notice' }], { source: { kind: 'plugin', plugin: 'x' } })
  377. return [{ type: 'text', text: 'ok' }]
  378. },
  379. }))
  380. send(agent, 'go')
  381. await waitForIdle(ctx, agent)
  382. // Exactly ONE turn ran (no synthetic injection turn), and the mid-turn
  383. // context/message sits inside it.
  384. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  385. expect(turnStarts).toHaveLength(1)
  386. const ts0 = turnStarts[0]!
  387. expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
  388. expect(agent.session.events.some(e => e.type === 'context/message')).toBe(true)
  389. })
  390. it('agent/turn-continuation can force-continue (/loop pattern) and force-stop', async () => {
  391. // force-continue: model never calls tools, but a plugin forces 3 steps
  392. const adapter = new MockAdapter([
  393. textResponse('step 1'),
  394. textResponse('step 2'),
  395. textResponse('step 3'),
  396. ])
  397. const ctx = await harness(adapter)
  398. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  399. let steps = 0
  400. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  401. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, _signal, next) => {
  402. if (steps < 3) return { action: 'continue' as const }
  403. return next()
  404. })
  405. send(agent, 'go')
  406. await waitForIdle(ctx, agent)
  407. expect(steps).toBe(3)
  408. expect(adapter.requests).toHaveLength(3)
  409. })
  410. it('agent/turn-continuation can veto continuation despite tool calls (budget-guard pattern)', async () => {
  411. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  412. const ctx = await harness(adapter)
  413. ctx.tools.register(defineTool({
  414. name: 'echo',
  415. description: '',
  416. parameters: { text: { type: 'string' } },
  417. async execute(args) {
  418. return [{ type: 'text', text: String(args.text) }]
  419. },
  420. }))
  421. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  422. ctx.on('agent/turn-continuation', async () => ({ action: 'stop' }) as const)
  423. send(agent, 'go')
  424. await waitForIdle(ctx, agent)
  425. // only one model call despite the tool call requesting a follow-up
  426. expect(adapter.requests).toHaveLength(1)
  427. // tool still executed before the decision
  428. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  429. })
  430. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  431. const adapter = new MockAdapter([textResponse('ok')])
  432. const ctx = await harness(adapter)
  433. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  434. ctx.on('agent/request', async (_agent, _turn, _step, config, _signal, _next) => {
  435. // The seed is frozen — config is not a mutable per-call knob; a switch
  436. // is proposed by returning a replacement, and the loop logs it.
  437. expect(Object.isFrozen(config)).toBe(true)
  438. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  439. return { ...config, model: 'other-model' }
  440. })
  441. send(agent, 'hi')
  442. await waitForIdle(ctx, agent)
  443. expect(adapter.requests[0]!.model).toBe('other-model')
  444. // The header event records what the request ACTUALLY used — the switch is
  445. // a reconstructable fact, not silent drift.
  446. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  447. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  448. })
  449. it('agent/pre-step fires once per step before the step is opened', async () => {
  450. // Two steps (a tool call, then a final text turn) → two model calls → two
  451. // pre-step fires, each carrying the assembled full system prompt, BEFORE
  452. // the step is opened and its request is derived (the request the adapter
  453. // sees reflects any surface state at fire time).
  454. const adapter = new MockAdapter([
  455. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  456. textResponse('done'),
  457. ])
  458. const ctx = await harness(adapter)
  459. ctx.tools.register(defineTool({
  460. name: 'echo', description: 'echo', parameters: {},
  461. async execute() { return [{ type: 'text', text: 'echoed' }] },
  462. }))
  463. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  464. const fires: { turn: number; step: number; fullSystemPrompt: string }[] = []
  465. ctx.on('agent/pre-step', (subject, turn, step, fullSystemPrompt) => {
  466. if (subject === agent) fires.push({ turn, step, fullSystemPrompt })
  467. })
  468. send(agent, 'go')
  469. await waitForIdle(ctx, agent)
  470. // One fire per step, in order, each with the assembled system prompt
  471. // (here just the loop's own harness-identity section — no persona set).
  472. const HARNESS = 'You are an AI agent powered by the DeepSeek Harness SDK.'
  473. expect(fires).toEqual([
  474. { turn: 1, step: 1, fullSystemPrompt: HARNESS },
  475. { turn: 1, step: 2, fullSystemPrompt: HARNESS },
  476. ])
  477. })
  478. it('agent/pre-step fires BEFORE the step it precedes opens (events land outside the step)', async () => {
  479. // The append lands before step/start, yet derive happens afterwards and the
  480. // same step's request must include it.
  481. const adapter = new MockAdapter([textResponse('ok')])
  482. const ctx = await harness(adapter)
  483. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  484. let injected = false
  485. ctx.on('agent/pre-step', (subject) => {
  486. if (subject === agent && !injected) {
  487. injected = true
  488. subject.session.append('context/message', {
  489. content: [{ type: 'text', text: 'INJECTED-IN-PRE-STEP' }],
  490. source: { kind: 'plugin', plugin: 'test' },
  491. }, { surfaceOp: 'append' })
  492. }
  493. })
  494. send(agent, 'go')
  495. await waitForIdle(ctx, agent)
  496. // The adapter's request includes the node injected during pre-step (derive
  497. // reflects it).
  498. const text = JSON.stringify(adapter.requests[0]!.messages)
  499. expect(text).toContain('INJECTED-IN-PRE-STEP')
  500. // And the injected event sits BEFORE the first step/start in the log —
  501. // the seam fired outside the step.
  502. const events = agent.session.events
  503. const injectedSeq = events.find(e => e.type === 'context/message')!.seq
  504. const firstStepStartSeq = events.find(e => e.type === 'step/start')!.seq
  505. expect(injectedSeq).toBeLessThan(firstStepStartSeq)
  506. })
  507. it('a throwing agent/pre-step listener ends the turn (error), not the loop', async () => {
  508. // Before step/start, a pre-step throw reaches the turn catch: no step needs
  509. // closing, the turn records error, and the loop remains available.
  510. const adapter = new MockAdapter([textResponse('second turn ok')])
  511. const ctx = await harness(adapter)
  512. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  513. let throwOnce = true
  514. ctx.on('agent/pre-step', () => {
  515. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  516. })
  517. const errors: Error[] = []
  518. ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
  519. send(agent, 'first')
  520. await waitForIdle(ctx, agent)
  521. // The first turn failed at step 1 (no model call happened), surfaced via
  522. // agent/error, with the durable failure on turn/end.reason.
  523. expect(errors).toHaveLength(1)
  524. expect(errors[0]!.message).toContain('boom in pre-step')
  525. expect(adapter.requests.length).toBe(0)
  526. const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
  527. expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  528. // The step opened-and-closed count stays balanced even though it never ran.
  529. const types = agent.session.events.map(e => e.type)
  530. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  531. // The loop survived: a second prompt runs a normal completed turn.
  532. send(agent, 'second')
  533. await waitForIdle(ctx, agent)
  534. expect(adapter.requests.length).toBe(1)
  535. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  536. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  537. })
  538. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  539. const adapter = new MockAdapter(['hang'])
  540. const ctx = await harness(adapter)
  541. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  542. const reasons: TurnEndReason[] = []
  543. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  544. send(agent, 'go')
  545. // wait until the stream is hanging, then cancel
  546. await new Promise(r => setTimeout(r, 30))
  547. expect(agent.status).toBe('running')
  548. agent.cancel({ kind: 'user' })
  549. await waitForIdle(ctx, agent)
  550. expect(reasons).toEqual([{ kind: 'aborted' }])
  551. })
  552. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  553. // A single step that ends with a max-tokens finish (no tool calls): the
  554. // turn stops by default and ends max-tokens, not completed.
  555. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  556. const ctx = await harness(adapter)
  557. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  558. const reasons: TurnEndReason[] = []
  559. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  560. send(agent, 'go')
  561. await waitForIdle(ctx, agent)
  562. expect(adapter.requests).toHaveLength(1)
  563. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  564. // Assert the durable row, not only the live listener.
  565. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  566. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  567. })
  568. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  569. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  570. // must be FORCED to reach step 2 which finishes normally (stop).
  571. const adapter = new MockAdapter([
  572. maxTokensResponse('first half'),
  573. textResponse('second half'),
  574. ])
  575. const ctx = await harness(adapter)
  576. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  577. let steps = 0
  578. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  579. // Force exactly one continuation (step 1 → step 2), then defer to default
  580. // (step 2 is a plain stop with no tool calls → stops).
  581. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, _signal, next) => {
  582. if (steps < 2) return { action: 'continue' as const }
  583. return next()
  584. })
  585. const reasons: TurnEndReason[] = []
  586. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  587. send(agent, 'go')
  588. await waitForIdle(ctx, agent)
  589. expect(steps).toBe(2)
  590. expect(adapter.requests).toHaveLength(2)
  591. expect(adapter.requests[1]!.messages).toEqual([
  592. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  593. { role: 'assistant', content: [{ type: 'text', text: 'first half' }], provenance: { provider: 'mock', model: 'mock' } },
  594. ])
  595. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  596. })
  597. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  598. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  599. // stop. The per-turn reason must be independent — turn 2 ends completed.
  600. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  601. const ctx = await harness(adapter)
  602. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  603. const reasons: TurnEndReason[] = []
  604. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  605. send(agent, 'first')
  606. await waitForIdle(ctx, agent)
  607. send(agent, 'second')
  608. await waitForIdle(ctx, agent)
  609. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  610. })
  611. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  612. const callId = CallId('c1')
  613. const adapter = new MockAdapter([[
  614. { type: 'block-start', index: 0, blockType: 'tool-call' },
  615. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  616. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  617. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  618. { type: 'finish', reason: { kind: 'max-tokens' } },
  619. ]])
  620. const ctx = await harness(adapter)
  621. let executions = 0
  622. ctx.tools.register(defineTool({
  623. name: 'echo',
  624. description: '',
  625. parameters: { text: { type: 'string' } },
  626. async execute() {
  627. executions += 1
  628. return [{ type: 'text', text: 'should not run' }]
  629. },
  630. }))
  631. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  632. const reasons: TurnEndReason[] = []
  633. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  634. send(agent, 'go')
  635. await waitForIdle(ctx, agent)
  636. expect(executions).toBe(0)
  637. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  638. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  639. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  640. // Empty content still needs an assistant/message to carry usage; derivation
  641. // skips that host so it does not create a spurious assistant turn.
  642. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  643. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  644. turn: 1, step: 1, content: [], provenance: { provider: 'mock', model: 'mock' }, usage: { inputTokens: 10, outputTokens: 5 },
  645. })
  646. })
  647. it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
  648. // The truncated tool call is dropped from durable content, while the
  649. // successful provider call still needs an exact replay anchor.
  650. const callId = CallId('c1')
  651. const adapter = new MockAdapter([[
  652. { type: 'block-start', index: 0, blockType: 'tool-call' },
  653. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  654. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  655. { type: 'finish', reason: { kind: 'max-tokens' } },
  656. ]])
  657. const ctx = await harness(adapter)
  658. ctx.tools.register(defineTool({
  659. name: 'echo',
  660. description: '',
  661. parameters: { text: { type: 'string' } },
  662. async execute() { return [{ type: 'text', text: 'should not run' }] },
  663. }))
  664. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  665. const reasons: TurnEndReason[] = []
  666. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  667. send(agent, 'go')
  668. await waitForIdle(ctx, agent)
  669. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  670. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  671. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  672. turn: 1,
  673. step: 1,
  674. content: [],
  675. provenance: { provider: 'mock', model: 'mock' },
  676. })
  677. expect(assistant.sourceEventSeqs?.length).toBeGreaterThan(0)
  678. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  679. })
  680. it('appends an empty completion anchor for a normal stop with no usage', async () => {
  681. // A clean content-less call stays absent from derived messages but remains
  682. // a durable successful-call boundary for replay consumers.
  683. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  684. const ctx = await harness(adapter)
  685. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  686. const reasons: TurnEndReason[] = []
  687. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  688. send(agent, 'go')
  689. await waitForIdle(ctx, agent)
  690. expect(reasons).toEqual([{ kind: 'completed' }])
  691. const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
  692. expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
  693. turn: 1,
  694. step: 1,
  695. content: [],
  696. provenance: { provider: 'mock', model: 'mock' },
  697. })
  698. expect(assistant.sourceEventSeqs?.length).toBe(1)
  699. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  700. })
  701. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  702. const callId = CallId('c1')
  703. const adapter = new MockAdapter([[
  704. { type: 'block-start', index: 0, blockType: 'text' },
  705. { type: 'text-delta', index: 0, text: 'partial text' },
  706. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  707. { type: 'block-start', index: 1, blockType: 'tool-call' },
  708. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  709. { type: 'finish', reason: { kind: 'max-tokens' } },
  710. ]])
  711. const ctx = await harness(adapter)
  712. let stepResults = 0
  713. ctx.on('agent/step-result', async (_agent, _turn, _step, message, _signal, next) => {
  714. stepResults += 1
  715. expect(message.content).toEqual([{ type: 'text', text: 'partial text' }])
  716. return next()
  717. })
  718. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  719. send(agent, 'go')
  720. await waitForIdle(ctx, agent)
  721. expect(stepResults).toBe(1)
  722. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  723. expect(agent.session.deriveMessages()).toEqual([
  724. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  725. { role: 'assistant', content: [{ type: 'text', text: 'partial text' }], provenance: { provider: 'mock', model: 'mock' } },
  726. ])
  727. })
  728. it('contains a step/end observer failure without changing continuation', async () => {
  729. const adapter = new MockAdapter([
  730. toolCallResponse('c1', 'echo', { text: 'x' }),
  731. textResponse('continued after tool call'),
  732. ])
  733. const ctx = await harness(adapter)
  734. ctx.tools.register(defineTool({
  735. name: 'echo',
  736. description: '',
  737. parameters: { text: { type: 'string' } },
  738. async execute(args) {
  739. return [{ type: 'text', text: String(args.text) }]
  740. },
  741. }))
  742. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  743. let threw = false
  744. // Post-commit session observers cannot control the loop. The tool call still
  745. // drives the second model request, and the turn completes normally.
  746. ctx.on('session/event', (_session, event) => {
  747. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  748. })
  749. send(agent, 'go')
  750. await waitForIdle(ctx, agent)
  751. expect(adapter.requests).toHaveLength(2)
  752. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  753. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  754. })
  755. it('chains queued messages into consecutive turns', async () => {
  756. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  757. const ctx = await harness(adapter)
  758. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  759. const turns: number[] = []
  760. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  761. // queue two messages while idle — first starts turn 1 immediately;
  762. // queue the second during turn 1 when the first assistant chunk streams
  763. let queued = false
  764. ctx.on('session/event', (_s, event) => {
  765. if (event.type === 'assistant/chunk' && !queued) {
  766. queued = true
  767. send(agent, 'second message')
  768. }
  769. })
  770. send(agent, 'first message')
  771. await waitForIdle(ctx, agent)
  772. expect(turns).toEqual([1, 2])
  773. expect(adapter.requests).toHaveLength(2)
  774. })
  775. it('awaits session/flush at turn end (persistence checkpoint)', async () => {
  776. const adapter = new MockAdapter([textResponse('ok')])
  777. const ctx = await harness(adapter)
  778. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  779. let flushed = 0
  780. let flushedBeforeIdle = false
  781. ctx.on('session/flush', async (session) => {
  782. await new Promise(r => setTimeout(r, 10))
  783. flushed++
  784. flushedBeforeIdle = agent.status !== 'idle'
  785. void session
  786. })
  787. send(agent, 'hi')
  788. await waitForIdle(ctx, agent)
  789. expect(flushed).toBe(1)
  790. expect(flushedBeforeIdle).toBe(true)
  791. })
  792. it('errors from the model surface as agent/error and end the turn', async () => {
  793. const adapter = new MockAdapter([]) // script exhausted → throws
  794. const ctx = await harness(adapter)
  795. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  796. const errors: Error[] = []
  797. const reasons: TurnEndReason[] = []
  798. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  799. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  800. send(agent, 'hi')
  801. await waitForIdle(ctx, agent)
  802. expect(errors).toHaveLength(1)
  803. expect(errors[0]!.message).toContain('script exhausted')
  804. expect(reasons[0]).toMatchObject({ kind: 'error' })
  805. // The durable failure lives entirely on turn/end.reason (with the failing
  806. // step), not a standalone error event.
  807. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  808. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  809. })
  810. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  811. const adapter = new MockAdapter(['hang'])
  812. const ctx = await harness(adapter)
  813. let agent!: ReactLoopAgent
  814. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  815. agent = inner.agentLoop.create(AgentId('scoped'), { provider: 'mock', model: 'mock' })
  816. }, { inject: ['agentLoop'] }))
  817. expect(ctx.agents.get(AgentId('scoped'))).toBe(agent)
  818. send(agent, 'go')
  819. await new Promise(r => setTimeout(r, 30))
  820. expect(agent.status).toBe('running')
  821. await fiber.dispose()
  822. await agent.done
  823. expect(agent.status).toBe('disposed')
  824. expect(ctx.agents.get(AgentId('scoped'))).toBeUndefined()
  825. expect(() => { send(agent, 'too late') }).toThrow('disposed')
  826. })
  827. it('creates agents from config on startup', async () => {
  828. const adapter = new MockAdapter([textResponse('from config')])
  829. const ctx = new Context()
  830. await ctx.plugin(LlmService)
  831. await ctx.plugin(SessionStore)
  832. await ctx.plugin(SystemPrompt)
  833. await ctx.plugin(ToolRegistry)
  834. await ctx.plugin(AgentRegistry)
  835. await ctx.plugin(AgentExecutionProvider)
  836. await ctx.plugin(AgentLoop, {
  837. agents: [{ id: AgentId('config-agent'), provider: 'mock', model: 'mock' }],
  838. })
  839. ctx.llm.registerAdapter(['mock'], adapter)
  840. const agent = ctx.agents.get(AgentId('config-agent'))! as ReactLoopAgent
  841. expect(agent).toBeDefined()
  842. expect(agent.id).toBe('config-agent')
  843. expect(agent.options.model).toBe('mock')
  844. // the agent is alive: send triggers a turn
  845. send(agent, 'hi')
  846. await waitForIdle(ctx, agent)
  847. expect(adapter.requests).toHaveLength(1)
  848. })
  849. it('attaches config agent cwd to the fresh session header', async () => {
  850. const ctx = new Context()
  851. await ctx.plugin(LlmService)
  852. await ctx.plugin(SessionStore)
  853. await ctx.plugin(SystemPrompt)
  854. await ctx.plugin(ToolRegistry)
  855. await ctx.plugin(AgentRegistry)
  856. await ctx.plugin(AgentExecutionProvider)
  857. await ctx.plugin(AgentLoop, {
  858. agents: [{ id: AgentId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
  859. })
  860. const agent = ctx.agents.get(AgentId('config-agent'))! as ReactLoopAgent
  861. expect(agent.session.header.cwd).toBe('/work/project')
  862. })
  863. it('replays a session log into an identical derived history', async () => {
  864. const adapter = new MockAdapter([
  865. toolCallResponse('c1', 'echo', { text: 'x' }),
  866. textResponse('done'),
  867. ])
  868. const ctx = await harness(adapter)
  869. ctx.tools.register(defineTool({
  870. name: 'echo',
  871. description: '',
  872. parameters: { text: { type: 'string' } },
  873. async execute(args) {
  874. return [{ type: 'text', text: String(args.text) }]
  875. },
  876. }))
  877. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  878. send(agent, 'run')
  879. await waitForIdle(ctx, agent)
  880. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  881. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  882. // event-by-event identity of types
  883. expect(replayed.events.map(e => e.type)).toEqual(
  884. agent.session.events.map(e => e.type))
  885. })
  886. })