@crewhaus/runtime-core 0.7.0 → 0.8.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.
package/dist/index.d.ts CHANGED
@@ -9,11 +9,12 @@ import { type EventLog } from "@crewhaus/event-log";
9
9
  import { type HookDef } from "@crewhaus/hooks-engine";
10
10
  import { type ModelProfile, type ModelThinking, type RequestParams, type RouteRule } from "@crewhaus/model-plan";
11
11
  import { type JustificationJudge, type PermissionMode, type RuleSet } from "@crewhaus/permission-engine";
12
+ import { type ProofBundle, type ProvabilityLevel } from "@crewhaus/provability";
12
13
  import { type RateLimiter } from "@crewhaus/rate-limiter";
13
14
  import { type NamedFailureClass } from "@crewhaus/recovery-engine";
14
15
  import { type Scoreboard } from "@crewhaus/routing-store";
15
16
  import { type RunContext } from "@crewhaus/run-context";
16
- import { type PendingApproval, type PendingApprovalStore } from "@crewhaus/session-store";
17
+ import { type ApprovalPlace, type PendingApproval, type PendingApprovalStore } from "@crewhaus/session-store";
17
18
  import { type SkillRef } from "@crewhaus/skills-registry";
18
19
  import { type SlashCommand } from "@crewhaus/slash-commands";
19
20
  import type { RegisteredTool } from "@crewhaus/tool-catalog";
@@ -133,13 +134,14 @@ export { createInMemoryKV, createNodeWorkerPlatform } from "./worker-platform";
133
134
  export { createEdgeAnthropicAdapter, classifyEdgeTool, EDGE_SAFE_TOOLS, HOST_ONLY_TOOLS, isEdgeSafeTool, partitionEdgeTools, runWorkerLoop, } from "@crewhaus/worker-runtime";
134
135
  export type { EdgeToolPartition, EdgeToolVerdict, KVLike, RunWorkerLoopOptions, TraceSink as WorkerTraceSink, WorkerLimits, WorkerLoopResult, WorkerPlatform, WorkerStopReason, WorkerThinking, WorkerTraceEvent, } from "@crewhaus/worker-runtime";
135
136
  export { createJanitor } from "./janitor";
137
+ export { GATE_RESOLVE_SINK_ID, type LineageScreenOptions, lineageEgressScreen, } from "./lineage-screen";
136
138
  export { JANITOR_BUILTIN_STEPS } from "./janitor";
137
139
  export type { CreateJanitorOptions, Janitor, JanitorBuiltinStepName, JanitorReservationStore, JanitorRunResult, JanitorStep, JanitorStepName, JanitorStepOutcome, JanitorStepResult, JanitorStepStatus, } from "./janitor";
138
140
  export { AGENT_IDENTITY_SCHEMA_VERSION, DEFAULT_IDENTITY_DIR, IDENTITY_FILENAME, agentFingerprint, loadOrCreateAgentIdentity, } from "./identity";
139
141
  export { describeHintEvidence, isSyntheticMessage, latestHumanUserMessage, markSynthetic, messageHasImages, messageText, preRoute, stripDirectiveFromMessage, } from "./pre-route";
140
142
  export type { PreRouteArm, PreRouteClassifierVerdict, PreRouteContext, PreRouteForced, PreRouteResult, } from "./pre-route";
141
143
  export type { AgentIdentityFile } from "./identity";
142
- export { type ApprovalDecision, type PendingApproval, type PendingApprovalStore, type PendingApprovalStoreOptions, createPendingApprovalStore, evictExpiredApprovals, generateApprovalId, hashApprovalInput, } from "@crewhaus/session-store";
144
+ export { type ApprovalDecision, type ApprovalPlace, type PendingApproval, type PendingApprovalStore, type PendingApprovalStoreOptions, type SupersededApproval, createPendingApprovalStore, evictExpiredApprovals, generateApprovalId, hashApprovalInput, } from "@crewhaus/session-store";
143
145
  /**
144
146
  * How long after an operator's DECISION a grant may still satisfy a call the
145
147
  * model has re-worded. Generous enough for a resume (which follows the grant
@@ -185,6 +187,40 @@ export declare function findReplayableGrant(store: Pick<PendingApprovalStore, "p
185
187
  /** Override the window (tests). */
186
188
  readonly maxAgeMs?: number;
187
189
  }): Promise<PendingApproval | undefined>;
190
+ /**
191
+ * 0.7.1 — the gate's record of where a call lands: every path it read for
192
+ * the call and where each one landed, and whether each lands where it reads
193
+ * on its face (`placeRecordingCanonicalizer`).
194
+ */
195
+ export type CallPlaces = {
196
+ readonly places: () => ReadonlyArray<ApprovalPlace>;
197
+ readonly allAsWritten: () => boolean;
198
+ };
199
+ /**
200
+ * 0.7.1 — does the decision on `record` cover a call that now lands at
201
+ * `call`?
202
+ *
203
+ * An operator approves a call where it acts. The record is keyed on the
204
+ * input, and the same input can be made to act somewhere else: retarget a
205
+ * symlinked directory between park and resume — any allowed call in the
206
+ * resumed turn can — and a grant for `pub/link/x.md` would write wherever
207
+ * the link now points, a place the operator never saw and one an
208
+ * `alwaysAsk` rule may name. So the record carries the places the gate
209
+ * found when it parked, and decides the call only while it lands there.
210
+ *
211
+ * A record written before approvals were bound (no `places`: 0.7.0, or an
212
+ * earlier 0.7.1 build) showed its approver only the input as written, so
213
+ * the one place it can be said to cover is the one that input names on its
214
+ * face. It decides the call when every path lands exactly there — no
215
+ * symlink followed, nothing elsewhere — and otherwise the call is asked
216
+ * again: never run somewhere the approver could not have seen. A record
217
+ * whose `places` is not the shape written here (a foreign or hand-edited
218
+ * line) covers nothing.
219
+ *
220
+ * Binding is about where a call RUNS, so the gate asks this of a grant or a
221
+ * park it would re-use; a deny refuses the call wherever it lands.
222
+ */
223
+ export declare function landsWhereApproved(record: Pick<PendingApproval, "places">, call: CallPlaces): boolean;
188
224
  export { type AlertBreachPayload, type AlertSink, type AttachDefaultSubscribersOptions, attachDefaultSubscribers, } from "./observability";
189
225
  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";
190
226
  export { type AttachIncidentCollectorOptions, type IncidentCapture, type IncidentTriggerKind, attachIncidentCollector, classifyIncidentTrigger, } from "./incident-collector";
@@ -239,10 +275,17 @@ export declare function replayMessageHistory(log: EventLog): Promise<Anthropic.M
239
275
  * the documented verbatim shape `{ toolName, justification, verdict, reason,
240
276
  * judgeModel, confidence? }` (the justification IS the audit artifact — stored
241
277
  * verbatim, never redacted).
278
+ *
279
+ * 0.8.0 (design/0.8.0-provability-release.md §5.3) — the provability gate
280
+ * appends to the same hash-chained log: one `provability_evaluated` record
281
+ * per verification pass, carrying the bundle SUMMARY (`{ level, verdict,
282
+ * score, …, bundleHash, turnNumber, sessionId }`), never the bundle. Both
283
+ * kinds are AuditKinds `@crewhaus/audit-log` accepts, so a real `AuditLog`
284
+ * satisfies the widened union unchanged.
242
285
  */
243
286
  export type JustificationAuditSink = {
244
287
  append(input: {
245
- readonly kind: "permission_justification_evaluated";
288
+ readonly kind: "permission_justification_evaluated" | "provability_evaluated";
246
289
  readonly payload: unknown;
247
290
  }): Promise<unknown>;
248
291
  };
@@ -371,6 +414,163 @@ export type AuxRequestParams = {
371
414
  readonly maxTokens?: number;
372
415
  readonly temperature?: number;
373
416
  };
417
+ /**
418
+ * 0.8.0 (design/0.8.0-provability-release.md §5.1) — what the injected
419
+ * provability verifier receives: the same completed-turn view the in-loop
420
+ * judge gets, plus where the turn sits (for the session-scoped evidence index
421
+ * and the bundle's file name) and which gate-triggered retry this is.
422
+ */
423
+ export type ProvabilityTurn = EvaluationTurn & {
424
+ readonly turnNumber: number;
425
+ readonly retryIndex: number;
426
+ /** The run's session id, when it has one (evidence is read from its log). */
427
+ readonly sessionId?: string;
428
+ readonly signal?: AbortSignal;
429
+ /**
430
+ * 0.8.0 (design §6.2) — whether auxiliary spend has reached
431
+ * `budget.judge_share`, read live: past the share the paraphrase-waiver
432
+ * judge is skipped, not guessed. Absent (an unbudgeted run) ⇒ never.
433
+ */
434
+ readonly judgeShareExhausted?: () => boolean;
435
+ /**
436
+ * 0.8.0 (design §6.1, §10) — the run's durable egress sink, when one is
437
+ * wired: a `sources.resolve: head` request is an egress, and the verifier
438
+ * records each one it decides as an `egress_decision` (sink
439
+ * `provability.resolve`).
440
+ */
441
+ readonly egressAuditSink?: EgressAuditSink;
442
+ /**
443
+ * 0.8.0 (design §6.1, §10; AGENTS.md Pillar 3) — the sink-side check an
444
+ * egress the VERIFIER makes goes through before it is sent: `payload` (a
445
+ * cited URL, path and query included) is classified against the run's
446
+ * data lineage like a tool call to a destination the model chose
447
+ * (`external-dynamic`, the run's egress matcher), and the screen
448
+ * publishes the `permission_decision` trace event. On `block` the
449
+ * verifier sends nothing. The runtime always supplies it; a hand-wired
450
+ * verifier without it has no lineage to screen with.
451
+ */
452
+ readonly screenEgress?: (payload: string, sinkId: string) => Promise<GateEgressScreen>;
453
+ };
454
+ /** 0.8.0 — what {@link ProvabilityTurn.screenEgress} decided about one outbound payload. */
455
+ export type GateEgressScreen = {
456
+ readonly verdict: "pass" | "warn" | "block";
457
+ /** Always `external-dynamic`: the destination is one the model wrote. */
458
+ readonly sinkScope: "external-configured" | "external-dynamic";
459
+ /** Origins of tagged content found in the payload (empty when none). */
460
+ readonly originsFound: ReadonlyArray<string>;
461
+ readonly matchCount: number;
462
+ };
463
+ /**
464
+ * 0.8.0 (design §5.1) — the provability gate seam (spec `provability:` on
465
+ * cli/channel/managed). After a turn COMPLETES, and BEFORE the `evaluation:`
466
+ * gate (if any) grades it — provability first, it is free and deterministic;
467
+ * the judge may spend — the injected `verify` checks every claim in the final
468
+ * text against the declared floor and returns a `ProofBundle`. Every attempt
469
+ * the turn produces is verified, an evaluation retry's and an escalation's
470
+ * included, and the judge grades only an answer the gate accepted or ran out
471
+ * of retries on. One `provability_graded` trace event + event-log line is
472
+ * published per pass. On `verdict: "fail"`:
473
+ *
474
+ * - `onFail: "retry"` — the runtime appends a synthetic corrective user
475
+ * message composed from the bundle (the unmet claims, the evidence each
476
+ * cited, the reason — never fetched content) and re-runs the turn, up to
477
+ * `maxRetries` times (re-runs the judge asks for are not counted here:
478
+ * each gate keeps its own cap).
479
+ * - `onFail: "halt"` — classified terminal stop: `run_failed` (class
480
+ * `"provability"`, exit {@link EXIT_CODES.provability}).
481
+ * - `onFail: "note"` — the failing event is the whole story; the answer stands.
482
+ * - `onFail: "escalate"` — re-run the turn on the pool's escalation rung
483
+ * (`escalateTo`, else the strongest candidate), then grade it like any
484
+ * answer; it counts against `maxRetries` AND the turn's `max_escalations`
485
+ * (shared with the evaluation cascade). Without a pool, note semantics
486
+ * with one warning.
487
+ *
488
+ * Bundles are filed per SESSION turn: a resumed run (every channel message
489
+ * after a thread's first, a managed `runs.continue`, `--resume`) numbers its
490
+ * turns after the ones the session already ran.
491
+ *
492
+ * A verifier that THROWS is grading-infrastructure failure, not a verdict:
493
+ * logged, fail-open (the answer stands), and the bundle records
494
+ * `verdict: "unverified"` so no surface prints a ✓. Runtime-core never builds
495
+ * the verifier itself (`@crewhaus/evaluation-service` does), so it gains no
496
+ * dependency beyond the bundle TYPE. Absent → zero behaviour change.
497
+ */
498
+ export type RunProvability = {
499
+ readonly level: ProvabilityLevel;
500
+ readonly onFail: "retry" | "halt" | "note" | "escalate";
501
+ /** Hard cap on gate-triggered re-runs (>= 0; resolved default 1). */
502
+ readonly maxRetries: number;
503
+ readonly threshold: number;
504
+ /** Under `onFail: "escalate"`: the roster arm to re-run on (resolved like `RunEvaluation.escalateTo`). */
505
+ readonly escalateTo?: string;
506
+ /** How the bundle shows beside the answer (`render`): a one-line footer, the JSON, or nothing. */
507
+ readonly render: "footer" | "none" | "json";
508
+ /**
509
+ * Where the rendered bundle goes: `"stream"` writes it to the run's output
510
+ * after the answer (cli); `"reply"` appends it to the text the run returns
511
+ * (a channel bot sends that text); `"none"` renders it nowhere — the caller
512
+ * carries the bundle itself (`onBundle`: the managed gateway's `proof`
513
+ * field, an eval bridge's artifact), so the returned text is the answer
514
+ * alone, the text a program consumes and a token meter counts. Default
515
+ * `"stream"`. Where there is no returned text to carry it — the REPL, and
516
+ * a `halt` — a `"reply"` footer is written to the output instead. It never
517
+ * enters the transcript either way.
518
+ *
519
+ * Where the reader reads the turn as it streams (the REPL, `"stream"`),
520
+ * every attempt is on screen before it is graded, so the gate answers for
521
+ * all of it: a rejected attempt gets its ✗ footer before the turn is
522
+ * re-run, and a final message that states nothing has the turn's whole
523
+ * printed text graded in its place (a claim made before a tool call, an
524
+ * earlier attempt it points back at). A `halt` there stops the run under
525
+ * the ✗ of an answer that has already printed — the classified stop and
526
+ * exit code are what refuse it.
527
+ */
528
+ readonly footerTarget?: "stream" | "reply" | "none";
529
+ /**
530
+ * Does the reader read this turn as it streams, whatever `footerTarget`
531
+ * says? `crewhaus run --prompt` prints every attempt to stdout as it is
532
+ * written and the footer rides the returned result (`"reply"`): there the
533
+ * turn streams too, so a rejected attempt is marked ✗ under it and a
534
+ * claimless final message has the turn's printed text graded. Absent ⇒
535
+ * read off `footerTarget` and the loop's mode (the REPL, or `"stream"`).
536
+ */
537
+ readonly streamed?: boolean;
538
+ /**
539
+ * The verifier. `turn.finalText` is the text graded: the terminal
540
+ * assistant message's, or — where the turn streams to its reader and that
541
+ * message states nothing — everything the turn printed (see
542
+ * `footerTarget`).
543
+ */
544
+ readonly verify: (turn: ProvabilityTurn) => Promise<ProofBundle>;
545
+ /** Render the bundle for `render` (footer line / JSON). Absent ⇒ nothing is rendered. */
546
+ readonly renderBundle?: (bundle: ProofBundle, bundlePath?: string) => string | undefined;
547
+ /** Compose the retry nudge from a failing bundle. */
548
+ readonly nudge: (bundle: ProofBundle) => string;
549
+ /**
550
+ * How a persisted bundle's path is shown on the run's LIVE surfaces — the
551
+ * `provability_graded` trace event (which `runs.subscribe` streams to a
552
+ * gateway client) and a `halt`'s failure detail — the footer's rule
553
+ * (design §5.3, §8): relative to the tenant's root inside a tenant scope,
554
+ * else the workspace. The durable event-log line keeps the path as
555
+ * persisted. Absent ⇒ shown as persisted.
556
+ */
557
+ readonly displayPath?: (bundlePath: string) => string;
558
+ /** Persist the bundle; returns where it landed. Failures are logged, never fatal. */
559
+ readonly persist?: (bundle: ProofBundle, at: {
560
+ readonly sessionId?: string;
561
+ readonly turnNumber: number;
562
+ }) => Promise<string | undefined>;
563
+ /** Observe every bundle (the gateway envelope, the research report, tests). */
564
+ readonly onBundle?: (bundle: ProofBundle, bundlePath?: string) => void;
565
+ /**
566
+ * 0.8.0 (design §8) — the rendered `provability` skill text. Never read by
567
+ * this loop's own gate: the bridge projects it, with `level`, as the
568
+ * READ-ONLY provability seam a Task child receives, so researcher children
569
+ * cite the way the parent's gate reads. Absent ⇒ children get the floor
570
+ * alone (the spawner's own framing).
571
+ */
572
+ readonly skill?: string;
573
+ };
374
574
  /**
375
575
  * Loop contract 0.4 (G02) — the in-loop evaluation seam (spec
376
576
  * `evaluation:` on cli/channel/managed). See
@@ -733,10 +933,11 @@ export type RunChatLoopOptions = {
733
933
  * Only `tools` are the chat loop's to bind: they are APPENDED to `opts.tools`
734
934
  * and advertised to the model, with first-party tools winning any name
735
935
  * collision (a plugin can augment the catalog but not silently shadow a
736
- * built-in). The other contribution kinds bind at their own hosts — channels
737
- * at the channel daemon, models at the model-router, graders at the eval
738
- * stack, target emitters at the compiler — so they are deliberately not
739
- * accepted here. A compiled bundle instead registers plugin tools directly on
936
+ * built-in). The other contribution kinds (channels, models, graders,
937
+ * target emitters) are bound by no host in this release —
938
+ * `activatePlugins` collects them and says at boot that they have no effect
939
+ * (plugin-loader's `UNBOUND_CONTRIBUTION_KINDS`) — so they are not accepted
940
+ * here. A compiled bundle instead registers plugin tools directly on
740
941
  * its `defaultCatalog`; this option is the interpreter path's equivalent so a
741
942
  * `runChatLoop` caller need not mutate a global catalog. Absent → the run is
742
943
  * byte-identical to a pre-G32 runtime.
@@ -1256,11 +1457,13 @@ export type RunChatLoopOptions = {
1256
1457
  /**
1257
1458
  * Pillar 3 sink-side — classify a tool sink as `"external-configured"` (a
1258
1459
  * spec-declared sink → warn on non-user content) or `"external-dynamic"` (a
1259
- * runtime-joined sink → block on non-user content). Defaults to treating
1260
- * `mcp__*` sinks as dynamic and everything else as configured (#144); wire
1261
- * this to mark federation-joined or other runtime-discovered sinks dynamic.
1460
+ * runtime-joined sink → block on non-user content). Defaults to
1461
+ * {@link defaultSinkScope}: `mcp__*` sinks and tools that send to a
1462
+ * destination the model chooses are dynamic, everything else configured
1463
+ * (#144); wire this to mark federation-joined or other runtime-discovered
1464
+ * sinks dynamic. It receives the tool as well as its name.
1262
1465
  */
1263
- resolveSinkScope?: (toolName: string) => SinkScope;
1466
+ resolveSinkScope?: (toolName: string, tool?: RegisteredTool) => SinkScope;
1264
1467
  /**
1265
1468
  * Hard cap on the number of model→tool cycles in a single turn. The loop
1266
1469
  * detector is advisory (it only injects a one-time warning and is defeated
@@ -1830,6 +2033,15 @@ export type RunChatLoopOptions = {
1830
2033
  * is not evaluated. Absent → zero behaviour change for existing callers.
1831
2034
  */
1832
2035
  evaluation?: RunEvaluation;
2036
+ /**
2037
+ * 0.8.0 (design/0.8.0-provability-release.md §5.1) — the provability gate.
2038
+ * See {@link RunProvability}. Runs on every completed attempt BEFORE
2039
+ * `evaluation` grades it (provability first: free and deterministic, the
2040
+ * judge may spend); a failing verdict re-runs the turn without a judge
2041
+ * call, so a served answer has passed both gates when retries allow.
2042
+ * Absent → zero behaviour change.
2043
+ */
2044
+ provability?: RunProvability;
1833
2045
  /**
1834
2046
  * Loop contract 0.4 (Batch C, item 4) — the publishing agent's identity
1835
2047
  * fingerprint (the `agentId` from `loadOrCreateAgentIdentity`). When set AND
@@ -1943,15 +2155,41 @@ export declare function resolveSessionRootDir(optsRoot: string | undefined): str
1943
2155
  */
1944
2156
  export declare function resolveToolResultRoot(): string | undefined;
1945
2157
  /**
1946
- * Default egress sink-scope. Runtime-joined MCP sinks (`mcp__*`) are the
1947
- * canonical dynamically-discovered external sink, and the model-destination
1948
- * built-ins above are dynamic by virtue of their model-chosen target — both
1949
- * classify as `"external-dynamic"` so the egress block tier is reachable for
1950
- * non-user-origin payloads (#144). Other spec-declared built-in sinks stay
1951
- * `"external-configured"` (warn). Override via `runChatLoop({ resolveSinkScope })`
1952
- * to mark federation-joined or other runtime sinks dynamic too.
2158
+ * 0.7.1 — re-key a tool-name map (rate limits) written with the pre-0.7.1
2159
+ * MCP spelling `<server>__<tool>` onto the registered `mcp__<server>__<tool>`
2160
+ * name. A key that already names a tool, `"*"`, or an old spelling whose new
2161
+ * name the map also carries is left alone. Returns the input by reference
2162
+ * when nothing moved.
2163
+ */
2164
+ export declare function rekeyLegacyMcpToolKeys<V>(map: Readonly<Record<string, V>> | undefined, toolNames: ReadonlySet<string>): Readonly<Record<string, V>> | undefined;
2165
+ /**
2166
+ * Default egress sink-scope.
2167
+ *
2168
+ * A sink whose DESTINATION the (prompt-injectable) model chooses is dynamic
2169
+ * even when the spec declares the tool: an attacker who steers the model
2170
+ * picks where the data goes, so content from a non-user origin reaching it
2171
+ * must reach the egress BLOCK tier, not merely warn (#144). Which tools those
2172
+ * are is read from the tool itself: an external tool whose `operativeArgs`
2173
+ * include a `url` or a `recipient` (`hasModelChosenDestination`) — Fetch,
2174
+ * HttpRequest, HttpBatch, WebhookPost, EmailSend, OpenExternal, the RPC
2175
+ * readers, … (permission-integration#5). Runtime-joined MCP sinks (`mcp__*`)
2176
+ * are dynamic too.
2177
+ *
2178
+ * A fixed-destination sink stays `"external-configured"` (warn): `SendMessage`
2179
+ * replies to the operator's channel, `WebSearch` and `ImageGenerate` call a
2180
+ * fixed provider, a code host is reached at its configured origin. The
2181
+ * names that were dynamic before tools declared their destinations (Fetch,
2182
+ * WebFetch, Navigate, EvmSendTransaction) stay dynamic, so a caller that
2183
+ * passes only a name gets the 0.7.0 answer. Override per deployment with
2184
+ * `runChatLoop({ resolveSinkScope })`.
2185
+ */
2186
+ export declare function defaultSinkScope(toolName: string, tool?: Pick<RegisteredTool, "scope" | "operativeArgs">): SinkScope;
2187
+ /**
2188
+ * 0.7.1 — every model string the run was configured with, for the bridge's
2189
+ * `specModels` (the Task tool's allow-list for a `.crewhaus/sub-agents`
2190
+ * definition's models). Exact strings, in first-seen order, no duplicates.
1953
2191
  */
1954
- export declare function defaultSinkScope(toolName: string): SinkScope;
2192
+ export declare function specModelsOf(opts: Pick<RunChatLoopOptions, "model" | "modelFallbacks" | "modelTiers" | "modelPool" | "compactionModel" | "budget">): ReadonlyArray<string>;
1955
2193
  /**
1956
2194
  * Everything the loop needs to serve ONE model — computed once per pool
1957
2195
  * candidate at boot (plus one `primaryPlan` for the single-model path and