loop.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /**
  2. * Drives one agent across queued durable turns. Turn failures are contained so
  3. * later work can run; the session log, not this driver, owns conversation state.
  4. * See docs/rfc/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md.
  5. * @module dsh-agent-loop/loop
  6. */
  7. import type { Context } from 'cordis'
  8. import type { FinishReason, GenerateOptions, LlmCallConfig, Message } from '@deepseek-ai/dsh-llm'
  9. import { BlockAssembler, HarnessError, deepFreeze } from '@deepseek-ai/dsh-llm'
  10. import { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent'
  11. import type { AgentEventDispatch, ContinuationDecision, HookContext, PromptDecision } from '@deepseek-ai/dsh-agent'
  12. import { canonicalHeader } from '@deepseek-ai/dsh-session'
  13. import type { Session, TurnEndReason, TurnTrigger } from '@deepseek-ai/dsh-session'
  14. import { createTransmissionLog, recordRequestHeader } from './request-log.ts'
  15. import type { TransmissionLog } from './request-log.ts'
  16. import { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
  17. import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt'
  18. import type {} from '@deepseek-ai/dsh-tools'
  19. import type { ReactLoopAgent } from './agent.ts'
  20. import type { Inbox } from './inbox.ts'
  21. /** An Error with an optional machine-readable code (e.g., from LlmError or a throwing plugin). */
  22. type CodedError = Error & { code?: string }
  23. /** Normalize thrown values while preserving an existing error code. */
  24. function toError(error: unknown): CodedError {
  25. return error instanceof Error ? error : new HarnessError(String(error), 'UNKNOWN', { cause: error })
  26. }
  27. /** Convert terminal failure finishes into step errors; unknown extensible finishes remain successful. */
  28. function finishError(finish: FinishReason): CodedError | undefined {
  29. switch (finish.kind) {
  30. case 'error': {
  31. const error: CodedError = new Error(finish.message)
  32. if (finish.code !== undefined) error.code = finish.code
  33. return error
  34. }
  35. case 'aborted': {
  36. const error: CodedError = new Error('model stream aborted')
  37. error.code = 'ABORTED'
  38. return error
  39. }
  40. // stop / tool-calls / max-tokens / plugin-added kinds → not a failure.
  41. default:
  42. return undefined
  43. }
  44. }
  45. /**
  46. * Build the `{ message, code? }` part of an error payload, omitting the
  47. * `code` key entirely when absent (exactOptionalPropertyTypes-correct).
  48. */
  49. function errorData(err: CodedError): { message: string; code?: string } {
  50. return { message: err.message, ...typeof err.code === 'string' ? { code: err.code } : {} }
  51. }
  52. /** Map a successful max-token finish onto the turn reason; other successful finishes add nothing. */
  53. function stepFinishReason(finish: FinishReason): TurnEndReason | undefined {
  54. switch (finish.kind) {
  55. case 'max-tokens':
  56. return { kind: 'max-tokens' }
  57. // stop / tool-calls / plugin-added kinds → no turn-end contribution
  58. // beyond the default `completed`. FinishReason is merge-extensible, so a
  59. // default (not assertNever) handles unknown kinds as ordinary success.
  60. default:
  61. return undefined
  62. }
  63. }
  64. /** Mutable agent controls supplied to the loop driver. */
  65. export interface LoopHandle {
  66. /** Native-private agent inbox handed to the driver only at internal startup. */
  67. readonly inbox: Inbox
  68. setStatus(status: 'idle' | 'running'): void
  69. setAbort(controller: AbortController | undefined): void
  70. /** Resolves when the agent is disposed — unblocks the idle wait. */
  71. disposed: Promise<void>
  72. isDisposed(): boolean
  73. /** Whether cancellation is pending for the current loop iteration. */
  74. isCancelled(): boolean
  75. /** Resolved pending-cancellation reason; meaningful only while {@link isCancelled} is true. */
  76. cancelReason(): string
  77. /** Clear the cancel marker (called once per iteration after the turn returns). */
  78. clearCancel(): void
  79. /** Settle idle waiters when pre-running cancellation skips a turn, without emitting `agent/status`. */
  80. settleIdle(): void
  81. }
  82. /**
  83. * Drive queued batches as durable turns until disposal. Plugin failures end the
  84. * current turn without terminating the driver.
  85. * @param ctx - the plugin context the loop reaches events (agent/…, session/flush) and services (systemPrompt, llm, tools) through.
  86. * @param agent - the agent this invocation drives for its whole lifetime (its inbox, session, and options).
  87. * @param handle - the bridge to the agent's mutable state: status/abort setters plus the disposal and cancel-marker reads.
  88. */
  89. export async function runLoop(ctx: Context, agent: ReactLoopAgent, handle: LoopHandle): Promise<void> {
  90. // Per-instance prefix and request-header state; conversation history remains in the session log.
  91. const transmission = createTransmissionLog()
  92. const { session } = agent
  93. // Fused subject and scope carrier for every agent event below.
  94. const events = agentEvents(ctx, agent)
  95. while (!handle.isDisposed()) {
  96. await handle.inbox.waitForQueued(handle.disposed)
  97. if (handle.isDisposed()) break
  98. // Cancellation between wake and `running` skips only the cancelled work;
  99. // a replacement prompt still runs and owns the eventual idle transition.
  100. if (handle.isCancelled()) {
  101. handle.clearCancel()
  102. if (!handle.inbox.hasQueued) {
  103. handle.settleIdle()
  104. continue
  105. }
  106. }
  107. handle.setStatus('running')
  108. // A synchronous `running` listener can cancel before `runTurn`; balance the
  109. // status only when no replacement prompt was queued by that listener.
  110. if (handle.isCancelled()) {
  111. handle.clearCancel()
  112. if (!handle.inbox.hasQueued) {
  113. handle.setStatus('idle')
  114. continue
  115. }
  116. }
  117. // Idle injection can add a turn, so derive the next number from the log.
  118. const turn = lastTurnNumber(session) + 1
  119. let terminalStopped = false
  120. try {
  121. terminalStopped = await runTurn(ctx, events, agent, handle, turn, transmission)
  122. } catch (error: unknown) {
  123. // Pre-turn failure has no durable boundary to close; report it without appending outside a turn.
  124. const err = toError(error)
  125. ctx.logger.warn(`agent "${agent.id}": turn ${turn} failed before it started: ${err.message}`)
  126. try {
  127. events.emit('agent/error', turn, 0, err)
  128. } catch { /* contained: a throwing agent/error listener must not kill the driver */ }
  129. }
  130. // Reset per iteration, including when a prompt arrives during the flush window.
  131. handle.clearCancel()
  132. // Late steering becomes queued input unless terminal policy stopped the turn.
  133. for (const message of handle.inbox.drainSteering()) {
  134. if (!terminalStopped) handle.inbox.enqueue(message)
  135. }
  136. if (!handle.inbox.hasQueued) handle.setStatus('idle')
  137. }
  138. }
  139. async function runTurn(
  140. ctx: Context, events: AgentEventDispatch, agent: ReactLoopAgent, handle: LoopHandle, turn: number, transmission: TransmissionLog,
  141. ): Promise<boolean> {
  142. const { session } = agent
  143. // Drain before opening the turn, but append only after `turn/start`.
  144. const queued = handle.inbox.drainQueued()
  145. const first = queued[0]
  146. /* v8 ignore next 3 -- invariant guard: runLoop only calls runTurn when hasQueued */
  147. if (!first) throw new Error('runTurn invariant violated: no queued message at turn start')
  148. const trigger: TurnTrigger = { kind: 'message', source: first.source }
  149. let reason: TurnEndReason = { kind: 'completed' }
  150. let step = 0
  151. let stepOpen = false
  152. let errorReported = false
  153. let terminalStopped = false
  154. // Close the committed step once; pre-commit validation failure still escapes.
  155. const closeStep = (): void => {
  156. if (!stepOpen) return
  157. session.append('step/end', { turn, step })
  158. stepOpen = false
  159. }
  160. // Record the durable turn failure once and contain the live error notification.
  161. const failTurn = (err: CodedError): void => {
  162. if (errorReported) return
  163. errorReported = true
  164. reason = { kind: 'error', step, ...errorData(err) }
  165. try {
  166. events.emit('agent/error', turn, step, err)
  167. } catch {
  168. // contained: the error is already captured on `reason`; a throwing
  169. // agent/error listener must not prevent the turn from closing.
  170. }
  171. }
  172. // Pre-commit validation failure escapes rather than masquerading as a committed boundary.
  173. const closeTurn = (): void => {
  174. session.append('turn/end', { turn, reason })
  175. }
  176. try {
  177. // --- Turn boundary. Once turn/start is appended, a turn/end is owed no
  178. // matter what throws below; the catch + closeTurn guarantee it. A pre-commit
  179. // veto leaves no turn/start in the log and therefore owes no turn/end.
  180. session.append('turn/start', { turn, trigger })
  181. // Each drained queued message runs the `agent/prompt-submit` waterfall before
  182. // it becomes a `user/message` — a hook can rewrite the prompt or block it.
  183. // Recorded INSIDE the turn (after turn/start) so every event is turn-enclosed;
  184. // turn/end is now owed, so a throwing prompt-submit listener (the waterfall
  185. // throws) is caught below and the turn still closes.
  186. let anyAllowed = false
  187. // Seeded with a floor (only observable if the batch were empty, which
  188. // runTurn never allows — it is called with ≥1 queued message); each `block`
  189. // decision carries a required `reason` and overwrites it, so a fully-blocked
  190. // batch always reports the last vetoing reason.
  191. let lastBlockReason = 'prompt blocked by hook'
  192. for (const message of queued) {
  193. const decision = await events.waterfall(
  194. 'agent/prompt-submit', message.content, message.source,
  195. () => Promise.resolve<PromptDecision>({ kind: 'allow' }),
  196. )
  197. if (decision.kind === 'block') {
  198. lastBlockReason = decision.reason
  199. // Record the veto durably: `PromptDecision.reason` is the durable record
  200. // of why a prompt was blocked, but a fully-blocked batch's `rejected`
  201. // turn/end only preserves the LAST reason, and a MIXED batch (this prompt
  202. // blocked, another allowed) does not end `rejected` at all — so without
  203. // this append a blocked prompt would vanish from the log whenever any
  204. // sibling prompt is allowed. `prompt/blocked` sits in the open turn in
  205. // place of the `user/message` this prompt would have become.
  206. session.append('prompt/blocked', { content: message.content, source: message.source, reason: decision.reason })
  207. continue
  208. }
  209. anyAllowed = true
  210. // `allow.content` REPLACES the prompt bytes (a rewrite); absent keeps them.
  211. const content = decision.content ?? message.content
  212. session.append('user/message', { content, source: message.source }, { surfaceOp: 'append' })
  213. // Every `allow.additionalContexts` entry is a separate context/message the
  214. // next request also sees. The turn is open, so inject() appends each one
  215. // into THIS turn without flattening provenance, framing, or metadata.
  216. for (const context of decision.additionalContexts ?? []) {
  217. agent.inject(context.content, {
  218. source: context.source,
  219. ...context.envelope !== undefined ? { envelope: context.envelope } : {},
  220. ...context.meta !== undefined ? { meta: context.meta } : {},
  221. })
  222. }
  223. }
  224. while (true) {
  225. // A fully blocked batch closes its zero-step turn as rejected.
  226. if (!anyAllowed) {
  227. reason = { kind: 'rejected', reason: lastBlockReason }
  228. break
  229. }
  230. step += 1
  231. // Steering from the previous round's continuation listeners joins before
  232. // the request.
  233. drainSteering(agent, handle.inbox, turn)
  234. // The step's AbortController exists BEFORE any async pre-step work so a
  235. // dispose() or cancel() — in a synchronous turn-start listener or an
  236. // async listener whose effect fires before we block — always has an armed
  237. // abort to cancel against. isDisposed below covers disposal, which does
  238. // NOT set the cancel marker. Cleared on every exit path below.
  239. const abort = new AbortController()
  240. handle.setAbort(abort)
  241. // Assemble once before pre-step so pressure checks and the request share the same prompt.
  242. const assembly = await ctx.systemPrompt.assemble(assembleContextFor(agent))
  243. const fullSystemPrompt = renderPrompt(assembly)
  244. // Cancellation or disposal during assembly ends the turn before any step opens.
  245. if (handle.isCancelled() || handle.isDisposed()) {
  246. handle.setAbort(undefined)
  247. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  248. break
  249. }
  250. // Compose the request-only prefix once per loop instance before pressure
  251. // checks. It precedes all derived history and is recorded only in the
  252. // request header, not as session history.
  253. if (transmission.sessionPrefix === undefined) {
  254. const emptyPrefix: Message[] = deepFreeze([])
  255. const composed = await events.waterfall(
  256. 'agent/session-prefix', emptyPrefix, abort.signal,
  257. () => Promise.resolve(emptyPrefix),
  258. )
  259. // Never cache an interrupted composition; the next turn recomposes it.
  260. if (handle.isCancelled() || handle.isDisposed()) {
  261. handle.setAbort(undefined)
  262. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  263. break
  264. }
  265. transmission.sessionPrefix = deepFreeze(structuredClone(composed))
  266. }
  267. // Await surface mutations outside the step; pressure checks receive the pending prefix.
  268. await events.serial('agent/pre-step', turn, step, fullSystemPrompt, transmission.sessionPrefix, abort.signal)
  269. // Interruption landing during the pre-step seam: do not open an empty step.
  270. if (handle.isCancelled() || handle.isDisposed()) {
  271. handle.setAbort(undefined)
  272. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  273. break
  274. }
  275. // Snapshot the exact log prefix before step/start: the reconstruction
  276. // boundary. Appends after this synchronous snapshot join the next request.
  277. const boundaryMessages = session.deriveMessages()
  278. session.append('step/start', { turn, step })
  279. // Only a committed step/start creates a balancing obligation. A
  280. // pre-commit veto throws before this assignment; post-commit observers
  281. // are contained inside Session.append().
  282. stepOpen = true
  283. // Cancel landing in the step-start window: a synchronous `session/event`
  284. // step/start listener can cancel after the step is already open. Check
  285. // AFTER the step/start append and before `runStep`: drop the step, end the
  286. // turn accordingly. closeStep balances the already-appended step/start.
  287. if (handle.isCancelled() || handle.isDisposed()) {
  288. handle.setAbort(undefined)
  289. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  290. closeStep()
  291. break
  292. }
  293. let stepOutcome: { hadToolCalls: boolean; finish: FinishReason } | { error: Error }
  294. try {
  295. stepOutcome = await runStep(
  296. ctx, events, agent, turn, step, assembly, fullSystemPrompt, boundaryMessages, transmission, abort.signal)
  297. } catch (error: unknown) {
  298. stepOutcome = { error: toError(error) }
  299. } finally {
  300. handle.setAbort(undefined)
  301. }
  302. if ('error' in stepOutcome) {
  303. // Steering that arrived during the failed step stays in the inbox —
  304. // runLoop re-enqueues it as a queued message, so an abort-then-steer
  305. // starts a fresh turn instead of being silently consumed.
  306. closeStep()
  307. const { error } = stepOutcome
  308. if (handle.isDisposed()) {
  309. reason = { kind: 'disposed' }
  310. } else if (abort.signal.aborted) {
  311. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  312. reason = { kind: 'aborted', reason: String(abort.signal.reason ?? 'aborted') }
  313. } else {
  314. failTurn(error)
  315. }
  316. break
  317. }
  318. // Preserve max-token completion unless a later disposal, abort, or error wins.
  319. const stepReason = stepFinishReason(stepOutcome.finish)
  320. if (stepReason) reason = stepReason
  321. // Steering that arrived during streaming/tool execution.
  322. const steered = drainSteering(agent, handle.inbox, turn)
  323. closeStep()
  324. const defaultDecision: ContinuationDecision = { action: stepOutcome.hadToolCalls || steered ? 'continue' : 'stop' }
  325. let decision: ContinuationDecision
  326. try {
  327. decision = await events.waterfall(
  328. 'agent/turn-continuation', turn, defaultDecision,
  329. () => Promise.resolve(defaultDecision),
  330. )
  331. } catch (error: unknown) {
  332. // A broken continuation plugin ends the turn, not the loop.
  333. failTurn(toError(error))
  334. break
  335. }
  336. // A continuation reason becomes next-step steering.
  337. if (decision.action === 'continue' && decision.reason) {
  338. handle.inbox.steer({ content: decision.reason.content, source: decision.reason.source })
  339. }
  340. let shouldContinue = decision.action === 'continue'
  341. // Pending steering overrides an ordinary stop.
  342. if (!shouldContinue && handle.inbox.hasSteering) shouldContinue = true
  343. // Terminal policy is monotonic and runs after ordinary continuation folding.
  344. let terminalStop = false
  345. try {
  346. const stop = await events.serial('agent/turn-stop', turn)
  347. terminalStop = stop !== undefined
  348. } catch (error: unknown) {
  349. // A broken terminal policy is an ordinary continuation failure: fail
  350. // this turn closed while leaving the driver alive for later turns.
  351. failTurn(toError(error))
  352. break
  353. }
  354. if (terminalStop) {
  355. terminalStopped = true
  356. // Terminal stop discards steering but preserves ordinary queued prompts.
  357. handle.inbox.drainSteering()
  358. shouldContinue = false
  359. }
  360. // The marker catches cancellation after the step controller was cleared.
  361. if (handle.isCancelled()) {
  362. reason = { kind: 'aborted', reason: handle.cancelReason() }
  363. break
  364. }
  365. if (!shouldContinue || handle.isDisposed()) {
  366. /* v8 ignore next -- disposal during continuation-decision window is a narrow race; error-path disposal is covered elsewhere */
  367. if (handle.isDisposed()) reason = { kind: 'disposed' }
  368. break
  369. }
  370. }
  371. // Normal / inline-error loop exit: close the turn.
  372. closeTurn()
  373. } catch (error: unknown) {
  374. // Close only a turn whose start committed to the log.
  375. const turnStartLogged = session.events.some(e => e.type === 'turn/start' && e.data.turn === turn)
  376. if (!turnStartLogged) throw error
  377. closeStep()
  378. // Preserve an established disposal reason; otherwise report the failure.
  379. if (handle.isDisposed() && !errorReported) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition
  380. reason = { kind: 'disposed' }
  381. } else {
  382. failTurn(toError(error))
  383. }
  384. closeTurn()
  385. }
  386. // Flush through the store-owned durability checkpoint without killing the driver on failure.
  387. try {
  388. await ctx.sessions.flush(session)
  389. } catch (error: unknown) {
  390. // The turn is closed, so report the failed flush live rather than append outside a turn.
  391. const err = toError(error)
  392. ctx.logger.warn(`agent "${agent.id}": session/flush failed at turn ${turn}: ${err.message}`)
  393. try {
  394. events.emit('agent/error', turn, step, err)
  395. } catch {
  396. // contained: a throwing agent/error listener must not escape the loop.
  397. }
  398. }
  399. return terminalStopped
  400. }
  401. /** Drain the steering queue into the session. Returns whether any arrived. */
  402. function drainSteering(agent: ReactLoopAgent, inbox: Inbox, turn: number): boolean {
  403. const messages = inbox.drainSteering()
  404. for (const message of messages) {
  405. agent.session.append('steering/message', { turn, content: message.content, source: message.source }, { surfaceOp: 'append' })
  406. }
  407. return messages.length > 0
  408. }
  409. /**
  410. * Run one committed step: transform call config, log the request header, build
  411. * the request from the cached prefix plus the step-boundary snapshot, stream and
  412. * record the response, then execute tools. The caller has already assembled the
  413. * prompt, run `agent/pre-step`, snapshotted history, and opened the step.
  414. */
  415. async function runStep(
  416. ctx: Context,
  417. events: AgentEventDispatch,
  418. agent: ReactLoopAgent,
  419. turn: number,
  420. step: number,
  421. assembly: PromptAssembly,
  422. system: string,
  423. boundaryMessages: Message[],
  424. transmission: TransmissionLog,
  425. signal: AbortSignal,
  426. ): Promise<{ hadToolCalls: boolean; finish: FinishReason }> {
  427. const { session, options } = agent
  428. // Seed the first request from agent options and later requests from the logged header;
  429. // detach and freeze so listeners must return an attributable replacement.
  430. const seedConfig: LlmCallConfig = deepFreeze(structuredClone(transmission.loggedHeader
  431. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- loggedHeader ⟹ a snapshot is in the log
  432. ? session.requestHeader()!.config
  433. : { model: options.model ?? '' }))
  434. // Listener replacements are recorded in the request header before dispatch.
  435. const config = await events.waterfall('agent/request', turn, step, seedConfig, () => Promise.resolve(seedConfig))
  436. if (!config.model) {
  437. throw new Error(`agent "${agent.id}" has no model: set AgentOptions.model or supply one via the agent/request waterfall`)
  438. }
  439. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- runTurn composes the prefix before every runStep call
  440. const sessionPrefix = transmission.sessionPrefix!
  441. // Record the canonical header, including the otherwise-unlogged prefix, before dispatch.
  442. const header = canonicalHeader({
  443. config,
  444. ...system ? { system } : {},
  445. ...assembly.tools.length > 0 ? { tools: assembly.tools } : {},
  446. ...sessionPrefix.length > 0 ? { messagePrefix: sessionPrefix } : {},
  447. })
  448. recordRequestHeader(session, transmission, header)
  449. // Freeze the logged header plus boundary snapshot; the prefix precedes derived history.
  450. const request: GenerateOptions = deepFreeze({
  451. model: header.config.model,
  452. messages: [...header.messagePrefix ?? [], ...boundaryMessages],
  453. ...header.system !== undefined ? { system: header.system } : {},
  454. ...header.tools !== undefined ? { tools: header.tools } : {},
  455. ...header.config.temperature !== undefined ? { temperature: header.config.temperature } : {},
  456. ...header.config.maxTokens !== undefined ? { maxTokens: header.config.maxTokens } : {},
  457. ...header.config.stop !== undefined ? { stop: header.config.stop } : {},
  458. sessionId: session.id,
  459. signal,
  460. })
  461. // --- Model call (streaming-first; raw chunks are the replay record) ---
  462. const assembler = new BlockAssembler()
  463. const chunkSeqs: number[] = []
  464. for await (const chunk of ctx.llm.stream(request)) {
  465. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  466. if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted'))
  467. const chunkEvent = session.append('assistant/chunk', { turn, step, chunk })
  468. chunkSeqs.push(chunkEvent.seq)
  469. assembler.push(chunk)
  470. }
  471. // Normalize failure finish chunks into the same path as thrown stream errors.
  472. const stepError = finishError(assembler.finish)
  473. if (stepError) throw stepError
  474. if (assembler.finish.kind === 'max-tokens') {
  475. let message: Message = withoutToolCalls(assembler.message())
  476. message = withoutToolCalls(await events.waterfall('agent/step-result', turn, step, message, () => Promise.resolve(message)))
  477. // Preserve usage even when max-token truncation produced no content.
  478. if (message.content.length > 0 || assembler.usage) {
  479. // The finish chunk guarantees non-empty provenance here.
  480. session.append(
  481. 'assistant/message',
  482. { turn, step, content: message.content, ...(assembler.usage ? { usage: assembler.usage } : {}) },
  483. { surfaceOp: 'append', sourceEventSeqs: chunkSeqs },
  484. )
  485. }
  486. return { hadToolCalls: false, finish: assembler.finish }
  487. }
  488. // Record the post-waterfall message that tool dispatch uses.
  489. let message: Message = assembler.message()
  490. message = await events.waterfall('agent/step-result', turn, step, message, () => Promise.resolve(message))
  491. // Empty messages exist only to carry usage; omit empty provenance.
  492. if (message.content.length > 0 || assembler.usage) {
  493. session.append(
  494. 'assistant/message',
  495. { turn, step, content: message.content, ...(assembler.usage ? { usage: assembler.usage } : {}) },
  496. { surfaceOp: 'append', ...(chunkSeqs.length > 0 ? { sourceEventSeqs: chunkSeqs } : {}) },
  497. )
  498. }
  499. // Tool execution stays sequential; recheck abort around each normalized result.
  500. const toolCalls = message.content.filter(block => block.type === 'tool-call')
  501. // Buffer context until all results are appended to preserve call/result adjacency.
  502. const pendingContext: HookContext[] = []
  503. for (const call of toolCalls) {
  504. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  505. if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted'))
  506. const callEvent = session.append('tool/call', { turn, step, callId: call.id, name: call.name, arguments: call.arguments })
  507. let parsedArguments: unknown
  508. try {
  509. parsedArguments = call.arguments ? JSON.parse(call.arguments) : {}
  510. } catch {
  511. parsedArguments = call.arguments
  512. }
  513. // TODO(pre-tool-input-rewrite): Keep logged history and live presentation aligned;
  514. // see docs/rfc/proposed/feature/2026-06-30-pre-tool-input-rewrite.md.
  515. const result = await ctx.tools.execute({
  516. callId: call.id,
  517. name: call.name,
  518. arguments: parsedArguments,
  519. agent,
  520. signal,
  521. })
  522. session.append('tool/result', {
  523. turn, step,
  524. // Correlation comes from the immutable execution input; the result does
  525. // not duplicate this authoritative transcript identity.
  526. callId: call.id,
  527. content: result.content,
  528. isError: result.isError,
  529. ...result.error ? { error: result.error } : {},
  530. // Persist tool-owned presentation data for replay.
  531. ...result.meta !== undefined ? { meta: result.meta } : {},
  532. }, { surfaceOp: 'append', sourceEventSeqs: [callEvent.seq] })
  533. pendingContext.push(...result.additionalContexts ?? [])
  534. // The signal may flip while the tool is awaited.
  535. /* v8 ignore start -- signal.reason default unreachable: cancel()/disposal always set it */
  536. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  537. if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted'))
  538. /* v8 ignore stop */
  539. }
  540. // Append buffered context after the complete result batch.
  541. for (const context of pendingContext) {
  542. agent.inject(context.content, {
  543. source: context.source,
  544. ...context.envelope !== undefined ? { envelope: context.envelope } : {},
  545. ...context.meta !== undefined ? { meta: context.meta } : {},
  546. })
  547. }
  548. return { hadToolCalls: toolCalls.length > 0, finish: assembler.finish }
  549. }
  550. function withoutToolCalls(message: Message): Message {
  551. return { ...message, content: message.content.filter(block => block.type !== 'tool-call') }
  552. }
  553. /**
  554. * The last turn number in a (possibly seeded) session log, or 0.
  555. * @param session - the session whose log is scanned for the latest `turn/start`.
  556. * @returns the latest `turn/start`'s turn number, or 0 when the log has none (the next turn is this plus one).
  557. */
  558. export function lastTurnNumber(session: Session): number {
  559. const lastStart = session.events.findLast(event => event.type === 'turn/start')
  560. return lastStart?.data.turn ?? 0
  561. }
  562. /**
  563. * Whether the session log has an unmatched `turn/start`. Agent status is not
  564. * sufficient during pre-start and post-end windows.
  565. * @param session - the session whose log is inspected.
  566. * @returns true when the log's last turn boundary is a `turn/start` with no matching `turn/end` yet.
  567. */
  568. export function isTurnOpen(session: Session): boolean {
  569. const last = session.events.findLast(e => e.type === 'turn/start' || e.type === 'turn/end')
  570. return last?.type === 'turn/start'
  571. }