loop.spec.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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 missing cwd variable must fail one turn without preventing a later valid turn.
  163. const adapter = new MockAdapter([textResponse('ok after rescue')])
  164. const ctx = await harness(adapter, 'In {{cwd}}.')
  165. const errors: Error[] = []
  166. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  167. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  168. send(agent, 'hi')
  169. await waitForIdle(ctx, agent)
  170. expect(adapter.requests).toHaveLength(0) // the request was never sent
  171. expect(errors.some(e => e.message.includes('no value for this assembly'))).toBe(true)
  172. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  173. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('error')
  174. // The loop survived: a waterfall listener rescues {{cwd}} and the SAME
  175. // agent completes a real model turn.
  176. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  177. assembly.variables['cwd'] = '/rescued'
  178. return next()
  179. })
  180. send(agent, 'again')
  181. await waitForIdle(ctx, agent)
  182. expect(adapter.requests).toHaveLength(1)
  183. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nIn /rescued.')
  184. const turnEnds = agent.session.events.filter(e => e.type === 'turn/end')
  185. expect(turnEnds).toHaveLength(2)
  186. expect(turnEnds[1]?.type === 'turn/end' && turnEnds[1].data.reason.kind).toBe('completed')
  187. })
  188. it('supports the model-via-agent/request path with a {{model}} persona: the supplier states it via the assemble waterfall', async () => {
  189. // AgentOptions.model unset: the model arrives in the agent/request
  190. // waterfall (the loop's documented fallback — see runStep's no-model
  191. // error). {{model}} renders BEFORE that waterfall, so the SAME plugin
  192. // states the fact early on system-prompt/assemble — the owner of a
  193. // late-bound fact owns stating it wherever it is claimed.
  194. const adapter = new MockAdapter([textResponse('ok')])
  195. const ctx = await harness(adapter, 'You run on {{model}}.')
  196. ctx.on('system-prompt/assemble', async (assembly, _context, next) => {
  197. assembly.variables['model'] = 'mock'
  198. return next()
  199. })
  200. ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => {
  201. return { ...config, model: 'mock' }
  202. })
  203. const agent = ctx.agentLoop.create(AgentId('a-late-model'), {})
  204. send(agent, 'hi')
  205. await waitForIdle(ctx, agent)
  206. expect(adapter.requests).toHaveLength(1)
  207. expect(adapter.requests[0]!.model).toBe('mock')
  208. expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou run on mock.')
  209. })
  210. it.each([
  211. ['BigInt', { n: 1n }],
  212. ['Map', new Map([['key', 'value']])],
  213. ['class instance', new (class ResultMeta { x = 1 })()],
  214. ])('normalizes non-JSON tool meta (%s) before the durable result commit', async (_kind, meta) => {
  215. const adapter = new MockAdapter([
  216. toolCallResponse('bad-meta-call', 'bad-meta', {}, 'calling'),
  217. textResponse('recovered'),
  218. ])
  219. const ctx = await harness(adapter)
  220. ctx.tools.register(defineTool({
  221. name: 'bad-meta',
  222. description: 'returns invalid durable metadata',
  223. parameters: {},
  224. execute: () => Promise.resolve({ content: [{ type: 'text' as const, text: 'apparent success' }], meta }),
  225. }))
  226. const agent = ctx.agentLoop.create(AgentId('bad-meta-agent'), { model: 'mock' })
  227. send(agent, 'use the tool')
  228. await waitForIdle(ctx, agent)
  229. const result = agent.session.events.find(event => event.type === 'tool/result')
  230. expect(result?.type).toBe('tool/result')
  231. if (result?.type === 'tool/result') {
  232. expect(result.data.callId).toBe('bad-meta-call')
  233. expect(result.data.isError).toBe(true)
  234. expect(result.data.meta).toBeUndefined()
  235. expect(result.data.content).toEqual([{
  236. type: 'text',
  237. text: 'Error: tool result must be losslessly JSON-serializable',
  238. }])
  239. }
  240. // The normalized failure was durably logged and fed back to the model; the
  241. // turn continued normally instead of failing after an apparent success.
  242. expect(adapter.requests).toHaveLength(2)
  243. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('losslessly JSON-serializable')
  244. })
  245. it('omits the system field when a system-prompt/assemble veto empties the assembly', async () => {
  246. // The documented escape valve: a deployment that must drop the harness
  247. // openers short-circuits the assemble waterfall; the request then carries
  248. // NO system field at all (not an empty string).
  249. const adapter = new MockAdapter([textResponse('ok')])
  250. const ctx = await harness(adapter)
  251. ctx.on('system-prompt/assemble', async () => ({ sections: [], tools: [], variables: {} }))
  252. const agent = ctx.agentLoop.create(AgentId('a-no-system'), { model: 'mock' })
  253. send(agent, 'hi')
  254. await waitForIdle(ctx, agent)
  255. expect(adapter.requests).toHaveLength(1)
  256. expect('system' in adapter.requests[0]!).toBe(false)
  257. })
  258. it('records raw chunks for replay as assistant/chunk session events', async () => {
  259. const adapter = new MockAdapter([textResponse('abc')])
  260. const ctx = await harness(adapter)
  261. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  262. send(agent, 'hi')
  263. await waitForIdle(ctx, agent)
  264. const chunkEvents = agent.session.events.filter(e => e.type === 'assistant/chunk')
  265. // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7
  266. expect(chunkEvents).toHaveLength(7)
  267. // replay: chunk events alone re-assemble to the recorded assistant message
  268. const deltaText = chunkEvents
  269. .flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : [])
  270. .filter((c: StreamChunk): c is Extract<StreamChunk, { type: 'text-delta' }> => c.type === 'text-delta')
  271. .map(c => c.text)
  272. .join('')
  273. expect(deltaText).toBe('abc')
  274. })
  275. it('injects steering between steps and continues the turn', async () => {
  276. const adapter = new MockAdapter([
  277. toolCallResponse('c1', 'slow', {}),
  278. textResponse('addressed the steering'),
  279. ])
  280. const ctx = await harness(adapter)
  281. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  282. ctx.tools.register(defineTool({
  283. name: 'slow',
  284. description: '',
  285. parameters: {},
  286. async execute() {
  287. // steer while the turn is running (during tool execution)
  288. agent.steer([{ type: 'text', text: 'change of plans' }])
  289. return [{ type: 'text', text: 'tool done' }]
  290. },
  291. }))
  292. send(agent, 'start')
  293. await waitForIdle(ctx, agent)
  294. const types = agent.session.events.map(e => e.type)
  295. expect(types).toContain('steering/message')
  296. // steering recorded before the second step's request derived its history
  297. const steeringSeq = agent.session.events.find(e => e.type === 'steering/message')!.seq
  298. const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1]
  299. expect(secondStepStart).toBeDefined()
  300. expect(steeringSeq).toBeLessThan(secondStepStart!.seq)
  301. // the second model request saw the steering content
  302. const secondRequest = adapter.requests[1]
  303. const flat = JSON.stringify(secondRequest!.messages)
  304. expect(flat).toContain('change of plans')
  305. })
  306. it('steering while idle behaves like send (starts a turn)', async () => {
  307. const adapter = new MockAdapter([textResponse('ok')])
  308. const ctx = await harness(adapter)
  309. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  310. agent.steer([{ type: 'text', text: 'hello' }])
  311. await waitForIdle(ctx, agent)
  312. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  313. })
  314. it('inject() while idle wraps context in a one-shot turn, visible to the next request', async () => {
  315. const adapter = new MockAdapter([textResponse('ok')])
  316. const ctx = await harness(adapter)
  317. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  318. agent.inject([{ type: 'text', text: 'file changed: a.ts' }], { source: { kind: 'plugin', plugin: 'watcher' } })
  319. // The idle inject records a self-contained turn (turn/start → context/message
  320. // → turn/end) so the event stays turn-enclosed, but does NOT run the model.
  321. await new Promise(r => setTimeout(r, 20))
  322. expect(agent.status).toBe('idle')
  323. expect(adapter.requests).toHaveLength(0)
  324. const injectedTurn = agent.session.events.filter(e => e.type === 'turn/start')
  325. expect(injectedTurn).toHaveLength(1)
  326. const it0 = injectedTurn[0]!
  327. expect(it0.type === 'turn/start' && it0.data.trigger.kind).toBe('injection')
  328. expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed
  329. send(agent, 'go')
  330. await waitForIdle(ctx, agent)
  331. const flat = JSON.stringify(adapter.requests[0]!.messages)
  332. expect(flat).toContain('file changed: a.ts')
  333. expect(flat).toContain('<context source=\\"plugin\\">')
  334. })
  335. it('inject() while running appends into the open turn (no extra synthetic turn)', async () => {
  336. const adapter = new MockAdapter([
  337. toolCallResponse('c1', 'noticer', {}, 'calling'),
  338. textResponse('done'),
  339. ])
  340. const ctx = await harness(adapter)
  341. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  342. // A tool that injects mid-execution: at this point the agent is running, so
  343. // inject must append the context/message into the ALREADY-open turn rather
  344. // than wrap it in its own one-shot turn.
  345. ctx.tools.register(defineTool({
  346. name: 'noticer',
  347. description: 'injects a notice',
  348. parameters: {},
  349. async execute() {
  350. agent.inject([{ type: 'text', text: 'mid-turn notice' }], { source: { kind: 'plugin', plugin: 'x' } })
  351. return [{ type: 'text', text: 'ok' }]
  352. },
  353. }))
  354. send(agent, 'go')
  355. await waitForIdle(ctx, agent)
  356. // Exactly ONE turn ran (no synthetic injection turn), and the mid-turn
  357. // context/message sits inside it.
  358. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  359. expect(turnStarts).toHaveLength(1)
  360. const ts0 = turnStarts[0]!
  361. expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
  362. expect(agent.session.events.some(e => e.type === 'context/message')).toBe(true)
  363. })
  364. it('agent/turn-continuation can force-continue (/loop pattern) and force-stop', async () => {
  365. // force-continue: model never calls tools, but a plugin forces 3 steps
  366. const adapter = new MockAdapter([
  367. textResponse('step 1'),
  368. textResponse('step 2'),
  369. textResponse('step 3'),
  370. ])
  371. const ctx = await harness(adapter)
  372. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  373. let steps = 0
  374. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  375. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  376. if (steps < 3) return { action: 'continue' as const }
  377. return next()
  378. })
  379. send(agent, 'go')
  380. await waitForIdle(ctx, agent)
  381. expect(steps).toBe(3)
  382. expect(adapter.requests).toHaveLength(3)
  383. })
  384. it('agent/turn-continuation can veto continuation despite tool calls (budget-guard pattern)', async () => {
  385. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
  386. const ctx = await harness(adapter)
  387. ctx.tools.register(defineTool({
  388. name: 'echo',
  389. description: '',
  390. parameters: { text: { type: 'string' } },
  391. async execute(args) {
  392. return [{ type: 'text', text: String(args.text) }]
  393. },
  394. }))
  395. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  396. ctx.on('agent/turn-continuation', async () => ({ action: 'stop' }) as const)
  397. send(agent, 'go')
  398. await waitForIdle(ctx, agent)
  399. // only one model call despite the tool call requesting a follow-up
  400. expect(adapter.requests).toHaveLength(1)
  401. // tool still executed before the decision
  402. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  403. })
  404. it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
  405. const adapter = new MockAdapter([textResponse('ok')])
  406. const ctx = await harness(adapter)
  407. ctx.llm.registerAdapter(['other-model'], adapter)
  408. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  409. ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => {
  410. // The seed is frozen — config is not a mutable per-call knob; a switch
  411. // is proposed by returning a replacement, and the loop logs it.
  412. expect(Object.isFrozen(config)).toBe(true)
  413. expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
  414. return { ...config, model: 'other-model' }
  415. })
  416. send(agent, 'hi')
  417. await waitForIdle(ctx, agent)
  418. expect(adapter.requests[0]!.model).toBe('other-model')
  419. // The header event records what the request ACTUALLY used — the switch is
  420. // a reconstructable fact, not silent drift.
  421. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  422. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
  423. })
  424. it('agent/pre-step fires once per step before the step is opened', async () => {
  425. // Two steps (a tool call, then a final text turn) → two model calls → two
  426. // pre-step fires, each carrying the assembled full system prompt, BEFORE
  427. // the step is opened and its request is derived (the request the adapter
  428. // sees reflects any surface state at fire time).
  429. const adapter = new MockAdapter([
  430. toolCallResponse('c1', 'echo', {}, 'calling echo'),
  431. textResponse('done'),
  432. ])
  433. const ctx = await harness(adapter)
  434. ctx.tools.register(defineTool({
  435. name: 'echo', description: 'echo', parameters: {},
  436. async execute() { return [{ type: 'text', text: 'echoed' }] },
  437. }))
  438. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  439. const fires: { turn: number; step: number; fullSystemPrompt: string }[] = []
  440. ctx.on('agent/pre-step', (subject, turn, step, fullSystemPrompt) => {
  441. if (subject === agent) fires.push({ turn, step, fullSystemPrompt })
  442. })
  443. send(agent, 'go')
  444. await waitForIdle(ctx, agent)
  445. // One fire per step, in order, each with the assembled system prompt
  446. // (here just the loop's own harness-identity section — no persona set).
  447. const HARNESS = 'You are an AI agent powered by the DeepSeek Harness SDK.'
  448. expect(fires).toEqual([
  449. { turn: 1, step: 1, fullSystemPrompt: HARNESS },
  450. { turn: 1, step: 2, fullSystemPrompt: HARNESS },
  451. ])
  452. })
  453. it('agent/pre-step fires BEFORE the step it precedes opens (events land outside the step)', async () => {
  454. // The append lands before step/start, yet derive happens afterwards and the
  455. // same step's request must include it.
  456. const adapter = new MockAdapter([textResponse('ok')])
  457. const ctx = await harness(adapter)
  458. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  459. let injected = false
  460. ctx.on('agent/pre-step', (subject) => {
  461. if (subject === agent && !injected) {
  462. injected = true
  463. subject.session.append('context/message', {
  464. content: [{ type: 'text', text: 'INJECTED-IN-PRE-STEP' }],
  465. source: { kind: 'plugin', plugin: 'test' },
  466. }, { surfaceOp: 'append' })
  467. }
  468. })
  469. send(agent, 'go')
  470. await waitForIdle(ctx, agent)
  471. // The adapter's request includes the node injected during pre-step (derive
  472. // reflects it).
  473. const text = JSON.stringify(adapter.requests[0]!.messages)
  474. expect(text).toContain('INJECTED-IN-PRE-STEP')
  475. // And the injected event sits BEFORE the first step/start in the log —
  476. // the seam fired outside the step.
  477. const events = agent.session.events
  478. const injectedSeq = events.find(e => e.type === 'context/message')!.seq
  479. const firstStepStartSeq = events.find(e => e.type === 'step/start')!.seq
  480. expect(injectedSeq).toBeLessThan(firstStepStartSeq)
  481. })
  482. it('a throwing agent/pre-step listener ends the turn (error), not the loop', async () => {
  483. // Before step/start, a pre-step throw reaches the turn catch: no step needs
  484. // closing, the turn records error, and the loop remains available.
  485. const adapter = new MockAdapter([textResponse('second turn ok')])
  486. const ctx = await harness(adapter)
  487. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  488. let throwOnce = true
  489. ctx.on('agent/pre-step', () => {
  490. if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
  491. })
  492. const errors: Error[] = []
  493. ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
  494. send(agent, 'first')
  495. await waitForIdle(ctx, agent)
  496. // The first turn failed at step 1 (no model call happened), surfaced via
  497. // agent/error, with the durable failure on turn/end.reason.
  498. expect(errors).toHaveLength(1)
  499. expect(errors[0]!.message).toContain('boom in pre-step')
  500. expect(adapter.requests.length).toBe(0)
  501. const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
  502. expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  503. // The step opened-and-closed count stays balanced even though it never ran.
  504. const types = agent.session.events.map(e => e.type)
  505. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  506. // The loop survived: a second prompt runs a normal completed turn.
  507. send(agent, 'second')
  508. await waitForIdle(ctx, agent)
  509. expect(adapter.requests.length).toBe(1)
  510. const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  511. expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
  512. })
  513. it('cancel() mid-stream ends the turn with reason aborted', async () => {
  514. const adapter = new MockAdapter(['hang'])
  515. const ctx = await harness(adapter)
  516. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  517. const reasons: TurnEndReason[] = []
  518. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  519. send(agent, 'go')
  520. // wait until the stream is hanging, then cancel
  521. await new Promise(r => setTimeout(r, 30))
  522. expect(agent.status).toBe('running')
  523. agent.cancel('user interrupt')
  524. await waitForIdle(ctx, agent)
  525. expect(reasons).toEqual([{ kind: 'aborted', reason: 'user interrupt' }])
  526. })
  527. it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
  528. // A single step that ends with a max-tokens finish (no tool calls): the
  529. // turn stops by default and ends max-tokens, not completed.
  530. const adapter = new MockAdapter([maxTokensResponse('truncat')])
  531. const ctx = await harness(adapter)
  532. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  533. const reasons: TurnEndReason[] = []
  534. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  535. send(agent, 'go')
  536. await waitForIdle(ctx, agent)
  537. expect(adapter.requests).toHaveLength(1)
  538. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  539. // Assert the durable row, not only the live listener.
  540. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  541. expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
  542. })
  543. it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
  544. // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
  545. // must be FORCED to reach step 2 which finishes normally (stop).
  546. const adapter = new MockAdapter([
  547. maxTokensResponse('first half'),
  548. textResponse('second half'),
  549. ])
  550. const ctx = await harness(adapter)
  551. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  552. let steps = 0
  553. ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
  554. // Force exactly one continuation (step 1 → step 2), then defer to default
  555. // (step 2 is a plain stop with no tool calls → stops).
  556. ctx.on('agent/turn-continuation', async (_agent, _turn, _defaultDecision, next) => {
  557. if (steps < 2) return { action: 'continue' as const }
  558. return next()
  559. })
  560. const reasons: TurnEndReason[] = []
  561. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  562. send(agent, 'go')
  563. await waitForIdle(ctx, agent)
  564. expect(steps).toBe(2)
  565. expect(adapter.requests).toHaveLength(2)
  566. expect(adapter.requests[1]!.messages).toEqual([
  567. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  568. { role: 'assistant', content: [{ type: 'text', text: 'first half' }] },
  569. ])
  570. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  571. })
  572. it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
  573. // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
  574. // stop. The per-turn reason must be independent — turn 2 ends completed.
  575. const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
  576. const ctx = await harness(adapter)
  577. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  578. const reasons: TurnEndReason[] = []
  579. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  580. send(agent, 'first')
  581. await waitForIdle(ctx, agent)
  582. send(agent, 'second')
  583. await waitForIdle(ctx, agent)
  584. expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
  585. })
  586. it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
  587. const callId = CallId('c1')
  588. const adapter = new MockAdapter([[
  589. { type: 'block-start', index: 0, blockType: 'tool-call' },
  590. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  591. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  592. { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
  593. { type: 'finish', reason: { kind: 'max-tokens' } },
  594. ]])
  595. const ctx = await harness(adapter)
  596. let executions = 0
  597. ctx.tools.register(defineTool({
  598. name: 'echo',
  599. description: '',
  600. parameters: { text: { type: 'string' } },
  601. async execute() {
  602. executions += 1
  603. return [{ type: 'text', text: 'should not run' }]
  604. },
  605. }))
  606. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  607. const reasons: TurnEndReason[] = []
  608. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  609. send(agent, 'go')
  610. await waitForIdle(ctx, agent)
  611. expect(executions).toBe(0)
  612. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  613. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  614. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  615. // Empty content still needs an assistant/message to carry usage; derivation
  616. // skips that host so it does not create a spurious assistant turn.
  617. const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
  618. expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
  619. turn: 1, step: 1, content: [], usage: { inputTokens: 10, outputTokens: 5 },
  620. })
  621. })
  622. it('appends no assistant/message for a max-tokens step with empty content and no usage', async () => {
  623. // A max-tokens step truncated to a dropped tool call AND with no usage chunk has nothing to
  624. // record: empty content and no accounting → no assistant/message (the empty-content host
  625. // exists only to carry usage).
  626. const callId = CallId('c1')
  627. const adapter = new MockAdapter([[
  628. { type: 'block-start', index: 0, blockType: 'tool-call' },
  629. { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
  630. { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
  631. { type: 'finish', reason: { kind: 'max-tokens' } },
  632. ]])
  633. const ctx = await harness(adapter)
  634. ctx.tools.register(defineTool({
  635. name: 'echo',
  636. description: '',
  637. parameters: { text: { type: 'string' } },
  638. async execute() { return [{ type: 'text', text: 'should not run' }] },
  639. }))
  640. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  641. const reasons: TurnEndReason[] = []
  642. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  643. send(agent, 'go')
  644. await waitForIdle(ctx, agent)
  645. expect(reasons).toEqual([{ kind: 'max-tokens' }])
  646. expect(agent.session.events.some(e => e.type === 'assistant/message')).toBe(false)
  647. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  648. })
  649. it('appends no assistant/message for a normal stop finish with empty content and no usage', async () => {
  650. // A clean `stop` finish that streamed nothing assembled (no blocks) and
  651. // carried no usage chunk has nothing to record: the content-or-usage guard
  652. // on the normal step path suppresses a pure trace-only empty assistant/message.
  653. const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
  654. const ctx = await harness(adapter)
  655. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  656. const reasons: TurnEndReason[] = []
  657. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  658. send(agent, 'go')
  659. await waitForIdle(ctx, agent)
  660. expect(reasons).toEqual([{ kind: 'completed' }])
  661. expect(agent.session.events.some(e => e.type === 'assistant/message')).toBe(false)
  662. expect(agent.session.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'go' }] }])
  663. })
  664. it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
  665. const callId = CallId('c1')
  666. const adapter = new MockAdapter([[
  667. { type: 'block-start', index: 0, blockType: 'text' },
  668. { type: 'text-delta', index: 0, text: 'partial text' },
  669. { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
  670. { type: 'block-start', index: 1, blockType: 'tool-call' },
  671. { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
  672. { type: 'finish', reason: { kind: 'max-tokens' } },
  673. ]])
  674. const ctx = await harness(adapter)
  675. let stepResults = 0
  676. ctx.on('agent/step-result', async (_agent, _turn, _step, message, next) => {
  677. stepResults += 1
  678. expect(message.content).toEqual([{ type: 'text', text: 'partial text' }])
  679. return next()
  680. })
  681. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  682. send(agent, 'go')
  683. await waitForIdle(ctx, agent)
  684. expect(stepResults).toBe(1)
  685. expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
  686. expect(agent.session.deriveMessages()).toEqual([
  687. { role: 'user', content: [{ type: 'text', text: 'go' }] },
  688. { role: 'assistant', content: [{ type: 'text', text: 'partial text' }] },
  689. ])
  690. })
  691. it('contains a step/end observer failure without changing continuation', async () => {
  692. const adapter = new MockAdapter([
  693. toolCallResponse('c1', 'echo', { text: 'x' }),
  694. textResponse('continued after tool call'),
  695. ])
  696. const ctx = await harness(adapter)
  697. ctx.tools.register(defineTool({
  698. name: 'echo',
  699. description: '',
  700. parameters: { text: { type: 'string' } },
  701. async execute(args) {
  702. return [{ type: 'text', text: String(args.text) }]
  703. },
  704. }))
  705. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  706. let threw = false
  707. // Post-commit session observers cannot control the loop. The tool call still
  708. // drives the second model request, and the turn completes normally.
  709. ctx.on('session/event', (_session, event) => {
  710. if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
  711. })
  712. send(agent, 'go')
  713. await waitForIdle(ctx, agent)
  714. expect(adapter.requests).toHaveLength(2)
  715. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  716. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
  717. })
  718. it('chains queued messages into consecutive turns', async () => {
  719. const adapter = new MockAdapter([textResponse('first'), textResponse('second')])
  720. const ctx = await harness(adapter)
  721. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  722. const turns: number[] = []
  723. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
  724. // queue two messages while idle — first starts turn 1 immediately;
  725. // queue the second during turn 1 when the first assistant chunk streams
  726. let queued = false
  727. ctx.on('session/event', (_s, event) => {
  728. if (event.type === 'assistant/chunk' && !queued) {
  729. queued = true
  730. send(agent, 'second message')
  731. }
  732. })
  733. send(agent, 'first message')
  734. await waitForIdle(ctx, agent)
  735. expect(turns).toEqual([1, 2])
  736. expect(adapter.requests).toHaveLength(2)
  737. })
  738. it('awaits session/flush at turn end (persistence checkpoint)', async () => {
  739. const adapter = new MockAdapter([textResponse('ok')])
  740. const ctx = await harness(adapter)
  741. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  742. let flushed = 0
  743. let flushedBeforeIdle = false
  744. ctx.on('session/flush', async (session) => {
  745. await new Promise(r => setTimeout(r, 10))
  746. flushed++
  747. flushedBeforeIdle = agent.status !== 'idle'
  748. void session
  749. })
  750. send(agent, 'hi')
  751. await waitForIdle(ctx, agent)
  752. expect(flushed).toBe(1)
  753. expect(flushedBeforeIdle).toBe(true)
  754. })
  755. it('errors from the model surface as agent/error and end the turn', async () => {
  756. const adapter = new MockAdapter([]) // script exhausted → throws
  757. const ctx = await harness(adapter)
  758. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  759. const errors: Error[] = []
  760. const reasons: TurnEndReason[] = []
  761. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  762. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  763. send(agent, 'hi')
  764. await waitForIdle(ctx, agent)
  765. expect(errors).toHaveLength(1)
  766. expect(errors[0]!.message).toContain('script exhausted')
  767. expect(reasons[0]).toMatchObject({ kind: 'error' })
  768. // The durable failure lives entirely on turn/end.reason (with the failing
  769. // step), not a standalone error event.
  770. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  771. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
  772. })
  773. it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
  774. const adapter = new MockAdapter(['hang'])
  775. const ctx = await harness(adapter)
  776. let agent!: ReactLoopAgent
  777. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  778. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  779. }, { inject: ['agentLoop'] }))
  780. expect(ctx.agents.get(AgentId('scoped'))).toBe(agent)
  781. send(agent, 'go')
  782. await new Promise(r => setTimeout(r, 30))
  783. expect(agent.status).toBe('running')
  784. await fiber.dispose()
  785. await agent.done
  786. expect(agent.status).toBe('disposed')
  787. expect(ctx.agents.get(AgentId('scoped'))).toBeUndefined()
  788. expect(() => { send(agent, 'too late') }).toThrow('disposed')
  789. })
  790. it('creates agents from config on startup', async () => {
  791. const adapter = new MockAdapter([textResponse('from config')])
  792. const ctx = new Context()
  793. await ctx.plugin(LlmService)
  794. await ctx.plugin(SessionStore)
  795. await ctx.plugin(SystemPrompt)
  796. await ctx.plugin(ToolRegistry)
  797. await ctx.plugin(AgentRegistry)
  798. await ctx.plugin(AgentLoop, {
  799. agents: [{ id: AgentId('config-agent'), model: 'mock' }],
  800. })
  801. ctx.llm.registerAdapter(['mock'], adapter)
  802. const agent = ctx.agents.get(AgentId('config-agent'))! as ReactLoopAgent
  803. expect(agent).toBeDefined()
  804. expect(agent.id).toBe('config-agent')
  805. expect(agent.options.model).toBe('mock')
  806. // the agent is alive: send triggers a turn
  807. send(agent, 'hi')
  808. await waitForIdle(ctx, agent)
  809. expect(adapter.requests).toHaveLength(1)
  810. })
  811. it('attaches config agent cwd to the fresh session header', async () => {
  812. const ctx = new Context()
  813. await ctx.plugin(LlmService)
  814. await ctx.plugin(SessionStore)
  815. await ctx.plugin(SystemPrompt)
  816. await ctx.plugin(ToolRegistry)
  817. await ctx.plugin(AgentRegistry)
  818. await ctx.plugin(AgentLoop, {
  819. agents: [{ id: AgentId('config-agent'), model: 'mock', cwd: '/work/project' }],
  820. })
  821. const agent = ctx.agents.get(AgentId('config-agent'))! as ReactLoopAgent
  822. expect(agent.session.header.cwd).toBe('/work/project')
  823. })
  824. it('replays a session log into an identical derived history', async () => {
  825. const adapter = new MockAdapter([
  826. toolCallResponse('c1', 'echo', { text: 'x' }),
  827. textResponse('done'),
  828. ])
  829. const ctx = await harness(adapter)
  830. ctx.tools.register(defineTool({
  831. name: 'echo',
  832. description: '',
  833. parameters: { text: { type: 'string' } },
  834. async execute(args) {
  835. return [{ type: 'text', text: String(args.text) }]
  836. },
  837. }))
  838. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  839. send(agent, 'run')
  840. await waitForIdle(ctx, agent)
  841. const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
  842. expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
  843. // event-by-event identity of types
  844. expect(replayed.events.map(e => e.type)).toEqual(
  845. agent.session.events.map(e => e.type))
  846. })
  847. })