@crewhaus/runtime-core 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2044 @@
1
+ import * as readline from "node:readline/promises";
2
+ import { createAbortTree } from "@crewhaus/abort-controller";
3
+ import { collectFinalMessage, consumeStream, } from "@crewhaus/adapter-anthropic";
4
+ import { setDefaultBoundaryLlmClassifier } from "@crewhaus/boundary-classifier";
5
+ import { wrap as wrapWithCircuitBreaker } from "@crewhaus/circuit-breaker";
6
+ import { autoCompact } from "@crewhaus/compaction-autocompact";
7
+ import { snip } from "@crewhaus/compaction-snip";
8
+ import { classifyEgress, summarizeEgress, } from "@crewhaus/egress-classifier";
9
+ import { ConfigError, RuntimeError } from "@crewhaus/errors";
10
+ import { openEventLog } from "@crewhaus/event-log";
11
+ import { aggregateDecisions, runHooks } from "@crewhaus/hooks-engine";
12
+ import { parseModelString, resolveModel } from "@crewhaus/model-router";
13
+ import { BUILTIN_DEFAULT_RULES, emptyRuleSet, evaluateJustification, evaluateWithReason, ruleBasedJustificationJudge, } from "@crewhaus/permission-engine";
14
+ import { manage as manageCacheMarkers } from "@crewhaus/prompt-cache-manager";
15
+ import { buildRedactionNotice, classifyText, llmClassifierEnabled, } from "@crewhaus/prompt-injection-detector";
16
+ import { advanceState, initialRecoveryState, recover, } from "@crewhaus/recovery-engine";
17
+ import { createRunContext, tagContent } from "@crewhaus/run-context";
18
+ import { createSessionStore } from "@crewhaus/session-store";
19
+ import { formatSkillsForPrompt } from "@crewhaus/skills-registry";
20
+ import { expand as expandSlash } from "@crewhaus/slash-commands";
21
+ import { createStore } from "@crewhaus/state-store";
22
+ import { executeStreaming } from "@crewhaus/streaming-tool-executor";
23
+ import { currentTenantContext } from "@crewhaus/tenancy";
24
+ import { TokenBudget, estimateTokens } from "@crewhaus/token-budget";
25
+ import { executeTool } from "@crewhaus/tool-executor";
26
+ import { detectLoop } from "@crewhaus/tool-loop-detection";
27
+ import { partitionToolCalls } from "@crewhaus/tool-orchestrator";
28
+ import { storeAndPreview } from "@crewhaus/tool-result-store";
29
+ import { TraceEventBus } from "@crewhaus/trace-event-bus";
30
+ import { initialState, transition, } from "@crewhaus/turn-state-machine";
31
+ import { zodToJsonSchema } from "zod-to-json-schema";
32
+ import { createCliMarkdownRenderer, isCliMarkdownEnabled, } from "./cli-markdown";
33
+ import { attachDefaultSubscribers } from "./observability";
34
+ import { loadProjectMemory } from "./project-memory";
35
+ import { createCliOutput, isSpinnerEnabled } from "./spinner";
36
+ /**
37
+ * Slice-scope runtime: a multi-turn streaming chat loop with prompt
38
+ * caching, tool execution, pre-turn context compaction, recovery taxonomy,
39
+ * permission gating, cooperative cancellation, and a partitioned/streaming
40
+ * tool layer. Maps to catalog R1 runtime-orchestrator + R1 recovery-engine
41
+ * + R8 permission-engine + R1 abort-controller + R3 tool-orchestrator /
42
+ * tool-loop-detection / tool-result-store / streaming-tool-executor, plus
43
+ * R2 model-adapter (Anthropic only).
44
+ *
45
+ * Auth resolution: ANTHROPIC_AUTH_TOKEN (Claude Pro/Max OAuth) takes
46
+ * precedence over ANTHROPIC_API_KEY (pay-per-token API key). OAuth tokens
47
+ * are detected by the `sk-ant-oat` prefix and given the beta + identity
48
+ * headers required to route through subscription billing.
49
+ *
50
+ * Tool support: when `tools` is provided, the loop forwards the tool
51
+ * definitions (Zod → JSON Schema) to the model, runs each tool through
52
+ * the permission engine, then executes via @crewhaus/tool-executor before
53
+ * re-calling the model. The state machine reaches Done(no_tools) when the
54
+ * assistant returns no further tool_use blocks for a turn.
55
+ *
56
+ * Tool layer enrichment (Section 8): tool execution is partitioned via
57
+ * `@crewhaus/tool-orchestrator` so concurrency-safe read-only calls run
58
+ * via `Promise.all` while destructive calls run serially. After each
59
+ * batch, `@crewhaus/tool-loop-detection` scans the per-run history; on a
60
+ * hit, a synthetic warning user message is appended (deduped per
61
+ * signature) so the model can self-correct. Every tool result flows
62
+ * through `@crewhaus/tool-result-store` — outputs over 10 KB are
63
+ * persisted to `.crewhaus/tool-results/<runId>/<toolUseId>.txt` and the
64
+ * model sees a preview pointing at the full file. Behind a
65
+ * `streaming: true` option, the loop swaps to
66
+ * `@crewhaus/streaming-tool-executor`, which dispatches tools mid-stream
67
+ * via the SDK's `contentBlock` event.
68
+ *
69
+ * Compaction: at the start of each user turn, estimate the conversation's
70
+ * token count against `contextLimit` (default 200_000). When usage crosses
71
+ * `compactionThreshold` (default 0.85), apply the cheap snip first, then
72
+ * fall back to autocompact if still over. Reactive compaction is also
73
+ * triggered in-turn when the recovery engine returns a `compact` action.
74
+ *
75
+ * Recovery: every model call is wrapped in try/catch. Errors flow through
76
+ * the `recovery-engine` taxonomy: prompt_too_long → reactive compact;
77
+ * max_output_tokens → continue; overloaded/5xx → exponential-backoff
78
+ * retry; invalid_request → tombstone. Budgets enforced per turn.
79
+ *
80
+ * Permissions: every tool_use is evaluated by `permission-engine`. In
81
+ * default and auto modes, an `ask` decision prompts the user via stdin in
82
+ * REPL mode (single-turn mode treats `ask` as deny — non-interactive).
83
+ *
84
+ * Cancellation: the `runContext.abortSignal` becomes the root of an abort
85
+ * tree; each turn gets a child, each tool call gets a grandchild. First
86
+ * SIGINT cancels the current turn; second SIGINT exits the process.
87
+ *
88
+ * Persistence (Section 10): every `runChatLoop` invocation either creates
89
+ * a new session via `@crewhaus/session-store` or resumes an existing one
90
+ * (`opts.resume`); the session's `.json` metadata file lives at
91
+ * `.crewhaus/sessions/<id>.json` alongside an append-only `.jsonl`
92
+ * transcript opened via `@crewhaus/event-log`. Every user input,
93
+ * assistant turn, tool_use, tool_result, recovery error, and compaction
94
+ * is appended as one JSON line. On `--resume`, the runtime walks the
95
+ * `.jsonl` and replays `user_message` + `assistant_message` events into
96
+ * the message history before the loop starts. A per-run
97
+ * `@crewhaus/state-store` is also instantiated as a coordination surface
98
+ * for hooks/skills/tools (consumed by Section 11+). Eviction: any
99
+ * session whose `.json` mtime is older than 30 days is purged on the
100
+ * next `sessionStore.list()` (called once at the top of every
101
+ * `runChatLoop`).
102
+ */
103
+ const DEFAULT_CONTEXT_LIMIT = 200_000;
104
+ // Hard per-turn cap on model→tool cycles. Generous enough that no realistic
105
+ // agentic turn reaches it, low enough to stop a runaway/injected tool loop
106
+ // before it burns a provider quota.
107
+ const DEFAULT_MAX_TOOL_ITERATIONS = 500;
108
+ const DEFAULT_COMPACTION_THRESHOLD = 0.85;
109
+ const DEFAULT_SNIP_KEEP_HEAD = 4;
110
+ const DEFAULT_SNIP_KEEP_TAIL = 20;
111
+ // Section 17 — `resolveAuth` / `createAnthropicClient` / `ResolvedAuth` /
112
+ // `OAUTH_BETAS` / `CLAUDE_CODE_HEADERS` / `CLAUDE_CODE_SYSTEM_PREFIX`
113
+ // moved into `@crewhaus/adapter-anthropic`. Re-exported here so legacy
114
+ // importers (eval-judge fallback, downstream tests) keep compiling.
115
+ export { CLAUDE_CODE_HEADERS, CLAUDE_CODE_SYSTEM_PREFIX, OAUTH_BETAS, createAnthropicClient, resolveAuth, } from "@crewhaus/adapter-anthropic";
116
+ /**
117
+ * Reconcile a message history by dropping "orphan" `tool_use` blocks — a
118
+ * `tool_use` with no answering `tool_result` anywhere later in the
119
+ * conversation. The Claude Messages API requires every `tool_use` to be
120
+ * followed by a matching `tool_result`; an orphan makes every subsequent
121
+ * request 400 with `tool_use` ids "found without `tool_result` blocks
122
+ * immediately after". Orphans are born when the model is cut off mid-`tool_use`
123
+ * by `stop_reason: "max_tokens"`: the partial call is never executed (so a
124
+ * result is never logged) and its input is truncated / `__parse_error`
125
+ * garbage, so the only safe reconciliation is to drop it and let the model
126
+ * re-issue the call. An assistant message left empty after stripping is
127
+ * removed entirely.
128
+ *
129
+ * Idempotent and a no-op on healthy histories. Applied on `--resume` replay
130
+ * (so a session bricked by a pre-fix runtime self-heals) and by the
131
+ * `tombstone` recovery action (a universal backstop for any path that still
132
+ * commits an orphan).
133
+ */
134
+ export function sanitizeOrphanToolUses(messages) {
135
+ const answered = new Set();
136
+ for (const m of messages) {
137
+ if (!Array.isArray(m.content))
138
+ continue;
139
+ for (const block of m.content) {
140
+ const b = block;
141
+ if (b.type === "tool_result" && typeof b.tool_use_id === "string") {
142
+ answered.add(b.tool_use_id);
143
+ }
144
+ }
145
+ }
146
+ let removed = 0;
147
+ const out = [];
148
+ for (const m of messages) {
149
+ if (m.role !== "assistant" || !Array.isArray(m.content)) {
150
+ out.push(m);
151
+ continue;
152
+ }
153
+ const kept = m.content.filter((block) => {
154
+ const b = block;
155
+ if (b.type === "tool_use" && typeof b.id === "string" && !answered.has(b.id)) {
156
+ removed += 1;
157
+ return false;
158
+ }
159
+ return true;
160
+ });
161
+ if (kept.length === 0)
162
+ continue;
163
+ out.push(kept.length === m.content.length ? m : { ...m, content: kept });
164
+ }
165
+ return { messages: out, removed };
166
+ }
167
+ /**
168
+ * Walk an `EventLog` and reconstruct the SDK message history. Only
169
+ * `user_message` and `assistant_message` events contribute — `tool_use`
170
+ * and `tool_result` events are audit-only because the same data already
171
+ * lives inside the assistant/user message content arrays. `error` and
172
+ * `compaction` events are observability-only and skipped.
173
+ *
174
+ * Exported so consumers (the `--resume` path in `apps/cli`, the T4
175
+ * replay test, and any future inspector) can reproduce the same history
176
+ * the runtime would build.
177
+ */
178
+ export async function replayMessageHistory(log) {
179
+ const messages = [];
180
+ // Crew sessions and sub-agent spawners share one append-only log.
181
+ // Events emitted between a2a_turn_start / a2a_turn_end (Section 22)
182
+ // or sub_agent_start / sub_agent_end (Section 13) are nested
183
+ // transcripts that should NOT bleed into the outer role's history —
184
+ // their `user_message` and `assistant_message` events would otherwise
185
+ // sit between the parent's tool_use and its tool_result, breaking
186
+ // Claude API's adjacency requirement. Track nesting depth and only
187
+ // surface user/assistant events at depth 0.
188
+ let depth = 0;
189
+ for await (const ev of log.read()) {
190
+ if (ev.kind === "a2a_turn_start" || ev.kind === "sub_agent_start") {
191
+ depth += 1;
192
+ continue;
193
+ }
194
+ if (ev.kind === "a2a_turn_end" || ev.kind === "sub_agent_end") {
195
+ depth = Math.max(0, depth - 1);
196
+ continue;
197
+ }
198
+ if (depth > 0)
199
+ continue;
200
+ if (ev.kind === "user_message") {
201
+ const p = ev.payload;
202
+ messages.push({ role: "user", content: p.content });
203
+ }
204
+ else if (ev.kind === "assistant_message") {
205
+ const p = ev.payload;
206
+ messages.push({ role: "assistant", content: p.content });
207
+ }
208
+ }
209
+ // A session persisted by a pre-fix runtime can carry a dangling `tool_use`
210
+ // the model was cut off mid-emitting (`stop_reason: "max_tokens"`) with no
211
+ // following `tool_result`; replaying it verbatim would 400 the first resumed
212
+ // request. Drop such orphans so `--resume` self-heals. No-op on healthy logs.
213
+ return sanitizeOrphanToolUses(messages).messages;
214
+ }
215
+ /**
216
+ * Runs the streaming chat loop and returns the terminal assistant text.
217
+ *
218
+ * - REPL mode (default): reads stdin in a loop, prints assistant turns to
219
+ * stdout, returns `""` when the loop exits.
220
+ * - Single-turn mode (`singleTurn: true`): runs one turn from the seeded
221
+ * message history and returns the concatenated text content of the final
222
+ * assistant message. Does not touch stdin.
223
+ */
224
+ /**
225
+ * Resolve the root directory for session + event-log persistence (and the
226
+ * sub-agent storage it threads onward).
227
+ *
228
+ * Tenant isolation is MANDATORY at the storage layer, not cooperative: the
229
+ * managed daemon wraps every gateway request in `withTenant(...)`, so when a
230
+ * tenant context is active we use that tenant's path-rebased `sessionRoot`
231
+ * and never fall back to the process-global default — one tenant's prompts
232
+ * and transcripts can no longer land in another tenant's directory (#142).
233
+ *
234
+ * Precedence: an explicit per-call `optsRoot` (set only by trusted callers
235
+ * such as a target emitter or a test) wins; then the active tenant's
236
+ * `sessionRoot`; then `CREWHAUS_SESSION_DIR`; otherwise `undefined` (which
237
+ * lets `session-store` apply its own non-tenant default). The env var and the
238
+ * global default are only consulted OUTSIDE any tenant scope.
239
+ */
240
+ export function resolveSessionRootDir(optsRoot) {
241
+ if (optsRoot !== undefined)
242
+ return optsRoot;
243
+ const tenant = currentTenantContext()?.tenant;
244
+ if (tenant !== undefined)
245
+ return tenant.sessionRoot;
246
+ return process.env["CREWHAUS_SESSION_DIR"] ?? undefined;
247
+ }
248
+ /**
249
+ * Tenant-scoped root for the tool-result spill store, mirroring
250
+ * resolveSessionRootDir (#150). Inside a tenant scope the tenant's rebased
251
+ * `toolResultRoot` is used so one tenant's persisted tool outputs never share
252
+ * a directory with another's; otherwise `undefined` lets tool-result-store
253
+ * apply its own non-tenant default.
254
+ */
255
+ export function resolveToolResultRoot() {
256
+ return currentTenantContext()?.tenant.toolResultRoot;
257
+ }
258
+ /**
259
+ * Sinks whose DESTINATION is chosen at runtime by the (prompt-injectable)
260
+ * model — a fetched/navigated URL, an on-chain recipient — are effectively
261
+ * dynamic even though they are spec-declared built-in tools: an attacker who
262
+ * steers the model picks where the data goes. So non-user cross-origin content
263
+ * reaching them must reach the egress BLOCK tier, not merely warn. Fixed-
264
+ * destination sinks are intentionally NOT here: `SendMessage` replies to the
265
+ * operator-configured channel, `WebSearch`/`ImageGenerate` hit a fixed provider
266
+ * API — classifying those dynamic would block legitimate replies, so they stay
267
+ * `"external-configured"` (warn) and can be tightened per-deployment via the
268
+ * `resolveSinkScope` override or the spec's egress policy.
269
+ */
270
+ const MODEL_DESTINATION_SINKS = new Set([
271
+ "Fetch",
272
+ "WebFetch",
273
+ "Navigate",
274
+ "EvmSendTransaction",
275
+ ]);
276
+ /**
277
+ * Default egress sink-scope. Runtime-joined MCP sinks (`mcp__*`) are the
278
+ * canonical dynamically-discovered external sink, and the model-destination
279
+ * built-ins above are dynamic by virtue of their model-chosen target — both
280
+ * classify as `"external-dynamic"` so the egress block tier is reachable for
281
+ * non-user-origin payloads (#144). Other spec-declared built-in sinks stay
282
+ * `"external-configured"` (warn). Override via `runChatLoop({ resolveSinkScope })`
283
+ * to mark federation-joined or other runtime sinks dynamic too.
284
+ */
285
+ export function defaultSinkScope(toolName) {
286
+ if (toolName.startsWith("mcp__"))
287
+ return "external-dynamic";
288
+ if (MODEL_DESTINATION_SINKS.has(toolName))
289
+ return "external-dynamic";
290
+ return "external-configured";
291
+ }
292
+ /**
293
+ * Strip the model-string provider grammar down to the wire model id
294
+ * (`"bedrock/us.anthropic.claude-..."` → `"us.anthropic.claude-..."`)
295
+ * WITHOUT loading the provider package. Used on the `_adapter` injection
296
+ * path where `resolveModel` is bypassed entirely; synthetic ids that
297
+ * don't parse (`"test-model"`) pass through verbatim so existing test
298
+ * stubs keep their ids untouched.
299
+ */
300
+ function bestEffortWireModelId(modelString) {
301
+ try {
302
+ return parseModelString(modelString).modelId;
303
+ }
304
+ catch {
305
+ return modelString;
306
+ }
307
+ }
308
+ export async function runChatLoop(opts) {
309
+ // Pillar 3 — make the model-backed Layer-3 classifier reachable at EVERY
310
+ // trust boundary (MCP / sub-agent / channel / federation / skill /
311
+ // compaction / chain / orchestrator). Boundary call sites don't thread an
312
+ // `llmClassifier` through, so we register the runtime's classifier as the
313
+ // process-wide default — gated on the same `llmClassifierEnabled` env switch
314
+ // as the post-tool path. Set-or-clear on each entry keeps boundary behaviour
315
+ // consistent with that gate; idempotent re-registration is a no-op.
316
+ setDefaultBoundaryLlmClassifier(opts.promptInjectionLlmClassifier !== undefined && llmClassifierEnabled(process.env)
317
+ ? opts.promptInjectionLlmClassifier
318
+ : undefined);
319
+ // Section 17 — resolve the primary adapter via the model-router.
320
+ // The router lazy-loads the matching provider package; an
321
+ // Anthropic-only spec never pulls AWS / OpenAI / Gemini SDKs.
322
+ // Section 17 — resolve the primary adapter via the model-router and
323
+ // capture the *stripped* modelId (the form the provider expects, e.g.
324
+ // `openai/gpt-4o-mini` → `gpt-4o-mini`). When the caller injects an
325
+ // `_adapter`, still strip any provider prefix grammar (best-effort) so
326
+ // trace events carry the same wire model id either way — but fall back
327
+ // to `opts.model` verbatim for the synthetic ids tests typically pass
328
+ // (`"test-model"`), which the stub adapter ignores.
329
+ const primaryResolution = opts._adapter
330
+ ? {
331
+ adapter: opts._adapter,
332
+ modelId: bestEffortWireModelId(opts.model),
333
+ providerId: opts._adapter.providerId,
334
+ }
335
+ : await resolveModel(opts.model);
336
+ // Section 27 — wrap the primary adapter in a circuit breaker when
337
+ // `circuitBreaker` opts are set (or by default in production codegen).
338
+ // The breaker is hung off the run-context's bus so state-change events
339
+ // surface for audit-log + structured-event-printer + OTel.
340
+ const baseAdapter = primaryResolution.adapter;
341
+ let breakerWrap;
342
+ const adapter = (() => {
343
+ if (opts.circuitBreaker === undefined)
344
+ return baseAdapter;
345
+ breakerWrap = wrapWithCircuitBreaker(baseAdapter, {
346
+ ...opts.circuitBreaker,
347
+ adapterName: baseAdapter.providerId,
348
+ bus: opts.runContext?.eventBus,
349
+ });
350
+ return breakerWrap;
351
+ })();
352
+ void breakerWrap; // exposed via runtime stats once gateway/eval consumers land
353
+ const providerId = primaryResolution.providerId;
354
+ const wireModelId = primaryResolution.modelId;
355
+ // Section 17 — feature gate: a spec that declares tools cannot run on an
356
+ // adapter that doesn't speak tool use (e.g. Bedrock Llama/Mistral
357
+ // families). Fail with a clear ConfigError naming the model instead of
358
+ // letting the provider 400 (or silently drop the tools) mid-run.
359
+ if ((opts.tools ?? []).length > 0 && adapter.features.tool_use === false) {
360
+ throw new ConfigError(`model "${opts.model}" (provider ${providerId}) does not support tool use — remove tools or pick a tool-capable model`);
361
+ }
362
+ let compactionAdapter;
363
+ let compactionWireModelId;
364
+ if (opts._compactionAdapter !== undefined) {
365
+ compactionAdapter = opts._compactionAdapter;
366
+ compactionWireModelId = opts.compactionModel ?? wireModelId;
367
+ }
368
+ else if (opts.compactionModel !== undefined) {
369
+ const c = await resolveModel(opts.compactionModel);
370
+ compactionAdapter = c.adapter;
371
+ compactionWireModelId = c.modelId;
372
+ }
373
+ else {
374
+ compactionAdapter = adapter;
375
+ compactionWireModelId = wireModelId;
376
+ }
377
+ // Default model max OUTPUT tokens for one turn. Callers thread the spec's
378
+ // `agent.max_tokens` here when set (the CLI target's codegen + apps/cli);
379
+ // this fallback applies when the spec is silent. Kept comfortably above the
380
+ // old 4096 floor so a single turn that writes a few files no longer truncates
381
+ // mid-`tool_use` by default — every supported Claude model accepts >= 8192
382
+ // output tokens. A truncation is no longer fatal regardless (see the
383
+ // `max_tokens` recovery + `sanitizeOrphanToolUses`), but a higher ceiling
384
+ // avoids the churn. Raise it per spec with `agent.max_tokens`.
385
+ const maxTokens = opts.maxTokens ?? 8192;
386
+ // Mutual exclusion: resume takes priority and replaces any seedMessages
387
+ // in REPL mode (the resume payload becomes the seed). Section 12 carves
388
+ // out an exception for singleTurn + resume: the seed is the NEW inbound
389
+ // message, the resumed history is the prefix.
390
+ if (opts.resume !== undefined && opts.seedMessages !== undefined && opts.singleTurn !== true) {
391
+ throw new RuntimeError("runChatLoop: `resume` and `seedMessages` are mutually exclusive in REPL mode — the resume payload becomes the seed");
392
+ }
393
+ // Section 12: singleTurn + resume IS supported — used by the channel-bot
394
+ // session-router for "resume the thread, append the inbound message, run
395
+ // one turn". The seed must contain only the new turn's input (a single
396
+ // user message); the replayed event-log history becomes the prefix and
397
+ // is NOT re-logged.
398
+ if (opts.runContext !== undefined &&
399
+ opts.resume !== undefined &&
400
+ opts.runContext.sessionId !== opts.resume.sessionId) {
401
+ throw new RuntimeError("runChatLoop: opts.runContext.sessionId must match opts.resume.sessionId when both are supplied");
402
+ }
403
+ // Persistence boot: session create/resume + event log open. Runs first
404
+ // so the run context's sessionId — possibly carried over from a prior
405
+ // run — is the one the rest of the loop logs against.
406
+ const sessionRootDir = resolveSessionRootDir(opts.sessionRootDir);
407
+ const sessionStore = createSessionStore({ rootDir: sessionRootDir });
408
+ // Housekeeping side-effect: evicts any session whose mtime is older than
409
+ // the TTL (default 30 days). The returned list is intentionally discarded.
410
+ await sessionStore.list();
411
+ let sessionId;
412
+ let resumedMessages;
413
+ if (opts.resume) {
414
+ const existing = await sessionStore.get(opts.resume.sessionId);
415
+ if (existing === null) {
416
+ throw new RuntimeError(`cannot --resume "${opts.resume.sessionId}": session not found in ${sessionRootDir ?? ".crewhaus/sessions"}`);
417
+ }
418
+ sessionId = existing.id;
419
+ const replayLog = await openEventLog(sessionId, { rootDir: sessionRootDir });
420
+ resumedMessages = await replayMessageHistory(replayLog);
421
+ await replayLog.close();
422
+ }
423
+ else {
424
+ // If the caller supplied a runContext, honour its sessionId (already
425
+ // sess_<16 hex> by construction) so logs and the persisted file agree.
426
+ // Otherwise, let session-store mint a fresh id.
427
+ const created = await sessionStore.create({
428
+ id: opts.runContext?.sessionId,
429
+ name: opts.sessionName ?? "(unnamed)",
430
+ target: opts.sessionTarget ?? "cli",
431
+ model: opts.model,
432
+ });
433
+ sessionId = created.id;
434
+ }
435
+ // Use the supplied runContext as-is when it agrees with the resolved
436
+ // sessionId; otherwise build a fresh context bound to that sessionId.
437
+ // Tests that pass their own runContext rely on observing turnNumber on
438
+ // it after the loop returns, so we never silently swap it out.
439
+ const runContext = opts.runContext ?? createRunContext({ sessionId });
440
+ // Section 15 — every observability subscriber (otel, metrics, printer)
441
+ // hangs off this single bus. The default constructor in `createRunContext`
442
+ // mints a no-subscriber bus; here we attach the env-gated set so a fresh
443
+ // run with `OTEL_EXPORTER_OTLP_ENDPOINT` set automatically exports.
444
+ const bus = runContext.eventBus;
445
+ void TraceEventBus; // keep type import alive for future direct constructions
446
+ const subscribers = await attachDefaultSubscribers(bus, runContext);
447
+ // Working-indicator spinner. Auto-enables only for an interactive REPL on a
448
+ // TTY (see `isSpinnerEnabled`); `singleTurn`/injected-`input`/piped runs stay
449
+ // byte-identical to before. `out.write` is the spinner-aware stdout sink:
450
+ // every interactive write that can land while the animation is live goes
451
+ // through it so the two never collide. `opts.spinner` overrides the auto
452
+ // decision.
453
+ const spinnerEnabled = opts.spinner ?? (opts.singleTurn !== true && opts.input === undefined && isSpinnerEnabled());
454
+ const out = createCliOutput({ enabled: spinnerEnabled });
455
+ // M2.1 — CLI markdown renderer (env-gated). When CREWHAUS_CLI_MARKDOWN=1,
456
+ // text-delta chunks flow through a streaming markdown → ANSI transform so
457
+ // the user sees rendered bold/italic/headers/lists/code-fences instead of
458
+ // raw asterisks. The renderer is line-buffered; chunks accumulate until a
459
+ // `\n` arrives, then the rendered line writes to stdout. `end()` is
460
+ // called after the per-turn `\n` to flush any tail content. Its sink is the
461
+ // spinner-aware writer so a flushed line erases any live animation first.
462
+ const mdRenderer = isCliMarkdownEnabled()
463
+ ? createCliMarkdownRenderer({ write: (s) => out.write(s) })
464
+ : undefined;
465
+ const writeText = (chunk) => {
466
+ // First real assistant text ends the "thinking" wait; clear the spinner
467
+ // (idempotent on later chunks) before the answer streams.
468
+ out.spinner.stop();
469
+ if (mdRenderer)
470
+ mdRenderer.push(chunk);
471
+ else
472
+ out.write(chunk);
473
+ };
474
+ const endTurn = () => {
475
+ // Covers the no-text/no-tool case where the spinner is still up.
476
+ out.spinner.stop();
477
+ if (mdRenderer)
478
+ mdRenderer.end();
479
+ out.write("\n");
480
+ };
481
+ const eventLog = await openEventLog(sessionId, { rootDir: sessionRootDir });
482
+ // Section 27 — mirror per-call cost_accrual events from the trace bus into
483
+ // the session JSONL so `crewhaus cost-summary --session <id>` can sum spend
484
+ // after the run. Gated on the same switch that attaches the cost-tracker
485
+ // (CREWHAUS_COST_TRACKING): no tracker → no accruals to persist, and the
486
+ // message-only transcript stays unchanged by default. Per-call accruals only
487
+ // — skip the FR-003 terminal `summary` aggregate so a run total never
488
+ // double-counts. `append()` writes synchronously, and a persist failure must
489
+ // never abort a turn, so the result is logged rather than thrown.
490
+ let costPersistUnsubscribe;
491
+ if (subscribers.costTracker !== undefined) {
492
+ costPersistUnsubscribe = bus.subscribe((event) => {
493
+ if (event.kind !== "cost_accrual")
494
+ return;
495
+ const ev = event;
496
+ if (ev.summary === true)
497
+ return;
498
+ void eventLog
499
+ .append({
500
+ kind: "cost_accrual",
501
+ payload: {
502
+ provider: ev.provider,
503
+ modelId: ev.modelId,
504
+ ...(ev.specModel !== undefined ? { specModel: ev.specModel } : {}),
505
+ inputTokens: ev.inputTokens,
506
+ outputTokens: ev.outputTokens,
507
+ cachedReadTokens: ev.cachedReadTokens,
508
+ costUsdMicros: ev.costUsdMicros,
509
+ ...(ev.tenantId !== undefined ? { tenantId: ev.tenantId } : {}),
510
+ },
511
+ })
512
+ .catch((err) => {
513
+ runContext.logger.error("cost_accrual.persist_failed", {
514
+ message: err instanceof Error ? err.message : String(err),
515
+ });
516
+ });
517
+ });
518
+ }
519
+ // Per-run state container — coordination surface for hooks/skills/tools
520
+ // landing in Section 11+. Section 10 only ships the plumbing; the
521
+ // underscore prefix marks the intentional non-consumer.
522
+ const _runState = createStore({});
523
+ void _runState;
524
+ // Section 13 — RuntimeBridge. Built once per run, handed to every
525
+ // tool execution through the executor's ExecutionContext. Framework-
526
+ // aware tools (only `Task` today) cast `ctx.bridge` to RuntimeBridge.
527
+ // Built lazily inside executeOneToolUse so it captures the latest
528
+ // permission-mode/-rules and tool list — the values themselves are
529
+ // stable for the run, but the closure keeps the call-site at the
530
+ // tool-execute boundary tidy.
531
+ // Tight helper so call sites stay one line. Errors propagate so an I/O
532
+ // failure on the audit trail surfaces rather than silently dropping.
533
+ async function logEvent(kind, payload) {
534
+ await eventLog.append({ kind, payload });
535
+ }
536
+ // Section 11 — fire matching hooks for `event` and aggregate the result.
537
+ // No-ops when no hooks are configured. The aggregated decision exposes
538
+ // `allowed` / `reason` / `mutate`; v1 callers honour `mutate` only for
539
+ // `pre-slash` (the `expanded` field). Errors are caught and surfaced as
540
+ // a deny so a misbehaving hook implementation does not crash the run.
541
+ const hooks = opts.hooks ?? [];
542
+ async function fireHook(event, payload) {
543
+ if (hooks.length === 0)
544
+ return { allowed: true };
545
+ try {
546
+ const results = await runHooks(event, payload, hooks, {
547
+ logger: runContext.logger,
548
+ eventBus: bus,
549
+ });
550
+ return aggregateDecisions(results);
551
+ }
552
+ catch (err) {
553
+ runContext.logger.warn("hook firing failed", {
554
+ event,
555
+ error: err.message,
556
+ });
557
+ return { allowed: true };
558
+ }
559
+ }
560
+ // Section 11 — `session-start` fires once after the persistence + run
561
+ // context boot is complete. Observational only (no deny/block effect).
562
+ await fireHook("session-start", {
563
+ sessionId,
564
+ model: opts.model,
565
+ target: opts.sessionTarget ?? "cli",
566
+ resumed: opts.resume !== undefined,
567
+ });
568
+ const contextLimit = opts.contextLimit ?? DEFAULT_CONTEXT_LIMIT;
569
+ const compactionThreshold = opts.compactionThreshold ?? DEFAULT_COMPACTION_THRESHOLD;
570
+ const snipKeepHead = opts.snipKeepHead ?? DEFAULT_SNIP_KEEP_HEAD;
571
+ const snipKeepTail = opts.snipKeepTail ?? DEFAULT_SNIP_KEEP_TAIL;
572
+ const permissionMode = opts.permissionMode ?? "default";
573
+ const permissionRules = opts.permissionRules ?? {
574
+ ...emptyRuleSet,
575
+ builtin: BUILTIN_DEFAULT_RULES,
576
+ };
577
+ const userInstructions = {
578
+ type: "text",
579
+ text: opts.instructions,
580
+ cache_control: { type: "ephemeral" },
581
+ };
582
+ // Section 11 — append a "Available skills:" block to the system prompt
583
+ // when skills are configured. The block lists names + descriptions only;
584
+ // the model reaches each skill's body by calling the `Skill` tool (which
585
+ // the caller is responsible for adding to the tools array).
586
+ const skills = opts.skills ?? [];
587
+ const skillsText = skills.length > 0 ? formatSkillsForPrompt(skills) : "";
588
+ const skillsBlock = skillsText.length > 0
589
+ ? [{ type: "text", text: skillsText, cache_control: { type: "ephemeral" } }]
590
+ : [];
591
+ // M3.1 — auto-load project memory files (AGENTS.md / CLAUDE.md /
592
+ // CODE-COMPANION.md / AGENT.md) from cwd at session start. Follows the
593
+ // vendor-neutral agents.md convention; compatible with Claude Code's
594
+ // CLAUDE.md auto-load behaviour. Pillar 3 compliance: each file's content
595
+ // is classified via boundary-classifier with origin "user" inside
596
+ // loadProjectMemory() (the user's repo is developer-trusted).
597
+ const projectMemory = await loadProjectMemory();
598
+ const projectMemoryBlock = projectMemory.prompt.length > 0
599
+ ? [
600
+ {
601
+ type: "text",
602
+ text: projectMemory.prompt,
603
+ cache_control: { type: "ephemeral" },
604
+ },
605
+ ]
606
+ : [];
607
+ if (projectMemory.files.length > 0) {
608
+ process.stdout.write(`[memory] loaded ${projectMemory.files.length} project memory file(s): ${projectMemory.files
609
+ .map((f) => f.filename)
610
+ .join(", ")}\n`);
611
+ }
612
+ // Section 17 — runtime-core no longer prepends the Claude Code OAuth
613
+ // prefix; `adapter-anthropic` handles that internally so each adapter
614
+ // owns its provider-specific auth-shape requirements.
615
+ let systemBlocks = [
616
+ userInstructions,
617
+ ...projectMemoryBlock,
618
+ ...skillsBlock,
619
+ ];
620
+ // Section 27 — rotate cache markers on the system block array if the
621
+ // last refresh is older than the rotation interval. Skips automatically
622
+ // when the adapter doesn't support explicit caching (OpenAI / Bedrock
623
+ // Llama / Mistral). This keeps long-running CHN/MGD/RES daemons under
624
+ // Anthropic's 30-day TTL.
625
+ if (adapter.features.caching === "explicit") {
626
+ const cacheManaged = manageCacheMarkers(systemBlocks.map((b) => ({
627
+ type: "text",
628
+ text: b.text,
629
+ ...(b.cache_control !== undefined ? { cache_control: b.cache_control } : {}),
630
+ })), {
631
+ features: adapter.features,
632
+ ...(opts.promptCacheLastRotatedAt !== undefined
633
+ ? { lastRotatedAt: opts.promptCacheLastRotatedAt }
634
+ : {}),
635
+ });
636
+ if (cacheManaged.rotated) {
637
+ systemBlocks = cacheManaged.blocks.map((b) => ({
638
+ type: "text",
639
+ text: b.text,
640
+ ...(b.cache_control !== undefined ? { cache_control: b.cache_control } : {}),
641
+ }));
642
+ }
643
+ }
644
+ const tools = opts.tools ?? [];
645
+ const anthropicTools = tools.length > 0
646
+ ? tools.map((t) => ({
647
+ name: t.name,
648
+ description: t.description,
649
+ input_schema: (t.jsonSchema ??
650
+ zodToJsonSchema(t.inputSchema, {
651
+ $refStrategy: "none",
652
+ })),
653
+ }))
654
+ : undefined;
655
+ const toolByName = new Map(tools.map((t) => [t.name, t]));
656
+ // Root abort tree for the whole run; each turn gets a child.
657
+ const runAbort = createAbortTree(runContext.abortSignal);
658
+ // Per-turn abort tree, replaced at the start of each turn so a SIGINT
659
+ // during turn N doesn't leave turn N+1 born-aborted.
660
+ let turnAbort = runAbort.child();
661
+ // Latest error captured from a model call, fed to recover() on entry to NeedRecovery.
662
+ let lastErrorForRecovery = undefined;
663
+ // Permission-ask prompter. Set in REPL mode after the readline interface
664
+ // exists; remains undefined in single-turn mode (where ask collapses to deny).
665
+ // The initial assignment makes the second assignment legal under biome's
666
+ // `useConst` rule (which fires on exactly-one-assignment lets).
667
+ let askApproval = undefined;
668
+ // Per-run state for tool-loop detection and warning de-dup. Both span
669
+ // turns within a single `runChatLoop` invocation so cross-turn loops
670
+ // (e.g. "keep running date") get caught and warned at most once per
671
+ // signature.
672
+ const toolUseHistory = [];
673
+ const warnedLoopSignatures = new Set();
674
+ // Working-indicator bookkeeping for tool execution. A single shared spinner
675
+ // serves the whole loop, so the set tracks which tools are mid-flight to
676
+ // support the concurrent (read-only) partition: the label reflects how many
677
+ // run at once, and the animation only stops when the last one settles.
678
+ const activeToolNames = [];
679
+ const toolSpinnerLabel = () => activeToolNames.length === 1
680
+ ? `running ${activeToolNames[0]}`
681
+ : `running ${activeToolNames.length} tools`;
682
+ const beginToolWork = (name) => {
683
+ activeToolNames.push(name);
684
+ out.spinner.start(toolSpinnerLabel());
685
+ };
686
+ const endToolWork = (name) => {
687
+ const i = activeToolNames.indexOf(name);
688
+ if (i >= 0)
689
+ activeToolNames.splice(i, 1);
690
+ if (activeToolNames.length === 0)
691
+ out.spinner.stop();
692
+ else
693
+ out.spinner.setLabel(toolSpinnerLabel());
694
+ };
695
+ /**
696
+ * Execute one tool_use block end-to-end: permission gate → executeTool
697
+ * with the per-tool abort signal → wrap large output through
698
+ * `tool-result-store`. Returns a fully-formed `ToolResultBlockParam`
699
+ * suitable for appending to message history.
700
+ *
701
+ * Used by both the partitioned (post-stream) path and the streaming
702
+ * path so the permission/abort/store contract is uniform.
703
+ */
704
+ async function executeOneToolUse(tu) {
705
+ // End the "thinking" wait — but only when no tool is already mid-flight.
706
+ // The streaming executor dispatches concurrency-safe tools with overlap, so
707
+ // an unconditional stop here would tear down a sibling tool's live spinner;
708
+ // gate on the ref-count so we stop the thinking animation (none running)
709
+ // without disturbing a running-tools one. The header then goes through the
710
+ // spinner-aware sink, which erases+redraws around it so the persistent
711
+ // `[tool: …]` line sits cleanly above any animation that follows.
712
+ if (activeToolNames.length === 0)
713
+ out.spinner.stop();
714
+ out.write(`[tool: ${tu.name}]\n`);
715
+ await logEvent("tool_use", { id: tu.id, name: tu.name, input: tu.input });
716
+ const inputBytes = Buffer.byteLength(JSON.stringify(tu.input ?? null), "utf8");
717
+ const toolStartEnvelope = bus.envelope();
718
+ bus.publish({
719
+ ...toolStartEnvelope,
720
+ kind: "tool_call_start",
721
+ toolUseId: tu.id,
722
+ toolName: tu.name,
723
+ inputBytes,
724
+ });
725
+ const t0Tool = performance.now();
726
+ const tool = toolByName.get(tu.name);
727
+ const finish = async (result) => {
728
+ await logEvent("tool_result", {
729
+ toolUseId: tu.id,
730
+ content: typeof result.content === "string"
731
+ ? result.content
732
+ : summariseNonStringContent(result.content),
733
+ isError: result.is_error === true,
734
+ });
735
+ const outputContent = result.content;
736
+ const outputBytes = typeof outputContent === "string"
737
+ ? Buffer.byteLength(outputContent, "utf8")
738
+ : Buffer.byteLength(JSON.stringify(outputContent ?? null), "utf8");
739
+ bus.publish({
740
+ ...bus.envelope(),
741
+ spanId: toolStartEnvelope.spanId,
742
+ kind: "tool_call_end",
743
+ toolUseId: tu.id,
744
+ toolName: tu.name,
745
+ isError: result.is_error === true,
746
+ outputBytes,
747
+ durationMs: performance.now() - t0Tool,
748
+ });
749
+ // Section 11 — fire post-tool after the result is captured. Decision
750
+ // is observational here: a deny on post-tool logs a warning but does
751
+ // not rewrite the result (the model has already received it once on
752
+ // the prior turn in some streaming scenarios).
753
+ const post = await fireHook("post-tool", {
754
+ id: tu.id,
755
+ name: tu.name,
756
+ isError: result.is_error === true,
757
+ });
758
+ if (!post.allowed) {
759
+ runContext.logger.warn("post-tool hook denied", {
760
+ tool: tu.name,
761
+ reason: post.reason,
762
+ });
763
+ }
764
+ return result;
765
+ };
766
+ if (!tool) {
767
+ return finish({
768
+ type: "tool_result",
769
+ tool_use_id: tu.id,
770
+ content: `unknown tool "${tu.name}"`,
771
+ is_error: true,
772
+ });
773
+ }
774
+ // Section 11 — pre-tool hook: short-circuit with the hook's reason
775
+ // when any matching hook returns deny/block.
776
+ const preHook = await fireHook("pre-tool", { id: tu.id, name: tu.name, input: tu.input });
777
+ if (!preHook.allowed) {
778
+ return finish({
779
+ type: "tool_result",
780
+ tool_use_id: tu.id,
781
+ content: `[blocked by hook] ${preHook.reason ?? "denied"}`,
782
+ is_error: true,
783
+ });
784
+ }
785
+ const decisionDetails = evaluateWithReason({
786
+ toolName: tu.name,
787
+ input: tu.input,
788
+ readOnly: tool.readOnly,
789
+ destructive: tool.destructive,
790
+ requiresSandbox: tool.requiresSandbox,
791
+ }, permissionMode, permissionRules, { sandboxAvailable: opts.sandboxAvailable === true });
792
+ const decision = decisionDetails.decision;
793
+ bus.publish({
794
+ ...bus.envelope(),
795
+ kind: "permission_decision",
796
+ toolName: tu.name,
797
+ decision,
798
+ mode: permissionMode,
799
+ ...(decisionDetails.reason !== undefined ? { reason: decisionDetails.reason } : {}),
800
+ });
801
+ let approved = decision === "allow";
802
+ let denialMessage;
803
+ if (decision === "deny") {
804
+ denialMessage = decisionDetails.reason ?? "tool denied by permission policy";
805
+ }
806
+ else if (decision === "ask") {
807
+ if (askApproval !== undefined) {
808
+ approved = await askApproval(tu.name, tu.input);
809
+ if (!approved)
810
+ denialMessage = "tool denied by user";
811
+ }
812
+ else {
813
+ denialMessage =
814
+ `tool denied: \`${tu.name}\` defaulted to "ask" and single-turn mode has no interactive surface to prompt on. ` +
815
+ `Add an explicit rule to permissions.rules in your spec, e.g. \`{ type: alwaysAllow, pattern: ${tu.name} }\`, or run in REPL mode where "ask" can prompt.`;
816
+ }
817
+ }
818
+ if (!approved) {
819
+ return finish({
820
+ type: "tool_result",
821
+ tool_use_id: tu.id,
822
+ content: denialMessage ?? "tool denied",
823
+ is_error: true,
824
+ });
825
+ }
826
+ // Pillar 3 intent gate — when the tool descriptor demands a justification,
827
+ // require the model to include one in the input and evaluate it via the
828
+ // configured judge (rule-based by default; runtime callers can pass an
829
+ // LLM-backed judge for production). The justification is captured to
830
+ // audit-log verbatim. The session goal we compare against is the spec's
831
+ // `instructions` field — fixed at compile time, not influenced by runtime
832
+ // input, so an attacker who controls the user prompt cannot also
833
+ // re-define the goal under which their justification gets scored.
834
+ if (tool.requireJustification === true) {
835
+ const input = tu.input;
836
+ const rawJustification = input?.["justification"];
837
+ const justification = typeof rawJustification === "string" ? rawJustification : "";
838
+ const judge = opts.justificationJudge ?? ruleBasedJustificationJudge;
839
+ const verdict = await evaluateJustification({
840
+ toolName: tu.name,
841
+ justification,
842
+ sessionGoal: opts.instructions ?? "",
843
+ input: tu.input,
844
+ }, judge);
845
+ bus.publish({
846
+ ...bus.envelope(),
847
+ kind: "permission_decision",
848
+ toolName: tu.name,
849
+ decision: verdict.allow ? "allow" : "deny",
850
+ mode: permissionMode,
851
+ reason: `justification: ${verdict.reason} [judge=${verdict.judgeModel}]`,
852
+ // FR-004 — promote the judge identity (and confidence) to
853
+ // first-class fields on the canonical permission_decision event so
854
+ // the `permission_justification_evaluated` audit story records WHO
855
+ // judged, not just an embedded substring of `reason`. Absent on
856
+ // ordinary (non-justification) permission decisions.
857
+ judgeModel: verdict.judgeModel,
858
+ ...(verdict.confidence !== undefined
859
+ ? { justificationConfidence: verdict.confidence }
860
+ : {}),
861
+ });
862
+ runContext.logger.info("justification evaluated", {
863
+ toolUseId: tu.id,
864
+ toolName: tu.name,
865
+ allow: verdict.allow,
866
+ judgeModel: verdict.judgeModel,
867
+ confidence: verdict.confidence,
868
+ });
869
+ // FR-004 — emit the durable `permission_justification_evaluated` audit
870
+ // record. The trace event above is ephemeral; THIS is the hash-chained,
871
+ // tamper-evident artifact the AuditKind was created for. We append one
872
+ // record per justification-evaluated call (allow OR deny — the audit
873
+ // trail must capture denials too), storing the justification VERBATIM
874
+ // alongside the verdict and the judge identity, exactly the payload
875
+ // shape `@crewhaus/audit-log` documents for this kind. Best-effort but
876
+ // surfaced: an I/O failure on the audit trail is logged and swallowed so
877
+ // a full audit disk does not crash a governed run, mirroring how the
878
+ // egress fabric treats its own audit surface. Absent sink → no-op.
879
+ if (opts.justificationAuditSink !== undefined) {
880
+ try {
881
+ await opts.justificationAuditSink.append({
882
+ kind: "permission_justification_evaluated",
883
+ payload: {
884
+ toolName: tu.name,
885
+ justification,
886
+ verdict: verdict.allow ? "allow" : "deny",
887
+ reason: verdict.reason,
888
+ judgeModel: verdict.judgeModel,
889
+ ...(verdict.confidence !== undefined ? { confidence: verdict.confidence } : {}),
890
+ },
891
+ });
892
+ }
893
+ catch (err) {
894
+ runContext.logger.warn("justification audit append failed", {
895
+ toolUseId: tu.id,
896
+ toolName: tu.name,
897
+ error: err.message,
898
+ });
899
+ }
900
+ }
901
+ if (!verdict.allow) {
902
+ return finish({
903
+ type: "tool_result",
904
+ tool_use_id: tu.id,
905
+ content: `[justification denied] ${verdict.reason}. Reformulate the call with a justification that ties to the session's declared goal, or omit this tool from the call.`,
906
+ is_error: true,
907
+ });
908
+ }
909
+ }
910
+ // Pillar 3 sink-side fabric — for tools that transmit to an external
911
+ // sink, scan the input payload against the run-context's data-lineage
912
+ // map. A `block` verdict means the payload contains content that was
913
+ // tagged from a non-`"user"` origin and policy disallows transmission;
914
+ // we deny the call before it fires. `warn` logs but proceeds.
915
+ //
916
+ // Resolve the sink-scope so the egress block tier is actually reachable
917
+ // (#144): runtime-joined MCP sinks default to `"external-dynamic"` (block
918
+ // non-user-origin content), while spec-declared sinks stay
919
+ // `"external-configured"` (warn). Callers can override via
920
+ // `opts.resolveSinkScope` to mark federation-joined or other dynamic sinks.
921
+ if (tool.scope === "external") {
922
+ const payload = JSON.stringify(tu.input ?? null);
923
+ const sinkScope = (opts.resolveSinkScope ?? defaultSinkScope)(tu.name);
924
+ const egress = await classifyEgress(payload, runContext, {
925
+ sinkId: tu.name,
926
+ sinkScope,
927
+ // FR-006: forward the caller-selected matcher when present. Absent
928
+ // (every existing caller) → classifyEgress defaults to the
929
+ // substring matcher, so the scope gate / sinkScope / policy fold
930
+ // below are byte-for-byte unchanged.
931
+ ...(opts.egressMatcher !== undefined ? { matcher: opts.egressMatcher } : {}),
932
+ });
933
+ const egressOutcome = egress.verdict === "pass"
934
+ ? "egress-passed"
935
+ : egress.verdict === "warn"
936
+ ? "egress-warned"
937
+ : "egress-blocked";
938
+ bus.publish({
939
+ ...bus.envelope(),
940
+ kind: "permission_decision",
941
+ toolName: tu.name,
942
+ decision: egress.verdict === "block" ? "deny" : "allow",
943
+ mode: permissionMode,
944
+ outcome: egressOutcome,
945
+ ...(egress.originsFound.length > 0 ? { reason: `egress: ${summarizeEgress(egress)}` } : {}),
946
+ });
947
+ if (egress.verdict !== "pass") {
948
+ runContext.logger.warn("egress classification non-clean", {
949
+ toolUseId: tu.id,
950
+ toolName: tu.name,
951
+ verdict: egress.verdict,
952
+ originsFound: egress.originsFound,
953
+ matchCount: egress.matchCount,
954
+ });
955
+ }
956
+ if (egress.verdict === "block") {
957
+ return finish({
958
+ type: "tool_result",
959
+ tool_use_id: tu.id,
960
+ content: "[egress denied] outbound payload contains content tagged from a non-user origin under a strict-policy sink. " +
961
+ "Inspect the prior tool/sub-agent results that fed this call's input; the egress classifier's `dataLineage` records which boundary site introduced the flagged substring.",
962
+ is_error: true,
963
+ });
964
+ }
965
+ }
966
+ const toolAbort = turnAbort.child();
967
+ // Build the bridge for this call. Built on EVERY run (#160 follow-up):
968
+ // it carries `runContext`, which Pillar-3 boundary-site tools (tool-mcp,
969
+ // skills-registry) read to tag their external content's provenance under
970
+ // the precise "mcp"/"skill" origin. Previously the bridge was skipped
971
+ // unless `spawnSubAgent`/`crewMailbox` was injected, so a plain top-level
972
+ // run gave those tools no RunContext and their content fell back to the
973
+ // coarse "tool" origin. The Task-tool-only fields (`spawnSubAgent`,
974
+ // `crewMailbox`, `subAgents`) stay conditional — they're omitted when not
975
+ // wired, and the Task tool already checks for undefined before using them.
976
+ const bridge = {
977
+ runContext,
978
+ eventLog,
979
+ permissionMode,
980
+ permissionRules,
981
+ tools,
982
+ model: opts.model,
983
+ maxTokens,
984
+ ...(sessionRootDir !== undefined ? { sessionRootDir } : {}),
985
+ hooks,
986
+ ...(opts.subAgents !== undefined ? { subAgents: opts.subAgents } : {}),
987
+ ...(opts.spawnSubAgent !== undefined ? { spawnSubAgent: opts.spawnSubAgent } : {}),
988
+ ...(opts.crewMailbox !== undefined ? { crewMailbox: opts.crewMailbox } : {}),
989
+ };
990
+ // Spin "running <tool>…" for exactly the execution window — started after
991
+ // every gate (permission/justification/egress) so it never overlaps the
992
+ // approval prompt, and torn down in `.finally` on success or throw.
993
+ beginToolWork(tu.name);
994
+ const raw = await executeTool(tool, tu.input, {
995
+ toolUseId: tu.id,
996
+ signal: toolAbort.signal,
997
+ // #160 follow-up — the bridge (built on every run, above) carries
998
+ // `runContext`, which boundary-site tools (tool-mcp, skills-registry)
999
+ // read to tag their external content under the precise "mcp"/"skill"
1000
+ // origin. `tool-executor` forwards `bridge` verbatim; those tools read
1001
+ // `ctx.runContext` first and fall back to `ctx.bridge.runContext`, so
1002
+ // the bridge is what activates the precise tag today. (Threading
1003
+ // `runContext` as a first-class field on this call would also require
1004
+ // adding it to `tool-executor`'s `ExecutionContext`, which is owned
1005
+ // elsewhere; the bridge path needs no such change.)
1006
+ bridge,
1007
+ // Section 18 — runtime-core wires this so streaming tools
1008
+ // (`tool-code-execution`) can publish `tool_stream_chunk` events as
1009
+ // they pipe stdout/stderr from the sandbox container.
1010
+ onStreamChunk: (stream, chunk) => {
1011
+ bus.publish({
1012
+ ...bus.envelope(),
1013
+ spanId: toolStartEnvelope.spanId,
1014
+ kind: "tool_stream_chunk",
1015
+ toolUseId: tu.id,
1016
+ toolName: tu.name,
1017
+ stream,
1018
+ bytes: Buffer.byteLength(chunk, "utf8"),
1019
+ }, { ephemeral: true });
1020
+ },
1021
+ }).finally(() => endToolWork(tu.name));
1022
+ const toolResultRoot = resolveToolResultRoot();
1023
+ const stored = await storeAndPreview({ toolUseId: raw.toolUseId, content: raw.content, isError: raw.isError }, {
1024
+ runId: runContext.runId,
1025
+ toolUseId: tu.id,
1026
+ ...(toolResultRoot !== undefined ? { rootDir: toolResultRoot } : {}),
1027
+ });
1028
+ if (stored.persisted) {
1029
+ runContext.logger.info("tool result persisted", {
1030
+ toolUseId: tu.id,
1031
+ toolName: tu.name,
1032
+ fullPath: stored.fullPath,
1033
+ });
1034
+ }
1035
+ // Section 18 — post-tool prompt-injection classifier. Runs after the
1036
+ // tool result has been stored but before the model sees it. On a
1037
+ // malicious verdict the previewContent is replaced with a redaction
1038
+ // notice; on suspicious it's kept but the trace event records a
1039
+ // warning. Tools opt out by setting `classifyOutput: false` (only the
1040
+ // in-process Task wrapper does today).
1041
+ const finalPreview = await applyInjectionClassification(tool, tu, stored.previewContent);
1042
+ // Pillar 3 sink-side fabric — tag the (post-classification) tool result
1043
+ // into run-context's dataLineage so the egress classifier can detect
1044
+ // exfiltration of this content on a subsequent external-tool call.
1045
+ // Skipped for the in-process Task wrapper (`classifyOutput: false`)
1046
+ // because the sub-agent's finalMessage is already tagged at the
1047
+ // sub-agent-spawner boundary with the more-specific "subagent" origin.
1048
+ // MCP tools additionally tag their FULL response under the more-precise
1049
+ // "mcp" origin inside tool-mcp; since #160 follow-up the runtime threads
1050
+ // a RunContext (via `bridge`/`ctx.runContext`) on EVERY run, so that
1051
+ // precise tag now fires unconditionally. This coarse "tool" tag of the
1052
+ // (possibly truncated) preview still fires for them as a redundant
1053
+ // backstop so the content has lineage even if the precise tag is missed.
1054
+ // ERROR results are tagged too: an `is_error` tool result is just as
1055
+ // attacker-controllable and just as exfiltratable as a successful one, so
1056
+ // it must carry lineage (the `!raw.isError` skip here used to let the
1057
+ // egress fabric lose track of error-sourced content entirely).
1058
+ if (tool.classifyOutput !== false) {
1059
+ const taggable = typeof finalPreview === "string"
1060
+ ? finalPreview
1061
+ : finalPreview.map((b) => (b.type === "text" ? b.text : "")).join("\n");
1062
+ if (taggable.length > 0) {
1063
+ tagContent(runContext, taggable, "tool");
1064
+ }
1065
+ }
1066
+ return finish({
1067
+ type: "tool_result",
1068
+ tool_use_id: tu.id,
1069
+ // Section 14 — pass non-string content (image content arrays) through
1070
+ // verbatim so the model sees the image. Anthropic's ToolResultBlockParam
1071
+ // already accepts string | Array<TextBlockParam | ImageBlockParam>.
1072
+ content: typeof finalPreview === "string"
1073
+ ? finalPreview
1074
+ : finalPreview,
1075
+ is_error: raw.isError,
1076
+ });
1077
+ }
1078
+ /**
1079
+ * Section 18 — classify the previewContent we are about to hand to the
1080
+ * model. Returns the (possibly rewritten) content. Publishes
1081
+ * `permission_decision { outcome }` for any non-clean classification so
1082
+ * the audit trail records exactly what was redacted/warned.
1083
+ */
1084
+ let injectionWarningEmitted = false;
1085
+ async function applyInjectionClassification(tool, tu, previewContent) {
1086
+ // Runs on ALL tool results, including `is_error` ones: an error preview is
1087
+ // just as prompt-injectable as a successful one (e.g. an MCP error string),
1088
+ // so it must be scrubbed before the model sees it.
1089
+ if (tool.classifyOutput === false)
1090
+ return previewContent;
1091
+ // Concatenate text-only content for classification. Image blocks are
1092
+ // never injection vectors at the byte level we examine here.
1093
+ const textForClassification = typeof previewContent === "string"
1094
+ ? previewContent
1095
+ : previewContent.map((b) => (b.type === "text" ? b.text : "")).join("\n");
1096
+ if (textForClassification.length === 0)
1097
+ return previewContent;
1098
+ const llmEnabled = opts.promptInjectionLlmClassifier !== undefined && llmClassifierEnabled(process.env);
1099
+ const verdict = await classifyText(textForClassification, llmEnabled ? { llmClassifier: opts.promptInjectionLlmClassifier } : {});
1100
+ if (verdict.classification === "clean")
1101
+ return previewContent;
1102
+ const ruleIds = [...new Set(verdict.hits.map((h) => h.rule))];
1103
+ if (verdict.classification === "malicious") {
1104
+ const notice = buildRedactionNotice(verdict.hits);
1105
+ bus.publish({
1106
+ ...bus.envelope(),
1107
+ kind: "permission_decision",
1108
+ toolName: tu.name,
1109
+ decision: "allow",
1110
+ mode: permissionMode,
1111
+ outcome: "redacted",
1112
+ rules: ruleIds,
1113
+ reason: `prompt injection in tool output (${ruleIds.slice(0, 3).join(", ")})`,
1114
+ });
1115
+ runContext.logger.warn("tool output redacted (prompt injection detected)", {
1116
+ toolUseId: tu.id,
1117
+ toolName: tu.name,
1118
+ rules: ruleIds,
1119
+ });
1120
+ return notice;
1121
+ }
1122
+ // suspicious — keep content but emit a once-per-session warning.
1123
+ bus.publish({
1124
+ ...bus.envelope(),
1125
+ kind: "permission_decision",
1126
+ toolName: tu.name,
1127
+ decision: "allow",
1128
+ mode: permissionMode,
1129
+ outcome: "warned",
1130
+ rules: ruleIds,
1131
+ reason: `suspicious tool output (${ruleIds.slice(0, 3).join(", ")})`,
1132
+ });
1133
+ if (!injectionWarningEmitted) {
1134
+ injectionWarningEmitted = true;
1135
+ runContext.logger.warn("suspicious tool output — kept but flagged (further suspicious outputs in this session will not be re-warned)", { toolUseId: tu.id, toolName: tu.name, rules: ruleIds });
1136
+ }
1137
+ return previewContent;
1138
+ }
1139
+ /**
1140
+ * Section 14 — short summary used in the audit-log payload when a tool
1141
+ * returns a non-string content array (e.g. ReadImage's image block). The
1142
+ * full content still reaches the model via tool_result.content above; the
1143
+ * audit log just gets a length-aware tag.
1144
+ */
1145
+ // Takes the non-string member of ToolResultBlockParam["content"] — the
1146
+ // sole caller (`finish`) only invokes this on the non-string branch of a
1147
+ // `typeof result.content === "string"` ternary, so the string/undefined
1148
+ // case is statically excluded here and no dead guard is needed.
1149
+ function summariseNonStringContent(content) {
1150
+ let images = 0;
1151
+ let texts = 0;
1152
+ let other = 0;
1153
+ let totalChars = 0;
1154
+ for (const block of content) {
1155
+ if (block.type === "image") {
1156
+ images++;
1157
+ if (block.source.type === "base64")
1158
+ totalChars += block.source.data.length;
1159
+ }
1160
+ else if (block.type === "text") {
1161
+ texts++;
1162
+ totalChars += block.text.length;
1163
+ }
1164
+ else {
1165
+ other++;
1166
+ }
1167
+ }
1168
+ const parts = [];
1169
+ if (images > 0)
1170
+ parts.push(`${images} image block${images > 1 ? "s" : ""}`);
1171
+ if (texts > 0)
1172
+ parts.push(`${texts} text block${texts > 1 ? "s" : ""}`);
1173
+ if (other > 0)
1174
+ parts.push(`${other} other block${other > 1 ? "s" : ""}`);
1175
+ return `[${parts.join(", ")}, ${totalChars} chars]`;
1176
+ }
1177
+ /**
1178
+ * Run a list of tool calls honouring the orchestrator's partition:
1179
+ * concurrent-safe batches via `Promise.all`, then serial calls one at
1180
+ * a time. Results are returned in the original `toolUses` order so
1181
+ * they line up with the assistant turn's tool_use blocks.
1182
+ */
1183
+ async function runToolBatch(toolUses) {
1184
+ const partition = partitionToolCalls(toolUses, (n) => toolByName.get(n));
1185
+ runContext.logger.debug("tool partition", {
1186
+ concurrent: partition.concurrent.map((b) => b.length),
1187
+ serial: partition.serial.length,
1188
+ });
1189
+ // Map each tool_use's identity to its slot in the original order so
1190
+ // results can be placed back in order regardless of the
1191
+ // concurrent/serial execution shape. `partitionToolCalls` is total —
1192
+ // every input block lands in exactly one partition bucket — and
1193
+ // `executeOneToolUse` always resolves to a result, so every slot is
1194
+ // filled; there is no missing-result case to defend against.
1195
+ const indexByBlock = new Map();
1196
+ toolUses.forEach((tu, idx) => indexByBlock.set(tu, idx));
1197
+ const results = new Array(toolUses.length);
1198
+ for (const batch of partition.concurrent) {
1199
+ const settled = await Promise.all(batch.map((tu) => executeOneToolUse(tu)));
1200
+ batch.forEach((tu, i) => {
1201
+ // biome-ignore lint/style/noNonNullAssertion: every block came from toolUses, so its index is registered.
1202
+ results[indexByBlock.get(tu)] = settled[i];
1203
+ });
1204
+ }
1205
+ for (const tu of partition.serial) {
1206
+ // biome-ignore lint/style/noNonNullAssertion: every block came from toolUses, so its index is registered.
1207
+ results[indexByBlock.get(tu)] = await executeOneToolUse(tu);
1208
+ }
1209
+ return results;
1210
+ }
1211
+ /**
1212
+ * Convert a freshly-detected loop into a synthetic user message that
1213
+ * nudges the model to break the cycle. Returns `null` if no loop is
1214
+ * currently detected, or if this signature has already produced a
1215
+ * warning earlier in the run.
1216
+ */
1217
+ function maybeBuildLoopWarning() {
1218
+ const detection = detectLoop(toolUseHistory);
1219
+ if (detection === null)
1220
+ return null;
1221
+ if (warnedLoopSignatures.has(detection.signature))
1222
+ return null;
1223
+ warnedLoopSignatures.add(detection.signature);
1224
+ runContext.logger.warn("tool loop detected", {
1225
+ signature: detection.signature,
1226
+ toolName: detection.toolName,
1227
+ count: detection.count,
1228
+ });
1229
+ return {
1230
+ role: "user",
1231
+ content: `[runtime] possible loop detected: tool "${detection.toolName}" has been called ${detection.count} times with the same input within the last ${detection.windowSize} calls. Reconsider before repeating; respond with a different approach or final text.`,
1232
+ };
1233
+ }
1234
+ /**
1235
+ * Run one user→assistant turn through the state machine. Mutates
1236
+ * `messages` in place (pushes the assistant turn and any tool_results).
1237
+ * Returns the final assistant content blocks so callers can extract
1238
+ * text. Closes over client/model/maxTokens/etc.
1239
+ */
1240
+ async function runOneTurn(messages) {
1241
+ let state = initialState;
1242
+ let terminalContent = [];
1243
+ let recovery = initialRecoveryState;
1244
+ const maxToolIterations = opts.maxToolIterations ?? DEFAULT_MAX_TOOL_ITERATIONS;
1245
+ let toolIterations = 0;
1246
+ while (state.kind !== "Done") {
1247
+ if (turnAbort.signal.aborted) {
1248
+ state = transition(state, { kind: "Aborted" });
1249
+ continue;
1250
+ }
1251
+ switch (state.kind) {
1252
+ case "NeedModel": {
1253
+ out.write("agent> ");
1254
+ // Section 11 — pre-model hook. Deny short-circuits the turn with
1255
+ // a synthetic "[blocked by hook]" assistant message so the loop
1256
+ // exits cleanly (state transitions through ModelReturnedText →
1257
+ // Done(no_tools)).
1258
+ const preModel = await fireHook("pre-model", {
1259
+ model: opts.model,
1260
+ streaming: opts.streaming === true,
1261
+ messageCount: messages.length,
1262
+ });
1263
+ if (!preModel.allowed) {
1264
+ const blockedText = `[blocked by hook] ${preModel.reason ?? "denied"}`;
1265
+ out.write(`${blockedText}\n`);
1266
+ const blockedBlock = {
1267
+ type: "text",
1268
+ text: blockedText,
1269
+ citations: null,
1270
+ };
1271
+ messages.push({ role: "assistant", content: [blockedBlock] });
1272
+ await logEvent("assistant_message", { content: [blockedBlock] });
1273
+ terminalContent = [blockedBlock];
1274
+ state = transition(state, { kind: "ModelReturnedText" });
1275
+ break;
1276
+ }
1277
+ // Animate "thinking…" through the model wait. The `agent> ` prefix
1278
+ // is kept across redraws and left behind when the spinner stops on
1279
+ // the first text delta (`writeText`) or tool header — so the silent
1280
+ // gap before the model responds now shows live progress. Cleared in
1281
+ // the catch below on any model-call error.
1282
+ out.spinner.start("thinking", { prefix: "agent> " });
1283
+ try {
1284
+ // Section 27 — rate-limit the model call before opening the
1285
+ // stream. The keys are caller-configured (typically
1286
+ // `[provider, tenant?]`); a missing bucket fails closed and
1287
+ // surfaces the RateLimitError up to recovery-engine.
1288
+ if (opts.rateLimiter && opts.rateLimitKeys && opts.rateLimitKeys.length > 0) {
1289
+ await opts.rateLimiter.acquire(opts.rateLimitKeys, 1);
1290
+ }
1291
+ const modelStartEnv = bus.envelope();
1292
+ // Section 27 — `model` carries the WIRE model id (the stripped
1293
+ // form the provider bills against, e.g. `bedrock/us.anthropic.…`
1294
+ // → `us.anthropic.…`) so cost-tracker pricing lookups and the
1295
+ // OTel `gen_ai.request.model` attribute match; the original
1296
+ // spec string rides along as `specModel` when it differs.
1297
+ bus.publish({
1298
+ ...modelStartEnv,
1299
+ kind: "model_request",
1300
+ model: wireModelId,
1301
+ ...(opts.model !== wireModelId ? { specModel: opts.model } : {}),
1302
+ provider: providerId,
1303
+ messageCount: messages.length,
1304
+ toolCount: anthropicTools?.length ?? 0,
1305
+ streaming: opts.streaming === true,
1306
+ });
1307
+ const t0Model = performance.now();
1308
+ let streamChunkIndex = 0;
1309
+ // Section 17 — `adapter.stream(req)` returns
1310
+ // `AsyncIterable<StreamEvent>`; we accumulate via
1311
+ // `consumeStream` (callbacks for stdout streaming + token
1312
+ // telemetry) and pull the final canonical message at the
1313
+ // end. The canonical content blocks are wire-compatible
1314
+ // with `Anthropic.ContentBlock` so existing message-history
1315
+ // bookkeeping continues to work.
1316
+ // Note: `messages` is `Anthropic.MessageParam[]` whose
1317
+ // content union is structurally a superset of canonical
1318
+ // (it includes `document`, deprecated `tool_result`
1319
+ // shapes, etc.). Cast to the canonical surface — the
1320
+ // bookkeeping is wire-compatible for the block kinds we
1321
+ // actually consume (text / image / tool_use / tool_result
1322
+ // / thinking).
1323
+ const reqStream = adapter.stream({
1324
+ model: wireModelId,
1325
+ system: systemBlocks.map((b) => ({
1326
+ type: "text",
1327
+ text: b.text,
1328
+ ...(b.cache_control !== undefined ? { cache_control: b.cache_control } : {}),
1329
+ })),
1330
+ messages: messages,
1331
+ tools: anthropicTools !== undefined
1332
+ ? anthropicTools.map((t) => ({
1333
+ name: t.name,
1334
+ description: t.description ?? "",
1335
+ input_schema: t.input_schema,
1336
+ }))
1337
+ : undefined,
1338
+ maxTokens,
1339
+ signal: turnAbort.signal,
1340
+ });
1341
+ if (opts.streaming) {
1342
+ // Streaming path: dispatch tools mid-stream via the
1343
+ // refactored streaming-tool-executor (now consumes
1344
+ // AsyncIterable<StreamEvent> directly).
1345
+ void modelStartEnv;
1346
+ const onTextDelta = (chunk) => {
1347
+ writeText(chunk);
1348
+ bus.publish({
1349
+ ...bus.envelope(),
1350
+ kind: "model_stream_token",
1351
+ chunkIndex: streamChunkIndex++,
1352
+ deltaChars: chunk.length,
1353
+ }, { ephemeral: true });
1354
+ };
1355
+ const { finalContent, toolResults, stopReason, usage } = await executeStreaming(reqStream, {
1356
+ toolByName,
1357
+ abortSignal: turnAbort.signal,
1358
+ onTextDelta,
1359
+ runTool: (block) => executeOneToolUse({
1360
+ id: block.id,
1361
+ name: block.name,
1362
+ input: block.input,
1363
+ }),
1364
+ onEvent: (e) => {
1365
+ runContext.logger.debug("streaming-tool", { ...e });
1366
+ },
1367
+ });
1368
+ endTurn();
1369
+ // On `stop_reason: "max_tokens"` the model may have been cut off
1370
+ // mid-`tool_use`; the streaming executor only runs a call once its
1371
+ // input JSON closes, so a truncated call has no `tool_result`.
1372
+ // Strip such orphans before they enter history — an unanswered
1373
+ // `tool_use` 400s every later request (see the non-streaming path
1374
+ // and `sanitizeOrphanToolUses`).
1375
+ const answeredStreamIds = new Set(toolResults
1376
+ .map((r) => r.tool_use_id)
1377
+ .filter((id) => typeof id === "string"));
1378
+ const committedStreamContent = stopReason === "max_tokens"
1379
+ ? finalContent.filter((b) => b.type !== "tool_use" ||
1380
+ (b.id !== undefined &&
1381
+ answeredStreamIds.has(b.id)))
1382
+ : finalContent;
1383
+ if (committedStreamContent.length > 0) {
1384
+ messages.push({
1385
+ role: "assistant",
1386
+ content: committedStreamContent,
1387
+ });
1388
+ await logEvent("assistant_message", { content: committedStreamContent });
1389
+ }
1390
+ terminalContent = [...committedStreamContent];
1391
+ bus.publish({
1392
+ ...bus.envelope(),
1393
+ spanId: modelStartEnv.spanId,
1394
+ kind: "model_response",
1395
+ // Wire model id, NOT the spec string — cost-tracker resolves
1396
+ // pricing on this field (see the model_request publish above).
1397
+ model: wireModelId,
1398
+ ...(opts.model !== wireModelId ? { specModel: opts.model } : {}),
1399
+ provider: providerId,
1400
+ stopReason: stopReason ?? "end_turn",
1401
+ usage,
1402
+ durationMs: performance.now() - t0Model,
1403
+ });
1404
+ await fireHook("post-model", {
1405
+ streaming: true,
1406
+ contentBlocks: finalContent.length,
1407
+ });
1408
+ const toolUses = committedStreamContent.filter((b) => b.type === "tool_use");
1409
+ if (toolUses.length === 0) {
1410
+ state = transition(state, { kind: "ModelReturnedText" });
1411
+ break;
1412
+ }
1413
+ for (const tu of toolUses) {
1414
+ toolUseHistory.push({ id: tu.id, name: tu.name, input: tu.input });
1415
+ }
1416
+ messages.push({ role: "user", content: [...toolResults] });
1417
+ await logEvent("user_message", { content: [...toolResults] });
1418
+ const warning = maybeBuildLoopWarning();
1419
+ if (warning !== null) {
1420
+ messages.push(warning);
1421
+ await logEvent("user_message", { content: warning.content });
1422
+ }
1423
+ // Synthesize the two transitions the state machine expects:
1424
+ // tools have already executed during the stream so we
1425
+ // collapse ModelReturnedToolUse → ToolsExecuted into a
1426
+ // single hop back to NeedModel.
1427
+ const tsmBlocks = toolUses.map((t) => ({
1428
+ id: t.id,
1429
+ name: t.name,
1430
+ input: t.input,
1431
+ }));
1432
+ state = transition(state, { kind: "ModelReturnedToolUse", toolUses: tsmBlocks });
1433
+ state = transition(state, { kind: "ToolsExecuted" });
1434
+ break;
1435
+ }
1436
+ // Non-streaming path: drain the AsyncIterable into a final
1437
+ // `ProviderMessage` while emitting text deltas to stdout.
1438
+ const final = await consumeStream(reqStream, {
1439
+ onTextDelta: (chunk) => {
1440
+ writeText(chunk);
1441
+ bus.publish({
1442
+ ...bus.envelope(),
1443
+ kind: "model_stream_token",
1444
+ chunkIndex: streamChunkIndex++,
1445
+ deltaChars: chunk.length,
1446
+ }, { ephemeral: true });
1447
+ },
1448
+ });
1449
+ endTurn();
1450
+ bus.publish({
1451
+ ...bus.envelope(),
1452
+ spanId: modelStartEnv.spanId,
1453
+ kind: "model_response",
1454
+ // Wire model id, NOT the spec string — cost-tracker resolves
1455
+ // pricing on this field (see the model_request publish above).
1456
+ model: wireModelId,
1457
+ ...(opts.model !== wireModelId ? { specModel: opts.model } : {}),
1458
+ provider: providerId,
1459
+ stopReason: final.stopReason,
1460
+ usage: final.usage,
1461
+ durationMs: performance.now() - t0Model,
1462
+ });
1463
+ // Persist the assistant turn. On a clean stop the FULL content-block
1464
+ // array is committed so subsequent `tool_result` references resolve.
1465
+ //
1466
+ // On `stop_reason: "max_tokens"` the model was cut off mid-reply, so
1467
+ // any `tool_use` it emitted is necessarily un-executed — the
1468
+ // truncation routes to recovery below, BEFORE the `NeedTools` state
1469
+ // runs a tool — and its input is truncated / `__parse_error`
1470
+ // garbage. Committing such an orphan `tool_use` would make every
1471
+ // later request 400 ("tool_use ids ... without tool_result blocks
1472
+ // immediately after"); the recovery loop cannot clear that by
1473
+ // appending a text nudge, so the run bricks once the tombstone
1474
+ // budget is spent. Strip the orphan here, before it enters either
1475
+ // in-memory history OR the resumable event log.
1476
+ const truncatedTurn = final.stopReason === "max_tokens";
1477
+ const committedContent = truncatedTurn
1478
+ ? final.content.filter((b) => b.type !== "tool_use")
1479
+ : final.content;
1480
+ if (committedContent.length > 0) {
1481
+ messages.push({
1482
+ role: "assistant",
1483
+ content: committedContent,
1484
+ });
1485
+ await logEvent("assistant_message", { content: committedContent });
1486
+ }
1487
+ terminalContent = [...committedContent];
1488
+ await fireHook("post-model", {
1489
+ streaming: false,
1490
+ stopReason: final.stopReason,
1491
+ contentBlocks: final.content.length,
1492
+ });
1493
+ // Synthetic max_output_tokens recovery: route the truncation through
1494
+ // the recovery state machine so we ask the model to continue. The
1495
+ // orphan `tool_use` (if any) was stripped above, so the `continue`
1496
+ // nudge produces an API-valid next request.
1497
+ if (truncatedTurn) {
1498
+ lastErrorForRecovery = {
1499
+ name: "MaxTokensError",
1500
+ error: { type: "max_output_tokens" },
1501
+ message: "stop_reason: max_tokens",
1502
+ };
1503
+ state = transition(state, {
1504
+ kind: "RecoverableError",
1505
+ error: { name: "MaxTokensError", message: "stop_reason: max_tokens" },
1506
+ });
1507
+ break;
1508
+ }
1509
+ const toolUses = final.content.filter((b) => b.type === "tool_use");
1510
+ if (toolUses.length === 0) {
1511
+ state = transition(state, { kind: "ModelReturnedText" });
1512
+ }
1513
+ else {
1514
+ const tsmBlocks = toolUses.map((t) => ({
1515
+ id: t.id,
1516
+ name: t.name,
1517
+ input: t.input,
1518
+ }));
1519
+ for (const tu of tsmBlocks)
1520
+ toolUseHistory.push(tu);
1521
+ state = transition(state, { kind: "ModelReturnedToolUse", toolUses: tsmBlocks });
1522
+ }
1523
+ }
1524
+ catch (err) {
1525
+ // Tear down the "thinking" animation before any error/abort output.
1526
+ out.spinner.stop();
1527
+ if (isAbortError(err)) {
1528
+ state = transition(state, { kind: "Aborted" });
1529
+ break;
1530
+ }
1531
+ lastErrorForRecovery = err;
1532
+ const errObj = err;
1533
+ const errorName = typeof errObj.name === "string" ? errObj.name : "Error";
1534
+ const errorMessage = typeof errObj.message === "string" ? errObj.message : String(err);
1535
+ await logEvent("error", { name: errorName, message: errorMessage });
1536
+ state = transition(state, {
1537
+ kind: "RecoverableError",
1538
+ error: { name: errorName, message: errorMessage },
1539
+ });
1540
+ }
1541
+ break;
1542
+ }
1543
+ case "NeedTools": {
1544
+ toolIterations += 1;
1545
+ if (toolIterations > maxToolIterations) {
1546
+ // Enforcing loop bound — the advisory loop-detector can't stop a
1547
+ // runaway tool loop (it only warns and is defeated by argument
1548
+ // churn), so fail closed here.
1549
+ await logEvent("error", {
1550
+ name: "ToolLoopLimit",
1551
+ message: `aborting turn: exceeded maxToolIterations (${maxToolIterations}) — possible runaway tool loop`,
1552
+ });
1553
+ runContext.logger.error("tool-iteration cap exceeded — aborting turn", {
1554
+ maxToolIterations,
1555
+ });
1556
+ state = transition(state, { kind: "Aborted" });
1557
+ break;
1558
+ }
1559
+ const toolResults = await runToolBatch(state.toolUses);
1560
+ messages.push({ role: "user", content: toolResults });
1561
+ await logEvent("user_message", { content: toolResults });
1562
+ const warning = maybeBuildLoopWarning();
1563
+ if (warning !== null) {
1564
+ messages.push(warning);
1565
+ await logEvent("user_message", { content: warning.content });
1566
+ }
1567
+ state = transition(state, { kind: "ToolsExecuted" });
1568
+ break;
1569
+ }
1570
+ // NOTE: there is no `case "NeedCompaction"` here, and it is
1571
+ // unreachable by construction: the turn-state-machine only enters
1572
+ // `NeedCompaction` on a `BudgetExceeded` event, and this loop never
1573
+ // emits one — pre-turn compaction runs outside the state machine (see
1574
+ // `maybeCompact`) and in-turn reactive compaction is handled inline by
1575
+ // the `compact` recovery action below. If a future change starts
1576
+ // emitting `BudgetExceeded` from `runOneTurn`, restore a
1577
+ // `NeedCompaction` → `CompactionDone` arm (and cover it) here.
1578
+ case "NeedRecovery": {
1579
+ const action = recover(lastErrorForRecovery, recovery);
1580
+ recovery = advanceState(recovery, action);
1581
+ runContext.logger.info("recovery.action", {
1582
+ kind: action.kind,
1583
+ errorName: state.error.name,
1584
+ recoveryDepth: recovery.retryCount + recovery.compactCount + recovery.continueCount,
1585
+ });
1586
+ bus.publish({
1587
+ ...bus.envelope(),
1588
+ kind: "error_recovered",
1589
+ action: action.kind,
1590
+ errorName: state.error.name,
1591
+ depth: recovery.retryCount + recovery.compactCount + recovery.continueCount,
1592
+ });
1593
+ switch (action.kind) {
1594
+ case "compact": {
1595
+ const before = messages.length;
1596
+ await fireHook("pre-compact", { kind: "reactive", before });
1597
+ // Reactive compaction summarizes via a model call — show the wait.
1598
+ out.spinner.start("compacting context");
1599
+ const compacted = await forceCompact({
1600
+ messages,
1601
+ adapter: compactionAdapter,
1602
+ model: compactionWireModelId,
1603
+ snipKeepHead,
1604
+ snipKeepTail,
1605
+ logger: runContext.logger,
1606
+ }).finally(() => out.spinner.stop());
1607
+ messages.length = 0;
1608
+ messages.push(...compacted);
1609
+ await logEvent("compaction", {
1610
+ kind: "reactive",
1611
+ before,
1612
+ after: messages.length,
1613
+ });
1614
+ bus.publish({
1615
+ ...bus.envelope(),
1616
+ kind: "compaction_fired",
1617
+ subKind: "reactive",
1618
+ before,
1619
+ after: messages.length,
1620
+ phase: "reactive",
1621
+ });
1622
+ await fireHook("post-compact", {
1623
+ kind: "reactive",
1624
+ before,
1625
+ after: messages.length,
1626
+ });
1627
+ state = transition(state, { kind: "RecoveryDone" });
1628
+ break;
1629
+ }
1630
+ case "retry":
1631
+ // Surface the back-off wait instead of stalling silently.
1632
+ out.spinner.start("retrying");
1633
+ await new Promise((resolve) => setTimeout(resolve, action.delayMs));
1634
+ out.spinner.stop();
1635
+ state = transition(state, { kind: "RecoveryDone" });
1636
+ break;
1637
+ case "continue": {
1638
+ const continueMsg = "Please continue from where you left off.";
1639
+ messages.push({ role: "user", content: continueMsg });
1640
+ await logEvent("user_message", { content: continueMsg });
1641
+ state = transition(state, { kind: "RecoveryDone" });
1642
+ break;
1643
+ }
1644
+ case "tombstone": {
1645
+ // A tombstone fires on an `invalid_request` (400) from the model
1646
+ // call. The dominant cause is a dangling `tool_use` with no
1647
+ // answering `tool_result` — an orphan the model left when a
1648
+ // `stop_reason: "max_tokens"` cut it off mid-call. (The earlier
1649
+ // claim that the assistant stream is "atomic w.r.t. history" was
1650
+ // wrong: the `max_tokens` path commits the assistant turn and THEN
1651
+ // routes here. The non-streaming path now strips orphans at the
1652
+ // source, but a streaming truncation or a resumed pre-fix session
1653
+ // can still surface one.) Appending a text nudge alone does NOT
1654
+ // clear that 400 — the orphan stays in history and every retry
1655
+ // 400s again until the tombstone budget is spent and the run
1656
+ // bricks. So reconcile FIRST: drop any orphan `tool_use`, then
1657
+ // append the retry nudge. No-op on a healthy history, where the
1658
+ // nudge handles a genuinely malformed block as before.
1659
+ const reconciled = sanitizeOrphanToolUses(messages);
1660
+ if (reconciled.removed > 0) {
1661
+ messages.length = 0;
1662
+ messages.push(...reconciled.messages);
1663
+ runContext.logger.info("recovery.tombstone reconciled orphan tool_use", {
1664
+ removed: reconciled.removed,
1665
+ });
1666
+ }
1667
+ const tombstoneMsg = "[previous assistant turn was rejected as invalid; please retry]";
1668
+ messages.push({ role: "user", content: tombstoneMsg });
1669
+ await logEvent("user_message", { content: tombstoneMsg });
1670
+ state = transition(state, { kind: "RecoveryDone" });
1671
+ break;
1672
+ }
1673
+ case "fail":
1674
+ throw new RuntimeError(`recovery failed: ${action.reason}`);
1675
+ }
1676
+ break;
1677
+ }
1678
+ }
1679
+ }
1680
+ return { terminalContent };
1681
+ }
1682
+ // Single-shot path used by the workflow target and (Section 12) the
1683
+ // channel-bot session router. Runs one user→assistant turn (with the tool
1684
+ // inner-loop until Done), persists the transcript, returns the terminal
1685
+ // assistant text. Never reads stdin.
1686
+ if (opts.singleTurn) {
1687
+ const seed = opts.seedMessages ?? [];
1688
+ const last = seed[seed.length - 1];
1689
+ if (!last || last.role !== "user") {
1690
+ throw new RuntimeError('runChatLoop({ singleTurn: true }) requires `seedMessages` to end with a `role: "user"` entry');
1691
+ }
1692
+ try {
1693
+ // When resuming, the replayed event-log history becomes the prefix
1694
+ // (already on disk — never re-logged). The seed is the new turn's
1695
+ // input, appended at the end. Without resume (workflow target), the
1696
+ // seed IS the entire turn and is logged through.
1697
+ const replayed = resumedMessages ?? [];
1698
+ let messages = [...replayed, ...seed];
1699
+ for (const m of seed) {
1700
+ if (m.role === "user") {
1701
+ await logEvent("user_message", { content: m.content });
1702
+ }
1703
+ else if (m.role === "assistant") {
1704
+ await logEvent("assistant_message", { content: m.content });
1705
+ }
1706
+ }
1707
+ runContext.turnNumber += 1;
1708
+ bus.setTurnNumber(runContext.turnNumber);
1709
+ const t0SingleTurn = performance.now();
1710
+ bus.publish({
1711
+ ...bus.envelope(),
1712
+ kind: "turn_start",
1713
+ turn: runContext.turnNumber,
1714
+ messageCount: messages.length,
1715
+ });
1716
+ runContext.logger.debug("turn start (single)", {
1717
+ turn: runContext.turnNumber,
1718
+ messages: messages.length,
1719
+ });
1720
+ messages = await maybeCompact({
1721
+ messages,
1722
+ adapter: compactionAdapter,
1723
+ model: compactionWireModelId,
1724
+ contextLimit,
1725
+ compactionThreshold,
1726
+ snipKeepHead,
1727
+ snipKeepTail,
1728
+ logger: runContext.logger,
1729
+ }, async (info) => {
1730
+ await logEvent("compaction", info);
1731
+ bus.publish({
1732
+ ...bus.envelope(),
1733
+ kind: "compaction_fired",
1734
+ subKind: info.kind,
1735
+ before: info.before,
1736
+ after: info.after,
1737
+ phase: "pre-turn",
1738
+ });
1739
+ // Fire one pre-compact (info has the before-count from the work
1740
+ // that just ran) followed by post-compact. Pre-compact in this
1741
+ // path is observational — by the time onCompaction fires the
1742
+ // step has already happened — but the pair lets hooks see both
1743
+ // events for symmetry with the reactive path.
1744
+ await fireHook("pre-compact", { ...info, phase: "pre-turn" });
1745
+ await fireHook("post-compact", { ...info, phase: "pre-turn" });
1746
+ });
1747
+ const { terminalContent } = await runOneTurn(messages);
1748
+ bus.publish({
1749
+ ...bus.envelope(),
1750
+ kind: "turn_end",
1751
+ turn: runContext.turnNumber,
1752
+ durationMs: performance.now() - t0SingleTurn,
1753
+ });
1754
+ return terminalContent
1755
+ .filter((b) => b.type === "text")
1756
+ .map((b) => b.text)
1757
+ .join("");
1758
+ }
1759
+ finally {
1760
+ out.spinner.stop();
1761
+ await fireHook("stop", {
1762
+ sessionId,
1763
+ turnCount: runContext.turnNumber,
1764
+ reason: "complete",
1765
+ });
1766
+ await subscribers.flushAll();
1767
+ await subscribers.shutdownAll();
1768
+ costPersistUnsubscribe?.();
1769
+ await sessionStore
1770
+ .update(sessionId, { lastTurnIndex: runContext.turnNumber })
1771
+ .catch((err) => {
1772
+ runContext.logger.warn("session-store: lastTurnIndex update failed", {
1773
+ error: err.message,
1774
+ });
1775
+ });
1776
+ await eventLog.close();
1777
+ }
1778
+ }
1779
+ // REPL mode (existing behavior). When resuming, the prior session's
1780
+ // transcript becomes the seed; otherwise honour any caller-supplied
1781
+ // seedMessages.
1782
+ let messages = resumedMessages
1783
+ ? [...resumedMessages]
1784
+ : opts.seedMessages
1785
+ ? [...opts.seedMessages]
1786
+ : [];
1787
+ const rl = readline.createInterface({
1788
+ input: opts.input ?? process.stdin,
1789
+ output: process.stdout,
1790
+ });
1791
+ // EOF on stdin (e.g. when input is piped in non-interactively) auto-closes
1792
+ // the readline interface. The next `rl.question` call would then crash with
1793
+ // ERR_USE_AFTER_CLOSE, so race each prompt against the close event and
1794
+ // also catch the post-close throw — close can fire either before we issue
1795
+ // the next prompt or while we're already awaiting one.
1796
+ const STDIN_CLOSED = Symbol("stdin-closed");
1797
+ const closedSignal = new Promise((resolve) => {
1798
+ rl.once("close", () => resolve(STDIN_CLOSED));
1799
+ });
1800
+ // Wire the permission-ask prompter once the readline interface exists.
1801
+ // Treats a closed stdin as "deny" so a piped non-interactive input does
1802
+ // not stall on the approval prompt.
1803
+ askApproval = async (toolName, input) => {
1804
+ const inputPreview = JSON.stringify(input).slice(0, 200);
1805
+ try {
1806
+ const result = await Promise.race([
1807
+ rl.question(`approve ${toolName} ${inputPreview} [y/N] > `),
1808
+ closedSignal,
1809
+ ]);
1810
+ if (result === STDIN_CLOSED)
1811
+ return false;
1812
+ const normalized = result.trim().toLowerCase();
1813
+ return normalized === "y" || normalized === "yes";
1814
+ }
1815
+ catch (err) {
1816
+ if (err.code === "ERR_USE_AFTER_CLOSE")
1817
+ return false;
1818
+ throw err;
1819
+ }
1820
+ };
1821
+ const providerNote = providerId === "anthropic" ? "" : ` [${providerId}]`;
1822
+ process.stdout.write(`agent ready (model: ${opts.model})${providerNote}. type "exit" to quit.\n`);
1823
+ // M3.2 — plan-mode UX indicator. When `permissions.mode: plan` is
1824
+ // active, the LLM-policy permission engine is the gate; show the
1825
+ // user it's on so they know destructive tools will be pushed back on.
1826
+ if (permissionMode === "plan") {
1827
+ process.stdout.write("\x1b[1m\x1b[33m[plan mode]\x1b[0m destructive tools (Write, Edit, Bash) gate through LLM policy; type a request to plan, then approve before execution.\n");
1828
+ }
1829
+ else if (permissionMode === "auto") {
1830
+ process.stdout.write("\x1b[1m\x1b[35m[auto mode]\x1b[0m all rules apply, no prompts — the agent acts under your declared permissions.\n");
1831
+ }
1832
+ else if (permissionMode === "bypass") {
1833
+ process.stdout.write("\x1b[1m\x1b[31m[BYPASS mode]\x1b[0m all permission rules are disabled. Use only on isolated machines.\n");
1834
+ }
1835
+ // SIGINT handler: first press during a turn aborts the turn; second
1836
+ // press exits. Counter resets at the start of each new turn. Default-on
1837
+ // whenever the runtime owns process.stdin (i.e. the test option
1838
+ // `opts.input` is unset). Tests that supply their own input stream skip
1839
+ // installation so they don't interfere with the test runner's signals.
1840
+ const shouldInstallSigint = opts.installSigintHandler ?? opts.input === undefined;
1841
+ let sigintPresses = 0;
1842
+ const sigintHandler = () => {
1843
+ // Clear any live animation (and restore the cursor) before the notice.
1844
+ out.spinner.stop();
1845
+ sigintPresses += 1;
1846
+ if (sigintPresses === 1) {
1847
+ out.write("\n[turn aborted; press Ctrl-C again to exit]\n");
1848
+ turnAbort.abort();
1849
+ }
1850
+ else {
1851
+ out.write("\n[exiting]\n");
1852
+ process.exit(130);
1853
+ }
1854
+ };
1855
+ if (shouldInstallSigint) {
1856
+ process.on("SIGINT", sigintHandler);
1857
+ }
1858
+ try {
1859
+ while (true) {
1860
+ if (runAbort.signal.aborted)
1861
+ break;
1862
+ // Fresh turn-abort tree so a previous turn's abort doesn't bleed in.
1863
+ turnAbort = runAbort.child();
1864
+ sigintPresses = 0;
1865
+ let userInput;
1866
+ try {
1867
+ const result = await Promise.race([rl.question("\nyou> "), closedSignal]);
1868
+ if (result === STDIN_CLOSED)
1869
+ break;
1870
+ userInput = result.trim();
1871
+ }
1872
+ catch (err) {
1873
+ if (err.code === "ERR_USE_AFTER_CLOSE")
1874
+ break;
1875
+ throw err;
1876
+ }
1877
+ if (userInput === "")
1878
+ continue;
1879
+ if (userInput === "exit" || userInput === "quit")
1880
+ break;
1881
+ // Section 11 — slash-command expansion. When the user input matches
1882
+ // a registered slash command, the markdown body (with $ARGUMENTS
1883
+ // substitution) becomes the effective user message. A `pre-slash`
1884
+ // hook fires first; deny falls through with the original input,
1885
+ // mutate.expanded overrides the substituted text.
1886
+ let effectiveInput = userInput;
1887
+ if (opts.slashCommands && opts.slashCommands.size > 0) {
1888
+ const slash = expandSlash(userInput, opts.slashCommands);
1889
+ if (slash.handled) {
1890
+ const decision = await fireHook("pre-slash", {
1891
+ name: slash.command?.name,
1892
+ arguments: slash.arguments,
1893
+ expanded: slash.expanded,
1894
+ });
1895
+ if (decision.allowed) {
1896
+ const override = decision.mutate?.["expanded"];
1897
+ effectiveInput = typeof override === "string" ? override : slash.expanded;
1898
+ }
1899
+ else {
1900
+ runContext.logger.info("pre-slash hook denied", {
1901
+ name: slash.command?.name,
1902
+ reason: decision.reason,
1903
+ });
1904
+ }
1905
+ }
1906
+ }
1907
+ messages.push({ role: "user", content: effectiveInput });
1908
+ await logEvent("user_message", { content: effectiveInput });
1909
+ runContext.turnNumber += 1;
1910
+ bus.setTurnNumber(runContext.turnNumber);
1911
+ const t0Turn = performance.now();
1912
+ bus.publish({
1913
+ ...bus.envelope(),
1914
+ kind: "turn_start",
1915
+ turn: runContext.turnNumber,
1916
+ messageCount: messages.length,
1917
+ });
1918
+ runContext.logger.debug("turn start", {
1919
+ turn: runContext.turnNumber,
1920
+ messages: messages.length,
1921
+ });
1922
+ // Pre-turn budget check: snip first (free), then autocompact if still over.
1923
+ messages = await maybeCompact({
1924
+ messages,
1925
+ adapter: compactionAdapter,
1926
+ model: compactionWireModelId,
1927
+ contextLimit,
1928
+ compactionThreshold,
1929
+ snipKeepHead,
1930
+ snipKeepTail,
1931
+ logger: runContext.logger,
1932
+ }, async (info) => {
1933
+ await logEvent("compaction", info);
1934
+ bus.publish({
1935
+ ...bus.envelope(),
1936
+ kind: "compaction_fired",
1937
+ subKind: info.kind,
1938
+ before: info.before,
1939
+ after: info.after,
1940
+ phase: "pre-turn",
1941
+ });
1942
+ await fireHook("pre-compact", { ...info, phase: "pre-turn" });
1943
+ await fireHook("post-compact", { ...info, phase: "pre-turn" });
1944
+ });
1945
+ try {
1946
+ await runOneTurn(messages);
1947
+ }
1948
+ catch (err) {
1949
+ // Defensive: tear down any animation a thrown turn left spinning.
1950
+ out.spinner.stop();
1951
+ if (isAbortError(err)) {
1952
+ // Already-handled abort; loop back to the prompt.
1953
+ out.write("\n[turn aborted]\n");
1954
+ }
1955
+ else {
1956
+ throw err;
1957
+ }
1958
+ }
1959
+ bus.publish({
1960
+ ...bus.envelope(),
1961
+ kind: "turn_end",
1962
+ turn: runContext.turnNumber,
1963
+ durationMs: performance.now() - t0Turn,
1964
+ });
1965
+ runContext.logger.debug("turn end", {
1966
+ turn: runContext.turnNumber,
1967
+ });
1968
+ }
1969
+ }
1970
+ finally {
1971
+ out.spinner.stop();
1972
+ await fireHook("stop", {
1973
+ sessionId,
1974
+ turnCount: runContext.turnNumber,
1975
+ reason: runAbort.signal.aborted ? "abort" : "exit",
1976
+ });
1977
+ await subscribers.flushAll();
1978
+ await subscribers.shutdownAll();
1979
+ costPersistUnsubscribe?.();
1980
+ if (shouldInstallSigint) {
1981
+ process.removeListener("SIGINT", sigintHandler);
1982
+ }
1983
+ rl.close();
1984
+ await sessionStore.update(sessionId, { lastTurnIndex: runContext.turnNumber }).catch((err) => {
1985
+ runContext.logger.warn("session-store: lastTurnIndex update failed", {
1986
+ error: err.message,
1987
+ });
1988
+ });
1989
+ await eventLog.close();
1990
+ }
1991
+ return "";
1992
+ }
1993
+ function isAbortError(err) {
1994
+ // Section 17 — runtime-core no longer imports the Anthropic SDK at
1995
+ // runtime, so we name-match instead of `instanceof`. The provider
1996
+ // adapters preserve the SDK error names through their normalisation
1997
+ // layers, so this catches both Anthropic and OpenAI/Gemini/Bedrock
1998
+ // abort errors uniformly.
1999
+ const name = err.name;
2000
+ return typeof name === "string" && (name === "AbortError" || name === "APIUserAbortError");
2001
+ }
2002
+ /**
2003
+ * Pre-turn compaction ladder: estimate → snip → re-estimate → autocompact.
2004
+ * Returns the (possibly replaced) messages array. Pure with respect to
2005
+ * the input array; callers reassign. The optional `onCompaction` callback
2006
+ * fires once per applied step so the runtime can append a `compaction`
2007
+ * event to the session log without duplicating the cost-estimation logic.
2008
+ */
2009
+ async function maybeCompact(args, onCompaction) {
2010
+ const { messages, adapter, model, contextLimit, compactionThreshold, snipKeepHead, snipKeepTail, logger, } = args;
2011
+ const initialBudget = new TokenBudget(contextLimit);
2012
+ initialBudget.add(estimateTokens(messages), 0);
2013
+ if (!initialBudget.isApproachingLimit(compactionThreshold)) {
2014
+ return messages;
2015
+ }
2016
+ const snipped = snip(messages, snipKeepHead, snipKeepTail);
2017
+ logger.info("snip applied", { before: messages.length, after: snipped.length });
2018
+ if (onCompaction !== undefined) {
2019
+ await onCompaction({ kind: "snip", before: messages.length, after: snipped.length });
2020
+ }
2021
+ const postSnipBudget = new TokenBudget(contextLimit);
2022
+ postSnipBudget.add(estimateTokens(snipped), 0);
2023
+ if (!postSnipBudget.isApproachingLimit(compactionThreshold)) {
2024
+ return snipped;
2025
+ }
2026
+ logger.info("autocompact triggered", { tokensAfterSnip: postSnipBudget.used });
2027
+ const after = await autoCompact(snipped, adapter, model);
2028
+ if (onCompaction !== undefined) {
2029
+ await onCompaction({ kind: "autocompact", before: snipped.length, after: after.length });
2030
+ }
2031
+ return after;
2032
+ }
2033
+ /**
2034
+ * Reactive compaction triggered by the recovery engine on a prompt_too_long
2035
+ * error. Unlike pre-turn `maybeCompact`, this one runs unconditionally:
2036
+ * snip first, then autocompact (whose model summary reliably trims the
2037
+ * largest blob).
2038
+ */
2039
+ async function forceCompact(args) {
2040
+ const { messages, adapter, model, snipKeepHead, snipKeepTail, logger } = args;
2041
+ const snipped = snip(messages, snipKeepHead, snipKeepTail);
2042
+ logger.info("reactive snip applied", { before: messages.length, after: snipped.length });
2043
+ return await autoCompact(snipped, adapter, model);
2044
+ }