@crewhaus/runtime-core 0.3.1 → 0.4.0

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.
@@ -0,0 +1,29 @@
1
+ /** Default directory the identity file lives in (the project `.crewhaus` dir). */
2
+ export declare const DEFAULT_IDENTITY_DIR = ".crewhaus";
3
+ export declare const IDENTITY_FILENAME = "identity.json";
4
+ export declare const AGENT_IDENTITY_SCHEMA_VERSION: 1;
5
+ /**
6
+ * The persisted identity. `agentId` is the stable, verifiable fingerprint
7
+ * stamped onto trace envelopes; `publicKey`/`privateKey` are base64 DER
8
+ * (SPKI / PKCS8) so the keypair round-trips through `crypto.createPublicKey`
9
+ * for a future signing/verification layer.
10
+ */
11
+ export type AgentIdentityFile = {
12
+ readonly schemaVersion: 1;
13
+ /** SHA-256 hex digest of the SPKI-DER public key. */
14
+ readonly agentId: string;
15
+ readonly algorithm: "ed25519";
16
+ /** base64 SPKI DER. */
17
+ readonly publicKey: string;
18
+ /** base64 PKCS8 DER. */
19
+ readonly privateKey: string;
20
+ readonly createdAt: string;
21
+ };
22
+ /** The public-key fingerprint that becomes `agentId`. */
23
+ export declare function agentFingerprint(spkiDer: Buffer): string;
24
+ /**
25
+ * Load the agent identity from `<dir>/identity.json`, or mint + persist one on
26
+ * first boot. Idempotent and race-safe (create-exclusive write). `now` is
27
+ * injectable for deterministic tests.
28
+ */
29
+ export declare function loadOrCreateAgentIdentity(dir?: string, now?: () => Date): AgentIdentityFile;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Loop contract 0.4 (Batch C, item 4) — agent identity.
3
+ *
4
+ * An Ed25519 keypair auto-generated at first boot into `.crewhaus/identity.json`.
5
+ * Its `agentId` — the SHA-256 fingerprint of the public key — is stamped onto
6
+ * every `TraceEvent` envelope (via the bus's `agentId`) and appended to
7
+ * audit-log records, so a trace event and its audit trail attribute to one
8
+ * agent. The private key lives beside it (mode 0600) for later record signing;
9
+ * this module only generates and loads — signing is a downstream concern.
10
+ *
11
+ * `loadOrCreateAgentIdentity` is idempotent: the first call mints and persists
12
+ * the keypair; every later call re-reads the same file and returns the same
13
+ * `agentId`. Creation is create-exclusive so two concurrent first-boots can't
14
+ * clobber each other's keypair (first writer wins; the loser re-reads it).
15
+ */
16
+ import { createHash, generateKeyPairSync } from "node:crypto";
17
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
18
+ import { dirname, resolve } from "node:path";
19
+ /** Default directory the identity file lives in (the project `.crewhaus` dir). */
20
+ export const DEFAULT_IDENTITY_DIR = ".crewhaus";
21
+ export const IDENTITY_FILENAME = "identity.json";
22
+ export const AGENT_IDENTITY_SCHEMA_VERSION = 1;
23
+ /** The public-key fingerprint that becomes `agentId`. */
24
+ export function agentFingerprint(spkiDer) {
25
+ return createHash("sha256").update(spkiDer).digest("hex");
26
+ }
27
+ function mint(now) {
28
+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");
29
+ const spki = publicKey.export({ type: "spki", format: "der" });
30
+ const pkcs8 = privateKey.export({ type: "pkcs8", format: "der" });
31
+ return {
32
+ schemaVersion: AGENT_IDENTITY_SCHEMA_VERSION,
33
+ agentId: agentFingerprint(spki),
34
+ algorithm: "ed25519",
35
+ publicKey: spki.toString("base64"),
36
+ privateKey: pkcs8.toString("base64"),
37
+ createdAt: now().toISOString(),
38
+ };
39
+ }
40
+ function safeParse(path) {
41
+ if (!existsSync(path))
42
+ return undefined;
43
+ try {
44
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
45
+ if (typeof parsed.agentId === "string" &&
46
+ parsed.agentId.length > 0 &&
47
+ typeof parsed.publicKey === "string" &&
48
+ typeof parsed.privateKey === "string") {
49
+ return parsed;
50
+ }
51
+ }
52
+ catch {
53
+ // Corrupt/unreadable — the caller regenerates.
54
+ }
55
+ return undefined;
56
+ }
57
+ /**
58
+ * Load the agent identity from `<dir>/identity.json`, or mint + persist one on
59
+ * first boot. Idempotent and race-safe (create-exclusive write). `now` is
60
+ * injectable for deterministic tests.
61
+ */
62
+ export function loadOrCreateAgentIdentity(dir = DEFAULT_IDENTITY_DIR, now = () => new Date()) {
63
+ const path = resolve(dir, IDENTITY_FILENAME);
64
+ const existing = safeParse(path);
65
+ if (existing !== undefined)
66
+ return existing;
67
+ const identity = mint(now);
68
+ const body = `${JSON.stringify(identity, null, 2)}\n`;
69
+ mkdirSync(dirname(path), { recursive: true });
70
+ try {
71
+ // create-exclusive: the first concurrent first-boot wins the keypair.
72
+ writeFileSync(path, body, { flag: "wx", mode: 0o600 });
73
+ return identity;
74
+ }
75
+ catch (err) {
76
+ if (err.code !== "EEXIST")
77
+ throw err;
78
+ // Lost the create race, or a corrupt file squats the path.
79
+ const winner = safeParse(path);
80
+ if (winner !== undefined)
81
+ return winner;
82
+ writeFileSync(path, body, { mode: 0o600 });
83
+ return identity;
84
+ }
85
+ }
package/dist/index.d.ts CHANGED
@@ -1,17 +1,21 @@
1
1
  import type Anthropic from "@anthropic-ai/sdk";
2
2
  import { type ProviderAdapter } from "@crewhaus/adapter-anthropic";
3
3
  import type { CrewMailbox, SpawnSubAgentFn, SubAgentDefinition } from "@crewhaus/agent-context-isolation";
4
+ import { type EmbedderFn } from "@crewhaus/compaction-curator";
4
5
  import { type EgressMatcher, type SinkScope } from "@crewhaus/egress-classifier";
6
+ import { type FailureReport } from "@crewhaus/errors";
5
7
  import { type EventLog } from "@crewhaus/event-log";
6
8
  import { type HookDef } from "@crewhaus/hooks-engine";
7
9
  import { type JustificationJudge, type PermissionMode, type RuleSet } from "@crewhaus/permission-engine";
8
- import type { RateLimiter } from "@crewhaus/rate-limiter";
10
+ import { type RateLimiter } from "@crewhaus/rate-limiter";
9
11
  import { type NamedFailureClass } from "@crewhaus/recovery-engine";
10
12
  import { type Scoreboard } from "@crewhaus/routing-store";
11
13
  import { type RunContext } from "@crewhaus/run-context";
14
+ import { type PendingApproval, type PendingApprovalStore } from "@crewhaus/session-store";
12
15
  import { type SkillRef } from "@crewhaus/skills-registry";
13
16
  import { type SlashCommand } from "@crewhaus/slash-commands";
14
17
  import type { RegisteredTool } from "@crewhaus/tool-catalog";
18
+ import { type ModelUsage } from "@crewhaus/trace-event-bus";
15
19
  import { type AlertSink } from "./observability";
16
20
  import type { SloMitigationSink, SloTargets } from "./slo-monitor";
17
21
  /**
@@ -112,9 +116,15 @@ export declare function renderContinuityTail(input: {
112
116
  export declare function mapWithConcurrency<T, R>(items: ReadonlyArray<T>, limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
113
117
  export { CLAUDE_CODE_HEADERS, CLAUDE_CODE_SYSTEM_PREFIX, OAUTH_BETAS, createAnthropicClient, resolveAuth, } from "@crewhaus/adapter-anthropic";
114
118
  export type { ResolvedAuth } from "@crewhaus/adapter-anthropic";
119
+ export { createInMemoryKV, createNodeWorkerPlatform } from "./worker-platform";
120
+ export { createEdgeAnthropicAdapter, classifyEdgeTool, EDGE_SAFE_TOOLS, HOST_ONLY_TOOLS, isEdgeSafeTool, partitionEdgeTools, runWorkerLoop, } from "@crewhaus/worker-runtime";
121
+ export type { EdgeToolPartition, EdgeToolVerdict, KVLike, RunWorkerLoopOptions, TraceSink as WorkerTraceSink, WorkerLimits, WorkerLoopResult, WorkerPlatform, WorkerStopReason, WorkerThinking, WorkerTraceEvent, } from "@crewhaus/worker-runtime";
115
122
  export { createJanitor } from "./janitor";
116
123
  export { JANITOR_BUILTIN_STEPS } from "./janitor";
117
124
  export type { CreateJanitorOptions, Janitor, JanitorBuiltinStepName, JanitorReservationStore, JanitorRunResult, JanitorStep, JanitorStepName, JanitorStepOutcome, JanitorStepResult, JanitorStepStatus, } from "./janitor";
125
+ export { AGENT_IDENTITY_SCHEMA_VERSION, DEFAULT_IDENTITY_DIR, IDENTITY_FILENAME, agentFingerprint, loadOrCreateAgentIdentity, } from "./identity";
126
+ export type { AgentIdentityFile } from "./identity";
127
+ export { type ApprovalDecision, type PendingApproval, type PendingApprovalStore, type PendingApprovalStoreOptions, createPendingApprovalStore, generateApprovalId, hashApprovalInput, } from "@crewhaus/session-store";
118
128
  export { type AlertBreachPayload, type AlertSink, type AttachDefaultSubscribersOptions, attachDefaultSubscribers, } from "./observability";
119
129
  export { type AttachedSloMonitor, type AttachSloMonitorOptions, type SloBreach, type SloMitigationEvent, type SloMitigationRung, type SloMitigationSink, type SloTargets, type SloWindowMetrics, DEFAULT_SLO_WINDOW_MS, MIN_SLO_SAMPLES, SloWindow, attachSloMonitor, detectSloBreaches, } from "./slo-monitor";
120
130
  export { type AttachIncidentCollectorOptions, type IncidentCapture, type IncidentTriggerKind, attachIncidentCollector, classifyIncidentTrigger, } from "./incident-collector";
@@ -200,6 +210,71 @@ export type EgressAuditSink = {
200
210
  readonly payload: unknown;
201
211
  }): Promise<unknown>;
202
212
  };
213
+ /**
214
+ * Loop contract 0.4 (G02) — the observable output of ONE completed
215
+ * user→assistant turn, handed to the injected in-loop evaluator. A "turn"
216
+ * here is the whole tool inner-loop until the state machine reaches Done —
217
+ * the evaluator NEVER sees tool-only intermediate iterations.
218
+ */
219
+ export type EvaluationTurn = {
220
+ /**
221
+ * Concatenated text of the terminal assistant message (`""` when the
222
+ * turn produced no text blocks). This is exactly the string a
223
+ * `singleTurn` run returns to its caller.
224
+ */
225
+ readonly finalText: string;
226
+ /**
227
+ * The full conversation history as of turn completion (read-only view —
228
+ * evaluators must not mutate it; the runtime owns the array).
229
+ */
230
+ readonly messages: ReadonlyArray<Anthropic.MessageParam>;
231
+ /**
232
+ * Aggregate token usage across every MAIN-turn model call this attempt
233
+ * made (all tool iterations included; compaction/judge side-calls are
234
+ * not main-turn calls and are excluded). On an evaluation-triggered
235
+ * retry the re-run attempt gets a fresh accumulator, so each `evaluate`
236
+ * invocation sees the usage of exactly the attempt it is grading.
237
+ */
238
+ readonly usage: ModelUsage;
239
+ };
240
+ /** The injected grader's verdict for one graded attempt. */
241
+ export type EvaluationResult = {
242
+ /** Score in [0,1]; compared against `threshold` (>= passes). A non-finite
243
+ * score is treated as 0 (fail) defensively. */
244
+ readonly score: number;
245
+ /** Grader explanation; appended to the retry nudge when `onFail: "retry"`. */
246
+ readonly rationale?: string;
247
+ };
248
+ /**
249
+ * Loop contract 0.4 (G02) — the in-loop evaluation seam (spec
250
+ * `evaluation:` on cli/channel/managed). See
251
+ * {@link RunChatLoopOptions.evaluation} for semantics.
252
+ */
253
+ export type RunEvaluation = {
254
+ /**
255
+ * The grader, INJECTED by the caller (target emitters construct it from
256
+ * the IR's `evaluation.grader` — an llm_judge side-call or a
257
+ * deterministic contains/regex check). runtime-core never constructs a
258
+ * judge itself, so it gains no eval dependency. A grader that throws is
259
+ * treated as grading INFRASTRUCTURE failure, not a verdict: the error is
260
+ * logged (`error` event) and the turn stands un-gated (fail-open) — a
261
+ * flaky judge model must not kill an otherwise healthy run.
262
+ */
263
+ readonly evaluate: (turn: EvaluationTurn) => Promise<EvaluationResult>;
264
+ /** Passing bar: `score >= threshold` passes. (The compiler resolves the
265
+ * spec default: 0.7 for llm_judge; deterministic graders use 1.) */
266
+ readonly threshold: number;
267
+ /** What a failing verdict does — see the option docblock. */
268
+ readonly onFail: "retry" | "halt" | "note";
269
+ /** Hard cap on evaluation-triggered re-runs (>= 0; resolved default 1). */
270
+ readonly maxRetries: number;
271
+ /**
272
+ * Which grader kind produced the score — stamped verbatim onto every
273
+ * `eval_graded` trace event (the event field is required, and only the
274
+ * caller knows what it built `evaluate` from).
275
+ */
276
+ readonly graderType: "llm_judge" | "contains" | "regex";
277
+ };
203
278
  export type RunChatLoopOptions = {
204
279
  model: string;
205
280
  instructions: string;
@@ -248,6 +323,25 @@ export type RunChatLoopOptions = {
248
323
  input?: NodeJS.ReadableStream;
249
324
  /** Tools the model may invoke. When empty/undefined, tools are not advertised. */
250
325
  tools?: ReadonlyArray<RegisteredTool>;
326
+ /**
327
+ * Item 3 (G32) — plugin-contributed pieces to fold into this run. The caller
328
+ * activates the spec's `plugins:` list (or the `--plugins` override) via
329
+ * `@crewhaus/plugin-loader`'s `activatePlugins` and passes the result here.
330
+ *
331
+ * Only `tools` are the chat loop's to bind: they are APPENDED to `opts.tools`
332
+ * and advertised to the model, with first-party tools winning any name
333
+ * collision (a plugin can augment the catalog but not silently shadow a
334
+ * built-in). The other contribution kinds bind at their own hosts — channels
335
+ * at the channel daemon, models at the model-router, graders at the eval
336
+ * stack, target emitters at the compiler — so they are deliberately not
337
+ * accepted here. A compiled bundle instead registers plugin tools directly on
338
+ * its `defaultCatalog`; this option is the interpreter path's equivalent so a
339
+ * `runChatLoop` caller need not mutate a global catalog. Absent → the run is
340
+ * byte-identical to a pre-G32 runtime.
341
+ */
342
+ plugins?: {
343
+ readonly tools?: ReadonlyArray<RegisteredTool>;
344
+ };
251
345
  /** Per-run identity, abort signal, and logger. Defaults to a fresh `createRunContext()`. */
252
346
  runContext?: RunContext;
253
347
  /** Context-window limit in tokens. Defaults to 200_000 (Claude opus/sonnet 4.x). */
@@ -374,6 +468,49 @@ export type RunChatLoopOptions = {
374
468
  /** Invoked at teardown with the completed user-text turn count and the
375
469
  * run's session id (so the callback can read the transcript to summarize). */
376
470
  readonly onCapture?: (completedTurns: number, sessionId: string) => Promise<void>;
471
+ /**
472
+ * Loop contract 0.4 (Batch E, G21) — WHEN auto-recall runs, lowered from
473
+ * `IrMemory.recallMode`. `"session-start"` (the implicit default) recalls
474
+ * ONCE at boot into the frozen, cache-marked system prefix — the pre-0.4
475
+ * behaviour. `"per-turn"` instead re-runs `recall` against the LATEST user
476
+ * message every `refreshEvery` turns and swaps a VOLATILE recalled block
477
+ * that sits in the mutable tail region (alongside the continuity tail),
478
+ * NEVER re-injecting into the frozen cache prefix — so a long daemon's
479
+ * recalled evidence tracks the conversation instead of drifting from a
480
+ * stale boot-time snapshot. Requires `recall` + `autoRecall: true`.
481
+ */
482
+ readonly recallMode?: "session-start" | "per-turn";
483
+ /**
484
+ * Loop contract 0.4 (Batch E, G21) — turns between per-turn recall
485
+ * refreshes (`IrMemory.refreshEvery`, int > 0; runtime clamps to >= 1 and
486
+ * defaults to 1). Only meaningful when `recallMode` is `"per-turn"`.
487
+ */
488
+ readonly refreshEvery?: number;
489
+ };
490
+ /**
491
+ * Loop contract 0.4 (Batch E, G19) — the active-context curation pre-pass
492
+ * (spec `compaction.curate`, lowered from `IrCompaction`; presence GATES the
493
+ * pass). Once the pre-turn compaction ladder decides the context is already
494
+ * approaching the limit, the runtime runs `@crewhaus/compaction-curator`
495
+ * BEFORE snip→autocompact: it drops semantically-duplicate transcript
496
+ * messages (embedding cosine when an `embedder` is injected, a BM25-family
497
+ * lexical fallback when not) and — when `relevanceTopK` is set — keeps only
498
+ * the top-K most relevant to the latest user message, re-sorted back into
499
+ * transcript order (the curator's relevance ranking SELECTS survivors; it
500
+ * never scrambles the conversation, and messages carrying tool_use/tool_result
501
+ * pairs or inside the snip-protected head/tail are never touched). When the
502
+ * pass frees enough headroom the expensive summarizer call is skipped
503
+ * entirely. Every pass publishes a `curate` trace event
504
+ * (`before`/`after`/`dropped`/`bytesSaved`/`embedded`). The embedder is
505
+ * INJECTED (runtime-core carries no embedder dependency): callers resolve it
506
+ * from `memory.embedder ?? memory.wiki.embedder`; absent → lexical dedupe
507
+ * (`embedded: false`). Absent block → no curation, byte-identical to a
508
+ * pre-0.4 runtime.
509
+ */
510
+ curate?: {
511
+ readonly embedder?: EmbedderFn;
512
+ readonly dedupeThreshold?: number;
513
+ readonly relevanceTopK?: number;
377
514
  };
378
515
  /**
379
516
  * v0.3.0 Goal 1 — the continuity seam (§2.3 requirements ledger, §2.5
@@ -763,6 +900,194 @@ export type RunChatLoopOptions = {
763
900
  readonly model: string;
764
901
  };
765
902
  };
903
+ /**
904
+ * Loop contract 0.4 (G10) — whole-run wall-clock ceiling in ms (spec
905
+ * `limits.deadline_ms`). Armed once at loop start; on fire it aborts the
906
+ * ROOT of the abort tree (`runAbort`) with a branded reason, the in-flight
907
+ * turn winds down through the normal cancellation paths, and the run ends
908
+ * with a classified `run_failed` (class `"timeout"`, exit
909
+ * `EXIT_CODES.timeout`) + `RunFailedError` throw — in REPL mode too (a
910
+ * deadline is terminal everywhere, including while idle at the prompt).
911
+ * Absent → no timer (zero behaviour change).
912
+ */
913
+ deadlineMs?: number;
914
+ /**
915
+ * Loop contract 0.4 (G10) — per-turn wall-clock ceiling in ms (spec
916
+ * `limits.turn_timeout_ms`). Armed when a user→assistant turn starts and
917
+ * cleared when it ends; on fire it aborts the TURN (`turnAbort`) with a
918
+ * branded reason, cancelling the in-flight model call / tool children.
919
+ * In `singleTurn` mode the turn IS the run, so the stop is terminal:
920
+ * classified `run_failed` (class `"timeout"`) + `RunFailedError`. In REPL
921
+ * mode it mirrors the first-SIGINT semantics — the turn aborts with a
922
+ * printed notice and an `error` event (name `"TurnTimeout"`), and the
923
+ * session continues at the prompt (no `run_failed`: the run didn't end).
924
+ */
925
+ turnTimeoutMs?: number;
926
+ /**
927
+ * Loop contract 0.4 (G10) — per-model-call wall-clock ceiling in ms (spec
928
+ * `limits.model_call_timeout_ms`), the hung-stream watchdog. Re-armed
929
+ * before EVERY main-turn stream and cleared when the stream drains; on
930
+ * fire it aborts the turn (`turnAbort` — the turn cannot proceed without
931
+ * its model call) with a branded reason. Terminal/REPL posture identical
932
+ * to `turnTimeoutMs` (error-event name `"ModelCallTimeout"`). Note: under
933
+ * `streaming: true` the drain overlaps mid-stream tool dispatch, so the
934
+ * window covers those tools too — use `turnTimeoutMs` for tool-inclusive
935
+ * bounds and keep this one comfortably above normal stream latency.
936
+ */
937
+ modelCallTimeoutMs?: number;
938
+ /**
939
+ * Loop contract 0.4 (G27) — tool-loop detection tuning + escalation
940
+ * ladder (spec `limits.loop_detection`). `window`/`threshold` thread to
941
+ * `@crewhaus/tool-loop-detection.detectLoop` (defaults 10 / 3). The
942
+ * detector now has a NEAR-DUPLICATE tier — same tool, inputs identical
943
+ * after volatile-substring stripping (numbers/UUIDs/hashes/whitespace),
944
+ * counted at reduced weight — so trivial argument churn no longer defeats
945
+ * it. `escalation` picks what happens when a signature trips detection
946
+ * AGAIN after its one-time warning was ignored:
947
+ * - `"warn"` (default) — nothing further; byte-identical to the pre-0.4
948
+ * warn-once behaviour.
949
+ * - `"justify"` — inject a requireJustification-STYLE demand as a
950
+ * synthetic user message: the model must state a one-sentence
951
+ * justification tied to the session goal before repeating the call.
952
+ * (Deliberately NOT the permission-engine justification gate: that
953
+ * gate is a per-tool-descriptor compile-time contract whose schema
954
+ * advertises a `justification` input field — retrofitting descriptors
955
+ * mid-run would change the advertised tool schema under the model.
956
+ * The synthetic nudge is the proportionate in-band mechanism.)
957
+ * - `"abort"` — abort the TURN, ToolLoopLimit-style: an `error` event
958
+ * (name `"ToolLoopAbort"`) is logged and the state machine takes the
959
+ * Aborted transition, exactly like the `maxToolIterations` cap.
960
+ */
961
+ loopDetection?: {
962
+ readonly window?: number;
963
+ readonly threshold?: number;
964
+ readonly escalation?: "warn" | "justify" | "abort";
965
+ };
966
+ /**
967
+ * Loop contract 0.4 (G17) — per-tool rate limits (spec
968
+ * `agent.rate_limits`): tool name (or `"*"` for the every-tool default)
969
+ * → sustained `rpm` + optional short-burst allowance. At loop start the
970
+ * runtime builds a `@crewhaus/rate-limiter` with one token bucket per
971
+ * entry (`refillPerSec = rpm/60`, `capacity = burst ?? rpm`) and every
972
+ * tool execution acquires `tool:<name>` BEFORE dispatch (after the
973
+ * permission/justification/egress gates, so denied calls never consume
974
+ * tokens). Tools with neither a named bucket nor a `"*"` default are not
975
+ * gated. An acquire that exhausts the limiter's wait budget fails just
976
+ * that call with an `is_error` tool_result (`[rate-limited] …`) so the
977
+ * model can adapt — it never kills the run. Independent of the
978
+ * model-call `rateLimiter`/`rateLimitKeys` pair above.
979
+ */
980
+ rateLimits?: Readonly<Record<string, {
981
+ readonly rpm: number;
982
+ readonly burst?: number;
983
+ }>>;
984
+ /**
985
+ * Loop contract 0.4 (G01) — extended thinking for every MAIN-TURN model
986
+ * stream (spec `thinking`; same two forms as `IrThinking`). Compaction
987
+ * and judge side-calls are deliberately untouched — they build their own
988
+ * `ProviderRequest`s and summarization/grading gains nothing from
989
+ * spending thinking tokens.
990
+ * - `{ budgetTokens }` → `ProviderRequest.thinking =
991
+ * { type: "enabled", budget_tokens }` verbatim.
992
+ * - `{ effort }` → BOTH fields are set: `thinking` converted through
993
+ * `EFFORT_THINKING_BUDGET_TOKENS` (for budget-style providers:
994
+ * anthropic/bedrock/gemini) AND `reasoningEffort` passed through (for
995
+ * native-effort providers: openai). Adapters ignore the field they
996
+ * don't support; anthropic's translate gives an explicit `thinking`
997
+ * precedence, so setting both is convergent.
998
+ * When the resolved budget crowds out the output budget (Anthropic
999
+ * requires `max_tokens > thinking.budget_tokens`), the per-request token
1000
+ * ceiling is lifted to `budget + maxTokens` so the declared output budget
1001
+ * survives intact (logged once at boot).
1002
+ */
1003
+ thinking?: {
1004
+ readonly budgetTokens: number;
1005
+ } | {
1006
+ readonly effort: "low" | "medium" | "high";
1007
+ };
1008
+ /**
1009
+ * Loop contract 0.4 (G02) — in-loop evaluation of every COMPLETED turn
1010
+ * (spec `evaluation:` on cli/channel/managed; both `singleTurn` and REPL
1011
+ * paths). After the turn's tool inner-loop reaches Done — never on a
1012
+ * tool-only intermediate iteration — the injected `evaluate` grades the
1013
+ * terminal assistant text and one `eval_graded` trace event is published
1014
+ * per grading pass (`retryIndex` 0 for the original attempt, n for the
1015
+ * n-th evaluation-triggered retry). On `score < threshold`:
1016
+ *
1017
+ * - `onFail: "retry"` — the grader rationale is appended to history as a
1018
+ * synthetic corrective user message (event-logged `synthetic: true`,
1019
+ * like the recovery/loop nudges) and the turn re-runs, up to
1020
+ * `maxRetries` times. Each re-run makes REAL model calls, so its spend
1021
+ * accrues through the existing cost path (`model_response` → budget
1022
+ * meter) and counts against `budget:` exactly like any other call.
1023
+ * Retries exhausted → the last attempt stands and the run continues
1024
+ * (the failing verdict trail is on the trace bus).
1025
+ * - `onFail: "halt"` — classified terminal stop: `run_failed` (class
1026
+ * `"evaluation"`, exit {@link EXIT_CODES.evaluation}) is published +
1027
+ * event-logged and the matching `RunFailedError` is thrown, in REPL
1028
+ * mode too (a quality-floor halt is terminal everywhere).
1029
+ * - `onFail: "note"` — the failing `eval_graded` event is the whole
1030
+ * story; the turn stands and the run continues.
1031
+ *
1032
+ * A turn that ABORTED (SIGINT / wall-clock timer) never completed, so it
1033
+ * is not evaluated. Absent → zero behaviour change for existing callers.
1034
+ */
1035
+ evaluation?: RunEvaluation;
1036
+ /**
1037
+ * Loop contract 0.4 (Batch C, item 4) — the publishing agent's identity
1038
+ * fingerprint (the `agentId` from `loadOrCreateAgentIdentity`). When set AND
1039
+ * runChatLoop constructs the run context itself (no `opts.runContext`), the
1040
+ * run's `TraceEventBus` is built with this `agentId` so every trace envelope
1041
+ * carries it and audit sinks can attribute the run to one agent. When the
1042
+ * caller supplies `opts.runContext`, they own `agentId` on its bus (a
1043
+ * sub-agent spawner threads the parent's `agentId` into the child bus) and
1044
+ * this field is ignored — matching how `runContext` overrides the other
1045
+ * per-run construction inputs. Absent → no stamping (byte-identical to a
1046
+ * pre-0.4 runtime).
1047
+ */
1048
+ agentId?: string;
1049
+ /**
1050
+ * Loop contract 0.4 (Batch C, G11) — how a tool permission that resolves to
1051
+ * `ask` behaves on a NON-interactive surface (`permissions.ask_mode`,
1052
+ * lowered from the IR; absent ⇒ `"pause"`):
1053
+ * - `"pause"` (default) — WITH an `approvals` store, PARK the run: persist
1054
+ * a `PendingApproval`, publish `approval_requested`, and end with the
1055
+ * `approval_pending` failure class so the call can be granted/denied out
1056
+ * of band and re-resolved on the next execution. WITHOUT an `approvals`
1057
+ * store there is nowhere to park, so it collapses to the pre-0.4 deny.
1058
+ * - `"deny"` — the pre-0.4 collapse-in-place: the ask denies immediately
1059
+ * with a note (never parks), regardless of any `approvals` store.
1060
+ * The interactive REPL path is unaffected either way — an `ask` there always
1061
+ * prompts on stdin.
1062
+ */
1063
+ askMode?: "pause" | "deny";
1064
+ /**
1065
+ * Loop contract 0.4 (Batch C, G11) — the pending-approval seam. When
1066
+ * supplied AND `askMode` is `"pause"` (the default), a headless `ask`
1067
+ * consults `store.get(toolName, inputHash)`:
1068
+ * - a `"grant"` → allow this ONE call (the grant is one-shot: consumed via
1069
+ * `store.persist`, so a later identical call re-asks);
1070
+ * - a `"deny"` → deny with a note;
1071
+ * - nothing yet → persist a fresh `PendingApproval`, fire `notify` (if
1072
+ * given), publish `approval_requested`, and PARK the run.
1073
+ * The store is injected (the CLI builds `createPendingApprovalStore`); the
1074
+ * `surface` classifier stamps the `approval_requested` event (defaults to
1075
+ * `"single-turn"` under `singleTurn`, else `"headless"`). Omitted → no
1076
+ * parking (headless `ask` collapses to the pre-0.4 deny).
1077
+ */
1078
+ approvals?: {
1079
+ /**
1080
+ * The persistence seam. Only `{ persist, get, resolve }` are contracted;
1081
+ * the runtime calls `get` (look up a prior decision) and `persist` (park a
1082
+ * fresh request / consume a one-shot grant), while `resolve` is the
1083
+ * out-of-band CLI/Slack surface's entry point on the SAME store. Narrowed
1084
+ * from the full `PendingApprovalStore` so a caller may inject a minimal
1085
+ * store; the concrete `createPendingApprovalStore` satisfies it.
1086
+ */
1087
+ readonly store: Pick<PendingApprovalStore, "persist" | "get" | "resolve">;
1088
+ readonly notify?: (approval: PendingApproval) => Promise<void>;
1089
+ readonly surface?: string;
1090
+ };
766
1091
  };
767
1092
  /**
768
1093
  * Runs the streaming chat loop and returns the terminal assistant text.
@@ -808,4 +1133,25 @@ export declare function resolveToolResultRoot(): string | undefined;
808
1133
  * to mark federation-joined or other runtime sinks dynamic too.
809
1134
  */
810
1135
  export declare function defaultSinkScope(toolName: string): SinkScope;
1136
+ /** Which configured limit fired. `run` = `limits.deadline_ms`,
1137
+ * `turn` = `limits.turn_timeout_ms`, `model_call` = `limits.model_call_timeout_ms`. */
1138
+ export type TimeoutScope = "run" | "turn" | "model_call";
1139
+ /** The branded abort reason a G10 timer aborts with. Carried on
1140
+ * `AbortSignal.reason` (the abort tree propagates reasons parent→child, so
1141
+ * a run-deadline reason is visible on the turn signal too). */
1142
+ export type TimeoutAbortReason = {
1143
+ readonly crewhausTimeout: TimeoutScope;
1144
+ readonly limitMs: number;
1145
+ };
1146
+ /** Read the branded timeout reason off an aborted signal, or undefined when
1147
+ * the signal is not aborted / was aborted for another cause (SIGINT, EOF). */
1148
+ export declare function timeoutAbortReason(signal: AbortSignal): TimeoutAbortReason | undefined;
1149
+ /**
1150
+ * G10 — build the classified terminal report for a fired wall-clock limit.
1151
+ * `class: "timeout"` / exit {@link EXIT_CODES.timeout} joins the failure
1152
+ * taxonomy beside `crewhaus_budget`: like the spend cap, the stop was
1153
+ * CrewHaus's OWN configured ceiling, not a provider failure. Exported for
1154
+ * emitters/tests that render or assert on the report.
1155
+ */
1156
+ export declare function buildTimeoutFailureReport(timeout: TimeoutAbortReason): FailureReport;
811
1157
  export declare function runChatLoop(opts: RunChatLoopOptions): Promise<string>;