loop.spec.ts 42 KB

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