loop.ts 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. /**
  2. * The agent loop driver: one `runLoop()` invocation drives one agent for its
  3. * whole lifetime. Error-contained at the turn level — a throwing plugin ends
  4. * the turn, never kills the loop. See the JSDoc on `runLoop()` for the full
  5. * lifecycle pseudo-code.
  6. *
  7. * @module dsh-agent-loop/loop
  8. */
  9. import type { Context } from 'cordis'
  10. import type { FinishReason, GenerateOptions, LlmCallConfig, Message } from '@deepseek-ai/dsh-llm'
  11. import { BlockAssembler, HarnessError, deepFreeze } from '@deepseek-ai/dsh-llm'
  12. import { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent'
  13. import type { AgentEventDispatch, ContinuationDecision, ContinuationStop, HookContext, PromptDecision } from '@deepseek-ai/dsh-agent'
  14. import { canonicalHeader } from '@deepseek-ai/dsh-session'
  15. import type { Session, TurnEndReason, TurnTrigger } from '@deepseek-ai/dsh-session'
  16. import { createTransmissionLog, recordRequestHeader } from './request-log.ts'
  17. import type { TransmissionLog } from './request-log.ts'
  18. import { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
  19. import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt'
  20. import type {} from '@deepseek-ai/dsh-tools'
  21. import type { ReactLoopAgent } from './agent.ts'
  22. import type { Inbox } from './inbox.ts'
  23. /** An Error with an optional machine-readable code (e.g., from LlmError or a throwing plugin). */
  24. type CodedError = Error & { code?: string }
  25. /**
  26. * Normalize an arbitrary thrown value into a coded Error. A real Error passes
  27. * through (its `code`, if any, is preserved by {@link errorData}); a non-Error
  28. * throw is wrapped in a {@link HarnessError} with code `UNKNOWN` and the
  29. * original value chained as `cause`, so a bad throw still carries a routable
  30. * code instead of degrading to a bare message.
  31. */
  32. function toError(error: unknown): CodedError {
  33. return error instanceof Error ? error : new HarnessError(String(error), 'UNKNOWN', { cause: error })
  34. }
  35. /**
  36. * Validate the runtime result of the terminal-stop serial event. Event types
  37. * protect TypeScript listeners, but JavaScript and casts can still return an
  38. * arbitrary bail value; accepting one as an implicit stop would hide a broken
  39. * policy plugin.
  40. */
  41. function assertContinuationStop(value: unknown): asserts value is ContinuationStop | undefined {
  42. if (value === undefined) return
  43. const candidate = Object(value) as { action?: unknown }
  44. if (candidate.action !== 'stop') {
  45. throw new Error('agent/turn-stop returned an invalid result; expected { action: \'stop\' } or undefined')
  46. }
  47. }
  48. /**
  49. * Map a model-call {@link FinishReason} to the step error it should raise, or
  50. * `undefined` when the step completed normally.
  51. *
  52. * Adapters report provider/transport failures one of two sanctioned ways (see
  53. * the StreamChunk contract in dsh-llm): throw from `stream()` (handled by the
  54. * caller's try/catch), OR end the stream with a finish-error/aborted chunk
  55. * (the only option for adapters that can't throw mid-stream, e.g.
  56. * library-backed ones). This translates the latter into a thrown step error
  57. * so the turn ends error/aborted (the failure recorded on `turn/end.reason`),
  58. * never as a normal `completed` assistant message.
  59. *
  60. * `FinishReason` is merge-extensible (plugins/adapters can add `kind`s), so
  61. * the switch handles the known terminal-failure kinds and treats every other
  62. * kind — `stop`, `tool-calls`, `max-tokens`, future additions — as success.
  63. */
  64. function finishError(finish: FinishReason): CodedError | undefined {
  65. switch (finish.kind) {
  66. case 'error': {
  67. const error: CodedError = new Error(finish.message)
  68. if (finish.code !== undefined) error.code = finish.code
  69. return error
  70. }
  71. case 'aborted': {
  72. const error: CodedError = new Error('model stream aborted')
  73. error.code = 'ABORTED'
  74. return error
  75. }
  76. // stop / tool-calls / max-tokens / plugin-added kinds → not a failure.
  77. default:
  78. return undefined
  79. }
  80. }
  81. /**
  82. * Build the `{ message, code? }` part of an error payload, omitting the
  83. * `code` key entirely when absent (exactOptionalPropertyTypes-correct).
  84. */
  85. function errorData(err: CodedError): { message: string; code?: string } {
  86. return { message: err.message, ...typeof err.code === 'string' ? { code: err.code } : {} }
  87. }
  88. /**
  89. * The turn-end contribution of a step's *successful* finish, or `undefined`
  90. * when the step finished ordinarily (a plain `completed`).
  91. *
  92. * {@link finishError} has already converted `error`/`aborted` finishes into
  93. * thrown step errors, so the finishes that reach here are `stop`,
  94. * `tool-calls`, `max-tokens`, or a future merge-extensible kind. Only
  95. * `max-tokens` carries forward as a distinct {@link TurnEndReason}: a step that
  96. * hit the output-token ceiling ended the turn cut-short rather than by the
  97. * model's choice. `stop`/`tool-calls`/unknown kinds contribute nothing beyond
  98. * the default `completed`. {@link runTurn} applies this with the rule "any
  99. * `max-tokens` step in the turn makes the turn end `max-tokens`".
  100. */
  101. function stepFinishReason(finish: FinishReason): TurnEndReason | undefined {
  102. switch (finish.kind) {
  103. case 'max-tokens':
  104. return { kind: 'max-tokens' }
  105. // stop / tool-calls / plugin-added kinds → no turn-end contribution
  106. // beyond the default `completed`. FinishReason is merge-extensible, so a
  107. // default (not assertNever) handles unknown kinds as ordinary success.
  108. default:
  109. return undefined
  110. }
  111. }
  112. /**
  113. * Ambient handles the loop driver receives from the agent. Decouples the
  114. * pure function `runLoop` from the mutable ReactLoopAgent fields, making the
  115. * loop testable without a real agent.
  116. */
  117. export interface LoopHandle {
  118. /** Native-private agent inbox handed to the driver only at internal startup. */
  119. readonly inbox: Inbox
  120. setStatus(status: 'idle' | 'running'): void
  121. setAbort(controller: AbortController | undefined): void
  122. /** Resolves when the agent is disposed — unblocks the idle wait. */
  123. disposed: Promise<void>
  124. isDisposed(): boolean
  125. /**
  126. * Whether a `cancel()` is pending for the current turn. The driver checks this
  127. * at every decision point where a turn could start or continue (right after
  128. * the idle wait, after the `running` flip, before each step, and at the
  129. * continuation gate) and drops the about-to-run / continuing turn. Reset once
  130. * per loop iteration via {@link clearCancel} after the turn returns, so the
  131. * marker governs exactly one cancellation and never leaks to a later prompt.
  132. */
  133. isCancelled(): boolean
  134. /**
  135. * The resolved reason for the pending cancel (`reason ?? 'cancelled'`), read
  136. * by the marker branches (pre-step / continuation) so a turn dropped where no
  137. * `AbortController` carries the reason still records the caller's
  138. * `cancel(reason)` value — matching the mid-step abort path. Only meaningful
  139. * when {@link isCancelled} is true.
  140. */
  141. cancelReason(): string
  142. /** Clear the cancel marker (called once per iteration after the turn returns). */
  143. clearCancel(): void
  144. /**
  145. * Settle pending `whenIdle()` waiters WITHOUT a status transition. Used by the
  146. * pre-step cancel-skip path: it drops the about-to-run turn and re-parks at the
  147. * idle wait, so no `running→idle` transition fires to settle a `whenIdle()`
  148. * waiter that was registered in the pre-step window — this settles it directly
  149. * (it emits no `agent/status`, so an ACP `agent/status` listener never sees a
  150. * spurious idle that would resolve a freshly-queued prompt as cancelled).
  151. */
  152. settleIdle(): void
  153. }
  154. /**
  155. * The agent loop. One invocation drives one agent for its whole lifetime:
  156. *
  157. * ```
  158. * create agent → emit agent/session-start(source) ⟵ once, before turn 1
  159. * forever:
  160. * wait for queued messages (idle)
  161. * TURN (error-contained — a throwing plugin ends the turn, never the loop):
  162. * 'turn/start'; each queued msg: waterfall agent/prompt-submit ⟵ durable turn boundary (no agent/* mirror)
  163. * allow → session('user/message'…) (+ inject additionalContext) | block → drop
  164. * every prompt blocked → 'turn/end'(rejected), 0 steps
  165. * STEP loop:
  166. * drain steering → session('steering/message') ⟵ catches late steering
  167. * assembly = ctx.systemPrompt.assemble(assembleContextFor(agent)) ⟵ waterfall system-prompt/assemble
  168. * (scope-filtered; scoped sections/tools join); renderPrompt
  169. * (persona section + {{variables}}) IS the full prompt
  170. * prefix ??= waterfall agent/session-prefix ⟵ once per loop instance (first step): frozen
  171. * session prefix; logged on the header, never
  172. * session history (scope-filtered, fused dispatch)
  173. * await events.serial('agent/pre-step', …, prefix) ⟵ surface mutation (compaction) OUTSIDE the step;
  174. * pressure gates see the prefix the request carries
  175. * boundary = session.deriveMessages() ⟵ the reconstruction boundary: snapshot in the
  176. * session('step/start') same sync frame, strictly before step/start
  177. * config = waterfall agent/request(config) ⟵ frozen seed; a returned replacement switches
  178. * session('request/header'|'request/header-delta') ⟵ the header event this request owes the
  179. * log (initial/resume anchor, delta, fallback)
  180. * req = freeze({header..., messages: prefix+boundary, sessionId, signal})
  181. * stream ctx.llm.stream(req) ⟵ waterfall llm/stream (raw chunks, frozen req)
  182. * session('assistant/chunk')
  183. * msg = waterfall agent/step-result ⟵ BEFORE the log append, so the
  184. * session('assistant/message' {content, usage?}) session records what actually ran
  185. * each tool-call in msg (sequential, abort-checked):
  186. * session('tool/call'); ctx.tools.execute() ⟵ tools/pre-execute (allow/deny/ask)
  187. * → dispatch → tools/post-execute
  188. * session('tool/result')
  189. * append buffered post-execute additionalContext → session('context/message')(s)
  190. * drain steering → session('steering/message')
  191. * session('step/end') ⟵ durable step boundary (no agent/* mirror)
  192. * cont = waterfall agent/turn-continuation ⟵ ContinuationDecision; default
  193. * {action: hadToolCalls||steered ? 'continue':'stop'}; a continue.reason is
  194. * recorded as next-step steering
  195. * if action==stop && steering arrived (step/end/continuation listeners): continue anyway
  196. * terminal = serial agent/turn-stop ⟵ stop or abstain; after all ordinary
  197. * continuation and steering folding
  198. * if terminal: discard pending steering and break
  199. * if action==stop: break
  200. * session('turn/end') ⟵ durable turn boundary (no agent/* mirror)
  201. * await ctx.sessions.flush(session) ⟵ durability checkpoint (store-owned carrier)
  202. * re-enqueue leftover steering as queued ⟵ steering is never stranded
  203. * idle (emit agent/status) unless more queued
  204. * ```
  205. * @param ctx - the plugin context the loop reaches events (agent/…, session/flush) and services (systemPrompt, llm, tools) through.
  206. * @param agent - the agent this invocation drives for its whole lifetime (its inbox, session, and options).
  207. * @param handle - the bridge to the agent's mutable state: status/abort setters plus the disposal and cancel-marker reads.
  208. */
  209. export async function runLoop(ctx: Context, agent: ReactLoopAgent, handle: LoopHandle): Promise<void> {
  210. // Per-instance transmission bookkeeping: whether THIS loop instance has
  211. // anchored the log's header fold yet (its first request logs a
  212. // 'initial'/'resume' request/header snapshot). Everything else the request
  213. // needs is read from the session log itself — the loop holds no
  214. // conversation state (the reconstructability RFC).
  215. const transmission = createTransmissionLog()
  216. const { session } = agent
  217. // The fused agent-subject dispatcher: every agent/* dispatch below carries
  218. // the agent's scope (an `agent.ctx` listener hears only this agent) with
  219. // the subject injected — one spelling, checked by the dev invariants.
  220. const events = agentEvents(ctx, agent)
  221. while (!handle.isDisposed()) {
  222. await handle.inbox.waitForQueued(handle.disposed)
  223. if (handle.isDisposed()) break
  224. // Pre-step cancel (window 1): a `cancel()` landed after a `send()` woke the
  225. // idle wait but before we flip to `running`. The cancelled queued/steering
  226. // work is already cleared by `cancel()`. Clear the marker, then:
  227. // - if NOTHING new is queued, drop the about-to-run turn and re-park,
  228. // settling any `whenIdle()` waiter DIRECTLY (no running→idle transition
  229. // fires here to settle it) and WITHOUT emitting `agent/status` (an ACP
  230. // listener must not see a spurious idle that resolves a freshly-queued
  231. // prompt as cancelled);
  232. // - if a NEW prompt was queued AFTER the cancel (a send() that raced in
  233. // before the loop resumed), the marker was for the cancelled work only —
  234. // fall through and run the new prompt's turn. Do NOT settle waiters here:
  235. // a whenIdle() waiter must wait for that new turn's running→idle, not
  236. // resolve before it runs (the quiescence contract).
  237. if (handle.isCancelled()) {
  238. handle.clearCancel()
  239. if (!handle.inbox.hasQueued) {
  240. handle.settleIdle()
  241. continue
  242. }
  243. }
  244. handle.setStatus('running')
  245. // Pre-step cancel (window 2): `setStatus('running')` emits `agent/status`
  246. // SYNCHRONOUSLY, so a `running` listener can `cancel()` in the gap between the
  247. // check above and `runTurn`. Mirror window 1: clear the marker, then
  248. // - if NOTHING new is queued, drop the about-to-run turn and transition
  249. // back to `idle` (`running` was already emitted, so a real idle
  250. // transition balances the status AND settles `whenIdle()` waiters);
  251. // - if a NEW prompt was queued AFTER the cancel (a `running` listener that
  252. // cancels then sends), the marker was for the cancelled work only — fall
  253. // through and run the new prompt's turn (status is already `running`), so
  254. // a `whenIdle()` waiter resolves on THAT turn's running→idle, not before
  255. // it runs. Settling here would resolve quiescence while the replacement
  256. // is still queued and unrun (the same early-resolve race window 1 fixes).
  257. if (handle.isCancelled()) {
  258. handle.clearCancel()
  259. if (!handle.inbox.hasQueued) {
  260. handle.setStatus('idle')
  261. continue
  262. }
  263. }
  264. // Re-derive the turn number from the log each iteration (do NOT keep a local
  265. // counter): an idle `agent.inject()` can append its own one-shot turn while
  266. // the loop waits above, so the next real turn must continue from whatever
  267. // turn number is actually last in the log — a stale counter would collide.
  268. const turn = lastTurnNumber(session) + 1
  269. let terminalStopped = false
  270. try {
  271. terminalStopped = await runTurn(ctx, events, agent, handle, turn, transmission)
  272. } catch (error: unknown) {
  273. // Backstop: runTurn rethrows only a PRE-turn throw (the invariant guard
  274. // before turn/start) — no turn/start was appended, so no turn is open and
  275. // none is owed. A session `error` here would land outside any turn (after
  276. // the previous turn/end), where the persistence backend drops it as a
  277. // crash tail (the turn-enclosure RFC). Report via agent/error + the logger only; the
  278. // driver survives and moves on.
  279. const err = toError(error)
  280. ctx.logger.warn(`agent "${agent.id}": turn ${turn} failed before it started: ${err.message}`)
  281. try {
  282. events.emit('agent/error', turn, 0, err)
  283. } catch { /* contained: a throwing agent/error listener must not kill the driver */ }
  284. }
  285. // Reset the cancel marker UNCONDITIONALLY here, after the turn returns and
  286. // before the next iteration's idle wait. NOT gated on the idle transition
  287. // below: a `send()` that lands during the cancelled turn's flush window makes
  288. // `hasQueued` true at the `setStatus('idle')` guard, so an idle-gated reset
  289. // would never fire and the stale marker would wrongly drop that next prompt's
  290. // turn. Resetting per iteration scopes the marker to exactly the turn that was
  291. // cancelled.
  292. handle.clearCancel()
  293. // Steering that arrived too late to join an ordinary turn (turn-end
  294. // listeners, flush) becomes queued input so it is never stranded. A
  295. // terminal-stop owner is the deliberate exception: discard the steering
  296. // again after the close + flush window so terminal policy cannot be undone
  297. // after its in-turn drain. Ordinary queued sends live in a separate FIFO and
  298. // remain untouched.
  299. for (const message of handle.inbox.drainSteering()) {
  300. if (!terminalStopped) handle.inbox.enqueue(message)
  301. }
  302. if (!handle.inbox.hasQueued) handle.setStatus('idle')
  303. }
  304. }
  305. async function runTurn(
  306. ctx: Context, events: AgentEventDispatch, agent: ReactLoopAgent, handle: LoopHandle, turn: number, transmission: TransmissionLog,
  307. ): Promise<boolean> {
  308. const { session } = agent
  309. // --- Pre-turn. A throw here (the invariant guard) is owed NO turn/end —
  310. // turn/start has not been appended — so it propagates to runLoop's backstop
  311. // untouched. The queued messages are drained here but appended AFTER
  312. // turn/start (below), so every event in the log lives inside a turn.
  313. const queued = handle.inbox.drainQueued()
  314. const first = queued[0]
  315. /* v8 ignore next 3 -- invariant guard: runLoop only calls runTurn when hasQueued */
  316. if (!first) throw new Error('runTurn invariant violated: no queued message at turn start')
  317. const trigger: TurnTrigger = { kind: 'message', source: first.source }
  318. let reason: TurnEndReason = { kind: 'completed' }
  319. let step = 0
  320. let stepOpen = false
  321. let errorReported = false
  322. let terminalStopped = false
  323. // Close the open step exactly once (idempotent via stepOpen). Step boundaries
  324. // are durable session events only — there is no agent/* step emit to mirror
  325. // them (see the agent event-domain rule). A throwing step/end session-event
  326. // listener must not abort finalization and strand the turn open (turn/end
  327. // balance > notifying one bad listener); it is contained and surfaced as a
  328. // turn error below.
  329. const closeStep = (): boolean => {
  330. if (!stepOpen) return false
  331. stepOpen = false
  332. // Session.append pushes step/end BEFORE notifying session/event listeners,
  333. // so a throwing listener leaves step/end in the log (balance holds) but
  334. // would otherwise abort finalization. Contain it and surface it as a turn
  335. // error below.
  336. let failure: unknown
  337. try {
  338. session.append('step/end', { turn, step })
  339. } catch (error: unknown) {
  340. failure = error
  341. }
  342. // A throwing step/end session-event listener surfaces as a turn error via
  343. // failTurn (idempotent). This prevents a throwing listener from producing a
  344. // silent "completed" turn when the step itself succeeded, AND keeps
  345. // finalization going when closeStep runs from the outer catch.
  346. if (failure !== undefined) {
  347. failTurn(toError(failure))
  348. return true
  349. }
  350. return false
  351. }
  352. // Record a step/turn failure exactly once: set the error reason (carrying the
  353. // failing `step` — the durable failure lives entirely on turn/end.reason, there
  354. // is no separate session error event) and emit agent/error (contained — trap: a
  355. // throwing agent/error listener must not re-escape and strand the turn).
  356. // Disposal and abort set `reason` directly without calling this (they are not
  357. // failures).
  358. const failTurn = (err: CodedError): void => {
  359. if (errorReported) return
  360. errorReported = true
  361. // The turn is always still open here: the only failure that can reach
  362. // failTurn once turn/end is appended would be a throwing turn-boundary
  363. // listener, and turn boundaries are durable session events with no agent/*
  364. // mirror to throw. A throwing `turn/end` session-event listener is already
  365. // contained inside closeTurn (append pushes before notifying, so the
  366. // boundary is durable). So set the error reason for closeTurn to append.
  367. reason = { kind: 'error', step, ...errorData(err) }
  368. try {
  369. events.emit('agent/error', turn, step, err)
  370. } catch {
  371. // contained: the error is already captured on `reason`; a throwing
  372. // agent/error listener must not prevent the turn from closing.
  373. }
  374. }
  375. // Close the turn. Called exactly once per turn — the normal loop exit and the
  376. // outer catch are mutually exclusive paths, and this never throws (the append
  377. // is contained below), so there is no re-entry to guard against (unlike
  378. // closeStep, which the cancel branches and the outer catch can both reach).
  379. // Turn boundaries are durable session events only — there is no agent/* turn
  380. // emit to mirror them (see the agent event-domain rule).
  381. const closeTurn = (): void => {
  382. // Session.append pushes turn/end BEFORE notifying session/event listeners,
  383. // so a throwing listener leaves turn/end in the log (the turn is balanced)
  384. // but would otherwise escape — from the outer catch it would propagate to
  385. // the runLoop backstop. Contain it: the boundary is durable either way, and
  386. // finalization must not abort on a bad listener.
  387. try {
  388. session.append('turn/end', { turn, reason })
  389. } catch (error: unknown) {
  390. ctx.logger.warn(`agent "${agent.id}": session/event listener threw on turn/end at turn ${turn}: ${toError(error).message}`)
  391. }
  392. }
  393. try {
  394. // --- Turn boundary. Once turn/start is appended, a turn/end is owed no
  395. // matter what throws below; the catch + closeTurn guarantee it (the catch
  396. // decides "owed" from the log via isTurnOpen, so even a throwing turn/start
  397. // listener — append pushes before notifying — still gets its turn/end).
  398. session.append('turn/start', { turn, trigger })
  399. // Each drained queued message runs the `agent/prompt-submit` waterfall before
  400. // it becomes a `user/message` — a hook can rewrite the prompt or block it.
  401. // Recorded INSIDE the turn (after turn/start) so every event is turn-enclosed;
  402. // turn/end is now owed, so a throwing prompt-submit listener (the waterfall
  403. // throws) is caught below and the turn still closes.
  404. let anyAllowed = false
  405. // Seeded with a floor (only observable if the batch were empty, which
  406. // runTurn never allows — it is called with ≥1 queued message); each `block`
  407. // decision carries a required `reason` and overwrites it, so a fully-blocked
  408. // batch always reports the last vetoing reason.
  409. let lastBlockReason = 'prompt blocked by hook'
  410. for (const message of queued) {
  411. const decision = await events.waterfall(
  412. 'agent/prompt-submit', message.content, message.source,
  413. () => Promise.resolve<PromptDecision>({ kind: 'allow' }),
  414. )
  415. if (decision.kind === 'block') {
  416. lastBlockReason = decision.reason
  417. // Record the veto durably: `PromptDecision.reason` is the durable record
  418. // of why a prompt was blocked, but a fully-blocked batch's `rejected`
  419. // turn/end only preserves the LAST reason, and a MIXED batch (this prompt
  420. // blocked, another allowed) does not end `rejected` at all — so without
  421. // this append a blocked prompt would vanish from the log whenever any
  422. // sibling prompt is allowed. `prompt/blocked` sits in the open turn in
  423. // place of the `user/message` this prompt would have become.
  424. session.append('prompt/blocked', { content: message.content, source: message.source, reason: decision.reason })
  425. continue
  426. }
  427. anyAllowed = true
  428. // `allow.content` REPLACES the prompt bytes (a rewrite); absent keeps them.
  429. const content = decision.content ?? message.content
  430. session.append('user/message', { content, source: message.source }, { surfaceOp: 'append' })
  431. // `allow.additionalContext` is a SEPARATE context/message the next request
  432. // also sees. The turn is open, so inject() appends it into THIS turn.
  433. if (decision.additionalContext) {
  434. agent.inject(decision.additionalContext.content, { source: decision.additionalContext.source })
  435. }
  436. }
  437. while (true) {
  438. // A fully-blocked batch (every prompt vetoed by prompt-submit) opens a
  439. // zero-step turn that ends `rejected`: break BEFORE the first step so the
  440. // boundary stays balanced (turn/start → turn/end) and the block is a
  441. // durable in-turn fact. `anyAllowed` never changes inside the loop, so this
  442. // only ever fires on the first iteration.
  443. if (!anyAllowed) {
  444. reason = { kind: 'rejected', reason: lastBlockReason }
  445. break
  446. }
  447. step += 1
  448. // Steering from the previous round's continuation listeners joins before
  449. // the request.
  450. drainSteering(agent, handle.inbox, turn)
  451. // The step's AbortController exists BEFORE any async pre-step work so a
  452. // dispose() or cancel() — in a synchronous turn-start listener or an
  453. // async listener whose effect fires before we block — always has an armed
  454. // abort to cancel against. isDisposed below covers disposal, which does
  455. // NOT set the cancel marker. Cleared on every exit path below.
  456. const abort = new AbortController()
  457. handle.setAbort(abort)
  458. // Assemble the system prompt for this step. Done HERE (before step/start)
  459. // because the pre-step seam needs it: compaction measures token pressure
  460. // against the system prompt (it counts toward the budget). runStep reuses
  461. // this same assembly for the request, so the prompt is assembled once per
  462. // step. renderPrompt IS the full prompt — the persona is the order-0
  463. // section (registered by the AgentLoop plugin) and `{{variable}}`
  464. // interpolation happens in the render, so there is no separate join.
  465. const assembly = await ctx.systemPrompt.assemble(assembleContextFor(agent))
  466. const fullSystemPrompt = renderPrompt(assembly)
  467. // Interruption landing after assembly: dispose() or cancel() in a
  468. // turn-start listener (or a listener whose promise resolved before the
  469. // await above) arms either handle.isDisposed() or handle.isCancelled().
  470. // The Abort was created first, so any concurrent abort also lands on it.
  471. // Drop the about-to-start step WITHOUT running the seam — no step is open
  472. // yet, so end the turn accordingly (disposed wins for an unambiguous
  473. // reason).
  474. if (handle.isCancelled() || handle.isDisposed()) {
  475. handle.setAbort(undefined)
  476. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  477. break
  478. }
  479. // Compose the session prefix ONCE per loop instance, lazily before the
  480. // instance's first pre-step: request-only messages placed in front of
  481. // the ENTIRE derived history on every request this instance sends. It
  482. // MUST precede the pre-step seam so compaction gates on THIS instance's
  483. // prefix — reading a previous instance's logged prefix would let a
  484. // resumed/forked instance whose contributor grew skip compaction and
  485. // ship an over-window first request. The result is deep-cloned
  486. // (decoupled from listener-held references), deep-frozen, and cached on
  487. // the transmission bookkeeping, so reuse is structural — the prefix
  488. // cannot change mid-session and the provider prefix cache holds by
  489. // construction (resume = a new instance = a recompose, anchored by its
  490. // 'resume' snapshot). The prefix is not session history — the header
  491. // event in runStep is its only durable record
  492. // (EpochHeader.messagePrefix). The frozen empty seed serves both the
  493. // listener chain and the no-listener fallback: a contribution is a
  494. // RETURNED extension of `await next()`, never an in-place push. This
  495. // runs OUTSIDE the step, before the boundary snapshot: a composing
  496. // listener's session append lands before the boundary and joins the
  497. // CURRENT request.
  498. if (transmission.sessionPrefix === undefined) {
  499. const emptyPrefix: Message[] = deepFreeze([])
  500. const composed = await events.waterfall(
  501. 'agent/session-prefix', emptyPrefix, abort.signal,
  502. () => Promise.resolve(emptyPrefix),
  503. )
  504. // Interruption landing during prefix composition: mirror the assembly
  505. // window above — drop the about-to-start step without running the
  506. // seam, and DISCARD the composition instead of caching it. An
  507. // abort-aware listener may have returned a degraded fallback under
  508. // the firing signal; committing it would ship a prefix no request
  509. // ever used (and no header ever logged) on this instance's next real
  510. // request. The next turn recomposes under a live signal — the cache
  511. // only ever holds a fully composed prefix. The cache-hit path needs
  512. // no such check: nothing awaits between the assembly check above and
  513. // the pre-step seam.
  514. if (handle.isCancelled() || handle.isDisposed()) {
  515. handle.setAbort(undefined)
  516. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  517. break
  518. }
  519. transmission.sessionPrefix = deepFreeze(structuredClone(composed))
  520. }
  521. // Pre-step surface-mutation checkpoint (compaction), fired OUTSIDE the
  522. // step: after `turn/start` (and the prior step's close) but before
  523. // `step/start`, so a compaction's log-only `compact/*` records and its
  524. // replacement node land cleanly outside any step (honest structure that
  525. // crash-safety relies on — a dangling `compact/start` sits before the
  526. // synthetic `turn/end` repair appends). Serial (awaited, in order, no
  527. // veto): each listener completes its surface mutation before the next, so
  528. // concurrent listeners cannot interleave their `session.append`s. A
  529. // throwing listener escapes to the outer catch, which closes the (not-yet-
  530. // open) step as a no-op and ends the turn via failTurn — a broken
  531. // pre-step plugin ends the turn, not the loop. The composed session
  532. // prefix rides along so token-pressure listeners count everything the
  533. // request will actually carry.
  534. await events.serial('agent/pre-step', turn, step, fullSystemPrompt, transmission.sessionPrefix, abort.signal)
  535. // Interruption landing during the pre-step seam: do not open an empty step.
  536. if (handle.isCancelled() || handle.isDisposed()) {
  537. handle.setAbort(undefined)
  538. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  539. break
  540. }
  541. // The reconstruction boundary (the reconstructability RFC): the request's
  542. // messages are snapshotted HERE, in the same synchronous frame as the
  543. // step/start append directly below — so the snapshot is exactly the
  544. // derivation over the log prefix strictly before step/start's seq.
  545. // Anything appended later — by a step/start session/event listener, an
  546. // agent/request-window inject(), any concurrent task — lands after the
  547. // boundary and joins the NEXT request. An external reconstructor
  548. // recovers these exact messages by folding the surface over
  549. // events[0..stepStartSeq).
  550. const boundaryMessages = session.deriveMessages()
  551. // Mark the step open BEFORE the append: Session.append pushes the event
  552. // to the log before notifying session/event listeners, so a THROWING
  553. // step/start listener leaves step/start in the log. Setting stepOpen first
  554. // means the outer catch's closeStep() then appends the balancing step/end
  555. // (turn stays enclosed) instead of stranding an open step under turn/end.
  556. stepOpen = true
  557. session.append('step/start', { turn, step })
  558. // Cancel landing in the step-start window: a synchronous `session/event`
  559. // step/start listener can cancel after the step is already open. Check
  560. // AFTER the step/start append and before `runStep`: drop the step, end the
  561. // turn accordingly. closeStep balances the already-appended step/start.
  562. if (handle.isCancelled() || handle.isDisposed()) {
  563. handle.setAbort(undefined)
  564. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  565. closeStep()
  566. break
  567. }
  568. let stepOutcome: { hadToolCalls: boolean; finish: FinishReason } | { error: Error }
  569. try {
  570. stepOutcome = await runStep(
  571. ctx, events, agent, turn, step, assembly, fullSystemPrompt, boundaryMessages, transmission, abort.signal)
  572. } catch (error: unknown) {
  573. stepOutcome = { error: toError(error) }
  574. } finally {
  575. handle.setAbort(undefined)
  576. }
  577. if ('error' in stepOutcome) {
  578. // Steering that arrived during the failed step stays in the inbox —
  579. // runLoop re-enqueues it as a queued message, so an abort-then-steer
  580. // starts a fresh turn instead of being silently consumed.
  581. closeStep()
  582. const { error } = stepOutcome
  583. if (handle.isDisposed()) {
  584. reason = { kind: 'disposed' }
  585. } else if (abort.signal.aborted) {
  586. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  587. reason = { kind: 'aborted', reason: String(abort.signal.reason ?? 'aborted') }
  588. } else {
  589. failTurn(error)
  590. }
  591. break
  592. }
  593. // The successful step's finish reason carries forward: a `max-tokens`
  594. // step makes the whole turn end `max-tokens` (the ACP RFC's rule "any
  595. // max-tokens step surfaces as max-tokens"). `stepFinishReason` returns
  596. // `max-tokens` or `undefined`, so a later ordinary step never resets a
  597. // max-tokens turn back to completed, and a never-truncated turn keeps the
  598. // default `completed`. The disposal/abort/error branches above and the
  599. // continuation-window disposal check below override this — they win.
  600. const stepReason = stepFinishReason(stepOutcome.finish)
  601. if (stepReason) reason = stepReason
  602. // Steering that arrived during streaming/tool execution.
  603. const steered = drainSteering(agent, handle.inbox, turn)
  604. if (closeStep()) break
  605. const defaultDecision: ContinuationDecision = { action: stepOutcome.hadToolCalls || steered ? 'continue' : 'stop' }
  606. let decision: ContinuationDecision
  607. try {
  608. decision = await events.waterfall(
  609. 'agent/turn-continuation', turn, defaultDecision,
  610. () => Promise.resolve(defaultDecision),
  611. )
  612. } catch (error: unknown) {
  613. // A broken continuation plugin ends the turn, not the loop.
  614. failTurn(toError(error))
  615. break
  616. }
  617. // A forced `continue` may carry model-facing context: record it as
  618. // next-STEP steering (the steering channel), so the continued turn's next
  619. // iteration drains it before its request — the typed twin of the /goal
  620. // step/end-steer pattern.
  621. if (decision.action === 'continue' && decision.reason) {
  622. handle.inbox.steer({ content: decision.reason.content, source: decision.reason.source })
  623. }
  624. let shouldContinue = decision.action === 'continue'
  625. // Steering from step/end session-event or continuation listeners (the
  626. // /goal pattern) demands the model see it — it overrides a stop decision;
  627. // the next iteration's drain records it.
  628. if (!shouldContinue && handle.inbox.hasSteering) shouldContinue = true
  629. // Terminal policy runs only AFTER the extensible continuation waterfall,
  630. // its optional reason, and late steering have all been folded. Unlike the
  631. // waterfall, this serial seam is monotonic: the first stop bail wins, and
  632. // no later listener or steering override can resurrect the turn.
  633. let terminalStop = false
  634. try {
  635. const stop = await events.strictSerial('agent/turn-stop', turn)
  636. assertContinuationStop(stop)
  637. terminalStop = stop !== undefined
  638. } catch (error: unknown) {
  639. // A broken terminal policy is an ordinary continuation failure: fail
  640. // this turn closed while leaving the driver alive for later turns.
  641. failTurn(toError(error))
  642. break
  643. }
  644. if (terminalStop) {
  645. terminalStopped = true
  646. // A continuation reason or listener may have queued steering before the
  647. // terminal checkpoint. Discard only steering (never ordinary queued
  648. // prompts) so it cannot become a next step or be re-enqueued as a fresh
  649. // turn by runLoop's late-steering fallback.
  650. handle.inbox.drainSteering()
  651. shouldContinue = false
  652. }
  653. // A cancel that landed during the continuation window — after the step's
  654. // AbortController was cleared (setAbort(undefined)) but before the next
  655. // step starts — has no controller to observe it, so the turn-scoped marker
  656. // ends the turn here. cancel() also cleared the steering FIFO, so the
  657. // override above did not re-arm continuation.
  658. if (handle.isCancelled()) {
  659. reason = { kind: 'aborted', reason: handle.cancelReason() }
  660. break
  661. }
  662. if (!shouldContinue || handle.isDisposed()) {
  663. /* v8 ignore next -- disposal during continuation-decision window is a narrow race; error-path disposal is covered elsewhere */
  664. if (handle.isDisposed()) reason = { kind: 'disposed' }
  665. break
  666. }
  667. }
  668. // Normal / inline-error loop exit: close the turn.
  669. closeTurn()
  670. } catch (error: unknown) {
  671. // Decide whether this turn was ever opened from the LOG, not a flag.
  672. // Session.append pushes the event BEFORE notifying session/event listeners,
  673. // so a throwing listener on the `turn/start` append leaves turn/start in the
  674. // log even though execution never reached the lines after that append.
  675. // Gating on a "turn started" boolean would skip turn/end and leave a
  676. // permanently OPEN turn that poisons the next turn/replay (the turn-enclosure RFC). We
  677. // check the log for THIS turn's turn/start: present means a turn/end is owed
  678. // and the normal-exit `closeTurn()` did NOT run (we are here because a throw
  679. // preceded it — the two `closeTurn()` sites are on mutually exclusive paths),
  680. // so this catch appends turn/end with the disposed/error reason chosen below.
  681. // `closeStep()` IS idempotent (guarded by `stepOpen`) — it may have run
  682. // already in a step branch, so running it again is a safe no-op. Absent
  683. // turn/start means the append threw BEFORE its push (a non-serializable
  684. // trigger — impossible for our fixed trigger); nothing was opened, so rethrow
  685. // to the runLoop backstop.
  686. const turnStartLogged = session.events.some(e => e.type === 'turn/start' && e.data.turn === turn)
  687. if (!turnStartLogged) throw error
  688. closeStep()
  689. // Choose the close reason. Disposal wins only if no error was already
  690. // reported: a turn disposed mid-step sets reason=disposed in the step-error
  691. // branch (without reporting an error), so preserve disposed rather than
  692. // overwrite it. Otherwise a mid-step throw on a live agent is a real
  693. // failure → failTurn. (errorReported is mutated only inside the failTurn
  694. // closure, which the analyzer can't follow, hence the inline lint-disable.)
  695. if (handle.isDisposed() && !errorReported) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition
  696. reason = { kind: 'disposed' }
  697. } else {
  698. failTurn(toError(error))
  699. }
  700. closeTurn()
  701. }
  702. // Durability checkpoint: persistence plugins drain write-behind buffers.
  703. // A failing persistence plugin is reported but doesn't kill the agent.
  704. // Through the store's flush (the carrier owner), never a raw parallel.
  705. try {
  706. await ctx.sessions.flush(session)
  707. } catch (error: unknown) {
  708. // The turn is already closed (turn/end appended above) and flush must run
  709. // AFTER turn/end to be a checkpoint — so there is no in-turn position left
  710. // for a session `error` event. Appending one here would land it after the
  711. // last turn/end, where the persistence backend treats it as a crash tail
  712. // and drops it on resume (the turn-enclosure RFC: every event is turn-enclosed). Report
  713. // the failure via agent/error + the logger only; persistence keeps the
  714. // buffered events for the next flush/dispose, so nothing is lost.
  715. const err = toError(error)
  716. ctx.logger.warn(`agent "${agent.id}": session/flush failed at turn ${turn}: ${err.message}`)
  717. try {
  718. events.emit('agent/error', turn, step, err)
  719. } catch {
  720. // contained: a throwing agent/error listener must not escape the loop.
  721. }
  722. }
  723. return terminalStopped
  724. }
  725. /** Drain the steering queue into the session. Returns whether any arrived. */
  726. function drainSteering(agent: ReactLoopAgent, inbox: Inbox, turn: number): boolean {
  727. const messages = inbox.drainSteering()
  728. for (const message of messages) {
  729. agent.session.append('steering/message', { turn, content: message.content, source: message.source }, { surfaceOp: 'append' })
  730. }
  731. return messages.length > 0
  732. }
  733. /** One step: build the request from the boundary snapshot + the step's
  734. * header → compose the session prefix if this instance has none yet → log
  735. * the header event the request owes → stream model → record → execute
  736. * tools. The caller assembles the
  737. * system prompt, fires the `agent/pre-step` seam, snapshots the derivation,
  738. * and opens the step BEFORE calling this, so `boundaryMessages` is exactly
  739. * the surface prefix at step/start and already reflects any compaction. */
  740. async function runStep(
  741. ctx: Context,
  742. events: AgentEventDispatch,
  743. agent: ReactLoopAgent,
  744. turn: number,
  745. step: number,
  746. assembly: PromptAssembly,
  747. system: string,
  748. boundaryMessages: Message[],
  749. transmission: TransmissionLog,
  750. signal: AbortSignal,
  751. ): Promise<{ hadToolCalls: boolean; finish: FinishReason }> {
  752. const { session, options } = agent
  753. // Seed the call config: the first request of THIS loop instance seeds from
  754. // current AgentOptions — explicit options always win over the logged
  755. // baseline, which is what keeps fork model-overrides and resume-time
  756. // reconfiguration correct. Later steps seed from the log's folded header,
  757. // which by then is exactly what this instance last logged.
  758. // One deep-cloned, frozen seed serves BOTH the listener chain and the
  759. // no-listener fallback: structuredClone decouples it from the session's
  760. // cached header fold (a raw reference would let a delegating listener
  761. // mutate the fold in place and silently skip the delta log), and the freeze
  762. // makes in-place shaping unrepresentable — a switch is a RETURNED
  763. // replacement, which the header event below records.
  764. const seedConfig: LlmCallConfig = deepFreeze(structuredClone(transmission.loggedHeader
  765. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- loggedHeader ⟹ a snapshot is in the log
  766. ? session.requestHeader()!.config
  767. : { model: options.model ?? '' }))
  768. // Shape the call config: listeners return a replacement to switch model or
  769. // sampling (the seed is frozen — content shaping is not expressible here;
  770. // model-visible content flows through the log channels). The header event
  771. // below records whatever the request ACTUALLY uses, so a listener's switch
  772. // is a logged, reconstructable fact, never silent drift.
  773. const config = await events.waterfall('agent/request', turn, step, seedConfig, () => Promise.resolve(seedConfig))
  774. if (!config.model) {
  775. throw new Error(`agent "${agent.id}" has no model: set AgentOptions.model or supply one via the agent/request waterfall`)
  776. }
  777. // The session prefix was composed (once per instance) before this step's
  778. // pre-step seam — the caller guarantees it, so the cache is always set here.
  779. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- runTurn composes the prefix before every runStep call
  780. const sessionPrefix = transmission.sessionPrefix!
  781. // The request header (the log's request/header* vocabulary): canonical form,
  782. // recorded before dispatch so the log always explains the request —
  783. // including the session prefix, which no other event carries.
  784. const header = canonicalHeader({
  785. config,
  786. ...system ? { system } : {},
  787. ...assembly.tools.length > 0 ? { tools: assembly.tools } : {},
  788. ...sessionPrefix.length > 0 ? { messagePrefix: sessionPrefix } : {},
  789. })
  790. recordRequestHeader(session, transmission, header)
  791. // Build and freeze: the request is a pure function of (boundary snapshot,
  792. // logged header) — llm/stream listeners and adapters read it, mutation
  793. // throws. sessionId + frozen is the loop-built marker the dev invariant
  794. // keys on. Message order: header.messagePrefix, then the boundary
  795. // snapshot — the reconstruction equation the invariant recomputes.
  796. const request: GenerateOptions = deepFreeze({
  797. model: header.config.model,
  798. messages: [...header.messagePrefix ?? [], ...boundaryMessages],
  799. ...header.system !== undefined ? { system: header.system } : {},
  800. ...header.tools !== undefined ? { tools: header.tools } : {},
  801. ...header.config.temperature !== undefined ? { temperature: header.config.temperature } : {},
  802. ...header.config.maxTokens !== undefined ? { maxTokens: header.config.maxTokens } : {},
  803. ...header.config.stop !== undefined ? { stop: header.config.stop } : {},
  804. sessionId: session.id,
  805. signal,
  806. })
  807. // --- Model call (streaming-first; raw chunks are the replay record) ---
  808. const assembler = new BlockAssembler()
  809. const chunkSeqs: number[] = []
  810. for await (const chunk of ctx.llm.stream(request)) {
  811. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  812. if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted'))
  813. const chunkEvent = session.append('assistant/chunk', { turn, step, chunk })
  814. chunkSeqs.push(chunkEvent.seq)
  815. assembler.push(chunk)
  816. }
  817. // Adapters report provider/transport failures one of two sanctioned ways
  818. // (see the StreamChunk contract in dsh-llm): throw from stream() — already
  819. // handled by the caller's try/catch — OR end the stream with a
  820. // finish-error/aborted chunk. finishError() maps the latter to the step
  821. // error to raise (turn ends error/aborted, not a normal completed message).
  822. const stepError = finishError(assembler.finish)
  823. if (stepError) throw stepError
  824. if (assembler.finish.kind === 'max-tokens') {
  825. let message: Message = withoutToolCalls(assembler.message())
  826. message = withoutToolCalls(await events.waterfall('agent/step-result', turn, step, message, () => Promise.resolve(message)))
  827. // Fire the assistant/message when there is content OR usage: a max-tokens
  828. // step can be cut off with empty content but still carry token accounting,
  829. // and assistant/message is the only host for usage (there is no standalone
  830. // usage event). An empty-content assistant/message is skipped by
  831. // deriveMessages(), so hosting usage on it never injects a spurious assistant
  832. // turn into derived history.
  833. if (message.content.length > 0 || assembler.usage) {
  834. // A max-tokens finish is itself a streamed `finish` chunk, so chunkSeqs is
  835. // never empty here — pass the provenance unconditionally.
  836. session.append(
  837. 'assistant/message',
  838. { turn, step, content: message.content, ...(assembler.usage ? { usage: assembler.usage } : {}) },
  839. { surfaceOp: 'append', sourceEventSeqs: chunkSeqs },
  840. )
  841. }
  842. return { hadToolCalls: false, finish: assembler.finish }
  843. }
  844. // The step-result waterfall runs BEFORE the session append so the log (the
  845. // source of truth for derived history and replay) records the message that
  846. // tool dispatch actually uses.
  847. let message: Message = assembler.message()
  848. message = await events.waterfall('agent/step-result', turn, step, message, () => Promise.resolve(message))
  849. // Same content-or-usage guard as the max-tokens branch: a step that finishes
  850. // with neither assembled content nor usage (e.g. a bare `stop` finish that
  851. // streamed nothing) records no assistant/message — an empty-content message
  852. // exists only to host usage, and deriveMessages() skips it either way, so
  853. // appending one with no usage would be a pure trace-only row.
  854. //
  855. // sourceEventSeqs records the assistant/chunk provenance, but is omitted when
  856. // no chunks streamed (the surface invariant rejects an empty sourceEventSeqs).
  857. if (message.content.length > 0 || assembler.usage) {
  858. session.append(
  859. 'assistant/message',
  860. { turn, step, content: message.content, ...(assembler.usage ? { usage: assembler.usage } : {}) },
  861. { surfaceOp: 'append', ...(chunkSeqs.length > 0 ? { sourceEventSeqs: chunkSeqs } : {}) },
  862. )
  863. }
  864. // --- Tool execution (sequential; parallel execution is a TODO) ---
  865. // ToolRegistry.execute converts tool failures (including aborts) into
  866. // isError results, so abort is re-checked around every call here.
  867. const toolCalls = message.content.filter(block => block.type === 'tool-call')
  868. // Per-step buffer of `additionalContext` attached by tools/post-execute
  869. // listeners. Appended as context/message(s) only AFTER every tool/result for
  870. // the step, so a multi-call step keeps tool-call/result adjacency
  871. // (interleaving context between a call's result and the next call's would
  872. // break the pairing the next model request relies on).
  873. const pendingContext: HookContext[] = []
  874. for (const call of toolCalls) {
  875. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  876. if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted'))
  877. const callEvent = session.append('tool/call', { turn, step, callId: call.id, name: call.name, arguments: call.arguments })
  878. let parsedArguments: unknown
  879. try {
  880. parsedArguments = call.arguments ? JSON.parse(call.arguments) : {}
  881. } catch {
  882. parsedArguments = call.arguments
  883. }
  884. // TODO(pre-tool-input-rewrite): tools/pre-execute deliberately cannot rewrite
  885. // `arguments` — tool/call (the audit record) and assistant/message (the
  886. // model-history source) are logged BEFORE execute, and live consumers (ACP,
  887. // tool-bash presentation) read the pre-execution args, so an execution-only
  888. // rewrite would desync the UI from what ran. Designing that consistently is
  889. // its own proposed RFC (docs/rfc/proposed/feature/…-pre-tool-input-rewrite.md).
  890. const result = await ctx.tools.execute({
  891. callId: call.id,
  892. name: call.name,
  893. arguments: parsedArguments,
  894. agent,
  895. signal,
  896. })
  897. session.append('tool/result', {
  898. turn, step,
  899. // The correlation id MUST be the loop's authoritative call.id (the
  900. // model-transcript id that deriveMessages turns into toolCallId), NOT
  901. // result.callId — a post-execute waterfall listener returning a
  902. // mismatched id would otherwise orphan the call↔result pairing in the
  903. // next model request. A listener-internal id, if ever needed, belongs in
  904. // a separate diagnostic field, never overloaded onto callId.
  905. callId: call.id,
  906. content: result.content,
  907. isError: result.isError,
  908. ...result.error ? { error: result.error } : {},
  909. // The tool's private presentation payload (e.g. a result-time diff),
  910. // persisted so a UI bridge reproduces the card on replay.
  911. ...result.meta !== undefined ? { meta: result.meta } : {},
  912. }, { surfaceOp: 'append', sourceEventSeqs: [callEvent.seq] })
  913. // Buffer (don't append yet) any post-execute additionalContext for this call.
  914. if (result.additionalContext) pendingContext.push(result.additionalContext)
  915. // signal CAN flip during the await above (abort() inside a tool);
  916. // the analyzer can't see through the await boundary.
  917. /* v8 ignore start -- signal.reason default unreachable: cancel()/disposal always set it */
  918. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  919. if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted'))
  920. /* v8 ignore stop */
  921. }
  922. // Append buffered post-execute context AFTER every tool/result, preserving
  923. // tool-call/result adjacency across the whole batch. inject() appends into the
  924. // open turn (a context/message at its chronological position).
  925. for (const context of pendingContext) {
  926. agent.inject(context.content, { source: context.source })
  927. }
  928. return { hadToolCalls: toolCalls.length > 0, finish: assembler.finish }
  929. }
  930. function withoutToolCalls(message: Message): Message {
  931. return { ...message, content: message.content.filter(block => block.type !== 'tool-call') }
  932. }
  933. /**
  934. * The last turn number in a (possibly seeded) session log, or 0.
  935. * @param session - the session whose log is scanned for the latest `turn/start`.
  936. * @returns the latest `turn/start`'s turn number, or 0 when the log has none (the next turn is this plus one).
  937. */
  938. export function lastTurnNumber(session: Session): number {
  939. const lastStart = session.events.findLast(event => event.type === 'turn/start')
  940. return lastStart?.data.turn ?? 0
  941. }
  942. /**
  943. * Whether a turn is currently open in the session log (a `turn/start` with no
  944. * matching later `turn/end`). Decided from the LOG, not agent status: status
  945. * can be `running` while no turn is open (an `agent/status` listener firing
  946. * before `turn/start`, or the post-`turn/end` flush window before status
  947. * returns to idle), so status is not a reliable open-turn signal. Used by
  948. * `inject()` to choose between appending into an open turn vs. wrapping the
  949. * injection in its own one-shot turn (the turn-enclosure RFC).
  950. * @param session - the session whose log is inspected.
  951. * @returns true when the log's last turn boundary is a `turn/start` with no matching `turn/end` yet.
  952. */
  953. export function isTurnOpen(session: Session): boolean {
  954. const last = session.events.findLast(e => e.type === 'turn/start' || e.type === 'turn/end')
  955. return last?.type === 'turn/start'
  956. }