@rulvar/core 1.57.0 → 1.59.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
@@ -1035,6 +1035,90 @@ declare function maskSecrets(text: string): string;
1035
1035
  declare function maskSecretsDeep<T>(value: T): T;
1036
1036
  /** Convenience for hosts: masks a Json value (alias of the deep walk). */
1037
1037
  declare function maskSecretsJson(value: Json): Json;
1038
+ /** A compiled masking policy: text and deep-JSON forms of one pattern set. */
1039
+ interface SecretMasker {
1040
+ maskText(text: string): string;
1041
+ maskDeep<T>(value: T): T;
1042
+ }
1043
+ /**
1044
+ * Compiles the redaction policy: the DEFAULT credential pattern set
1045
+ * plus host-defined patterns (RV-217), for the telemetry boundary
1046
+ * (events and traces; never the journal, where lossless encryption is
1047
+ * the right tool). String patterns compile as global regexes; RegExp
1048
+ * patterns are recompiled with the global flag when it is missing, so
1049
+ * replace-all semantics always hold. An invalid pattern is a typed
1050
+ * ConfigError at compile time, before anything runs under the policy.
1051
+ */
1052
+ declare function compileSecretMasker(patterns?: ReadonlyArray<RegExp | string>, site?: string): SecretMasker;
1053
+ //#endregion
1054
+ //#region src/l0/encryption.d.ts
1055
+ /**
1056
+ * The KMS seam. `keyId` is a stable routing id stamped into every
1057
+ * envelope (a KMS key ARN or alias, or a local rotation label); the
1058
+ * two methods are the exact shape of KMS GenerateDataKey and Decrypt.
1059
+ * Both are called only inside `createEnvelopeEncryption`.
1060
+ */
1061
+ interface DataKeyProvider {
1062
+ readonly keyId: string;
1063
+ generateDataKey(): Promise<{
1064
+ plaintext: Bytes;
1065
+ wrapped: Bytes;
1066
+ }>;
1067
+ unwrapDataKey(wrapped: Bytes): Promise<Bytes>;
1068
+ }
1069
+ /**
1070
+ * The local reference DataKeyProvider: the key-encryption key is
1071
+ * HKDF-SHA256(secret, info), data keys are random 32-byte AES keys,
1072
+ * and wrapping is AES-256-GCM under the KEK. `info` partitions one
1073
+ * master secret into unrelated KEKs (tenant-scoped keys: one provider
1074
+ * per tenant with `info: tenantId`); a provider with different
1075
+ * secret or info CANNOT unwrap this provider's keys. For production
1076
+ * KMS, implement the same interface over GenerateDataKey/Decrypt.
1077
+ */
1078
+ declare function localKeyProvider(options: {
1079
+ secret: string | Bytes; /** Stamped into envelopes; default 'local:v1'. */
1080
+ keyId?: string; /** KEK partition label (e.g. a tenant id); default ''. */
1081
+ info?: string;
1082
+ }): DataKeyProvider;
1083
+ /** The journal envelope marker; a stored entry's whole value is this. */
1084
+ declare const JOURNAL_ENVELOPE_MARKER = "__rulvarEnvelope";
1085
+ interface EnvelopeEncryption {
1086
+ /** Pass as `createEngine({ serialization })`. */
1087
+ hook: SerializationHook;
1088
+ /** The provider's routing id, stamped into every envelope. */
1089
+ keyId: string;
1090
+ /**
1091
+ * The CURRENT wrapped data key. Every write stamps it into the
1092
+ * envelope, so nothing else must be persisted; it is exposed for
1093
+ * hosts that keep a rotation ledger.
1094
+ */
1095
+ wrappedDataKey: Bytes;
1096
+ }
1097
+ interface EnvelopeEncryptionOptions {
1098
+ provider: DataKeyProvider;
1099
+ /**
1100
+ * Wrapped data keys from earlier sessions or rotations that this
1101
+ * process must still read. Unwrapped once at creation; an envelope
1102
+ * carrying an UNREGISTERED wrapped key fails typed at read, naming
1103
+ * this list.
1104
+ */
1105
+ historicalWrappedKeys?: readonly Bytes[];
1106
+ /**
1107
+ * What a NON-enveloped stored entry or blob means at read:
1108
+ * 'reject' (default, fail closed) or 'passthrough' (explicit
1109
+ * migration mode for stores with pre-encryption history).
1110
+ */
1111
+ plaintextReads?: "reject" | "passthrough";
1112
+ }
1113
+ /**
1114
+ * Builds the envelope-encryption SerializationHook. All DataKeyProvider
1115
+ * calls happen HERE (the hook itself is synchronous, on in-memory data
1116
+ * keys): a fresh data key is minted and wrapped for this instance, and
1117
+ * every historical wrapped key is unwrapped for the read path.
1118
+ */
1119
+ declare function createEnvelopeEncryption(options: EnvelopeEncryptionOptions): Promise<EnvelopeEncryption>;
1120
+ /** Guards against non-constant-time comparisons in host key checks. */
1121
+ declare function constantTimeEqual(a: Bytes, b: Bytes): boolean;
1038
1122
  //#endregion
1039
1123
  //#region src/l0/usage.d.ts
1040
1124
  /**
@@ -1430,8 +1514,12 @@ interface ToolContext {
1430
1514
  }
1431
1515
  /**
1432
1516
  * Where execute runs. A declared capability consumed by dispatch and
1433
- * policy; only 'inprocess' is enforced in v1, subprocess/container remain
1434
- * declared capability while the executor design stays an open question.
1517
+ * policy. 'inprocess' runs the tool's `execute` closure in the engine
1518
+ * process (full host capabilities, an execution convenience). A
1519
+ * non-inprocess tag routes dispatch through the engine's registered
1520
+ * ToolExecutorProvider (RV-216) instead, so the tool's work runs out of
1521
+ * process under host-owned isolation; the shipped reference adapters live
1522
+ * in `@rulvar/executor`. The tag never enters toolsetHash.
1435
1523
  */
1436
1524
  type ToolExecutor = "inprocess" | "subprocess" | "container";
1437
1525
  /**
@@ -1449,6 +1537,14 @@ interface ToolDef<S extends SchemaSpec = SchemaSpec> {
1449
1537
  readonly version?: string;
1450
1538
  /** Default 'inprocess'. */
1451
1539
  readonly executor: ToolExecutor;
1540
+ /**
1541
+ * Opaque policy data for a non-inprocess executor: what THIS tool's
1542
+ * declared executor should run (for a subprocess adapter, the command
1543
+ * and its argv). Never identity: excluded from toolsetHash exactly like
1544
+ * `executor` and `risk`, and ignored for 'inprocess'. The engine passes
1545
+ * it verbatim to the ToolExecutorProvider (RV-216).
1546
+ */
1547
+ readonly executorSpec?: Json;
1452
1548
  /** Default false; the terminal permission default asks when true. */
1453
1549
  readonly needsApproval: boolean;
1454
1550
  readonly risk?: ToolRisk;
@@ -1691,6 +1787,67 @@ interface QuotaLimiter {
1691
1787
  reconcile(reservationId: string, usage: Usage): Promise<void>;
1692
1788
  }
1693
1789
  //#endregion
1790
+ //#region src/l0/spi/executor.d.ts
1791
+ /** The non-inprocess executor tags a provider can be registered under. */
1792
+ type IsolatedExecutorTag = Exclude<ToolExecutor, "inprocess">;
1793
+ /**
1794
+ * The per-call context handed to a ToolExecutorProvider. It carries the
1795
+ * tool span (so provider telemetry nests under the run tree), the
1796
+ * cancellation signal, and a stable idempotency key.
1797
+ */
1798
+ interface IsolatedExecContext {
1799
+ runId: string;
1800
+ /** The tool span, minted under the agent span exactly like inprocess. */
1801
+ spanId: string;
1802
+ agentType: string;
1803
+ /**
1804
+ * Stable identity of THIS logical tool call: identical
1805
+ * (runId, tool, args) always derive the same key, so a provider whose
1806
+ * work has external side effects can fold an at-least-once retry into
1807
+ * effectively-once. A rerun of the same call after a mid-flight crash
1808
+ * reuses the key; a different call never collides.
1809
+ */
1810
+ idempotencyKey: string;
1811
+ /** Fires on cancellation, a budget ceiling, or UsageLimits expiry. */
1812
+ signal: AbortSignal;
1813
+ /** Emits telemetry log events under the tool span; never journals. */
1814
+ log(level: "debug" | "info" | "warn" | "error", msg: string, data?: Json): void;
1815
+ }
1816
+ /** One out-of-process tool dispatch. */
1817
+ interface IsolatedExecRequest {
1818
+ /** The declared executor tag ('subprocess' | 'container'). */
1819
+ executor: IsolatedExecutorTag;
1820
+ /** The tool contract name. */
1821
+ tool: string;
1822
+ /** The validated arguments, after the permission chain rewrote them. */
1823
+ args: Json;
1824
+ /**
1825
+ * The tool's `executorSpec`: opaque host data telling THIS provider
1826
+ * what to run (for a subprocess adapter, the command and its argv).
1827
+ * Never identity; the engine passes it through verbatim.
1828
+ */
1829
+ spec: Json;
1830
+ ctx: IsolatedExecContext;
1831
+ }
1832
+ /**
1833
+ * The isolated tool executor seam. A provider runs one dispatch to its
1834
+ * JSON result. A thrown error becomes the call's error tool result, never
1835
+ * a run abort: an executor failure (non-zero exit, timeout kill,
1836
+ * unparseable output, infrastructure error) is surfaced to the model
1837
+ * exactly like any other tool error, so the loop can react and the run
1838
+ * stays durable.
1839
+ */
1840
+ interface ToolExecutorProvider {
1841
+ /** Runs one dispatch to its JSON result; throws to signal tool failure. */
1842
+ run(request: IsolatedExecRequest): Promise<Json>;
1843
+ }
1844
+ /**
1845
+ * The engine's executor registry: at most one provider per non-inprocess
1846
+ * tag. A tool whose `executor` tag is absent here fails typed at spawn
1847
+ * time, before any provider or model call.
1848
+ */
1849
+ type ExecutorRegistry = Partial<Record<IsolatedExecutorTag, ToolExecutorProvider>>;
1850
+ //#endregion
1694
1851
  //#region src/knowledge/decay.d.ts
1695
1852
  /**
1696
1853
  * The asymmetric TTL table:
@@ -3919,6 +4076,14 @@ interface ToolRuntime {
3919
4076
  contextFor(toolName: string): ToolContext;
3920
4077
  /** Permission chain evaluation (M3-T03); absent = every call allowed. */
3921
4078
  permission?: (call: ToolCallRequest) => Promise<PermissionGate>;
4079
+ /**
4080
+ * Runs a non-inprocess tool out of process through the engine's
4081
+ * registered ToolExecutorProvider (RV-216). Present whenever the frozen
4082
+ * toolset holds any non-inprocess tool; the ctx layer mints the tool
4083
+ * span and idempotency key and wires the provider. A throw becomes the
4084
+ * call's error tool result exactly like an inprocess execute throw.
4085
+ */
4086
+ executeExternal?: (def: ToolDef, args: Json) => Promise<unknown>;
3922
4087
  }
3923
4088
  /** One serving target of a phase: the primary or a failover fallback. */
3924
4089
  interface PhaseTarget {
@@ -4225,7 +4390,7 @@ declare function emptyToolset(): ResolvedToolset;
4225
4390
  * without one, string entries fail with the same unknown-name error as
4226
4391
  * a miss, so nothing outside the declared registry is ever reachable.
4227
4392
  */
4228
- declare function resolveToolset(specs: ToolsOption | undefined, session: ToolSourceSession, toolsets?: Record<string, ToolsOption>): Promise<ResolvedToolset>;
4393
+ declare function resolveToolset(specs: ToolsOption | undefined, session: ToolSourceSession, toolsets?: Record<string, ToolsOption>, executors?: ReadonlySet<string>): Promise<ResolvedToolset>;
4229
4394
  //#endregion
4230
4395
  //#region src/journal/termination.d.ts
4231
4396
  /** The frozen limits vector written into termination.init. */
@@ -5426,6 +5591,19 @@ interface CreateEngineOptions {
5426
5591
  sandbox?: ScriptRunner;
5427
5592
  };
5428
5593
  /**
5594
+ * Isolated tool executors (RV-216): one ToolExecutorProvider per
5595
+ * non-inprocess `executor` tag. A tool declaring `executor: 'subprocess'`
5596
+ * or `'container'` dispatches through the matching provider, so its work
5597
+ * runs OUT of the engine process under host-owned isolation instead of
5598
+ * as an inprocess closure with full host capabilities. The shipped
5599
+ * reference adapters (subprocessExecutor, containerExecutor) live in
5600
+ * `@rulvar/executor`. Absent = only inprocess tools are accepted, and a
5601
+ * non-inprocess tag is a typed ConfigError at spawn time. In-process
5602
+ * tools stay ordinary function calls: never a sandbox for hostile or
5603
+ * model-generated code.
5604
+ */
5605
+ executors?: ExecutorRegistry;
5606
+ /**
5429
5607
  * The InProcessRunner escalation hook:
5430
5608
  * receives escalated results when the call form cannot carry them; the
5431
5609
  * returned decision is journaled as the authoritative
@@ -5446,12 +5624,18 @@ interface CreateEngineOptions {
5446
5624
  */
5447
5625
  serialization?: SerializationHook;
5448
5626
  /**
5449
- * The default key-masking policy at the telemetry boundary. Default
5450
- * ON: key-shaped strings in every
5451
- * emitted WorkflowEvent are masked; never touches the journal.
5627
+ * The masking policy at the telemetry boundary. Default ON:
5628
+ * key-shaped strings in every emitted WorkflowEvent are masked;
5629
+ * never touches the journal (lossless encryption via `serialization`
5630
+ * is the persistence-side tool). `patterns` adds host-defined
5631
+ * redaction on top of the default credential set (RV-217): RegExp or
5632
+ * pattern strings, compiled once at construction, applied to every
5633
+ * string in every emitted event body. Feed the same patterns to the
5634
+ * OTel exporter for trace parity.
5452
5635
  */
5453
5636
  redaction?: {
5454
5637
  maskEvents?: boolean;
5638
+ patterns?: ReadonlyArray<RegExp | string>;
5455
5639
  };
5456
5640
  /**
5457
5641
  * Bare-nondeterminism detection over in-process workflow bodies
@@ -5465,6 +5649,21 @@ interface CreateEngineOptions {
5465
5649
  * runtime frames are classified exempt and stay silent.
5466
5650
  */
5467
5651
  determinism?: DeterminismConfig;
5652
+ /**
5653
+ * Metadata protection knobs (RV-217). `argsHashSalt` switches the
5654
+ * RunMeta.argsHash digest from plain sha256 to HMAC-SHA256 under the
5655
+ * salt: equal args stop correlating across deployments and
5656
+ * low-entropy args stop being recoverable from the digest. The salt
5657
+ * is deployment config, not a per-run secret: every engine (and the
5658
+ * CLI host config) resuming this store's runs must carry the SAME
5659
+ * salt, or the resume args gate refuses matching args. Runs recorded
5660
+ * before the salt keep their unsalted digests; the gate then simply
5661
+ * mismatches until forced, so introduce the salt on a fresh store or
5662
+ * accept --allow-args-change on legacy runs.
5663
+ */
5664
+ security?: {
5665
+ argsHashSalt?: string;
5666
+ };
5468
5667
  }
5469
5668
  interface RunOptions {
5470
5669
  /** Explicit id; otherwise the engine mints a ULID. */
@@ -5590,6 +5789,35 @@ interface Engine {
5590
5789
  pruneRun(runId: string, opts?: {
5591
5790
  lease?: Lease;
5592
5791
  }): Promise<number>;
5792
+ /**
5793
+ * Portable run export (RV-217): the meta record, every journal
5794
+ * entry, and every transcript blob, read through Engine.stores (the
5795
+ * one policy point), so an encrypted deployment exports PLAINTEXT
5796
+ * for a subject-access request or a store migration, without raw
5797
+ * store spelunking. Blobs are materialized in memory; export runs
5798
+ * one at a time, not catalogs.
5799
+ */
5800
+ exportRun(runId: string): Promise<RunExport>;
5801
+ /**
5802
+ * Imports a bundle produced by exportRun, under its ORIGINAL runId
5803
+ * (transcript refs and journal fields embed it; rewriting ids is
5804
+ * deliberately out of scope). Writes through Engine.stores, so an
5805
+ * encrypting target re-encrypts under its own policy. Refuses typed
5806
+ * when the run already exists in the target store, so an import can
5807
+ * never interleave with live history.
5808
+ */
5809
+ importRun(bundle: RunExport): Promise<void>;
5810
+ }
5811
+ /** The portable bundle exportRun produces and importRun consumes (RV-217). */
5812
+ interface RunExport {
5813
+ runId: string;
5814
+ /** Absent when the source store had no meta row for the run. */
5815
+ meta?: RunMeta;
5816
+ entries: JournalEntry[];
5817
+ blobs: Array<{
5818
+ ref: string;
5819
+ data: Bytes;
5820
+ }>;
5593
5821
  }
5594
5822
  /** Content hash of an in-process workflow body (run-to-definition binding). */
5595
5823
  declare function hashWorkflowBody(wf: Workflow<never, never> | Workflow<unknown, unknown>): string;
@@ -5613,7 +5841,9 @@ declare function workflowSourceRef(runId: string): string;
5613
5841
  * sensitive-derived metadata, not a value safe to publish (see the
5614
5842
  * `argsHash` field docs).
5615
5843
  */
5616
- declare function hashRunArgs(args: unknown): string | undefined;
5844
+ declare function hashRunArgs(args: unknown, options?: {
5845
+ salt?: string;
5846
+ }): string | undefined;
5617
5847
  /**
5618
5848
  * sha256 hex over the JCS canonical serialization of a run's result
5619
5849
  * value: the digest the engine records as `outputHash` on the journaled
@@ -7125,6 +7355,14 @@ interface RunInternals {
7125
7355
  /** The worktree lifecycle provider. */
7126
7356
  isolation?: IsolationProvider;
7127
7357
  /**
7358
+ * Isolated tool executors (RV-216): the ToolExecutorProvider registry
7359
+ * from createEngine, keyed by non-inprocess executor tag. A tool
7360
+ * declaring such a tag dispatches through the matching provider instead
7361
+ * of running its inprocess closure; absent means only inprocess tools
7362
+ * are accepted.
7363
+ */
7364
+ executors?: ExecutorRegistry;
7365
+ /**
7128
7366
  * The ModelKnowledge runtime handle (M10-T03): current()
7129
7367
  * only, commit physically absent. Present only when the engine was
7130
7368
  * given stores.modelKnowledge; absent means the feature is off and
@@ -7302,6 +7540,8 @@ interface ToolInit<S extends SchemaSpec> {
7302
7540
  version?: string;
7303
7541
  /** Default 'inprocess'. */
7304
7542
  executor?: ToolExecutor;
7543
+ /** Opaque data for a non-inprocess executor (RV-216); never identity. */
7544
+ executorSpec?: Json;
7305
7545
  /** Default false. */
7306
7546
  needsApproval?: boolean;
7307
7547
  /** Policy metadata; never identity. */
@@ -7545,6 +7785,37 @@ declare function implementationAgentProfile(options?: AgentProfileTemplateOption
7545
7785
  */
7546
7786
  declare function reviewAgentProfile(options?: AgentProfileTemplateOptions): AgentProfile;
7547
7787
  //#endregion
7788
+ //#region src/engine/audit.d.ts
7789
+ type AuditCategory = "suspension" | "resolution" | "abandon" | "decision" | "termination-denied" | "run-settle";
7790
+ /** One reviewable authority event, in journal order. */
7791
+ interface AuditRecord {
7792
+ /** The journal seq of the entry behind this record. */
7793
+ seq: number;
7794
+ /** The entry's startedAt timestamp. */
7795
+ at: string;
7796
+ scope: string;
7797
+ category: AuditCategory;
7798
+ /**
7799
+ * The finer type: the suspension kind ('external' | 'approval') for
7800
+ * suspensions, the journaled decisionType for decisions.
7801
+ */
7802
+ type?: string;
7803
+ /** Who acted: a ResolutionBy for resolutions, 'engine' for decisions. */
7804
+ by?: string;
7805
+ /** The seq of the entry this record acts on (resolution/abandon target). */
7806
+ target?: number;
7807
+ /** One deterministic reviewable line. */
7808
+ summary: string;
7809
+ /** The journaled payload, verbatim (plaintext through Engine.stores). */
7810
+ value?: Json;
7811
+ }
7812
+ /**
7813
+ * Folds a loaded journal into the audit trail, in seq order. Pass the
7814
+ * FULL entry list (`Engine.stores.journal.load(runId)` or
7815
+ * `exportRun(runId).entries`); filtering is the reducer's job.
7816
+ */
7817
+ declare function reduceAuditTrail(entries: readonly JournalEntry[]): AuditRecord[];
7818
+ //#endregion
7548
7819
  //#region src/journal/scope.d.ts
7549
7820
  /**
7550
7821
  * Scope-path grammar (M1-T04): deterministic structural paths, independent
@@ -8114,7 +8385,7 @@ declare class EventBus {
8114
8385
  private readonly runId;
8115
8386
  private readonly spans;
8116
8387
  private readonly now;
8117
- private readonly maskEvents;
8388
+ private readonly mask;
8118
8389
  private readonly subscribers;
8119
8390
  private readonly listeners;
8120
8391
  private seq;
@@ -8131,6 +8402,12 @@ declare class EventBus {
8131
8402
  */
8132
8403
  maskEvents?: boolean;
8133
8404
  /**
8405
+ * The compiled masking policy applied when maskEvents is on
8406
+ * (RV-217): the default credential set plus host patterns. Absent
8407
+ * falls back to the default maskSecretsDeep.
8408
+ */
8409
+ mask?: (body: WorkflowEventBody) => WorkflowEventBody;
8410
+ /**
8134
8411
  * First seq value (default 0): the resumed-segment base that keeps
8135
8412
  * seq strictly increasing per run across segments (v1.22.0 review
8136
8413
  * P1-2).
@@ -8311,4 +8588,4 @@ interface SandboxBridge {
8311
8588
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
8312
8589
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
8313
8590
  //#endregion
8314
- export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, type AdaptiveEvents, AdmissionController, AdmissionDecision, AdmissionRejectedError, AdmissionStatsBefore, AdmitLineage, AdmitRejectReason, AdmitSpec, AdmitVerdict, AgentCallError, AgentError, type AgentEvents, AgentIdentityInput, type AgentInvocationRow, AgentOpts, AgentProfile, AgentProfilePermissions, AgentProfileTemplateOptions, AgentResult, AgentResultMeta, AgentStatus, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, AuditRunsOptions, BUDGET_ABORT_REASON, BaseAppend, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildIdentityInput, ChildResultPage, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DebitResult, DeclaredLadder, DedupIndex, DedupNote, DedupedClaims, DerivedKey, DeriverRegistry, type DeterminismConfig, DeterminismError, type DeterminismEvents, type DeterminismMode, DispositionRule, DispositionTable, DonorCandidate, DonorRef, DroppedItem, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EffectiveUsageLimits, Effort, Engine, EngineDefaults, EngineQuotaConfig, EngineQuotaRuntime, EntryKind, EntryRef, EntryStatus, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, type ExplorationSummary, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, FinishValidationChild, FinishValidationInput, FinishValidationSpec, FinishValidationVerdict, FinishValidator, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, IncrementalSynthesisResult, InvalidResolutionError, InvocationRole, type InvocationTable, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, JournalSerializationHook, type JournalStore, type Json, JsonSchema, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, type KbProposal, type KbProposalTrigger, KeyDeriver, KeyRing, KeyedLimiter, KnowledgeCasError, type KnowledgeSnapshot, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LadderSpec, type LeasableStore, type Lease, LeaseHeldError, Ledger, LineageCounters, LineageIndex, LineageRef, LineageRelation, LineageStats, LogicalTaskId, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, MatchResult, McpConfig, McpToolSource, MechanicalGateProfile, MechanicalGateVerdict, MemoryQuotaLimiter, type MetaLookupStore, type ModelCaps, ModelChoice, type ModelClaim, ModelEpochInputs, type ModelKnowledgeHandle, type ModelKnowledgeStore, ModelListConstraint, ModelRef, ModelRetry, ModelSpec, Msg, NoProgressDetector, NodeId, NodeLinkValue, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OnEscalation, OperationDisposition, OrchestrateAcceptance, OrchestrateOptions, OrchestrateSynthesis, OrchestratorBudgetSpec, OrchestratorCapConfigError, OrchestratorExtension, OrchestratorExtensionIO, OrchestratorRuntime, Out, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, Part, PendingExternal, PendingToolTurn, PermissionConfig, PermissionGate, PermissionHook, PermissionPreset, PermissionRule, PermissionVerdict, type PhaseRow, PhaseTarget, PipelineCollected, PipelineOpts, PlanInvariantError, PriceTable, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, QUOTA_WINDOW_MS, QualityFloors, QuotaCounters, type QuotaDecision, type QuotaEstimate, type QuotaLimiter, type QuotaReservationRequest, QuotaRule, QuotaWindowSnapshot, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, RandIdentityInput, RandPayload, ReconcileOptions, ReconcileResult, RefEntryAppender, RefEntryClassification, RefusalInfo, RepeatedClaim, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, RepositoryResearchToolset, RepositoryResearchToolsetOptions, ResearchAgentProfileOptions, ResearchAgentProfileResult, ResearchEvidenceEntry, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunAuditVerdict, RunBudget, RunEventSink, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStateAudit, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, Semaphore, SerializationHook, Settled, ShellPatternRules, ShellSegment, ShellVerdict, SinglePhaseAppend, SpanMinter, SpanRegistry, SpawnAdmissionValue, SpawnAgentParams, SpawnKey, SpawnLineage, SpawnLineageOpt, SpawnOrigin, SpawnRecord, Spend, Stage, type StandardJSONSchemaV1, type StandardSchemaV1, StepIdentityInput, StructuredOutputTier, SuspendedAppend, SuspensionState, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, TerminalPatch, TerminationAccount, TerminationAccountSnapshot, TerminationDeniedValue, TerminationDeniedWriter, TerminationInitValue, TerminationLimits, TerminationResource, ToolCallRequest, ToolChoice, type ToolContext, ToolContextSeed, ToolContract, type ToolDef, type ToolEvents, type ToolExecutor, ToolInit, type ToolRisk, ToolRuntime, type ToolSource, type ToolSourceSession, ToolsOption, TranscriptSerializationHook, type TranscriptStore, TriggerClass, TtlState, Usage, UsageLimits, UsageSlice, VerifiedRecommendation, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, WakeBudgetBlock, WakeDigest, WakeTrigger, WireError, Workflow, WorkflowCallOpts, type WorkflowEvent, type WorkflowEventBody, WorkflowRegistry, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, identityJcs, implementationAgentProfile, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceCriticalPath, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
8591
+ export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, type AdaptiveEvents, AdmissionController, AdmissionDecision, AdmissionRejectedError, AdmissionStatsBefore, AdmitLineage, AdmitRejectReason, AdmitSpec, AdmitVerdict, AgentCallError, AgentError, type AgentEvents, AgentIdentityInput, type AgentInvocationRow, AgentOpts, AgentProfile, AgentProfilePermissions, AgentProfileTemplateOptions, AgentResult, AgentResultMeta, AgentStatus, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, AuditCategory, AuditRecord, AuditRunsOptions, BUDGET_ABORT_REASON, BaseAppend, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildIdentityInput, ChildResultPage, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DataKeyProvider, DebitResult, DeclaredLadder, DedupIndex, DedupNote, DedupedClaims, DerivedKey, DeriverRegistry, type DeterminismConfig, DeterminismError, type DeterminismEvents, type DeterminismMode, DispositionRule, DispositionTable, DonorCandidate, DonorRef, DroppedItem, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EffectiveUsageLimits, Effort, Engine, EngineDefaults, EngineQuotaConfig, EngineQuotaRuntime, EntryKind, EntryRef, EntryStatus, EnvelopeEncryption, EnvelopeEncryptionOptions, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, type ExecutorRegistry, type ExplorationSummary, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, FinishValidationChild, FinishValidationInput, FinishValidationSpec, FinishValidationVerdict, FinishValidator, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, IncrementalSynthesisResult, InvalidResolutionError, InvocationRole, type InvocationTable, type IsolatedExecContext, type IsolatedExecRequest, type IsolatedExecutorTag, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JOURNAL_ENVELOPE_MARKER, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, JournalSerializationHook, type JournalStore, type Json, JsonSchema, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, type KbProposal, type KbProposalTrigger, KeyDeriver, KeyRing, KeyedLimiter, KnowledgeCasError, type KnowledgeSnapshot, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LadderSpec, type LeasableStore, type Lease, LeaseHeldError, Ledger, LineageCounters, LineageIndex, LineageRef, LineageRelation, LineageStats, LogicalTaskId, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, MatchResult, McpConfig, McpToolSource, MechanicalGateProfile, MechanicalGateVerdict, MemoryQuotaLimiter, type MetaLookupStore, type ModelCaps, ModelChoice, type ModelClaim, ModelEpochInputs, type ModelKnowledgeHandle, type ModelKnowledgeStore, ModelListConstraint, ModelRef, ModelRetry, ModelSpec, Msg, NoProgressDetector, NodeId, NodeLinkValue, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OnEscalation, OperationDisposition, OrchestrateAcceptance, OrchestrateOptions, OrchestrateSynthesis, OrchestratorBudgetSpec, OrchestratorCapConfigError, OrchestratorExtension, OrchestratorExtensionIO, OrchestratorRuntime, Out, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, Part, PendingExternal, PendingToolTurn, PermissionConfig, PermissionGate, PermissionHook, PermissionPreset, PermissionRule, PermissionVerdict, type PhaseRow, PhaseTarget, PipelineCollected, PipelineOpts, PlanInvariantError, PriceTable, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, QUOTA_WINDOW_MS, QualityFloors, QuotaCounters, type QuotaDecision, type QuotaEstimate, type QuotaLimiter, type QuotaReservationRequest, QuotaRule, QuotaWindowSnapshot, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, RandIdentityInput, RandPayload, ReconcileOptions, ReconcileResult, RefEntryAppender, RefEntryClassification, RefusalInfo, RepeatedClaim, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, RepositoryResearchToolset, RepositoryResearchToolsetOptions, ResearchAgentProfileOptions, ResearchAgentProfileResult, ResearchEvidenceEntry, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunAuditVerdict, RunBudget, RunEventSink, RunExport, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStateAudit, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, SecretMasker, Semaphore, SerializationHook, Settled, ShellPatternRules, ShellSegment, ShellVerdict, SinglePhaseAppend, SpanMinter, SpanRegistry, SpawnAdmissionValue, SpawnAgentParams, SpawnKey, SpawnLineage, SpawnLineageOpt, SpawnOrigin, SpawnRecord, Spend, Stage, type StandardJSONSchemaV1, type StandardSchemaV1, StepIdentityInput, StructuredOutputTier, SuspendedAppend, SuspensionState, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, TerminalPatch, TerminationAccount, TerminationAccountSnapshot, TerminationDeniedValue, TerminationDeniedWriter, TerminationInitValue, TerminationLimits, TerminationResource, ToolCallRequest, ToolChoice, type ToolContext, ToolContextSeed, ToolContract, type ToolDef, type ToolEvents, type ToolExecutor, type ToolExecutorProvider, ToolInit, type ToolRisk, ToolRuntime, type ToolSource, type ToolSourceSession, ToolsOption, TranscriptSerializationHook, type TranscriptStore, TriggerClass, TtlState, Usage, UsageLimits, UsageSlice, VerifiedRecommendation, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, WakeBudgetBlock, WakeDigest, WakeTrigger, WireError, Workflow, WorkflowCallOpts, type WorkflowEvent, type WorkflowEventBody, WorkflowRegistry, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, identityJcs, implementationAgentProfile, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceAuditTrail, reduceCriticalPath, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createHash, getRandomValues, randomUUID } from "node:crypto";
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, getRandomValues, hkdfSync, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
2
  import { appendFileSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import path, { dirname, join, resolve, sep } from "node:path";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client";
@@ -491,6 +491,338 @@ function maskSecretsDeep(value) {
491
491
  function maskSecretsJson(value) {
492
492
  return maskSecretsDeep(value);
493
493
  }
494
+ /**
495
+ * Compiles the redaction policy: the DEFAULT credential pattern set
496
+ * plus host-defined patterns (RV-217), for the telemetry boundary
497
+ * (events and traces; never the journal, where lossless encryption is
498
+ * the right tool). String patterns compile as global regexes; RegExp
499
+ * patterns are recompiled with the global flag when it is missing, so
500
+ * replace-all semantics always hold. An invalid pattern is a typed
501
+ * ConfigError at compile time, before anything runs under the policy.
502
+ */
503
+ function compileSecretMasker(patterns = [], site = "redaction.patterns") {
504
+ const raw = patterns;
505
+ if (!Array.isArray(raw)) throw new ConfigError(`${site} must be an array of RegExp or string patterns`);
506
+ const compiled = raw.map((pattern, index) => {
507
+ const at = `${site}[${String(index)}]`;
508
+ if (pattern instanceof RegExp) return pattern.flags.includes("g") ? pattern : new RegExp(pattern.source, `${pattern.flags}g`);
509
+ if (typeof pattern !== "string" || pattern === "") throw new ConfigError(`${at} must be a RegExp or a nonempty pattern string`);
510
+ try {
511
+ return new RegExp(pattern, "g");
512
+ } catch (thrown) {
513
+ throw new ConfigError(`${at} is not a valid regular expression: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
514
+ }
515
+ });
516
+ const maskText = (text) => {
517
+ let masked = maskSecrets(text);
518
+ for (const pattern of compiled) masked = masked.replace(pattern, MASKED_SECRET);
519
+ return masked;
520
+ };
521
+ const maskDeep = (value) => deepMap(value, maskText);
522
+ return {
523
+ maskText,
524
+ maskDeep
525
+ };
526
+ }
527
+ /** Shared deep string walk preserving identity when nothing changed. */
528
+ function deepMap(value, mapText) {
529
+ if (typeof value === "string") {
530
+ const masked = mapText(value);
531
+ return masked === value ? value : masked;
532
+ }
533
+ if (Array.isArray(value)) {
534
+ let changed = false;
535
+ const next = value.map((item) => {
536
+ const masked = deepMap(item, mapText);
537
+ if (masked !== item) changed = true;
538
+ return masked;
539
+ });
540
+ return changed ? next : value;
541
+ }
542
+ if (value !== null && typeof value === "object") {
543
+ let changed = false;
544
+ const next = {};
545
+ for (const [key, item] of Object.entries(value)) {
546
+ const masked = deepMap(item, mapText);
547
+ if (masked !== item) changed = true;
548
+ next[key] = masked;
549
+ }
550
+ return changed ? next : value;
551
+ }
552
+ return value;
553
+ }
554
+ //#endregion
555
+ //#region src/l0/encryption.ts
556
+ /**
557
+ * Envelope encryption over the serialization hook (RV-217): the
558
+ * reference implementation of "PII never persists in plaintext". The
559
+ * hook seam (l0/serialization.ts) is the single policy point between
560
+ * the engine and persistence; this module puts real cryptography on
561
+ * it, KMS-shaped.
562
+ *
563
+ * The envelope pattern, exactly as cloud KMS services frame it:
564
+ *
565
+ * - A DataKeyProvider is the KMS seam. It mints a fresh DATA key and
566
+ * returns it in two forms (plaintext for this process's memory,
567
+ * wrapped for storage), and it unwraps previously wrapped keys. The
568
+ * shipped `localKeyProvider` derives its key-encryption key from a
569
+ * host secret via HKDF-SHA256; an AWS KMS provider maps 1:1 onto
570
+ * GenerateDataKey and Decrypt (the guide shows the sketch), and
571
+ * tenant-scoped keys are providers constructed per tenant (the
572
+ * `info` input partitions one master secret into unrelated KEKs).
573
+ * - All provider calls are ASYNC and happen ONCE, in
574
+ * `createEnvelopeEncryption`, never per entry: the hook contract is
575
+ * synchronous, so the factory unwraps everything up front and the
576
+ * hooks run on in-memory data keys. Entries carry the WRAPPED key in
577
+ * every envelope, so decrypt needs only the provider registration,
578
+ * not a live KMS on the read path.
579
+ * - Payload encryption is AES-256-GCM with a random IV per write and
580
+ * the entry identity as ASSOCIATED DATA (`seq` and `key` for journal
581
+ * entries, the ref for transcript blobs), so a ciphertext moved to a
582
+ * different entry fails authentication instead of decrypting into
583
+ * the wrong place.
584
+ * - Journal entries keep the kernel ordering/identity fields plus the
585
+ * operational timestamps and spanId in plaintext (stores index and
586
+ * humans operate on them; none carry payload content); EVERYTHING
587
+ * else (value, error, usage, servedBy, cost attribution, refs) is
588
+ * inside the ciphertext. `fromStored(toStored(e))` reproduces the
589
+ * entry, so replay, content keys, and the folds are untouched.
590
+ * - Reads of NON-enveloped stored data fail closed by default
591
+ * (`plaintextReads: 'reject'`); `'passthrough'` is the explicit
592
+ * migration mode for stores with pre-encryption history.
593
+ *
594
+ * Docs: https://docs.rulvar.com/guide/data-protection
595
+ */
596
+ const HKDF_SALT = "rulvar-envelope-kek-v1";
597
+ const GCM_IV_BYTES = 12;
598
+ const GCM_TAG_BYTES = 16;
599
+ const DATA_KEY_BYTES = 32;
600
+ /**
601
+ * The local reference DataKeyProvider: the key-encryption key is
602
+ * HKDF-SHA256(secret, info), data keys are random 32-byte AES keys,
603
+ * and wrapping is AES-256-GCM under the KEK. `info` partitions one
604
+ * master secret into unrelated KEKs (tenant-scoped keys: one provider
605
+ * per tenant with `info: tenantId`); a provider with different
606
+ * secret or info CANNOT unwrap this provider's keys. For production
607
+ * KMS, implement the same interface over GenerateDataKey/Decrypt.
608
+ */
609
+ function localKeyProvider(options) {
610
+ const raw = options.secret;
611
+ if ((typeof raw !== "string" || raw === "") && !(raw instanceof Uint8Array)) throw new ConfigError("localKeyProvider secret must be a nonempty string or bytes");
612
+ if (raw instanceof Uint8Array && raw.length < 16) throw new ConfigError("localKeyProvider secret bytes must be at least 16 bytes");
613
+ const keyId = options.keyId ?? "local:v1";
614
+ if (typeof keyId !== "string" || keyId === "") throw new ConfigError("localKeyProvider keyId must be a nonempty string when given");
615
+ const kek = Buffer.from(hkdfSync("sha256", typeof raw === "string" ? Buffer.from(raw, "utf8") : Buffer.from(raw), Buffer.from(HKDF_SALT, "utf8"), Buffer.from(options.info ?? "", "utf8"), DATA_KEY_BYTES));
616
+ return {
617
+ keyId,
618
+ async generateDataKey() {
619
+ const plaintext = randomBytes(DATA_KEY_BYTES);
620
+ const iv = randomBytes(GCM_IV_BYTES);
621
+ const cipher = createCipheriv("aes-256-gcm", kek, iv);
622
+ const ct = Buffer.concat([cipher.update(plaintext), cipher.final()]);
623
+ const wrapped = Buffer.concat([
624
+ iv,
625
+ cipher.getAuthTag(),
626
+ ct
627
+ ]);
628
+ return {
629
+ plaintext: new Uint8Array(plaintext),
630
+ wrapped: new Uint8Array(wrapped)
631
+ };
632
+ },
633
+ async unwrapDataKey(wrapped) {
634
+ const buffer = Buffer.from(wrapped);
635
+ if (buffer.length <= 28) throw new ConfigError("localKeyProvider: the wrapped data key is truncated");
636
+ const iv = buffer.subarray(0, GCM_IV_BYTES);
637
+ const tag = buffer.subarray(GCM_IV_BYTES, 28);
638
+ const ct = buffer.subarray(28);
639
+ const decipher = createDecipheriv("aes-256-gcm", kek, iv);
640
+ decipher.setAuthTag(tag);
641
+ try {
642
+ const plaintext = Buffer.concat([decipher.update(ct), decipher.final()]);
643
+ return new Uint8Array(plaintext);
644
+ } catch {
645
+ throw new ConfigError(`localKeyProvider '${keyId}': cannot unwrap the data key (wrong secret, wrong info partition, or a corrupted wrapped key)`);
646
+ }
647
+ }
648
+ };
649
+ }
650
+ /** The journal envelope marker; a stored entry's whole value is this. */
651
+ const JOURNAL_ENVELOPE_MARKER = "__rulvarEnvelope";
652
+ /** The transcript blob envelope magic (version 1). */
653
+ const BLOB_MAGIC = Buffer.from("RVE1", "utf8");
654
+ /**
655
+ * Plaintext fields of a stored journal entry: the kernel
656
+ * ordering/identity fields the hook contract pins, plus the
657
+ * operational metadata stores index and operators read (timestamps,
658
+ * spanId). None carry payload content.
659
+ */
660
+ const CLEAR_FIELDS = [
661
+ "hashVersion",
662
+ "seq",
663
+ "ref",
664
+ "scope",
665
+ "key",
666
+ "ordinal",
667
+ "kind",
668
+ "status",
669
+ "spanId",
670
+ "startedAt",
671
+ "endedAt"
672
+ ];
673
+ function b64(bytes) {
674
+ return Buffer.from(bytes).toString("base64");
675
+ }
676
+ function isEnvelope(value) {
677
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
678
+ const keys = Object.keys(value);
679
+ if (keys.length !== 1 || keys[0] !== "__rulvarEnvelope") return false;
680
+ const env = value[JOURNAL_ENVELOPE_MARKER];
681
+ return typeof env === "object" && env !== null && env.v === 1 && typeof env.keyId === "string" && typeof env.wrapped === "string" && typeof env.iv === "string" && typeof env.tag === "string" && typeof env.data === "string";
682
+ }
683
+ /**
684
+ * Builds the envelope-encryption SerializationHook. All DataKeyProvider
685
+ * calls happen HERE (the hook itself is synchronous, on in-memory data
686
+ * keys): a fresh data key is minted and wrapped for this instance, and
687
+ * every historical wrapped key is unwrapped for the read path.
688
+ */
689
+ async function createEnvelopeEncryption(options) {
690
+ const provider = options.provider;
691
+ if (typeof provider !== "object" || provider === null || typeof provider.keyId !== "string" || provider.keyId === "" || typeof provider.generateDataKey !== "function" || typeof provider.unwrapDataKey !== "function") throw new ConfigError("createEnvelopeEncryption: provider must implement DataKeyProvider (keyId, generateDataKey, unwrapDataKey)");
692
+ const plaintextReads = options.plaintextReads ?? "reject";
693
+ if (plaintextReads !== "reject" && plaintextReads !== "passthrough") throw new ConfigError("createEnvelopeEncryption: plaintextReads must be 'reject' or 'passthrough'");
694
+ const realProvider = options.provider;
695
+ const current = await realProvider.generateDataKey();
696
+ if (current.plaintext.length !== DATA_KEY_BYTES) throw new ConfigError(`createEnvelopeEncryption: the provider returned a ${String(current.plaintext.length)}-byte data key; AES-256-GCM needs exactly ${String(DATA_KEY_BYTES)}`);
697
+ const ring = /* @__PURE__ */ new Map();
698
+ ring.set(b64(current.wrapped), Buffer.from(current.plaintext));
699
+ for (const wrapped of options.historicalWrappedKeys ?? []) {
700
+ const plaintext = await realProvider.unwrapDataKey(wrapped);
701
+ if (plaintext.length !== DATA_KEY_BYTES) throw new ConfigError(`createEnvelopeEncryption: a historical wrapped key unwrapped to ${String(plaintext.length)} bytes; AES-256-GCM needs exactly ${String(DATA_KEY_BYTES)}`);
702
+ ring.set(b64(wrapped), Buffer.from(plaintext));
703
+ }
704
+ const keyId = realProvider.keyId;
705
+ const currentWrappedB64 = b64(current.wrapped);
706
+ const currentKey = ring.get(currentWrappedB64);
707
+ const keyFor = (envelopeKeyId, wrappedB64, site) => {
708
+ const key = ring.get(wrappedB64);
709
+ if (key === void 0) throw new ConfigError(`${site}: the stored envelope carries a data key (keyId '${envelopeKeyId}') that this process has not registered; pass it in historicalWrappedKeys so the factory can unwrap it, and check the provider secret and info match the writing deployment`);
710
+ return key;
711
+ };
712
+ const encrypt = (key, aad, plaintext) => {
713
+ const iv = randomBytes(GCM_IV_BYTES);
714
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
715
+ cipher.setAAD(aad);
716
+ const ct = Buffer.concat([cipher.update(plaintext), cipher.final()]);
717
+ return {
718
+ v: 1,
719
+ keyId,
720
+ wrapped: currentWrappedB64,
721
+ iv: iv.toString("base64"),
722
+ tag: cipher.getAuthTag().toString("base64"),
723
+ data: ct.toString("base64")
724
+ };
725
+ };
726
+ const decrypt = (key, aad, env, site) => {
727
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(env.iv, "base64"));
728
+ decipher.setAAD(aad);
729
+ decipher.setAuthTag(Buffer.from(env.tag, "base64"));
730
+ try {
731
+ return Buffer.concat([decipher.update(Buffer.from(env.data, "base64")), decipher.final()]);
732
+ } catch {
733
+ throw new ConfigError(`${site}: envelope authentication failed (a tampered ciphertext, or a ciphertext moved to a different entry; the entry identity is associated data)`);
734
+ }
735
+ };
736
+ return {
737
+ hook: {
738
+ journal: {
739
+ toStored(e) {
740
+ const clear = {};
741
+ const rest = {};
742
+ for (const [field, fieldValue] of Object.entries(e)) if (CLEAR_FIELDS.includes(field)) clear[field] = fieldValue;
743
+ else rest[field] = fieldValue;
744
+ const aad = Buffer.from(`journal:${String(e.seq)}:${e.key}`, "utf8");
745
+ const envelope = encrypt(currentKey, aad, Buffer.from(JSON.stringify(rest), "utf8"));
746
+ return {
747
+ ...clear,
748
+ value: { [JOURNAL_ENVELOPE_MARKER]: envelope }
749
+ };
750
+ },
751
+ fromStored(e) {
752
+ if (!isEnvelope(e.value)) {
753
+ if (plaintextReads === "passthrough") return e;
754
+ throw new ConfigError(`envelope encryption: stored entry seq ${String(e.seq)} is not enveloped and plaintextReads is 'reject'; enable 'passthrough' only for a deliberate migration of pre-encryption history`);
755
+ }
756
+ const env = e.value[JOURNAL_ENVELOPE_MARKER];
757
+ const key = keyFor(env.keyId, env.wrapped, "envelope encryption (journal read)");
758
+ const aad = Buffer.from(`journal:${String(e.seq)}:${e.key}`, "utf8");
759
+ const rest = JSON.parse(decrypt(key, aad, env, "envelope encryption (journal read)").toString("utf8"));
760
+ const clear = {};
761
+ for (const field of CLEAR_FIELDS) if (e[field] !== void 0) clear[field] = e[field];
762
+ return {
763
+ ...clear,
764
+ ...rest
765
+ };
766
+ }
767
+ },
768
+ transcripts: {
769
+ toStored(ref, blob) {
770
+ const iv = randomBytes(GCM_IV_BYTES);
771
+ const cipher = createCipheriv("aes-256-gcm", currentKey, iv);
772
+ cipher.setAAD(Buffer.from(`blob:${ref}`, "utf8"));
773
+ const ct = Buffer.concat([cipher.update(Buffer.from(blob)), cipher.final()]);
774
+ const keyIdBytes = Buffer.from(keyId, "utf8");
775
+ const wrappedBytes = Buffer.from(currentWrappedB64, "base64");
776
+ const header = Buffer.alloc(4);
777
+ header.writeUInt16BE(keyIdBytes.length, 0);
778
+ header.writeUInt16BE(wrappedBytes.length, 2);
779
+ return new Uint8Array(Buffer.concat([
780
+ BLOB_MAGIC,
781
+ header,
782
+ keyIdBytes,
783
+ wrappedBytes,
784
+ iv,
785
+ cipher.getAuthTag(),
786
+ ct
787
+ ]));
788
+ },
789
+ fromStored(ref, blob) {
790
+ const buffer = Buffer.from(blob);
791
+ if (buffer.length < BLOB_MAGIC.length || !buffer.subarray(0, 4).equals(BLOB_MAGIC)) {
792
+ if (plaintextReads === "passthrough") return blob;
793
+ throw new ConfigError(`envelope encryption: stored blob '${ref}' is not enveloped and plaintextReads is 'reject'; enable 'passthrough' only for a deliberate migration`);
794
+ }
795
+ let offset = BLOB_MAGIC.length;
796
+ const keyIdLen = buffer.readUInt16BE(offset);
797
+ const wrappedLen = buffer.readUInt16BE(offset + 2);
798
+ offset += 4;
799
+ const envelopeKeyId = buffer.subarray(offset, offset + keyIdLen).toString("utf8");
800
+ offset += keyIdLen;
801
+ const wrappedB64 = buffer.subarray(offset, offset + wrappedLen).toString("base64");
802
+ offset += wrappedLen;
803
+ const iv = buffer.subarray(offset, offset + GCM_IV_BYTES);
804
+ const tag = buffer.subarray(offset + GCM_IV_BYTES, offset + GCM_IV_BYTES + GCM_TAG_BYTES);
805
+ const ct = buffer.subarray(offset + GCM_IV_BYTES + GCM_TAG_BYTES);
806
+ const decipher = createDecipheriv("aes-256-gcm", keyFor(envelopeKeyId, wrappedB64, `envelope encryption (blob '${ref}')`), iv);
807
+ decipher.setAAD(Buffer.from(`blob:${ref}`, "utf8"));
808
+ decipher.setAuthTag(tag);
809
+ try {
810
+ return new Uint8Array(Buffer.concat([decipher.update(ct), decipher.final()]));
811
+ } catch {
812
+ throw new ConfigError(`envelope encryption: blob '${ref}' authentication failed (tampered ciphertext or a ciphertext moved between refs; the ref is associated data)`);
813
+ }
814
+ }
815
+ }
816
+ },
817
+ keyId,
818
+ wrappedDataKey: new Uint8Array(current.wrapped)
819
+ };
820
+ }
821
+ /** Guards against non-constant-time comparisons in host key checks. */
822
+ function constantTimeEqual(a, b) {
823
+ if (a.length !== b.length) return false;
824
+ return timingSafeEqual(Buffer.from(a), Buffer.from(b));
825
+ }
494
826
  //#endregion
495
827
  //#region src/vendor/ulid.ts
496
828
  /**
@@ -2902,6 +3234,7 @@ function tool(init) {
2902
3234
  executor: init.executor ?? "inprocess",
2903
3235
  needsApproval: init.needsApproval ?? false,
2904
3236
  ...init.version === void 0 ? {} : { version: init.version },
3237
+ ...init.executorSpec === void 0 ? {} : { executorSpec: init.executorSpec },
2905
3238
  ...init.risk === void 0 ? {} : { risk: init.risk },
2906
3239
  execute: init.execute
2907
3240
  };
@@ -2956,7 +3289,7 @@ function isToolDef(spec) {
2956
3289
  * without one, string entries fail with the same unknown-name error as
2957
3290
  * a miss, so nothing outside the declared registry is ever reachable.
2958
3291
  */
2959
- async function resolveToolset(specs, session, toolsets) {
3292
+ async function resolveToolset(specs, session, toolsets, executors) {
2960
3293
  if (specs === void 0 || specs.length === 0) return emptyToolset();
2961
3294
  const tools = [];
2962
3295
  for (const spec of specs) {
@@ -2983,7 +3316,7 @@ async function resolveToolset(specs, session, toolsets) {
2983
3316
  for (const def of tools) {
2984
3317
  if (!TOOL_NAME_PATTERN.test(def.name)) throw new ConfigError(`imported tool name '${def.name}' must match ^[a-zA-Z0-9_-]{1,64}$; namespace it with the source prefix option`);
2985
3318
  if (seen.has(def.name)) throw new ConfigError(`duplicate tool name '${def.name}' in one toolset; disambiguate with the MCP prefix option`);
2986
- if (def.executor !== "inprocess") throw new ConfigError(`tool '${def.name}' declares executor '${def.executor}', but this engine implements only 'inprocess' in v1`);
3319
+ if (def.executor !== "inprocess" && !(executors?.has(def.executor) ?? false)) throw new ConfigError(`tool '${def.name}' declares executor '${def.executor}', but no such executor is registered; register one via createEngine({ executors }) (https://docs.rulvar.com/guide/isolated-executor)`);
2987
3320
  seen.set(def.name, def);
2988
3321
  }
2989
3322
  const contracts = tools.map((def) => toolContract(def));
@@ -3941,6 +4274,90 @@ function reviewAgentProfile(options = {}) {
3941
4274
  };
3942
4275
  }
3943
4276
  //#endregion
4277
+ //#region src/engine/audit.ts
4278
+ function record(entry, fields) {
4279
+ return {
4280
+ seq: entry.seq,
4281
+ at: entry.startedAt,
4282
+ scope: entry.scope,
4283
+ ...fields
4284
+ };
4285
+ }
4286
+ /**
4287
+ * Folds a loaded journal into the audit trail, in seq order. Pass the
4288
+ * FULL entry list (`Engine.stores.journal.load(runId)` or
4289
+ * `exportRun(runId).entries`); filtering is the reducer's job.
4290
+ */
4291
+ function reduceAuditTrail(entries) {
4292
+ const trail = [];
4293
+ for (const entry of entries) {
4294
+ if ((entry.kind === "external" || entry.kind === "approval") && entry.status === "suspended") {
4295
+ trail.push(record(entry, {
4296
+ category: "suspension",
4297
+ type: entry.kind,
4298
+ summary: `${entry.kind} suspension opened` + (entry.deadlineAt === void 0 ? "" : ` (deadline ${entry.deadlineAt})`),
4299
+ ...entry.value === void 0 ? {} : { value: entry.value }
4300
+ }));
4301
+ continue;
4302
+ }
4303
+ if (entry.kind === "resolution") {
4304
+ const payload = entry.resolution;
4305
+ if (payload === void 0) continue;
4306
+ trail.push(record(entry, {
4307
+ category: "resolution",
4308
+ by: payload.by,
4309
+ target: payload.target,
4310
+ summary: `suspension #${String(payload.target)} resolved by ${payload.by}` + (payload.decisionRef === void 0 ? "" : ` (class decision #${String(payload.decisionRef)})`),
4311
+ value: payload.value
4312
+ }));
4313
+ continue;
4314
+ }
4315
+ if (entry.kind === "abandon") {
4316
+ const payload = entry.abandon;
4317
+ if (payload === void 0) continue;
4318
+ trail.push(record(entry, {
4319
+ category: "abandon",
4320
+ target: payload.target,
4321
+ by: `decision #${String(payload.authorizedBy)}`,
4322
+ summary: `#${String(payload.target)} abandoned: ${payload.reason}`
4323
+ }));
4324
+ continue;
4325
+ }
4326
+ if (entry.kind === "termination.denied") {
4327
+ trail.push(record(entry, {
4328
+ category: "termination-denied",
4329
+ by: "engine",
4330
+ summary: "a termination-limit action was denied",
4331
+ ...entry.value === void 0 ? {} : { value: entry.value }
4332
+ }));
4333
+ continue;
4334
+ }
4335
+ if (entry.kind === "decision") {
4336
+ const value = entry.value;
4337
+ const decisionType = typeof value?.decisionType === "string" ? value.decisionType : void 0;
4338
+ if (decisionType === void 0) continue;
4339
+ if (decisionType === "run_settle") {
4340
+ trail.push(record(entry, {
4341
+ category: "run-settle",
4342
+ by: "engine",
4343
+ type: decisionType,
4344
+ summary: `run settled ${typeof value?.runStatus === "string" ? value.runStatus : "unknown"}`,
4345
+ ...entry.value === void 0 ? {} : { value: entry.value }
4346
+ }));
4347
+ continue;
4348
+ }
4349
+ trail.push(record(entry, {
4350
+ category: "decision",
4351
+ by: "engine",
4352
+ type: decisionType,
4353
+ summary: `engine decision ${decisionType}`,
4354
+ ...entry.value === void 0 ? {} : { value: entry.value }
4355
+ }));
4356
+ }
4357
+ }
4358
+ return trail;
4359
+ }
4360
+ //#endregion
3944
4361
  //#region src/journal/identity.ts
3945
4362
  /**
3946
4363
  * Content-addressed entry identity (M1-T04): IdentityInput records per
@@ -9951,7 +10368,10 @@ async function executeToolCall(options) {
9951
10368
  issues: validation.issues.map((issue) => issue.message)
9952
10369
  }, "error");
9953
10370
  try {
9954
- const value = await def.execute(validation.value, runtime.contextFor(call.name));
10371
+ let value;
10372
+ if (def.executor === "inprocess") value = await def.execute(validation.value, runtime.contextFor(call.name));
10373
+ else if (runtime.executeExternal !== void 0) value = await runtime.executeExternal(def, validation.value);
10374
+ else return finish({ error: `tool '${call.name}' declares executor '${def.executor}' but no executor is registered` }, "error");
9955
10375
  const serialized = toJournalValue(value === void 0 ? null : value, `tool '${call.name}'`);
9956
10376
  options.retryCounts.delete(call.name);
9957
10377
  return finish(serialized, "ok");
@@ -12706,6 +13126,33 @@ function setLongTimeout(onDue, dueAtMs, now = Date.now) {
12706
13126
  } };
12707
13127
  }
12708
13128
  //#endregion
13129
+ //#region src/runtime/executor.ts
13130
+ /**
13131
+ * Isolated-executor dispatch helpers (RV-216). The engine routes a
13132
+ * non-inprocess tool call through the registered ToolExecutorProvider;
13133
+ * this module derives the stable per-call idempotency key the provider
13134
+ * receives, so an at-least-once retry of a side-effecting tool can be
13135
+ * folded into effectively-once.
13136
+ *
13137
+ * Public contract: https://docs.rulvar.com/guide/isolated-executor.
13138
+ */
13139
+ /**
13140
+ * Derives the idempotency key for one isolated tool dispatch. The key is
13141
+ * a pure function of the run, the tool name, and the JCS-canonical
13142
+ * arguments, so the same logical call always yields the same key
13143
+ * (byte-identical reruns dedupe) and distinct calls never collide. The
13144
+ * key never enters run identity; it exists only for the provider's own
13145
+ * side-effect deduplication.
13146
+ */
13147
+ function deriveExecIdempotencyKey(runId, tool, args) {
13148
+ const canonical = jcsSerialize({
13149
+ runId,
13150
+ tool,
13151
+ args
13152
+ });
13153
+ return createHash("sha256").update(canonical, "utf8").digest("hex");
13154
+ }
13155
+ //#endregion
12709
13156
  //#region src/engine/ctx.ts
12710
13157
  /**
12711
13158
  * Ctx primitives (M1-T07) plus the parallel/pipeline composition semantics
@@ -12977,7 +13424,7 @@ function createCtx(internals, rootWorkflow) {
12977
13424
  if (escalation.flavor === "B" && escalation.deadlineMs === void 0) throw new ConfigError("escalation flavor 'B' requires an explicit deadlineMs");
12978
13425
  }
12979
13426
  const declaredTools = opts.tools ?? profile?.tools ?? [];
12980
- const toolset = await resolveToolset(escalation === void 0 ? declaredTools : [...declaredTools, escalateTool()], { runId: internals.runId }, internals.defaults.toolsets);
13427
+ const toolset = await resolveToolset(escalation === void 0 ? declaredTools : [...declaredTools, escalateTool()], { runId: internals.runId }, internals.defaults.toolsets, internals.executors === void 0 ? void 0 : new Set(Object.keys(internals.executors)));
12981
13428
  const layers = [
12982
13429
  callLayer,
12983
13430
  profileLayer,
@@ -13499,6 +13946,38 @@ function createCtx(internals, rootWorkflow) {
13499
13946
  };
13500
13947
  }
13501
13948
  };
13949
+ if (internals.executors !== void 0) {
13950
+ const executors = internals.executors;
13951
+ toolRuntime.executeExternal = async (def, args) => {
13952
+ const tag = def.executor;
13953
+ const provider = executors[tag];
13954
+ if (provider === void 0) throw new ConfigError(`no executor registered for '${def.executor}'; register one via createEngine({ executors }) (https://docs.rulvar.com/guide/isolated-executor)`);
13955
+ const toolSpanId = internals.spans.mint(spanId);
13956
+ return provider.run({
13957
+ executor: tag,
13958
+ tool: def.name,
13959
+ args,
13960
+ spec: def.executorSpec ?? null,
13961
+ ctx: {
13962
+ runId: internals.runId,
13963
+ spanId: toolSpanId,
13964
+ agentType,
13965
+ idempotencyKey: deriveExecIdempotencyKey(internals.runId, def.name, args),
13966
+ signal: toolSignal,
13967
+ log: (level, msg, data) => internals.events.emit(data === void 0 ? {
13968
+ type: "log",
13969
+ level,
13970
+ msg
13971
+ } : {
13972
+ type: "log",
13973
+ level,
13974
+ msg,
13975
+ data
13976
+ }, toolSpanId)
13977
+ }
13978
+ });
13979
+ };
13980
+ }
13502
13981
  }
13503
13982
  const runAgentOptions = {
13504
13983
  prompt,
@@ -15949,7 +16428,7 @@ var EventBus = class {
15949
16428
  runId;
15950
16429
  spans;
15951
16430
  now;
15952
- maskEvents;
16431
+ mask;
15953
16432
  subscribers = /* @__PURE__ */ new Set();
15954
16433
  listeners = /* @__PURE__ */ new Set();
15955
16434
  seq;
@@ -15959,12 +16438,12 @@ var EventBus = class {
15959
16438
  this.runId = options.runId;
15960
16439
  this.spans = options.spans;
15961
16440
  this.now = options.now ?? realNow;
15962
- this.maskEvents = options.maskEvents ?? true;
16441
+ this.mask = options.maskEvents ?? true ? options.mask ?? maskSecretsDeep : void 0;
15963
16442
  this.seq = options.firstSeq ?? 0;
15964
16443
  }
15965
16444
  emit(body, spanId, replayed) {
15966
16445
  const parentSpanId = this.spans.parentOf(spanId);
15967
- const safeBody = this.maskEvents ? maskSecretsDeep(body) : body;
16446
+ const safeBody = this.mask === void 0 ? body : this.mask(body);
15968
16447
  const event = {
15969
16448
  runId: this.runId,
15970
16449
  seq: this.seq++,
@@ -16564,9 +17043,12 @@ function liftRunCompletion(candidate) {
16564
17043
  * sensitive-derived metadata, not a value safe to publish (see the
16565
17044
  * `argsHash` field docs).
16566
17045
  */
16567
- function hashRunArgs(args) {
17046
+ function hashRunArgs(args, options) {
16568
17047
  if (args === void 0) return;
16569
- return createHash("sha256").update(jcsSerialize(args), "utf8").digest("hex");
17048
+ const canonical = jcsSerialize(args);
17049
+ const salt = options?.salt;
17050
+ if (salt === void 0) return createHash("sha256").update(canonical, "utf8").digest("hex");
17051
+ return createHmac("sha256", Buffer.from(salt, "utf8")).update(canonical, "utf8").digest("hex");
16570
17052
  }
16571
17053
  /**
16572
17054
  * sha256 hex over the JCS canonical serialization of a run's result
@@ -16595,6 +17077,7 @@ function createEngine(options) {
16595
17077
  const journal = options.serialization?.journal === void 0 ? rawJournal : wrapJournalStore(rawJournal, options.serialization.journal);
16596
17078
  const transcripts = options.serialization?.transcripts === void 0 ? rawTranscripts : wrapTranscriptStore(rawTranscripts, options.serialization.transcripts);
16597
17079
  const maskEvents = options.redaction?.maskEvents ?? true;
17080
+ const eventMasker = options.redaction?.patterns === void 0 ? void 0 : compileSecretMasker(options.redaction.patterns, "createEngine redaction.patterns");
16598
17081
  const defaults = options.defaults ?? {};
16599
17082
  if (defaults.retry !== void 0) validateRetryPolicy(defaults.retry, "createEngine defaults.retry");
16600
17083
  if (options.concurrency?.perRun !== void 0) requirePositiveInteger(options.concurrency.perRun, "createEngine concurrency.perRun");
@@ -16618,6 +17101,8 @@ function createEngine(options) {
16618
17101
  }
16619
17102
  validateDeterminismConfig(options.determinism);
16620
17103
  validateEngineQuotaConfig(options.quota);
17104
+ if (options.security?.argsHashSalt !== void 0 && (typeof options.security.argsHashSalt !== "string" || options.security.argsHashSalt === "")) throw new ConfigError("createEngine security.argsHashSalt must be a nonempty string when given");
17105
+ const argsHashSalt = options.security?.argsHashSalt;
16621
17106
  const quotaRuntime = options.quota === void 0 ? void 0 : {
16622
17107
  limiter: options.quota.limiter,
16623
17108
  ...options.quota.tenant === void 0 ? {} : { tenant: options.quota.tenant },
@@ -16657,6 +17142,7 @@ function createEngine(options) {
16657
17142
  spans,
16658
17143
  now: realNow,
16659
17144
  maskEvents,
17145
+ ...eventMasker === void 0 ? {} : { mask: (body) => eventMasker.maskDeep(body) },
16660
17146
  firstSeq: telemetryBase
16661
17147
  });
16662
17148
  const rootSpanId = spans.mint();
@@ -16773,6 +17259,7 @@ function createEngine(options) {
16773
17259
  pricingOf,
16774
17260
  runSignal: controller.signal,
16775
17261
  ...defaults.isolation === void 0 ? {} : { isolation: defaults.isolation },
17262
+ ...options.executors === void 0 ? {} : { executors: options.executors },
16776
17263
  ...options.onEscalation === void 0 ? {} : { onEscalation: options.onEscalation },
16777
17264
  external,
16778
17265
  mintTranscriptRef: () => `${runId}/t${transcriptCounter++}`,
@@ -16783,7 +17270,7 @@ function createEngine(options) {
16783
17270
  if (resumeCtx === void 0) {
16784
17271
  argsBinding.argsProvided = args !== void 0;
16785
17272
  try {
16786
- const argsHash = hashRunArgs(args);
17273
+ const argsHash = hashRunArgs(args, argsHashSalt === void 0 ? void 0 : { salt: argsHashSalt });
16787
17274
  if (argsHash !== void 0) argsBinding.argsHash = argsHash;
16788
17275
  } catch {}
16789
17276
  } else {
@@ -17044,6 +17531,42 @@ function createEngine(options) {
17044
17531
  preview
17045
17532
  };
17046
17533
  }
17534
+ /** Portable export through the policy point (RV-217). */
17535
+ async function exportRun(runId) {
17536
+ const entries = await journal.load(runId);
17537
+ const meta = await readRunMeta(journal, runId);
17538
+ const blobs = [];
17539
+ for (const ref of await transcripts.list(runId)) {
17540
+ const data = await transcripts.get(ref);
17541
+ if (data !== null) blobs.push({
17542
+ ref,
17543
+ data
17544
+ });
17545
+ }
17546
+ if (entries.length === 0 && meta === void 0 && blobs.length === 0) throw new ConfigError(`exportRun: run '${runId}' does not exist in this engine's stores`);
17547
+ return {
17548
+ runId,
17549
+ ...meta === void 0 ? {} : { meta },
17550
+ entries,
17551
+ blobs
17552
+ };
17553
+ }
17554
+ /** Import under the original runId; refuses an existing run (RV-217). */
17555
+ async function importRun(bundle) {
17556
+ const raw = bundle;
17557
+ if (typeof raw !== "object" || raw === null || typeof raw.runId !== "string" || raw.runId === "" || !Array.isArray(raw.entries) || !Array.isArray(raw.blobs)) throw new ConfigError("importRun: the bundle must be a RunExport (runId, entries, blobs)");
17558
+ const runId = bundle.runId;
17559
+ const existingMeta = await readRunMeta(journal, runId);
17560
+ const existingEntries = await journal.load(runId);
17561
+ const existingBlobs = await transcripts.list(runId);
17562
+ if (existingMeta !== void 0 || existingEntries.length > 0 || existingBlobs.length > 0) throw new ConfigError(`importRun: run '${runId}' already exists in the target stores; an import never interleaves with live history (delete the run first if replacement is intended)`);
17563
+ for (const entry of bundle.entries) await journal.append(runId, entry);
17564
+ for (const blob of bundle.blobs) await transcripts.put(blob.ref, blob.data);
17565
+ if (bundle.meta !== void 0) await journal.putMeta({
17566
+ ...bundle.meta,
17567
+ runId
17568
+ });
17569
+ }
17047
17570
  /** Retention cascade (OQ-20 executed at M8-T04): blobs, then journal. */
17048
17571
  async function deleteRun(runId, opts) {
17049
17572
  const refs = await transcripts.list(runId);
@@ -17108,6 +17631,8 @@ function createEngine(options) {
17108
17631
  },
17109
17632
  deleteRun,
17110
17633
  pruneRun,
17634
+ exportRun,
17635
+ importRun,
17111
17636
  profileCard: (names) => {
17112
17637
  const registered = defaults.profiles ?? {};
17113
17638
  if (names === void 0) return profileCard(registered, defaults.toolsets);
@@ -17405,4 +17930,4 @@ function createSandboxBridge(ctx, options) {
17405
17930
  };
17406
17931
  }
17407
17932
  //#endregion
17408
- export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GitWorktreeProvider, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JournalCompatibilityError, JournalMatcher, JournalMissError, JournalOrderViolation, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, PlanInvariantError, QUOTA_WINDOW_MS, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, identityJcs, implementationAgentProfile, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceCriticalPath, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
17933
+ export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GitWorktreeProvider, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JOURNAL_ENVELOPE_MARKER, JournalCompatibilityError, JournalMatcher, JournalMissError, JournalOrderViolation, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, PlanInvariantError, QUOTA_WINDOW_MS, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, identityJcs, implementationAgentProfile, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceAuditTrail, reduceCriticalPath, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.57.0",
3
+ "version": "1.59.0",
4
4
  "description": "Rulvar core: L0 contracts, journal kernel, ctx primitives, agent runtime, model router, tool system, dynamic orchestrator, InMemory and JSONL stores, event stream.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",