import type { Session, Message, MessageContent, ModelContent, Usage, UsageSite, ProviderMeta, TruncatedToolResult, TurnEvent, RunConfig, ProviderAdapter, ProviderConfig, Tool, ToolRegistry, ToolContext, Store, FileStore, MediaStore, SystemContextRegistry, Vault, PromptFn, PermissionGate, FailureClass, } from './types.js'; import type { MatbotPlugin } from './plugin.js'; import type { ToolPresenter, SessionAppender, TurnToolSource } from '@matatbread/matbot-plugin-api'; import { recordSpan, recordUsage, withUsageSite, scopeIterable, callFrame, callFramesOf } from '@matatbread/matbot-plugin-api/host'; import { HookRegistry } from './hooks.js'; import { appendMessage, createMessage } from './session.js'; import { foldOntoUserTurn, bindPluginOps, bindGate, defaultingPrompt, failureOf, isRoboSubmit, withSenderShown } from '@matatbread/matbot-plugin-api'; import { addUsage } from './usage.js'; import { MEDIA_RESIDENCY_BYTES, resolveSessionMedia, withAttachmentsShown } from './media.js'; // Establish a usage call site across an async iteration. Wrapping the *loop* would not work: this // runner is itself an async generator, so it suspends at every `yield` and resumes under the consumer's // context, losing any scope entered around the loop body. Scoping each `next()` instead means the // tool's body — and anything it kicks off while running — always resumes under its own site. // // `scopeIterable` is the per-pull wrap `runAs` also uses for the principal. It wraps the iterator rather // than replacing it, so a class-based tool iterator keeps its own members, prototype and `instanceof`. const siteScoped = (site: UsageSite, src: AsyncIterable): AsyncIterable => scopeIterable(src, f => withUsageSite(site, f)); // Creator of the marker recording that a provider cut a response short. Marker-role, so it is durable // and visible to a reader while elided from every submission: the model's own text is already truncated // in the transcript, and a block telling it so invites narrating the cut-off rather than continuing. export const TRUNCATION_CREATOR = 'matbot-truncation'; /** An AbortSignal's reason as a turn-terminal string. `reason` is `any` by spec (a caller may abort with * anything), so the two abort exits both had to narrow it; they narrowed it identically. */ const abortReason = (signal: AbortSignal): string => typeof signal.reason === 'string' ? signal.reason : 'user-abort'; /** * A thrown value as a turn-terminal message, with its `cause` appended when it has one. * * A `throw` carries anything, so this narrows before reaching for `cause`: `'cause' in e` throws * TypeError on a primitive, which made the catch handler ITSELF throw for a provider that rejected * with a string — escaping the generator and skipping the `end()` commit that the branch calling this * exists to perform. The one place in this package that took `any` rather than narrow. */ // The cause rides along because it is usually the useful half: `TypeError: fetch failed` says nothing, // `SocketError: other side closed` says what. A cause that is not an Error is shown as data. export const errorText = (e: unknown): string => { const cause = typeof e === 'object' && e !== null && 'cause' in e ? (e as { cause?: unknown }).cause : undefined; if (!cause) return String(e); const why = cause instanceof Error || typeof cause !== 'object' ? String(cause) : safeJson(cause); return `${String(e)} (${why})`; }; const safeJson = (v: unknown): string => { try { return JSON.stringify(v); } catch { return String(v); } }; // A failure's class in words, for a reader that gets only the text — a model that delegated the work. It // says what happened and leaves the decision to that reader; unclassified is said too, since silence would // read as "nothing to add" rather than "nobody said". export function withFailureNote(text: string, failure: FailureClass | undefined): string { switch (failure) { case 'unavailable': return `${text} [temporary: the same request may work if tried again later]`; case 'denied': return `${text} [refused: trying again will not change this]`; case 'invalid': return `${text} [the request itself is wrong: trying it again unchanged will not help]`; case undefined: return `${text} [not classified: nothing said whether trying again could help]`; default: return text; } } /** How long a tool executor may keep the turn alive AFTER the turn was aborted, before the runner stops * reading it. An abort must abort: any executor can fail to end — a child process whose stdout was * inherited by an orphan, a generator awaiting something that never settles, a bridged remote that went * away — and the runner awaiting it is then the only thing holding a turn that nothing left in the * process can end. Abandoning is bounded rather than immediate because a well-behaved tool cleaning up * after a cut-off (flushing a partial result, closing a handle) is the common case and worth waiting for. * Only armed once `signal` is aborted, so a long-running tool on a healthy turn is never cut short. */ const ABANDONED_TOOL_GRACE_MS = 30_000; /** Resolves `ABANDON` once the signal has been aborted for `ms`, and never otherwise. */ const ABANDON = Symbol('abandon'); function abandonDeadline(signal: AbortSignal, ms: number): { wait: Promise; dispose: () => void } { let timer: ReturnType | undefined; let arm: (() => void) | undefined; const wait = new Promise(resolve => { arm = () => { timer = setTimeout(() => resolve(ABANDON), ms); }; if (signal.aborted) arm(); else signal.addEventListener('abort', arm, { once: true }); }); return { wait, dispose: () => { if (timer !== undefined) clearTimeout(timer); if (arm !== undefined) signal.removeEventListener('abort', arm); }, }; } // Substituted for an errored tool result when the turn was aborted (e.g. a mid-turn steer interrupt): // the tool was cut off, not genuinely faulty, and the raw abort reason ("Error: steer") is a leaked // internal token that reads as a real failure. A steer's continuation turn is the one place a model // reads this, so the wording tells it the call was interrupted and leaves re-running to its judgement — // deliberately NOT "re-run it", so a side-effecting tool isn't reflexively repeated. const INTERRUPTED_TOOL_RESULT = { error: 'Tool call interrupted before completion — the turn was interrupted while it was running. It may not have run to completion, and any side effect may or may not have occurred. Re-run it only if you still need its result.', } as const; /** * The turn tools `screen` offered (see {@link TurnToolSource}), as they stand for this round. Asked every * round because the turn itself changes the session they are derived from. A name the registry (or the * turn-start snapshot) already holds is dropped: the registered tool keeps it, since shadowing one is a * gated decision and a hook must not be a way round it. `warned` keeps that to one line per name a turn. * A source that throws is skipped, like a throwing hook — it must not take the turn down with it. */ async function resolveTurnTools( sources: readonly TurnToolSource[], session: Session, taken: (name: string) => boolean, warned: Set, ): Promise> { const out = new Map(); for (const source of sources) { let offered: readonly Tool[]; try { offered = await source(session); } catch (e) { console.warn(`[runner] a turn tool source failed: ${e instanceof Error ? e.message : String(e)}`); continue; } for (const tool of offered) { if (taken(tool.name)) { if (!warned.has(tool.name)) { warned.add(tool.name); console.warn(`[runner] turn tool "${tool.name}" dropped: a registered tool has that name.`); } continue; } if (!out.has(tool.name)) out.set(tool.name, tool); } } return out; } export interface RunSessionOpts { session: Session; config: RunConfig; provider: ProviderAdapter; providerConfig: ProviderConfig; tools?: ReadonlyMap; /** * Live registry consulted to *resolve the executor* at call time. The `tools` map above is a * turn-start snapshot — the stable menu advertised to the model for the whole turn — but a tool * that mutates the registry mid-turn (`plugin reload`/`add`/`remove`) must take effect for any * call later in the *same* turn, so execution resolves against this live registry rather than the * snapshot. Present ⇒ authoritative (a tool removed mid-turn resolves to null ⇒ "Unknown tool", * which is correct); absent ⇒ falls back to the snapshot (direct callers / tests that pass only * `tools`). */ toolRegistry?: ToolRegistry; /** * Optional presenter that picks which tools are advertised to the model on each provider call — a * read-only view over the `tools` snapshot (e.g. deferring a large library behind a search tool and * revealing matches mid-turn). Consulted *per provider call* so a reveal takes effect on the next * loop iteration; absent ⇒ the whole snapshot is advertised (unchanged behaviour). Presentation never * affects execution — a withheld tool still resolves by name through `toolRegistry`. */ toolPresenter?: ToolPresenter; store: Store; hooks?: HookRegistry; systemContext?: SystemContextRegistry; signal: AbortSignal; vault?: Vault; workdir?: string; files?: FileStore; /** Handed to tools as `ToolContext.appender`: set only by a runner whose sessions the machine's own * appender cannot reach (an ephemeral one). */ appender?: SessionAppender; /** Where user-attached session media lives. Resolved once per turn into the outgoing copy, newest-first * and inside {@link MEDIA_RESIDENCY_BYTES}; absent ⇒ every `file-ref` stays a ref and the converters * degrade it. Never read for anything else — the runner does not otherwise touch a file. */ mediaStore?: MediaStore; /** Supply a prompt implementation to allow tools to ask interactive questions. */ prompt?: PromptFn; /** The installation's permission policy, consulted by `ctx.gate` at every privileged tool call site. * The host passes its live `services.PermissionGate` (a capture-safe proxy, so a policy plugin * registered mid-session takes effect); absent — a direct `runSession` caller or a test — the * asking default stands in, which is the same behaviour the host boots with. */ permissionGate?: PermissionGate; /** * Turn-scoped context to inject ephemerally, exactly like a `screen` hook's `ephemeral` (tail-folded * onto the freshest non-marker message, never persisted) — merged ahead of whatever `screen` adds. * The pump supplies this for an agent-phase retract-redo: the trigger tool's output rides into the * re-run of the originating user turn. Empty/absent for an ordinary turn. */ injectedEphemeral?: MessageContent[]; /** * Consulted at the top of every round — the one point in a turn where the history is protocol-whole: * every `tool_use` so far is answered, and no provider call is in flight. Returns the session with * messages from outside the turn placed into it (the pump's parallel replies), and the traceIds to * announce as `merged`; `undefined` ⇒ nothing arrived. Where they go is the caller's decision. */ interject?: (session: Session) => { session: Session; merged: string[] } | undefined; loadPlugin: (specifier: string, prompt?: PromptFn, refresh?: boolean) => Promise; unloadPlugin: (specifier: string) => Promise; } // Yields TurnEvent, not PipelineEvent: a single turn never produces the session-level `idle` — that is // the pump's, emitted once its queue drains. Saying so in the type is the point of the two-union split. export async function* runSession(opts: RunSessionOpts): AsyncIterable { const { config, provider, providerConfig, store, signal } = opts; const tools = opts.tools ?? new Map(); const hookReg = opts.hooks ?? new HookRegistry(); // The stand-in answers with a field's own default where it has one — which is precisely why the gate // below is handed `opts.prompt` raw instead (see bindGate). const promptFn: PromptFn = opts.prompt ?? defaultingPrompt; const vault: Vault = opts.vault ?? { async createSecret() { throw new Error('No vault configured'); }, async writeSecret() { throw new Error('No vault configured'); }, hasKey() { return false; }, async readSecret() { return undefined; }, async resolve(ref: string) { return ref; }, scrub(text: string) { return text; }, }; const traceId = config.traceId ?? crypto.randomUUID(); let session = opts.session; // Every way a turn can end funnels through here: commit the session as it stands, then yield exactly // one terminal event. Each exit has its own legitimately different preamble — screen markers, a // streamed assistant partial, closing an unpaired tool_use — but the terminal itself must not vary, // and twice it had not: both the `toolcall`-abort and failed-provider-call exits returned with no // commit at all, silently discarding every completed round of the turn. // Nothing is written mid-turn, so "commit" here means the whole turn or none of it. // Closes over the reassigned `session` deliberately, so no exit can commit a stale copy. async function* end(terminal: TurnEvent): AsyncIterable { // One last pull, because this is the funnel every exit passes through. A parallel reply that settled // since the previous round boundary may already be in the store (the session runner places one as it // settles, so a turn parked in a long tool call does not hide it) — and the write below is the whole // document, so a reply this turn never took would be erased by it. Reachable: a turn aborted or // thrown during that same tool call never reaches another round top. const late = opts.interject?.(session); if (late !== undefined) session = late.session; await store.set(session.id, session); if (late !== undefined) for (const from of late.merged) yield { type: 'merged', traceId: from, into: traceId }; yield terminal; } // ── 1. screen — once per turn: shape/abort the incoming submission ────────── const screen = await hookReg.runScreen({ session, config, signal, prompt: promptFn }); session = screen.session; if (screen.abort) { // Hook-failure (and any other screen-injected) markers carried live, even on abort, so a // misconfigured hook surfaces this turn rather than only on a later reload. if (screen.markers.length > 0) yield { type: 'marker', content: screen.markers, traceId }; yield* end({ type: 'aborted', reason: screen.abort, session, traceId }); return; } // Durable context a screen hook folded onto the user message (e.g. a fired `contextual` trigger), // carried live so a frontend draws it now rather than only on a later reload. It is already part of // screen.session (origin: 'robo' blocks on the user turn) — this event is purely live delivery. // Emitted BEFORE the markers so the live order matches a reload: the durable blocks belong to the // user message (rendered with the turn), while screen markers were appended to the session AFTER it. if (screen.durable.length > 0) { yield { type: 'robo-user', content: screen.durable, traceId }; } // Hook-failure (and any other screen-injected) markers, carried live so the UI shows them this turn // rather than only on a later session reload. They are already persisted in screen.session. if (screen.markers.length > 0) { yield { type: 'marker', content: screen.markers, traceId }; } // Turn-scoped ephemeral context from screen — appended to the TAIL of the outgoing messages // (onto the content of the freshest history message, preserving its role), never persisted. // At the tail, not as a system prefix, because (a) a "do X now" directive needs the salience of // being the last thing the model reads — a system-block prefix sits above the whole history and // reads as stale once the turn has any momentum — and (b) per-turn content in the prefix would // bust the cached system/history prefix every turn; appended at the tail it leaves the prefix // byte-stable. Folding into the last message (rather than adding a trailing message) avoids // role-alternation hazards and survives both adapters (Anthropic folds system→system=; OpenAI // drops non-result content from tool-role messages — a separate trailing message would break on // one or the other). // injectedEphemeral (a pump-supplied retract-redo's context) leads, then screen's own — both share // the identical tail-fold path below. Mutable: a raced screen verdict (below) folds its correction // in here when it fires, and the loop re-runs with it. let ephemeral = [...(opts.injectedEphemeral ?? []), ...screen.ephemeral]; // Raced screen verdicts (see DeferredScreen): claimed — synchronously, never awaited — at each of the // three loop edges (before generating, mid-stream, and pre-commit). Claiming is one step, so the three // sites cannot disagree about it: take every verdict that has fired since the last claim (exactly once // each), fold `ephemeral` in ahead of what is already queued so the re-run reads it, fold `durable` // onto the user turn (persisted — the re-run and every later turn see it in history), and carry that // durable half live as a `robo-user`, which is what preserves a contextual fire's visible persistence // even though the verdict landed mid-turn. // // Returns whether anything was claimed. What the caller does with that is the part that legitimately // differs — proceed, abort the in-flight provider call, or re-run the loop — so it stays at the site. const deferred = screen.deferred; // Re-resolved at the top of every round (below), so a tool defined in one round is callable in the next. const turnToolSources = screen.tools; const turnToolWarned = new Set(); let turnTools = new Map(); async function* claimVerdicts(): AsyncGenerator { if (deferred.length === 0) return false; const ephemeralC: MessageContent[] = []; const durableC: MessageContent[] = []; for (const d of deferred) { const c = d.claim(); if (!c) continue; if (c.ephemeral) ephemeralC.push(...c.ephemeral); if (c.durable) durableC.push(...c.durable); } if (ephemeralC.length === 0 && durableC.length === 0) return false; if (ephemeralC.length > 0) ephemeral = [...ephemeralC, ...ephemeral]; if (durableC.length > 0) { const folded = foldOntoUserTurn(session, durableC); // Identity-unchanged ⇒ no user message to attach to, so the blocks were dropped: nothing durable // landed, hence nothing to carry live either. if (folded !== session) { session = folded; yield { type: 'robo-user', content: durableC, traceId }; } } return true; } // ── 2. System context (built once per submit, never persisted) ───────────── const systemText = opts.systemContext ? await opts.systemContext.build({ session, signal }) : null; const systemMsg = systemText !== null ? [createMessage({ role: 'system', content: [{ type: 'text', text: systemText }], traceId: '' })] : []; if (systemText !== null) { yield { type: 'system-context', text: systemText, traceId }; } // ── 3. Agentic loop ──────────────────────────────────────────────────────── // Rounds already run against this provider, where a round is one provider call plus the tool batch it // asked for. Compared against the provider profile's own `maxRounds` — a spend ceiling denominated in // the unit spend varies by. Absent ⇒ unbounded (`?? Infinity`), the historical behaviour. let round = 0; // Tool-supplied media, keyed by the tool message it answers — see the `model-content` ToolEvent. // Turn-scoped and wire-only: it is spliced into the outgoing copy below and dies with this call. const attachments = new Map(); // User-attached media, keyed by the message whose `file-ref` blocks it replaces. The mirror of // `attachments` — same splice, different source and different placement: tool media is *pinned after* // the tool message it answers, session media is swapped *in place*, so the model reads the image where // the person actually put it. Resolved once here, not per round: the bytes cannot change mid-turn, and // re-deciding each round could drop a message out of the byte budget between two calls — busting the // prompt cache and leaving the model referring to something no longer there. const sessionMedia = await resolveSessionMedia(session.messages, opts.mediaStore, MEDIA_RESIDENCY_BYTES, signal); for (;;) { // Respect an abort that arrived between turns (e.g. during tool execution). if (signal.aborted) { yield* end({ type: 'aborted', reason: abortReason(signal), session, traceId }); return; } // Checked HERE — before starting a round, not part-way through one — so the previous round's tool // results are already appended and there is nothing to reconcile: the same persist-and-yield as the // abort above. A turn stopped by the ceiling was cut short, not faulty, so it ends `aborted` rather // than `error`, and the reason is machine-readable for a frontend that wants to say why. if (round >= (providerConfig.maxRounds ?? Infinity)) { const reason = `round-limit: provider "${config.provider}" allows ${providerConfig.maxRounds} rounds per turn`; yield* end({ type: 'aborted', reason, session, traceId }); return; } round += 1; const interjected = opts.interject?.(session); if (interjected !== undefined) { session = interjected.session; for (const from of interjected.merged) yield { type: 'merged', traceId: from, into: traceId }; } // A raced screen verdict that already fired (settled during setup, or while a previous tool round // ran): fold its correction in before generating, so this call is informed directly rather than // discarded. This is the no-waste path — the verdict landed before we spent any tokens. yield* claimVerdicts(); if (turnToolSources.length > 0) { turnTools = await resolveTurnTools(turnToolSources, session, name => tools.has(name) || (opts.toolRegistry?.resolve(name) ?? null) !== null, turnToolWarned); } const pendingCalls: Array<{ id: string; name: string; input: unknown; meta?: ProviderMeta; truncated?: { bytes: number; stopReason?: string } }> = []; const assistantParts: MessageContent[] = []; let textAcc = ''; let turnUsage: Usage | undefined; // The round's bracket — set where the provider call is actually issued, below, so it measures the // call rather than the screen/contribute work that precedes it. let roundStartedAt = Date.now(); // Book the round's own spend as an entry the moment the stream settles — including when the response // is then thrown away (an in-situ restart) or the call died part-way. The tokens were billed either // way; tying the record to whether the *answer* survived is what made a restarted round free. Clears // as it books, so no exit path can double-count it. const bookRound = (): void => { const u = turnUsage; if (u === undefined) return; turnUsage = undefined; // Under the profile that ran, never an alias of it (`config.provider` may be one): an entry is priced // by the model's rates, and an alias moves. withUsageSite({ kind: 'round', round }, () => recordUsage(providerConfig.name, u, { startedAt: new Date(roundStartedAt).toISOString(), durationMs: Date.now() - roundStartedAt, })); }; let truncation: { reason: 'max-tokens' | 'stream-end'; raw?: string } | undefined; // Set if a raced verdict fires mid-generation: discard this response and re-run the loop (below). let restart = false; // One provider call. The outgoing array (system context + history, with screen's ephemeral // blocks appended onto the tail message) is assembled here and handed to `contribute` hooks for // a final ephemeral transform — none of this is written back to the session. // Fold onto the last NON-marker message: markers are elided from the wire, so the literal last // message can be a marker (e.g. a retract-redo leaves the retraction marker as the tail) — folding // there would drop the ephemeral with it. -1 ⇒ nothing to fold onto (no non-marker history). const foldIdx = ephemeral.length > 0 ? session.messages.findLastIndex(m => m.role !== 'marker') : -1; // Whether any message needs rewriting for the wire — an attachment to show, a robo-submit's sender — in one // pass, since this runs before every provider call and a session with neither should cost one scan. const rewrite = session.messages.some(m => isRoboSubmit(m) || m.content.some(c => c.type === 'file-ref')); const history = foldIdx >= 0 || attachments.size > 0 || rewrite ? session.messages.flatMap((m, i) => { const inlined = withAttachmentsShown(withSenderShown(m), sessionMedia.get(m.id)); const folded = i === foldIdx ? { ...inlined, content: [...inlined.content, ...ephemeral] } : inlined; const media = attachments.get(m.id); return media ? [folded, media] : [folded]; }) : session.messages; const outgoing = await hookReg.runContribute({ outgoing: [...systemMsg, ...history], session, config, signal, }); // Tools advertised for THIS call. A presenter (optional) may present a subset of the snapshot and // grow it across iterations as the model discovers tools; absent ⇒ the whole snapshot. Withheld // tools stay callable — execution resolves against the live registry (opts.toolRegistry), not this. // Scoped to the round: a presenter may itself run completions (deriving a tool's search terms), and // that spend belongs to the round that asked for it — it is neither a tool call nor a hook. // Turn tools go AFTER the presenter, never through it: they are few, made for this session, and // absent from the registry a presenter's own search reads — one it windowed out could not come back. const presented = opts.toolPresenter ? await withUsageSite({ kind: 'round', round }, () => opts.toolPresenter!.present([...tools.values()], { session, provider: config.provider })) : [...tools.values()]; const advertised = turnTools.size > 0 ? [...presented, ...turnTools.values()] : presented; // Per-call signal linked to the turn signal: an in-situ restart aborts THIS provider call (callAc) // to cancel the in-flight request and stop backend generation, without aborting the whole turn. const callAc = new AbortController(); const callSignal = AbortSignal.any([signal, callAc.signal]); try { roundStartedAt = Date.now(); for await (const ev of provider.complete(outgoing, providerConfig, advertised, callSignal)) { // A raced verdict firing mid-generation changes the premise: discard this doomed response and // restart the loop with the correction folded in. Polled BEFORE the event is emitted, so a // classifier faster than time-to-first-token is caught before any token reaches the frontend. if (yield* claimVerdicts()) { restart = true; callAc.abort('screen-restart'); break; } switch (ev.type) { case 'text-delta': textAcc += ev.delta; yield { type: 'text-delta', delta: ev.delta, traceId }; break; case 'thinking': yield { type: 'thinking', delta: ev.delta, traceId }; break; case 'progress': yield { type: 'progress', pct: ev.pct, ...(ev.message !== undefined ? { message: ev.message } : {}), traceId }; break; case 'thinking-block': assistantParts.push({ type: 'thinking', thinking: ev.thinking, signature: ev.signature, ...(ev.meta !== undefined ? { meta: ev.meta } : {}) }); break; case 'redacted-thinking': assistantParts.push({ type: 'redacted-thinking', data: ev.data }); break; case 'unknown-block': assistantParts.push({ type: 'unknown-content', blockType: ev.blockType, raw: ev.raw }); break; case 'reasoning-block': assistantParts.push({ type: 'reasoning', reasoning: ev.reasoning }); break; case 'tool-call': pendingCalls.push({ id: ev.id, name: ev.name, input: ev.input, ...(ev.meta !== undefined ? { meta: ev.meta } : {}), ...(ev.truncated !== undefined ? { truncated: ev.truncated } : {}) }); break; case 'truncated': truncation = { reason: ev.reason, ...(ev.raw !== undefined ? { raw: ev.raw } : {}) }; break; case 'usage': turnUsage = addUsage(turnUsage, ev); yield { type: 'usage', inputTokens: ev.inputTokens, outputTokens: ev.outputTokens, traceId, ...(ev.cacheReadTokens !== undefined ? { cacheReadTokens: ev.cacheReadTokens } : {}), ...(ev.cacheCreationTokens !== undefined ? { cacheCreationTokens: ev.cacheCreationTokens } : {}), ...(ev.reported !== undefined ? { reported: ev.reported } : {}) }; break; case 'done': break; } } } catch (e: unknown) { // A provider call cancelled by an in-situ restart (callAc, not the turn signal) is expected — fall // through to the restart below rather than surfacing it as a turn abort or an error. if (restart || (callAc.signal.aborted && !signal.aborted)) { restart = true; } else if (signal.aborted) { bookRound(); // Save whatever the LLM streamed before the abort hit. if (textAcc) assistantParts.push({ type: 'text', text: textAcc }); if (assistantParts.length > 0) { session = appendMessage(session, createMessage({ role: 'assistant', content: assistantParts, traceId, providerName: config.provider, })); } yield* end({ type: 'aborted', reason: abortReason(signal), session, traceId }); return; } else { // A failed provider call still commits the rounds that succeeded. Nothing is written mid-turn, so // returning without one discarded the whole turn — and the multi-round case is exactly the // tool-using one, so a provider 500 or a dropped connection on round 3 threw away two completed // rounds of assistant messages and tool results the frontend had already drawn, and which the // next turn (which re-reads from the store) would then be missing. // // Nothing partial is appended here, unlike the abort branch above: `textAcc` and `assistantParts` // belong to the call that failed, and the model never finished the thought. The `error` event // carries no session (a failure is not a transcript), so this yields the terminal itself rather // than the session — but it commits first, exactly like every other exit. bookRound(); const failure = failureOf(e); yield* end({ type: 'error', error: errorText(e), traceId, ...(failure !== undefined ? { failure } : {}) }); return; } } bookRound(); // In-situ restart: discard this iteration's (uncommitted) response and re-run the loop with the // raced correction now folded into `ephemeral`. No store write, no retraction marker — the clean // counterpart to a post-commit `followup` retract. if (restart) continue; // Pre-commit poll: the verdict may have settled exactly as the stream ended. Discard and re-run // rather than commit-then-retract, keeping the correction on the cheaper in-situ path. if (yield* claimVerdicts()) continue; // Build and store assistant message if (textAcc) assistantParts.push({ type: 'text', text: textAcc }); for (const tc of pendingCalls) { assistantParts.push({ type: 'tool-call', id: tc.id, name: tc.name, input: tc.input, ...(tc.meta !== undefined ? { meta: tc.meta } : {}) }); } if (assistantParts.length > 0) { const assistantMsg = createMessage({ role: 'assistant', content: assistantParts, traceId, providerName: config.provider, }); session = appendMessage(session, assistantMsg); } // The provider cut this response short rather than the model choosing to stop. Recorded whether or // not a tool call was caught in it — the commoner case has none, and prose stopping mid-sentence // previously left no trace anywhere. What to DO about it (continue, re-ask with a bigger budget) is // a `followup` hook's call, not the harness's. if (truncation) { const marker: MessageContent = { type: 'marker', creator: TRUNCATION_CREATOR, data: truncation }; session = appendMessage(session, createMessage({ role: 'marker', content: [marker], traceId })); yield { type: 'marker', content: [marker], traceId }; } if (assistantParts.length === 0) { // Diagnostic: the provider returned no text, no tool calls, no thinking — a genuinely empty // completion. The turn will end with no assistant message, which reads as "the agent never // replied". Logged here so a silent no-reply turn is traceable. (textAcc length is shown to // tell a truly empty stream apart from one that was only whitespace.) console.warn(`[runner] empty completion (no assistant content) on traceId ${traceId}; textAcc=${textAcc.length} chars, provider=${config.provider}`); } // No tool calls → done if (pendingCalls.length === 0) break; // ── 3. Execute tool calls ──────────────────────────────────────────────── const toolResults: MessageContent[] = []; const toolMarkers: MessageContent[] = []; const toolMedia: ModelContent[] = []; for (const [callIdx, tc] of pendingCalls.entries()) { yield { type: 'tool:start', callId: tc.id, name: tc.name, input: tc.input, traceId }; const tool = (opts.toolRegistry !== undefined ? opts.toolRegistry.resolve(tc.name) : tools.get(tc.name)) ?? turnTools.get(tc.name); if (!tool) { const err = { error: `Unknown tool: ${tc.name}` }; toolResults.push({ type: 'tool-result', id: tc.id, result: err, isError: true }); yield { type: 'tool:end', callId: tc.id, result: err, isError: true, traceId }; continue; } // Arguments severed mid-stream (the provider hit its token limit part-way through the call). // The call cannot run, but it must still be answered: the assistant message above carries a // `tool-call` block for it, and an unpaired `tool_use` is rejected by the next submission. So it // is recorded as a call that failed — no execution, no side effect — and the model reads the // failure in the slot it expects and retries smaller, which is the ordinary self-correction the // loop already does for a rejected or unknown tool. No retry counter: a model that keeps // overflowing burns rounds and meets `maxRounds`, exactly as one repeatedly calling any failing // tool does. // // `toolcall` is skipped — there is nothing to judge, the call cannot proceed whatever a hook // says — but `toolresult` runs, because it owns the LLM-facing text and is where a consumer // folds in advice the harness cannot have: which of THIS tool's parameters offers a cheaper // edit. See `isTruncatedToolResult`. if (tc.truncated) { const truncated: TruncatedToolResult = { error: `Arguments for "${tc.name}" were cut off after ${tc.truncated.bytes} bytes and could not be parsed` + `${tc.truncated.stopReason !== undefined ? ` (stop reason "${tc.truncated.stopReason}")` : ''}. ` + 'The call did NOT run and had no effect. Retry it smaller — fewer operations in one call, ' + 'or split the work across several calls.', truncated: { tool: tc.name, bytes: tc.truncated.bytes, ...(tc.truncated.stopReason !== undefined ? { stopReason: tc.truncated.stopReason } : {}) }, }; const shaped = await hookReg.runToolResult({ session, config, signal, toolCall: { id: tc.id, name: tc.name, input: tc.input }, tool, result: truncated, isError: true, durationMs: 0, }); toolResults.push({ type: 'tool-result', id: tc.id, result: shaped, isError: true }); yield { type: 'tool:end', callId: tc.id, result: shaped, isError: true, traceId }; continue; } const decision = await hookReg.runToolCall({ session, config, signal, toolCall: { id: tc.id, name: tc.name, input: tc.input }, tool, }); if (decision.abort) { // Commit the turn before leaving (`end`, above — nothing is written mid-turn, so an exit that // skips it discards the whole turn: every earlier round's assistant message and tool results, // plus this round's response, all of which the frontend had already drawn). This path is where // that was first found and fixed. // // Committing requires closing the tool_use/tool_result pairing first: the assistant message // above carries a `tool-call` block per pending call, and a `tool_use` left unpaired is // rejected by the next submission (Anthropic 400s; nothing downstream reconciles them). The // abort is a turn-level stop rather than a verdict on the tools, so the calls that never ran // are recorded as not-run. `tool:end` is carried only for the call the hook actually judged — // the rest never had a `tool:start`, so a frontend has no bubble to close for them. const stopped = { error: `Tool call not executed — the turn was aborted (${decision.abort}).` }; toolResults.push({ type: 'tool-result', id: tc.id, result: stopped, isError: true }); yield { type: 'tool:end', callId: tc.id, result: stopped, isError: true, traceId }; for (const rest of pendingCalls.slice(callIdx + 1)) { toolResults.push({ type: 'tool-result', id: rest.id, result: stopped, isError: true }); } session = appendMessage(session, createMessage({ role: 'tool', content: toolResults, traceId })); if (toolMarkers.length > 0) { session = appendMessage(session, createMessage({ role: 'marker', content: toolMarkers, traceId })); yield { type: 'marker', content: toolMarkers, traceId }; } yield* end({ type: 'aborted', reason: decision.abort, session, traceId }); return; } if (decision.rejectTool) { const err = { error: decision.rejectTool.message }; toolResults.push({ type: 'tool-result', id: tc.id, result: err, isError: true }); yield { type: 'tool:end', callId: tc.id, result: err, isError: true, traceId }; continue; } let result: unknown; let isError = false; // Token accounting for completions this tool runs (via singleTurn/complete) accrues into the // ambient turn scope, stamped with the site established below — never attached to this message. // A tool message is popped wholesale by a retract-and-rerun, which would take its accounting // somewhere no reduction over the session can reach; the entry lives on the turn head instead. const site: UsageSite = { kind: 'tool', callId: tc.id, tool: tc.name }; const startedAt = Date.now(); const toolCtx: ToolContext = { callId: tc.id, session, signal, vault, provider: config.provider, prompt: promptFn, ...bindPluginOps(opts, promptFn), // `opts.prompt`, deliberately NOT `promptFn`: the stand-in above answers with the field's own // default, so a gate handed it could never tell "no human is reachable" from "a human answered // with the default" — and would get the fallback back one layer too late to reason about. // `ToolContext.prompt` keeps the stand-in exactly as before; only the gate sees the truth. ...bindGate(opts.permissionGate, tool, opts.prompt, { session: session.id }, opts.toolRegistry ?? { resolve: n => tools.get(n) ?? null }), ...(opts.workdir !== undefined ? { workdir: opts.workdir } : {}), ...(opts.files !== undefined ? { files: opts.files } : {}), ...(opts.appender !== undefined ? { appender: opts.appender } : {}), ...(turnTools.size > 0 ? { turnTools } : {}), }; // Iterated by hand rather than with `for await`, so the read can be bounded once the turn is // aborted (see ABANDONED_TOOL_GRACE_MS): an executor that never returns would otherwise hold this // turn open for ever, with no path back for the session. const events = siteScoped(site, tool.executor.execute(tc.input, toolCtx))[Symbol.asyncIterator](); const deadline = abandonDeadline(signal, ABANDONED_TOOL_GRACE_MS); try { for (;;) { const step = await Promise.race([events.next(), deadline.wait]); if (step === ABANDON) { console.warn(`[matbot] tool "${tc.name}" did not return ${ABANDONED_TOOL_GRACE_MS}ms after the turn was aborted — abandoned.`); // Not awaited: a tool that ignored the abort may well not return from `return()` either, and // awaiting it here is the same hang one frame further out. void events.return?.(undefined as never); isError = true; break; } if (step.done === true) break; const toolEv = step.value; switch (toolEv.type) { case 'stdout': yield { type: 'tool:stdout', callId: tc.id, chunk: toolEv.chunk, traceId }; break; case 'stderr': yield { type: 'tool:stderr', callId: tc.id, chunk: toolEv.chunk, traceId }; break; case 'file': yield { type: 'file', handle: toolEv.handle, traceId }; break; case 'result': result = toolEv.value; break; // Built from `creator` and `data` alone: where the marker came from is the host's to say (CallFrame), // so this call's frame leads and only the frames a box attached for nested calls follow it. case 'marker': toolMarkers.push({ type: 'marker', creator: toolEv.creator, data: toolEv.data, by: [callFrame(tc.name, tool, tc.id), ...(callFramesOf(toolEv) ?? [])] }); break; case 'model-content': toolMedia.push(...toolEv.content); break; case 'progress': yield { type: 'tool:progress', callId: tc.id, pct: toolEv.pct, ...(toolEv.message !== undefined ? { message: toolEv.message } : {}), traceId }; break; case 'error': result = { error: toolEv.message, // Beside the message, so the model can tell "try again later" from "this will never work" // without the tool having had to say so in prose — the choice to retry is the model's. ...(toolEv.failure !== undefined ? { failure: toolEv.failure } : {}), ...(toolEv.stdout !== undefined ? { stdout: toolEv.stdout } : {}), ...(toolEv.stderr !== undefined ? { stderr: toolEv.stderr } : {}), }; isError = true; break; } } } catch (e) { const failure = failureOf(e); result = { error: errorText(e), ...(failure !== undefined ? { failure } : {}) }; isError = true; } finally { deadline.dispose(); } // A tool that errored under an aborted signal did so because it was cut off (a steer interrupt, // a user cancel), not a genuine fault — reframe it before it is recorded, so the raw abort reason // never reaches the model or the transcript. Covers both the throw and the yielded-`error` paths; // a successful result is left untouched. if (signal.aborted && isError) { result = INTERRUPTED_TOOL_RESULT; } // toolresult — last chance to transform the result before it's recorded/yielded (hard redaction), // or to observe it (auditing: args + result + timing). Owns the LLM-facing + persisted surfaces. const durationMs = Date.now() - startedAt; // The bracket, recorded for EVERY tool call — not just the ones that spent tokens. Most tools // (bash, http, workspace) run no completion at all, so hanging duration off an accounting record // would capture it precisely for the tools that happen to call an LLM and lose it for the rest. // Previously this number was computed, handed to the `toolresult` hook, and then discarded, so a // consumer had to re-derive it — less accurately — from event arrival times. recordSpan(site, new Date(startedAt).toISOString(), durationMs); result = await hookReg.runToolResult({ session, config, signal, toolCall: { id: tc.id, name: tc.name, input: tc.input }, tool, result, isError, durationMs, }); toolResults.push({ type: 'tool-result', id: tc.id, result, isError }); yield { type: 'tool:end', callId: tc.id, result, isError, durationMs, traceId }; } // Add tool results message, then loop for the next provider call. const toolMsg = createMessage({ role: 'tool', content: toolResults, traceId }); session = appendMessage(session, toolMsg); // Media the tools handed over for the model to look at. Held wire-side only — pinned directly // after the tool message it came from (so it keeps a stable history position, and so the model // reads it as the answer to that call) and spliced into `outgoing` on every remaining round of // this turn. Never appended to `session`: the transcript records what the tool returned, not the // bytes it showed. if (toolMedia.length > 0) { attachments.set(toolMsg.id, createMessage({ role: 'user', content: toolMedia, traceId })); } // Markers a tool emitted while running: persist as their own marker-role message (elided from // provider submission) and carry live so a frontend can render them without a reload. if (toolMarkers.length > 0) { session = appendMessage(session, createMessage({ role: 'marker', content: toolMarkers, traceId })); yield { type: 'marker', content: toolMarkers, traceId }; } } // ── 4. Persist and finish ────────────────────────────────────────────────── // `react` fires post-commit, in pump (the queue owner) — not here. yield* end({ type: 'done', session, traceId }); }