loop.ts 49 KB

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