1
0

loop.spec.ts 44 KB

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