loop.ts 47 KB

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