@crewhaus/runtime-core 0.1.8 → 0.2.1

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
@@ -6,12 +6,30 @@ import { type EventLog } from "@crewhaus/event-log";
6
6
  import { type HookDef } from "@crewhaus/hooks-engine";
7
7
  import { type JustificationJudge, type PermissionMode, type RuleSet } from "@crewhaus/permission-engine";
8
8
  import type { RateLimiter } from "@crewhaus/rate-limiter";
9
+ import { type NamedFailureClass } from "@crewhaus/recovery-engine";
10
+ import { type Scoreboard } from "@crewhaus/routing-store";
9
11
  import { type RunContext } from "@crewhaus/run-context";
10
12
  import { type SkillRef } from "@crewhaus/skills-registry";
11
13
  import { type SlashCommand } from "@crewhaus/slash-commands";
12
14
  import type { RegisteredTool } from "@crewhaus/tool-catalog";
15
+ import { type AlertSink } from "./observability";
16
+ import type { SloMitigationSink, SloTargets } from "./slo-monitor";
17
+ /**
18
+ * Run `items` through `fn` with at most `limit` in flight at once,
19
+ * preserving input order in the returned results. A pool of `limit`
20
+ * workers pull from a shared cursor, so a slow item never blocks a fast
21
+ * one behind it (unlike fixed-size `Promise.all` chunks). `limit <= 0`
22
+ * is clamped to 1; a limit larger than the batch just runs everything.
23
+ * Exported for unit testing of the concurrency bound.
24
+ */
25
+ export declare function mapWithConcurrency<T, R>(items: ReadonlyArray<T>, limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
13
26
  export { CLAUDE_CODE_HEADERS, CLAUDE_CODE_SYSTEM_PREFIX, OAUTH_BETAS, createAnthropicClient, resolveAuth, } from "@crewhaus/adapter-anthropic";
14
27
  export type { ResolvedAuth } from "@crewhaus/adapter-anthropic";
28
+ export { createJanitor } from "./janitor";
29
+ export type { CreateJanitorOptions, Janitor, JanitorReservationStore, JanitorRunResult, JanitorStepName, JanitorStepResult, JanitorStepStatus, } from "./janitor";
30
+ export { type AlertBreachPayload, type AlertSink, type AttachDefaultSubscribersOptions, attachDefaultSubscribers, } from "./observability";
31
+ 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";
32
+ export { type AttachIncidentCollectorOptions, type IncidentCapture, type IncidentTriggerKind, attachIncidentCollector, classifyIncidentTrigger, } from "./incident-collector";
15
33
  /**
16
34
  * Reconcile a message history by dropping "orphan" `tool_use` blocks — a
17
35
  * `tool_use` with no answering `tool_result` anywhere later in the
@@ -69,6 +87,31 @@ export type JustificationAuditSink = {
69
87
  readonly payload: unknown;
70
88
  }): Promise<unknown>;
71
89
  };
90
+ /**
91
+ * Pillar 3 sink-side fabric — the durable audit sink the egress classifier
92
+ * appends to. Structurally the same subset of `@crewhaus/audit-log`'s
93
+ * `AuditLog` as {@link JustificationAuditSink} (its `append({ kind, payload })`),
94
+ * declared as a minimal interface so runtime-core takes no dependency on (or
95
+ * cycle with) `@crewhaus/audit-log`.
96
+ *
97
+ * BACKGROUND (AUTOMATION-OPPORTUNITIES.md item 20): the `egress_decision`
98
+ * AuditKind was declared but had NO writer — egress verdicts existed ONLY as
99
+ * ephemeral trace-bus `permission_decision` events (outcome: `egress-*`), so
100
+ * nothing could triage egress history offline. This seam closes that: when a
101
+ * caller wires it, every NON-PASS egress verdict (warn OR block) appends one
102
+ * durable `egress_decision` record so `crewhaus egress review` can mine it.
103
+ * The RAW outbound payload is never stored — only the lineage summary the
104
+ * digest documents (`{ sinkId, sinkScope, verdict, originsFound, matchCount }`),
105
+ * exactly as `@crewhaus/audit-log`'s AuditKind header specifies. Pass verdicts
106
+ * are NOT written (they are the overwhelming common case and carry no triage
107
+ * signal). Omitting the sink is zero behaviour change for existing callers.
108
+ */
109
+ export type EgressAuditSink = {
110
+ append(input: {
111
+ readonly kind: "egress_decision";
112
+ readonly payload: unknown;
113
+ }): Promise<unknown>;
114
+ };
72
115
  export type RunChatLoopOptions = {
73
116
  model: string;
74
117
  instructions: string;
@@ -98,6 +141,21 @@ export type RunChatLoopOptions = {
98
141
  * When omitted, defaults to `_adapter` (or the routed primary).
99
142
  */
100
143
  _compactionAdapter?: ProviderAdapter;
144
+ /**
145
+ * Item 22 — same injection contract as `_adapter`, for the failover
146
+ * chain's fallback candidates: pre-built adapters keyed by their spec
147
+ * model string, bypassing the model-router. Only consulted when
148
+ * `modelFallbacks` is non-empty. Tests script per-candidate failures
149
+ * through this map; production callers leave it undefined.
150
+ */
151
+ _failoverAdapters?: ReadonlyMap<string, ProviderAdapter>;
152
+ /**
153
+ * Item 27 — test injection for the budget-degrade target: a pre-built
154
+ * adapter used in place of `resolveModel(budget.onExceed.model)` when a
155
+ * `degrade` breach fires. Production callers leave it undefined (the
156
+ * runtime resolves the degrade model through the normal router path).
157
+ */
158
+ _budgetDegradeAdapter?: ProviderAdapter;
101
159
  /** Override the input stream (testing). Defaults to process.stdin. */
102
160
  input?: NodeJS.ReadableStream;
103
161
  /** Tools the model may invoke. When empty/undefined, tools are not advertised. */
@@ -202,6 +260,40 @@ export type RunChatLoopOptions = {
202
260
  * `pre-slash` first; deny falls through to the original input.
203
261
  */
204
262
  slashCommands?: ReadonlyMap<string, SlashCommand>;
263
+ /**
264
+ * Feature #53 — cross-session memory auto-recall/auto-capture wiring. When
265
+ * `store` is supplied (the caller builds it from `createMemoryStore`), the
266
+ * runtime honours the auto-* switches:
267
+ * - `autoRecall`: at session start, recall the top-`recallK` memories for
268
+ * the current context and inject them into the system prompt (mirrors
269
+ * the project-memory auto-load block). `recallSeed` is the query used
270
+ * (defaults to the agent instructions).
271
+ * - `autoCapture`: at run teardown (in the same finally where the `stop`
272
+ * hook fires — NOT a credential-stripped hook), the caller-supplied
273
+ * `onCapture` is invoked with the completed-turn count so it can
274
+ * summarize the session's durable outcomes into the store.
275
+ * Omitted → no memory injection or capture (Remember/Recall passed via
276
+ * `tools` still work). Kept as an injected seam so runtime-core does not
277
+ * depend on memory-store.
278
+ */
279
+ memory?: {
280
+ readonly autoRecall?: boolean;
281
+ readonly recallK?: number;
282
+ readonly recallSeed?: string;
283
+ /** Return recalled memory lines to inject; runtime wraps them in a block. */
284
+ readonly recall?: (query: string, k: number) => Promise<readonly string[]>;
285
+ readonly autoCapture?: boolean;
286
+ /** Invoked at teardown with the completed user-text turn count and the
287
+ * run's session id (so the callback can read the transcript to summarize). */
288
+ readonly onCapture?: (completedTurns: number, sessionId: string) => Promise<void>;
289
+ };
290
+ /**
291
+ * Item #56 — absolute paths to per-user preference files injected at run
292
+ * start via the project-memory auto-load path (alongside LESSONS.md, which
293
+ * is now a canonical memory file). The CLI resolves the current user's
294
+ * `.crewhaus/preferences/<user>.md` and threads it here. Absent → no-op.
295
+ */
296
+ preferenceFiles?: ReadonlyArray<string>;
205
297
  /**
206
298
  * Section 13 — inline sub-agent definitions exposed via the `Task` tool.
207
299
  * Threaded into the `RuntimeBridge` and surfaced to framework-aware
@@ -266,6 +358,41 @@ export type RunChatLoopOptions = {
266
358
  * `.crewhaus/audit`.
267
359
  */
268
360
  justificationAuditSink?: JustificationAuditSink;
361
+ /**
362
+ * Ops item 31 — durable + off-box delivery for the alert watchdog (gated by
363
+ * CREWHAUS_ALERTS). When supplied, a baseline-threshold breach appends an
364
+ * audit record and/or fires the settings.json `alert` hook / webhook via
365
+ * these callbacks. Omitted → the watchdog still persists its per-session
366
+ * metrics snapshot and publishes the `alert_raised` trace event, it just has
367
+ * no durable/off-box delivery (zero behaviour change for existing callers).
368
+ * The CLI `run` path wires the audit log + settings.json alert hook here.
369
+ */
370
+ alertSink?: AlertSink;
371
+ /** Item 31 — override the per-session metrics-history dir (tests/tenants). */
372
+ alertMetricsDir?: string;
373
+ /**
374
+ * Ops item 37 — lowered `observability.slo` targets (gated by CREWHAUS_SLO).
375
+ * When supplied, the runtime SLO monitor folds live events into rolling
376
+ * windows and walks the declared mitigation ladder on a sustained breach.
377
+ * Omitted → no monitor (zero behaviour change). The CLI `run` path lowers
378
+ * the cwd spec's `observability.slo` block and wires the mitigation sink.
379
+ */
380
+ sloTargets?: SloTargets;
381
+ /** Item 37 — injected SLO mitigation ladder delivery (audit / pause-intake /
382
+ * rollback), supplied by the CLI so runtime-core owns no deploy/gateway I/O. */
383
+ sloSink?: SloMitigationSink;
384
+ /**
385
+ * Ops item 32 — spec identity stamped into an auto-assembled incident
386
+ * capture (gated by CREWHAUS_INCIDENTS). Absent → the capture records a null
387
+ * spec; the CLI `run` path passes `{ name, version?, hash? }`.
388
+ */
389
+ incidentSpec?: {
390
+ readonly name: string;
391
+ readonly version?: string;
392
+ readonly hash?: string;
393
+ };
394
+ /** Item 32 — override the incidents dir (tests/tenants). */
395
+ incidentsDir?: string;
269
396
  /**
270
397
  * Pillar 3 sink-side fabric (FR-006) — pluggable egress-matching
271
398
  * strategy. When supplied, every external-scope tool call routes its
@@ -279,6 +406,17 @@ export type RunChatLoopOptions = {
279
406
  * instance of `@crewhaus/egress-matcher-semantic`.
280
407
  */
281
408
  egressMatcher?: EgressMatcher;
409
+ /**
410
+ * Pillar 3 sink-side fabric — durable egress audit sink (item 20). When
411
+ * supplied, every NON-PASS egress verdict (warn OR block) appends one
412
+ * `egress_decision` record (lineage summary only, never the raw payload) to
413
+ * this hash-chained sink IN ADDITION to the ephemeral `permission_decision`
414
+ * trace event. This is what makes egress history triageable offline by
415
+ * `crewhaus egress review`. Omitting it leaves the trace bus as the only
416
+ * surface (no behaviour change for existing callers). The CLI `run` path
417
+ * wires a real `@crewhaus/audit-log` instance rooted at `.crewhaus/audit`.
418
+ */
419
+ egressAuditSink?: EgressAuditSink;
282
420
  /**
283
421
  * Pillar 3 sink-side — classify a tool sink as `"external-configured"` (a
284
422
  * spec-declared sink → warn on non-user content) or `"external-dynamic"` (a
@@ -298,16 +436,130 @@ export type RunChatLoopOptions = {
298
436
  */
299
437
  maxToolIterations?: number;
300
438
  /**
301
- * Section 27 — wrap the resolved primary `ProviderAdapter` in a circuit
302
- * breaker before any `stream()` call. When the breaker trips, subsequent
303
- * model calls reject immediately rather than hammering a degraded
304
- * upstream. Set via codegen when the spec lists `circuit_breaker:` opts.
439
+ * Max number of concurrency-safe tool calls executed in parallel within
440
+ * a single turn. Chiefly bounds parallel sub-agent (`Task`) fan-out so a
441
+ * wide dispatch can't open unbounded model connections; parallel reads
442
+ * are also capped but their per-call cost is negligible. Defaults to
443
+ * `DEFAULT_MAX_CONCURRENT_TOOLS` (4). `<= 0` is clamped to 1 (serial).
444
+ */
445
+ maxConcurrentTools?: number;
446
+ /**
447
+ * Section 27 / item 22 — wrap the resolved primary `ProviderAdapter` in a
448
+ * circuit breaker before any `stream()` call. When the breaker trips,
449
+ * subsequent model calls reject immediately rather than hammering a
450
+ * degraded upstream. Set by codegen (and the `crewhaus run` path) from the
451
+ * spec's `agent.circuit_breaker` block; field names mirror
452
+ * `CircuitBreakerOptions` in `@crewhaus/circuit-breaker`. When
453
+ * `modelFallbacks` is also set, this tuning applies to EVERY candidate's
454
+ * breaker in the failover chain.
305
455
  */
306
456
  circuitBreaker?: {
307
457
  readonly failureThreshold?: number;
308
458
  readonly windowMs?: number;
309
459
  readonly cooldownMs?: number;
310
460
  };
461
+ /**
462
+ * Item 22 — ordered fallback model strings (spec `agent.model_fallbacks`).
463
+ * When non-empty, the primary adapter is replaced by a
464
+ * `@crewhaus/model-router` failover chain: every candidate (primary
465
+ * first) gets its own circuit breaker, each model call routes to the
466
+ * first candidate whose breaker admits traffic, and routing changes are
467
+ * published as `model_failover` trace events. Fallbacks resolve their
468
+ * credentials lazily via the normal `resolveModel` path — a candidate
469
+ * with a missing key warns at boot (doctor-style, stderr) and is skipped
470
+ * when actually tried, never hard-failing boot. v1 scope: only the
471
+ * primary agent model gets the chain — `compactionModel` (when it names
472
+ * its own model) and judge/grader slots keep their single adapters. When
473
+ * compaction reuses the primary model (no `compactionModel`), it flows
474
+ * through the same chain by construction.
475
+ */
476
+ modelFallbacks?: ReadonlyArray<string>;
477
+ /**
478
+ * Item 26 — opt-in two-tier turn-difficulty router (spec `agent.model_tiers`).
479
+ * When set, BOTH tier adapters resolve at boot (mirroring the compaction
480
+ * second-adapter wiring), and each turn the loop picks a tier from
481
+ * deterministic signals (estimated context tokens, tools-in-play, turn
482
+ * index, prior-turn tool_use density), streams through the chosen tier's
483
+ * adapter, and publishes a `model_tier_route` trace event. A `fast`-tier
484
+ * turn that FAILS is re-run on `default` (misroute recovery). Absent → the
485
+ * single primary adapter path, unchanged. Mutually independent of
486
+ * `modelFallbacks`: when both are set the primary chain still governs the
487
+ * `default` tier; the `fast` tier is its own single adapter (v1 scope).
488
+ */
489
+ modelTiers?: {
490
+ readonly fast: string;
491
+ readonly default: string;
492
+ readonly routing?: {
493
+ readonly contextTokenThreshold?: number;
494
+ readonly toolsToDefault?: boolean;
495
+ readonly firstTurnToDefault?: boolean;
496
+ readonly priorToolDensityThreshold?: number;
497
+ };
498
+ };
499
+ /**
500
+ * Item 26 — test injection for the two tier adapters, keyed by their spec
501
+ * model string (mirrors `_failoverAdapters`). Production callers leave it
502
+ * undefined (the runtime resolves both tiers through the normal router).
503
+ */
504
+ _tierAdapters?: ReadonlyMap<string, ProviderAdapter>;
505
+ /**
506
+ * Adaptive model routing (spec `agent.model_pool`). When set, every
507
+ * candidate adapter resolves at boot and each turn a `PolicyRouter` selects
508
+ * one from deterministic signals (`static`/`heuristic`) or the durable reward
509
+ * scoreboard (`learned`), publishing a `model_route` trace event. After each
510
+ * turn the observed outcome (success, latency, cost) is folded into the
511
+ * scoreboard so selection improves the more the harness runs. Mutually
512
+ * exclusive with `modelTiers`/`modelFallbacks` (enforced in the spec); the
513
+ * pool takes precedence if all are somehow set. Absent → single-model path.
514
+ */
515
+ modelPool?: {
516
+ readonly candidates: ReadonlyArray<{
517
+ readonly model: string;
518
+ readonly tags: readonly string[];
519
+ }>;
520
+ readonly policy: "static" | "heuristic" | "learned";
521
+ readonly objective?: {
522
+ readonly quality?: number;
523
+ readonly cost?: number;
524
+ readonly latency?: number;
525
+ };
526
+ readonly routing?: {
527
+ readonly contextTokenThreshold?: number;
528
+ readonly toolsToDefault?: boolean;
529
+ readonly firstTurnToDefault?: boolean;
530
+ readonly priorToolDensityThreshold?: number;
531
+ readonly strongTag?: string;
532
+ readonly cheapTag?: string;
533
+ };
534
+ readonly learning?: {
535
+ readonly minSamplesPerArm?: number;
536
+ readonly costRefUsd?: number;
537
+ readonly latencyRefMs?: number;
538
+ };
539
+ };
540
+ /**
541
+ * Test injection for the pool candidate adapters, keyed by their spec model
542
+ * string (mirrors `_tierAdapters`). Production callers leave it undefined.
543
+ */
544
+ _poolAdapters?: ReadonlyMap<string, ProviderAdapter>;
545
+ /**
546
+ * Test injection for the reward scoreboard. Production callers leave it
547
+ * undefined (the runtime opens a file-backed scoreboard beside the sessions
548
+ * dir); tests inject an in-memory or tmp-dir instance to assert learning.
549
+ */
550
+ _scoreboard?: Scoreboard;
551
+ /**
552
+ * Section 55 (Track A) / item 23 — the spec's `failure_taxonomy`, lowered
553
+ * from the IR. Consulted by `recovery-engine.recover()` BEFORE its
554
+ * built-in classify+recover flow so user-named error classes take
555
+ * precedence (their declared `recovery` action wins). Item 23 adds the
556
+ * `switch-model` action: a matched entry reroutes the same turn onto the
557
+ * next provider-failover candidate (opening the active breaker) instead
558
+ * of exhausting backoff retries — only meaningful with `modelFallbacks`
559
+ * set; a no-op re-issue otherwise. When absent, recovery is the built-in
560
+ * taxonomy exactly as before (zero behaviour change for existing callers).
561
+ */
562
+ failureTaxonomy?: ReadonlyArray<NamedFailureClass>;
311
563
  /**
312
564
  * Section 27 — pre-call rate gating. The runtime calls
313
565
  * `rateLimiter.acquire(rateLimitKeys, 1)` before each model invocation.
@@ -328,6 +580,36 @@ export type RunChatLoopOptions = {
328
580
  * Pass `0` (or omit) to force a refresh on the first turn.
329
581
  */
330
582
  promptCacheLastRotatedAt?: number;
583
+ /**
584
+ * Item 27 — run-level spend cap with a degradation ladder. Generalizes
585
+ * the optimizer's `BudgetMeter` to normal runs (`crewhaus run
586
+ * --budget-usd` / spec `budget: { usd, on_exceed }`). An always-on cost
587
+ * meter (independent of `CREWHAUS_COST_TRACKING`) accrues per-response
588
+ * spend priced off the WIRE model that actually served, and a PRE-TURN
589
+ * check — beside the token-budget/compaction check — enforces the cap
590
+ * before the next user turn opens:
591
+ * - `on_exceed.kind: "stop"` ends the run cleanly with a `[budget]`
592
+ * notice (the current turn always completes; the cap gates the NEXT
593
+ * turn, so an in-flight turn is never severed mid-tool-call).
594
+ * - `on_exceed.kind: "degrade"` re-resolves the primary model to
595
+ * `on_exceed.model` ONCE (the cheaper rung of the ladder) and
596
+ * continues; a `model_failover` event (reason `budget_degrade`)
597
+ * records the switch. If spend later crosses the cap AGAIN on the
598
+ * degraded model, the run stops (the ladder has one rung in v1).
599
+ * `usdMicros` is the ceiling in USD-micros (1 USD = 1_000_000). Absent →
600
+ * no cap (zero behaviour change for existing callers). A model the
601
+ * pricing table can't price accrues $0, so an all-unpriced run degrades
602
+ * to uncapped — same posture as cost-tracker's pricing-miss handling.
603
+ */
604
+ budget?: {
605
+ readonly usdMicros: number;
606
+ readonly onExceed: {
607
+ readonly kind: "stop";
608
+ } | {
609
+ readonly kind: "degrade";
610
+ readonly model: string;
611
+ };
612
+ };
331
613
  };
332
614
  /**
333
615
  * Runs the streaming chat loop and returns the terminal assistant text.