loop.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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, Message } from '@deepseek-ai/dsh-llm'
  11. import { BlockAssembler, HarnessError } from '@deepseek-ai/dsh-llm'
  12. import type { Session, TurnEndReason, TurnTrigger } from '@deepseek-ai/dsh-session'
  13. import { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
  14. import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt'
  15. import type {} from '@deepseek-ai/dsh-tools'
  16. import type { ReactLoopAgent } from './agent.ts'
  17. /** An Error with an optional machine-readable code (e.g., from LlmError or a throwing plugin). */
  18. type CodedError = Error & { code?: string }
  19. /**
  20. * Normalize an arbitrary thrown value into a coded Error. A real Error passes
  21. * through (its `code`, if any, is preserved by {@link errorData}); a non-Error
  22. * throw is wrapped in a {@link HarnessError} with code `UNKNOWN` and the
  23. * original value chained as `cause`, so a bad throw still carries a routable
  24. * code instead of degrading to a bare message.
  25. */
  26. function toError(error: unknown): CodedError {
  27. return error instanceof Error ? error : new HarnessError(String(error), 'UNKNOWN', { cause: error })
  28. }
  29. /**
  30. * Map a model-call {@link FinishReason} to the step error it should raise, or
  31. * `undefined` when the step completed normally.
  32. *
  33. * Adapters report provider/transport failures one of two sanctioned ways (see
  34. * the StreamChunk contract in dsh-llm): throw from `stream()` (handled by the
  35. * caller's try/catch), OR end the stream with a finish-error/aborted chunk
  36. * (the only option for adapters that can't throw mid-stream, e.g.
  37. * library-backed ones). This translates the latter into a thrown step error
  38. * so the turn ends error/aborted (the failure recorded on `turn/end.reason`),
  39. * never as a normal `completed` assistant message.
  40. *
  41. * `FinishReason` is merge-extensible (plugins/adapters can add `kind`s), so
  42. * the switch handles the known terminal-failure kinds and treats every other
  43. * kind — `stop`, `tool-calls`, `max-tokens`, future additions — as success.
  44. */
  45. function finishError(finish: FinishReason): CodedError | undefined {
  46. switch (finish.kind) {
  47. case 'error': {
  48. const error: CodedError = new Error(finish.message)
  49. if (finish.code !== undefined) error.code = finish.code
  50. return error
  51. }
  52. case 'aborted': {
  53. const error: CodedError = new Error('model stream aborted')
  54. error.code = 'ABORTED'
  55. return error
  56. }
  57. // stop / tool-calls / max-tokens / plugin-added kinds → not a failure.
  58. default:
  59. return undefined
  60. }
  61. }
  62. /**
  63. * Build the `{ message, code? }` part of an error payload, omitting the
  64. * `code` key entirely when absent (exactOptionalPropertyTypes-correct).
  65. */
  66. function errorData(err: CodedError): { message: string; code?: string } {
  67. return { message: err.message, ...typeof err.code === 'string' ? { code: err.code } : {} }
  68. }
  69. /**
  70. * The turn-end contribution of a step's *successful* finish, or `undefined`
  71. * when the step finished ordinarily (a plain `completed`).
  72. *
  73. * {@link finishError} has already converted `error`/`aborted` finishes into
  74. * thrown step errors, so the finishes that reach here are `stop`,
  75. * `tool-calls`, `max-tokens`, or a future merge-extensible kind. Only
  76. * `max-tokens` carries forward as a distinct {@link TurnEndReason}: a step that
  77. * hit the output-token ceiling ended the turn cut-short rather than by the
  78. * model's choice. `stop`/`tool-calls`/unknown kinds contribute nothing beyond
  79. * the default `completed`. {@link runTurn} applies this with the rule "any
  80. * `max-tokens` step in the turn makes the turn end `max-tokens`".
  81. */
  82. function stepFinishReason(finish: FinishReason): TurnEndReason | undefined {
  83. switch (finish.kind) {
  84. case 'max-tokens':
  85. return { kind: 'max-tokens' }
  86. // stop / tool-calls / plugin-added kinds → no turn-end contribution
  87. // beyond the default `completed`. FinishReason is merge-extensible, so a
  88. // default (not assertNever) handles unknown kinds as ordinary success.
  89. default:
  90. return undefined
  91. }
  92. }
  93. /**
  94. * Ambient handles the loop driver receives from the agent. Decouples the
  95. * pure function `runLoop` from the mutable ReactLoopAgent fields, making the
  96. * loop testable without a real agent.
  97. */
  98. export interface LoopHandle {
  99. setStatus(status: 'idle' | 'running'): void
  100. setAbort(controller: AbortController | undefined): void
  101. /** Resolves when the agent is disposed — unblocks the idle wait. */
  102. disposed: Promise<void>
  103. isDisposed(): boolean
  104. /**
  105. * Whether a `cancel()` is pending for the current turn. The driver checks this
  106. * at every decision point where a turn could start or continue (right after
  107. * the idle wait, after the `running` flip, before each step, and at the
  108. * continuation gate) and drops the about-to-run / continuing turn. Reset once
  109. * per loop iteration via {@link clearCancel} after the turn returns, so the
  110. * marker governs exactly one cancellation and never leaks to a later prompt.
  111. */
  112. isCancelled(): boolean
  113. /**
  114. * The resolved reason for the pending cancel (`reason ?? 'cancelled'`), read
  115. * by the marker branches (pre-step / continuation) so a turn dropped where no
  116. * `AbortController` carries the reason still records the caller's
  117. * `cancel(reason)` value — matching the mid-step abort path. Only meaningful
  118. * when {@link isCancelled} is true.
  119. */
  120. cancelReason(): string
  121. /** Clear the cancel marker (called once per iteration after the turn returns). */
  122. clearCancel(): void
  123. /**
  124. * Settle pending `whenIdle()` waiters WITHOUT a status transition. Used by the
  125. * pre-step cancel-skip path: it drops the about-to-run turn and re-parks at the
  126. * idle wait, so no `running→idle` transition fires to settle a `whenIdle()`
  127. * waiter that was registered in the pre-step window — this settles it directly
  128. * (it emits no `agent/status`, so an ACP `agent/status` listener never sees a
  129. * spurious idle that would resolve a freshly-queued prompt as cancelled).
  130. */
  131. settleIdle(): void
  132. }
  133. /**
  134. * The agent loop. One invocation drives one agent for its whole lifetime:
  135. *
  136. * ```
  137. * forever:
  138. * wait for queued messages (idle)
  139. * TURN (error-contained — a throwing plugin ends the turn, never the loop):
  140. * drain queued → 'turn/start' → session('user/message'…) → emit agent/turn-start
  141. * STEP loop:
  142. * drain steering → session('steering/message') ⟵ catches late steering
  143. * assembly = ctx.systemPrompt.assemble() ⟵ waterfall system-prompt/assemble
  144. * await ctx.serial('agent/pre-step') ⟵ surface mutation (compaction) OUTSIDE the step
  145. * session('step/start'); emit agent/step-start ⟵ append before emit (the event-sourcing RFC)
  146. * req = {model, system, tools, messages: session.deriveMessages(), signal}
  147. * req = waterfall agent/request ⟵ hooks/model-switch
  148. * stream ctx.llm.stream(req) ⟵ waterfall llm/stream (raw chunks)
  149. * session('assistant/chunk'); emit agent/stream-chunk
  150. * msg = waterfall agent/step-result ⟵ BEFORE the log append, so the
  151. * session('assistant/message' {content, usage?}) session records what actually ran
  152. * each tool-call in msg (sequential, abort-checked):
  153. * session('tool/call'); ctx.tools.execute() ⟵ waterfall tools/execute
  154. * session('tool/result')
  155. * drain steering → session('steering/message'); emit agent/steering
  156. * emit agent/step-end
  157. * cont = waterfall agent/turn-continuation(default = hadToolCalls || steered)
  158. * if !cont && steering arrived from step-end/continuation listeners: cont = true
  159. * if !cont: break
  160. * session('turn/end'); emit agent/turn-end
  161. * await ctx.parallel('session/flush', session) ⟵ durability checkpoint
  162. * re-enqueue leftover steering as queued ⟵ steering is never stranded
  163. * idle (emit agent/status) unless more queued
  164. * ```
  165. */
  166. export async function runLoop(ctx: Context, agent: ReactLoopAgent, handle: LoopHandle): Promise<void> {
  167. const { session } = agent
  168. while (!handle.isDisposed()) {
  169. await agent.inbox.waitForQueued(handle.disposed)
  170. if (handle.isDisposed()) break
  171. // Pre-step cancel (window 1): a `cancel()` landed after a `send()` woke the
  172. // idle wait but before we flip to `running`. The cancelled queued/steering
  173. // work is already cleared by `cancel()`. Clear the marker, then:
  174. // - if NOTHING new is queued, drop the about-to-run turn and re-park,
  175. // settling any `whenIdle()` waiter DIRECTLY (no running→idle transition
  176. // fires here to settle it) and WITHOUT emitting `agent/status` (an ACP
  177. // listener must not see a spurious idle that resolves a freshly-queued
  178. // prompt as cancelled);
  179. // - if a NEW prompt was queued AFTER the cancel (a send() that raced in
  180. // before the loop resumed), the marker was for the cancelled work only —
  181. // fall through and run the new prompt's turn. Do NOT settle waiters here:
  182. // a whenIdle() waiter must wait for that new turn's running→idle, not
  183. // resolve before it runs (the quiescence contract).
  184. if (handle.isCancelled()) {
  185. handle.clearCancel()
  186. if (!agent.inbox.hasQueued) {
  187. handle.settleIdle()
  188. continue
  189. }
  190. }
  191. handle.setStatus('running')
  192. // Pre-step cancel (window 2): `setStatus('running')` emits `agent/status`
  193. // SYNCHRONOUSLY, so a `running` listener can `cancel()` in the gap between the
  194. // check above and `runTurn`. Mirror window 1: clear the marker, then
  195. // - if NOTHING new is queued, drop the about-to-run turn and transition
  196. // back to `idle` (`running` was already emitted, so a real idle
  197. // transition balances the status AND settles `whenIdle()` waiters);
  198. // - if a NEW prompt was queued AFTER the cancel (a `running` listener that
  199. // cancels then sends), the marker was for the cancelled work only — fall
  200. // through and run the new prompt's turn (status is already `running`), so
  201. // a `whenIdle()` waiter resolves on THAT turn's running→idle, not before
  202. // it runs. Settling here would resolve quiescence while the replacement
  203. // is still queued and unrun (the same early-resolve race window 1 fixes).
  204. if (handle.isCancelled()) {
  205. handle.clearCancel()
  206. if (!agent.inbox.hasQueued) {
  207. handle.setStatus('idle')
  208. continue
  209. }
  210. }
  211. // Re-derive the turn number from the log each iteration (do NOT keep a local
  212. // counter): an idle `agent.inject()` can append its own one-shot turn while
  213. // the loop waits above, so the next real turn must continue from whatever
  214. // turn number is actually last in the log — a stale counter would collide.
  215. const turn = lastTurnNumber(session) + 1
  216. try {
  217. await runTurn(ctx, agent, handle, turn)
  218. } catch (error: unknown) {
  219. // Backstop: runTurn rethrows only a PRE-turn throw (the invariant guard
  220. // before turn/start) — no turn/start was appended, so no turn is open and
  221. // none is owed. A session `error` here would land outside any turn (after
  222. // the previous turn/end), where the persistence backend drops it as a
  223. // crash tail (the turn-enclosure RFC). Report via agent/error + the logger only; the
  224. // driver survives and moves on.
  225. const err = toError(error)
  226. ctx.logger.warn(`agent "${agent.id}": turn ${turn} failed before it started: ${err.message}`)
  227. try {
  228. ctx.emit('agent/error', agent, turn, 0, err)
  229. } catch { /* contained: a throwing agent/error listener must not kill the driver */ }
  230. }
  231. // Reset the cancel marker UNCONDITIONALLY here, after the turn returns and
  232. // before the next iteration's idle wait. NOT gated on the idle transition
  233. // below: a `send()` that lands during the cancelled turn's flush window makes
  234. // `hasQueued` true at the `setStatus('idle')` guard, so an idle-gated reset
  235. // would never fire and the stale marker would wrongly drop that next prompt's
  236. // turn. Resetting per iteration scopes the marker to exactly the turn that was
  237. // cancelled.
  238. handle.clearCancel()
  239. // Steering that arrived too late to join this turn (turn-end listeners,
  240. // flush) becomes a queued message — it must never be stranded. (A cancelled
  241. // turn already cleared its steering, so there is nothing to re-enqueue.)
  242. for (const message of agent.inbox.drainSteering()) {
  243. agent.inbox.enqueue(message)
  244. }
  245. if (!agent.inbox.hasQueued) handle.setStatus('idle')
  246. }
  247. }
  248. async function runTurn(ctx: Context, agent: ReactLoopAgent, handle: LoopHandle, turn: number): Promise<void> {
  249. const { session } = agent
  250. // --- Pre-turn. A throw here (the invariant guard) is owed NO turn/end —
  251. // turn/start has not been appended — so it propagates to runLoop's backstop
  252. // untouched. The queued messages are drained here but appended AFTER
  253. // turn/start (below), so every event in the log lives inside a turn.
  254. const queued = agent.inbox.drainQueued()
  255. const first = queued[0]
  256. /* v8 ignore next 3 -- invariant guard: runLoop only calls runTurn when hasQueued */
  257. if (!first) throw new Error('runTurn invariant violated: no queued message at turn start')
  258. const trigger: TurnTrigger = { kind: 'message', source: first.source }
  259. let reason: TurnEndReason = { kind: 'completed' }
  260. let step = 0
  261. let turnEnded = false
  262. let stepOpen = false
  263. let errorReported = false
  264. // Close the open step exactly once (idempotent via stepOpen). The
  265. // agent/step-end emit is contained: a throwing step-end listener must not
  266. // abort finalization and strand the turn open (turn/end balance > notifying
  267. // one bad listener). Appended before the emit (the event-sourcing RFC append-before-emit).
  268. const closeStep = (): boolean => {
  269. if (!stepOpen) return false
  270. stepOpen = false
  271. // Session.append pushes step/end BEFORE notifying session/event listeners,
  272. // so a throwing listener leaves step/end in the log (balance holds) but
  273. // would otherwise abort finalization. Contain it and surface it as a turn
  274. // error below — the same outcome as a throwing agent/step-end listener.
  275. let failure: unknown
  276. try {
  277. session.append('step/end', { turn, step })
  278. } catch (error: unknown) {
  279. failure = error
  280. }
  281. try {
  282. ctx.emit('agent/step-end', agent, turn, step)
  283. } catch (error: unknown) {
  284. failure ??= error
  285. }
  286. // A throwing step/end session-event listener OR a throwing agent/step-end
  287. // listener surfaces as a turn error via failTurn (idempotent). This prevents
  288. // a throwing listener from producing a silent "completed" turn when the step
  289. // itself succeeded, AND keeps finalization going when closeStep runs from
  290. // the outer catch.
  291. if (failure !== undefined) {
  292. failTurn(toError(failure))
  293. return true
  294. }
  295. return false
  296. }
  297. // Record a step/turn failure exactly once: set the error reason (carrying the
  298. // failing `step` — the durable failure lives entirely on turn/end.reason, there
  299. // is no separate session error event) and emit agent/error (contained — trap: a
  300. // throwing agent/error listener must not re-escape and strand the turn).
  301. // Disposal and abort set `reason` directly without calling this (they are not
  302. // failures).
  303. const failTurn = (err: CodedError): void => {
  304. if (errorReported) return
  305. errorReported = true
  306. // Set the error reason ONLY while the turn is still open — closeTurn appends
  307. // turn/end with it. If the turn has already ended (the only way here: a
  308. // throwing agent/turn-end listener after closeTurn(true) already appended
  309. // turn/end), the reason can no longer affect the durable log, so log the late
  310. // throw directly instead — otherwise the listener exception would vanish.
  311. if (!turnEnded) {
  312. reason = { kind: 'error', step, ...errorData(err) }
  313. } else {
  314. ctx.logger.warn(`agent "${agent.id}": agent/turn-end listener threw after turn ${turn} closed: ${err.message}`)
  315. }
  316. try {
  317. ctx.emit('agent/error', agent, turn, step, err)
  318. } catch {
  319. // contained: the error is already captured (on `reason`, or via the logger
  320. // above); a throwing agent/error listener must not prevent the turn from
  321. // closing.
  322. }
  323. }
  324. // Close the turn exactly once (idempotent via turnEnded). `emit` is false on
  325. // the error path (the failure was already surfaced via agent/error) and true
  326. // on the normal/inline-error path. A throwing agent/turn-end listener on the
  327. // normal path escapes to the outer catch, which surfaces it via failTurn —
  328. // turn/end is already appended, so balance holds either way.
  329. const closeTurn = (emit: boolean): void => {
  330. if (turnEnded) return
  331. turnEnded = true
  332. // Session.append pushes turn/end BEFORE notifying session/event listeners,
  333. // so a throwing listener leaves turn/end in the log (the turn is balanced)
  334. // but would otherwise escape — from the outer catch's closeTurn(false) it
  335. // would propagate to the runLoop backstop, and from the normal-path
  336. // closeTurn(true) it would skip the agent/turn-end emit. Contain it: the
  337. // boundary is durable either way, and finalization must not abort on a bad
  338. // listener. (On the normal path the outer catch also re-runs closeTurn,
  339. // which is an idempotent no-op once turnEnded is set.)
  340. try {
  341. session.append('turn/end', { turn, reason })
  342. } catch (error: unknown) {
  343. ctx.logger.warn(`agent "${agent.id}": session/event listener threw on turn/end at turn ${turn}: ${toError(error).message}`)
  344. }
  345. if (emit) ctx.emit('agent/turn-end', agent, turn, reason)
  346. }
  347. try {
  348. // --- Turn boundary. Once turn/start is appended, a turn/end is owed no
  349. // matter what throws below; the catch + closeTurn guarantee it (the catch
  350. // decides "owed" from the log via isTurnOpen, so even a throwing turn/start
  351. // listener — append pushes before notifying — still gets its turn/end).
  352. session.append('turn/start', { turn, trigger })
  353. // Record the queued user messages INSIDE the turn (after turn/start), so
  354. // every event in the log is turn-enclosed. turn/end is now owed, so a throw
  355. // while appending these is caught below and the turn is still closed.
  356. for (const message of queued) {
  357. session.append('user/message', { content: message.content, source: message.source }, { surfaceOp: 'append' })
  358. }
  359. ctx.emit('agent/turn-start', agent, turn)
  360. while (true) {
  361. step += 1
  362. // Steering from the previous round's step-end/continuation listeners
  363. // (or turn-start listeners on the first step) joins before the request.
  364. drainSteering(ctx, agent, turn)
  365. // Assemble the system prompt for this step. Done HERE (before step/start)
  366. // because the pre-step seam needs it: compaction measures token pressure
  367. // against the system prompt (it counts toward the budget) and a listener
  368. // also receives the model to summarize with. runStep reuses this same
  369. // assembly for the request, so the prompt is assembled once per step.
  370. const assembly = await ctx.systemPrompt.assemble()
  371. const system = [renderPrompt(assembly), agent.options.systemPrompt ?? '']
  372. .filter(text => text.length > 0)
  373. .join('\n\n')
  374. // The step's AbortController exists BEFORE the pre-step seam so a cancel()
  375. // during the seam aborts any in-flight work a listener started (e.g. a
  376. // compaction summarization call). Cleared on every exit path below.
  377. const abort = new AbortController()
  378. handle.setAbort(abort)
  379. // Cancel landing before the seam: a synchronous `agent/turn-start` listener
  380. // (or the previous step's continuation listeners) can have called
  381. // `cancel()`. Drop the about-to-start step WITHOUT running the seam — no
  382. // step is open yet, so end the turn `aborted` directly.
  383. if (handle.isCancelled()) {
  384. handle.setAbort(undefined)
  385. reason = { kind: 'aborted', reason: handle.cancelReason() }
  386. break
  387. }
  388. // Pre-step surface-mutation checkpoint (compaction), fired OUTSIDE the
  389. // step: after `turn/start` (and the prior step's close) but before
  390. // `step/start`, so a compaction's log-only `compact/*` records and its
  391. // replacement node land cleanly outside any step (honest structure that
  392. // crash-safety relies on — a dangling `compact/start` sits before the
  393. // synthetic `turn/end` repair appends). Serial (awaited, in order, no
  394. // veto): each listener completes its surface mutation before the next, so
  395. // concurrent listeners cannot interleave their `session.append`s. A
  396. // throwing listener escapes to the outer catch, which closes the (not-yet-
  397. // open) step as a no-op and ends the turn via failTurn — a broken
  398. // pre-step plugin ends the turn, not the loop.
  399. await ctx.serial('agent/pre-step', agent, turn, step, system, agent.options.model ?? '', abort.signal)
  400. session.append('step/start', { turn, step })
  401. stepOpen = true
  402. ctx.emit('agent/step-start', agent, turn, step)
  403. // Cancel landing in the seam / step-start window: a `cancel()` during the
  404. // pre-step seam (it aborted `abort.signal` above) OR a synchronous
  405. // `agent/step-start` listener that cancels. Check AFTER setAbort/step-start
  406. // and before `runStep`: drop the step, end the turn `aborted`. closeStep
  407. // balances the already-appended step/start.
  408. if (handle.isCancelled()) {
  409. handle.setAbort(undefined)
  410. reason = { kind: 'aborted', reason: handle.cancelReason() }
  411. closeStep()
  412. break
  413. }
  414. let stepOutcome: { hadToolCalls: boolean; finish: FinishReason } | { error: Error }
  415. try {
  416. stepOutcome = await runStep(ctx, agent, turn, step, assembly, system, abort.signal)
  417. } catch (error: unknown) {
  418. stepOutcome = { error: toError(error) }
  419. } finally {
  420. handle.setAbort(undefined)
  421. }
  422. if ('error' in stepOutcome) {
  423. // Steering that arrived during the failed step stays in the inbox —
  424. // runLoop re-enqueues it as a queued message, so an abort-then-steer
  425. // starts a fresh turn instead of being silently consumed.
  426. closeStep()
  427. const { error } = stepOutcome
  428. if (handle.isDisposed()) {
  429. reason = { kind: 'disposed' }
  430. } else if (abort.signal.aborted) {
  431. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  432. reason = { kind: 'aborted', reason: String(abort.signal.reason ?? 'aborted') }
  433. } else {
  434. failTurn(error)
  435. }
  436. break
  437. }
  438. // The successful step's finish reason carries forward: a `max-tokens`
  439. // step makes the whole turn end `max-tokens` (the ACP RFC's rule "any
  440. // max-tokens step surfaces as max-tokens"). `stepFinishReason` returns
  441. // `max-tokens` or `undefined`, so a later ordinary step never resets a
  442. // max-tokens turn back to completed, and a never-truncated turn keeps the
  443. // default `completed`. The disposal/abort/error branches above and the
  444. // continuation-window disposal check below override this — they win.
  445. const stepReason = stepFinishReason(stepOutcome.finish)
  446. if (stepReason) reason = stepReason
  447. // Steering that arrived during streaming/tool execution.
  448. const steered = drainSteering(ctx, agent, turn)
  449. if (closeStep()) break
  450. const defaultDecision = stepOutcome.hadToolCalls || steered
  451. let shouldContinue: boolean
  452. try {
  453. shouldContinue = await ctx.waterfall(
  454. 'agent/turn-continuation', agent, turn, defaultDecision,
  455. () => Promise.resolve(defaultDecision),
  456. )
  457. } catch (error: unknown) {
  458. // A broken continuation plugin ends the turn, not the loop.
  459. failTurn(toError(error))
  460. break
  461. }
  462. // Steering from step-end/continuation listeners (the /goal pattern)
  463. // demands the model see it — it overrides a negative decision; the
  464. // next iteration's drain records it.
  465. if (!shouldContinue && agent.inbox.hasSteering) shouldContinue = true
  466. // A cancel that landed during the continuation window — after the step's
  467. // AbortController was cleared (setAbort(undefined)) but before the next
  468. // step starts — has no controller to observe it, so the turn-scoped marker
  469. // ends the turn here. cancel() also cleared the steering FIFO, so the
  470. // override above did not re-arm continuation.
  471. if (handle.isCancelled()) {
  472. reason = { kind: 'aborted', reason: handle.cancelReason() }
  473. break
  474. }
  475. if (!shouldContinue || handle.isDisposed()) {
  476. /* v8 ignore next -- disposal during continuation-decision window is a narrow race; error-path disposal is covered elsewhere */
  477. if (handle.isDisposed()) reason = { kind: 'disposed' }
  478. break
  479. }
  480. }
  481. // Normal / inline-error loop exit: close the turn and notify.
  482. closeTurn(true)
  483. } catch (error: unknown) {
  484. // Decide whether this turn was ever opened from the LOG, not a flag.
  485. // Session.append pushes the event BEFORE notifying session/event listeners,
  486. // so a throwing listener on the `turn/start` append leaves turn/start in the
  487. // log even though execution never reached the lines after that append.
  488. // Gating on a "turn started" boolean would skip turn/end and leave a
  489. // permanently OPEN turn that poisons the next turn/replay (the turn-enclosure RFC). We
  490. // check the log for THIS turn's turn/start: present means a turn/end is owed
  491. // (or was already appended — closeTurn/failTurn are idempotent, so running
  492. // them again is a safe no-op that still preserves the disposed/error reason
  493. // chosen below). Absent means the turn/start append threw BEFORE its push (a
  494. // non-serializable trigger — impossible for our fixed trigger); nothing was
  495. // opened, so rethrow to the runLoop backstop.
  496. const turnStartLogged = session.events.some(e => e.type === 'turn/start' && e.data.turn === turn)
  497. if (!turnStartLogged) throw error
  498. closeStep()
  499. // Choose the close reason. Disposal wins only if no error was already
  500. // reported: a turn disposed mid-step sets reason=disposed in the step-error
  501. // branch (without reporting an error), and if closeTurn(true)'s turn-end
  502. // emit then throws, we land here and must PRESERVE disposed rather than
  503. // overwrite it with the listener's throw. Otherwise a boundary-emit throw
  504. // on a live agent is a real failure → failTurn. (errorReported is mutated
  505. // only inside the failTurn closure, which the analyzer can't follow, hence
  506. // the inline lint-disable.)
  507. if (handle.isDisposed() && !errorReported) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition
  508. reason = { kind: 'disposed' }
  509. } else {
  510. failTurn(toError(error))
  511. }
  512. closeTurn(false)
  513. }
  514. // Durability checkpoint: persistence plugins drain write-behind buffers.
  515. // A failing persistence plugin is reported but doesn't kill the agent.
  516. try {
  517. await ctx.parallel('session/flush', session)
  518. } catch (error: unknown) {
  519. // The turn is already closed (turn/end appended above) and flush must run
  520. // AFTER turn/end to be a checkpoint — so there is no in-turn position left
  521. // for a session `error` event. Appending one here would land it after the
  522. // last turn/end, where the persistence backend treats it as a crash tail
  523. // and drops it on resume (the turn-enclosure RFC: every event is turn-enclosed). Report
  524. // the failure via agent/error + the logger only; persistence keeps the
  525. // buffered events for the next flush/dispose, so nothing is lost.
  526. const err = toError(error)
  527. ctx.logger.warn(`agent "${agent.id}": session/flush failed at turn ${turn}: ${err.message}`)
  528. try {
  529. ctx.emit('agent/error', agent, turn, step, err)
  530. } catch {
  531. // contained: a throwing agent/error listener must not escape the loop.
  532. }
  533. }
  534. }
  535. /** Drain the steering queue into the session. Returns whether any arrived. */
  536. function drainSteering(ctx: Context, agent: ReactLoopAgent, turn: number): boolean {
  537. const messages = agent.inbox.drainSteering()
  538. for (const message of messages) {
  539. agent.session.append('steering/message', { turn, content: message.content, source: message.source }, { surfaceOp: 'append' })
  540. ctx.emit('agent/steering', agent, turn, message.content, message.source)
  541. }
  542. return messages.length > 0
  543. }
  544. /** One step: derive request from the (already pre-step-mutated) surface →
  545. * stream model → record → execute tools. The caller assembles the system prompt
  546. * and fires the `agent/pre-step` seam BEFORE opening the step, then passes the
  547. * resulting `assembly`/`system` here, so the surface this step derives from
  548. * already reflects any compaction. */
  549. async function runStep(
  550. ctx: Context,
  551. agent: ReactLoopAgent,
  552. turn: number,
  553. step: number,
  554. assembly: PromptAssembly,
  555. system: string,
  556. signal: AbortSignal,
  557. ): Promise<{ hadToolCalls: boolean; finish: FinishReason }> {
  558. const { session, options } = agent
  559. let request: GenerateOptions = {
  560. model: options.model ?? '',
  561. messages: session.deriveMessages(),
  562. ...system ? { system } : {},
  563. ...assembly.tools.length > 0 ? { tools: assembly.tools } : {},
  564. sessionId: session.id,
  565. signal,
  566. }
  567. request = await ctx.waterfall('agent/request', agent, turn, step, request, () => Promise.resolve(request))
  568. if (!request.model) {
  569. throw new Error(`agent "${agent.id}" has no model: set AgentOptions.model or supply one via the agent/request waterfall`)
  570. }
  571. // --- Model call (streaming-first; raw chunks are the replay record) ---
  572. const assembler = new BlockAssembler()
  573. const chunkSeqs: number[] = []
  574. for await (const chunk of ctx.llm.stream(request)) {
  575. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  576. if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted'))
  577. const chunkEvent = session.append('assistant/chunk', { turn, step, chunk })
  578. chunkSeqs.push(chunkEvent.seq)
  579. ctx.emit('agent/stream-chunk', agent, turn, step, chunk)
  580. assembler.push(chunk)
  581. }
  582. // Adapters report provider/transport failures one of two sanctioned ways
  583. // (see the StreamChunk contract in dsh-llm): throw from stream() — already
  584. // handled by the caller's try/catch — OR end the stream with a
  585. // finish-error/aborted chunk. finishError() maps the latter to the step
  586. // error to raise (turn ends error/aborted, not a normal completed message).
  587. const stepError = finishError(assembler.finish)
  588. if (stepError) throw stepError
  589. if (assembler.finish.kind === 'max-tokens') {
  590. let message: Message = withoutToolCalls(assembler.message())
  591. message = withoutToolCalls(await ctx.waterfall('agent/step-result', agent, turn, step, message, () => Promise.resolve(message)))
  592. // Fire the assistant/message when there is content OR usage: a max-tokens
  593. // step can be cut off with empty content but still carry token accounting,
  594. // and assistant/message is the only host for usage (there is no standalone
  595. // usage event). An empty-content assistant/message is skipped by
  596. // deriveMessages(), so hosting usage on it never injects a spurious assistant
  597. // turn into derived history.
  598. if (message.content.length > 0 || assembler.usage) {
  599. // A max-tokens finish is itself a streamed `finish` chunk, so chunkSeqs is
  600. // never empty here — pass the provenance unconditionally.
  601. session.append(
  602. 'assistant/message',
  603. { turn, step, content: message.content, ...(assembler.usage ? { usage: assembler.usage } : {}) },
  604. { surfaceOp: 'append', sourceEventSeqs: chunkSeqs },
  605. )
  606. }
  607. return { hadToolCalls: false, finish: assembler.finish }
  608. }
  609. // The step-result waterfall runs BEFORE the session append so the log (the
  610. // source of truth for derived history and replay) records the message that
  611. // tool dispatch actually uses.
  612. let message: Message = assembler.message()
  613. message = await ctx.waterfall('agent/step-result', agent, turn, step, message, () => Promise.resolve(message))
  614. // Same content-or-usage guard as the max-tokens branch: a step that finishes
  615. // with neither assembled content nor usage (e.g. a bare `stop` finish that
  616. // streamed nothing) records no assistant/message — an empty-content message
  617. // exists only to host usage, and deriveMessages() skips it either way, so
  618. // appending one with no usage would be a pure trace-only row.
  619. //
  620. // sourceEventSeqs records the assistant/chunk provenance, but is omitted when
  621. // no chunks streamed (the surface invariant rejects an empty sourceEventSeqs).
  622. if (message.content.length > 0 || assembler.usage) {
  623. session.append(
  624. 'assistant/message',
  625. { turn, step, content: message.content, ...(assembler.usage ? { usage: assembler.usage } : {}) },
  626. { surfaceOp: 'append', ...(chunkSeqs.length > 0 ? { sourceEventSeqs: chunkSeqs } : {}) },
  627. )
  628. }
  629. // --- Tool execution (sequential; parallel execution is a TODO) ---
  630. // ToolRegistry.execute converts tool failures (including aborts) into
  631. // isError results, so abort is re-checked around every call here.
  632. const toolCalls = message.content.filter(block => block.type === 'tool-call')
  633. for (const call of toolCalls) {
  634. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  635. if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted'))
  636. const callEvent = session.append('tool/call', { turn, step, callId: call.id, name: call.name, arguments: call.arguments })
  637. let parsedArguments: unknown
  638. try {
  639. parsedArguments = call.arguments ? JSON.parse(call.arguments) : {}
  640. } catch {
  641. parsedArguments = call.arguments
  642. }
  643. const result = await ctx.tools.execute({
  644. callId: call.id,
  645. name: call.name,
  646. arguments: parsedArguments,
  647. agent,
  648. signal,
  649. })
  650. session.append('tool/result', {
  651. turn, step,
  652. // The correlation id MUST be the loop's authoritative call.id (the
  653. // model-transcript id that deriveMessages turns into toolCallId), NOT
  654. // result.callId — a tools/execute waterfall listener returning a
  655. // mismatched id would otherwise orphan the call↔result pairing in the
  656. // next model request. A listener-internal id, if ever needed, belongs in
  657. // a separate diagnostic field, never overloaded onto callId.
  658. callId: call.id,
  659. content: result.content,
  660. isError: result.isError,
  661. ...result.error ? { error: result.error } : {},
  662. }, { surfaceOp: 'append', sourceEventSeqs: [callEvent.seq] })
  663. // signal CAN flip during the await above (abort() inside a tool);
  664. // the analyzer can't see through the await boundary.
  665. /* v8 ignore start -- signal.reason default unreachable: cancel()/disposal always set it */
  666. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  667. if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted'))
  668. /* v8 ignore stop */
  669. }
  670. return { hadToolCalls: toolCalls.length > 0, finish: assembler.finish }
  671. }
  672. function withoutToolCalls(message: Message): Message {
  673. return { ...message, content: message.content.filter(block => block.type !== 'tool-call') }
  674. }
  675. /** The last turn number in a (possibly seeded) session log, or 0. */
  676. export function lastTurnNumber(session: Session): number {
  677. const lastStart = session.events.findLast(event => event.type === 'turn/start')
  678. return lastStart?.data.turn ?? 0
  679. }
  680. /**
  681. * Whether a turn is currently open in the session log (a `turn/start` with no
  682. * matching later `turn/end`). Decided from the LOG, not agent status: status
  683. * can be `running` while no turn is open (an `agent/status` listener firing
  684. * before `turn/start`, or the post-`turn/end` flush window before status
  685. * returns to idle), so status is not a reliable open-turn signal. Used by
  686. * `inject()` to choose between appending into an open turn vs. wrapping the
  687. * injection in its own one-shot turn (the turn-enclosure RFC).
  688. */
  689. export function isTurnOpen(session: Session): boolean {
  690. const last = session.events.findLast(e => e.type === 'turn/start' || e.type === 'turn/end')
  691. return last?.type === 'turn/start'
  692. }