@rulvar/core 1.55.0 → 1.57.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
@@ -1638,6 +1638,59 @@ interface KbProposal {
1638
1638
  note?: string;
1639
1639
  }
1640
1640
  //#endregion
1641
+ //#region src/l0/spi/quota.d.ts
1642
+ /**
1643
+ * The pre-dispatch estimate a reservation is admitted under. Token
1644
+ * estimates are heuristic (the engine uses its deterministic
1645
+ * four-characters-per-token prompt estimate plus the request's output
1646
+ * cap when one is set); reconcile() settles the difference against
1647
+ * actual usage inside the same accounting window.
1648
+ */
1649
+ interface QuotaEstimate {
1650
+ /** Wire calls this reservation admits; the engine always sends 1. */
1651
+ requests: number;
1652
+ /** Heuristic prompt estimate for the attempt. */
1653
+ inputTokens: number;
1654
+ /** The request's output token cap, when one is set. */
1655
+ maxOutputTokens?: number;
1656
+ }
1657
+ /** One admission request, dimensioned for tenant/model/provider rules. */
1658
+ interface QuotaReservationRequest {
1659
+ /**
1660
+ * The adapter id (the left segment of ModelRef), matching the keys
1661
+ * of `concurrency.perProvider`.
1662
+ */
1663
+ provider: string;
1664
+ /** The serving model, re-reserved per failover target. */
1665
+ model: string;
1666
+ /** The engine's configured tenant; absent when the host set none. */
1667
+ tenant?: string;
1668
+ /** The run paying for the attempt; observability only. */
1669
+ runId?: string;
1670
+ estimate: QuotaEstimate;
1671
+ }
1672
+ /**
1673
+ * The admission verdict. `retryAfterMs` on a denial is the
1674
+ * provider-shaped hint the retry engine honors verbatim: the time
1675
+ * until the limiter expects capacity (0 = retry immediately, e.g. a
1676
+ * request whose estimate can never fit its cap, so exhaustion and
1677
+ * failover happen without waiting; absent = the caller's backoff
1678
+ * policy applies).
1679
+ */
1680
+ type QuotaDecision = {
1681
+ granted: true;
1682
+ reservationId: string;
1683
+ } | {
1684
+ granted: false;
1685
+ retryAfterMs?: number;
1686
+ reason?: string;
1687
+ };
1688
+ /** The shared rate/quota limiter seam; see the module contract above. */
1689
+ interface QuotaLimiter {
1690
+ reserve(request: QuotaReservationRequest): Promise<QuotaDecision>;
1691
+ reconcile(reservationId: string, usage: Usage): Promise<void>;
1692
+ }
1693
+ //#endregion
1641
1694
  //#region src/knowledge/decay.d.ts
1642
1695
  /**
1643
1696
  * The asymmetric TTL table:
@@ -2227,12 +2280,21 @@ declare function replayDisposition(entry: JournalEntry, fold: AbandonFold, optio
2227
2280
  registry?: DeriverRegistry;
2228
2281
  terminal?: JournalEntry;
2229
2282
  invalidated?: ReadonlySet<number>;
2283
+ /**
2284
+ * True when the loaded journal carries a run settle with runStatus
2285
+ * 'ok' (the resume is a pure replay of a finished run): unstamped
2286
+ * limit entries then replay instead of re-running live. Terminal
2287
+ * settles other than ok keep the retry semantics.
2288
+ */
2289
+ runSettledOk?: boolean;
2230
2290
  }): ReplayDisposition;
2231
2291
  /**
2232
2292
  * Adapts the predicate to the matcher's disposition hook: two-phase
2233
2293
  * operations dispatch on their terminal, single-phase on themselves.
2234
2294
  */
2235
- declare function dispositionHook(fold: AbandonFold, registry: DeriverRegistry, invalidated?: ReadonlySet<number>): (op: JournalOperation) => ReplayDisposition;
2295
+ declare function dispositionHook(fold: AbandonFold, registry: DeriverRegistry, invalidated?: ReadonlySet<number>, options?: {
2296
+ runSettledOk?: boolean;
2297
+ }): (op: JournalOperation) => ReplayDisposition;
2236
2298
  //#endregion
2237
2299
  //#region src/journal/resolution.d.ts
2238
2300
  type ResolutionAttempt = {
@@ -2667,6 +2729,127 @@ declare class KeyedLimiter {
2667
2729
  withSlot<T>(key: string, fn: () => Promise<T>, onQueued?: () => void, signal?: AbortSignal): Promise<T>;
2668
2730
  }
2669
2731
  //#endregion
2732
+ //#region src/model/quota.d.ts
2733
+ /** The fixed accounting window every PerMinute cap counts over. */
2734
+ declare const QUOTA_WINDOW_MS = 6e4;
2735
+ /**
2736
+ * One shared-quota rule. The dimension fields select which requests
2737
+ * the rule governs (an absent dimension matches every value); EVERY
2738
+ * matching rule must admit a request, and a grant consumes capacity
2739
+ * from each of them. The counters are rule-scoped: one rule matching
2740
+ * two models pools them under one cap; write one rule per model for
2741
+ * per-model buckets.
2742
+ */
2743
+ interface QuotaRule {
2744
+ /** Adapter id, as in `concurrency.perProvider` keys. */
2745
+ provider?: string;
2746
+ model?: string;
2747
+ tenant?: string;
2748
+ /** Wire attempts admitted per window; the exact, hard cap. */
2749
+ requestsPerMinute?: number;
2750
+ /**
2751
+ * Input plus output tokens admitted per window: estimated at
2752
+ * admission, reconciled to actual usage.
2753
+ */
2754
+ tokensPerMinute?: number;
2755
+ }
2756
+ /**
2757
+ * Validates a quota rule set as a typed ConfigError before any
2758
+ * limiter can admit under it: a non-array or empty set, a rule
2759
+ * without a cap, a malformed dimension, or a malformed cap all fail
2760
+ * loud at construction. Shared by every reference implementation.
2761
+ */
2762
+ declare function validateQuotaRules(rules: readonly QuotaRule[], site?: string): void;
2763
+ /** True when every dimension the rule pins matches the request. */
2764
+ declare function quotaRuleMatches(rule: QuotaRule, request: QuotaReservationRequest): boolean;
2765
+ /** The tokens a reservation is admitted under: input estimate plus the output cap. */
2766
+ declare function quotaEstimateTokens(request: QuotaReservationRequest): number;
2767
+ /** The tokens a settled attempt actually consumed. */
2768
+ declare function quotaActualTokens(usage: Usage): number;
2769
+ /** Current-window counters of one rule bucket. */
2770
+ interface QuotaCounters {
2771
+ requests: number;
2772
+ tokens: number;
2773
+ }
2774
+ /**
2775
+ * One rule's admission verdict against its current-window counters,
2776
+ * the pure decision both reference implementations share. A denial
2777
+ * carries the window remainder as retryAfterMs, except when the
2778
+ * estimate alone can never fit the token cap: that denial says
2779
+ * retryAfterMs 0 (retry immediately), so the caller's bounded
2780
+ * attempts exhaust without waiting and failover gets its chance.
2781
+ */
2782
+ declare function quotaRuleAdmission(rule: QuotaRule, counters: QuotaCounters, estimate: QuotaCounters, msUntilWindowEnd: number): {
2783
+ admit: true;
2784
+ } | {
2785
+ admit: false;
2786
+ retryAfterMs: number;
2787
+ reason: string;
2788
+ };
2789
+ /**
2790
+ * Folds one more failing rule into the decision the caller returns:
2791
+ * the wait is the LONGEST failing horizon (every matching rule must
2792
+ * admit), and the FIRST failing rule names the denial.
2793
+ */
2794
+ declare function mergeQuotaDenial(current: {
2795
+ retryAfterMs: number;
2796
+ reason: string;
2797
+ } | undefined, next: {
2798
+ retryAfterMs: number;
2799
+ reason: string;
2800
+ }): {
2801
+ retryAfterMs: number;
2802
+ reason: string;
2803
+ };
2804
+ /** One rule's live counters, exposed by `snapshot()` for telemetry. */
2805
+ interface QuotaWindowSnapshot {
2806
+ rule: QuotaRule;
2807
+ windowStart: number;
2808
+ requests: number;
2809
+ tokens: number;
2810
+ }
2811
+ /** The in-process reference QuotaLimiter returned by memoryQuotaLimiter. */
2812
+ interface MemoryQuotaLimiter extends QuotaLimiter {
2813
+ /** Current-window counters per rule; rolled-over windows read as zero. */
2814
+ snapshot(): QuotaWindowSnapshot[];
2815
+ }
2816
+ /**
2817
+ * The in-process reference QuotaLimiter: fixed epoch-aligned
2818
+ * one-minute windows over the shared rule model. Coordinates every
2819
+ * engine that shares THIS instance inside one process; processes
2820
+ * coordinate through a shared-storage implementation of the same SPI
2821
+ * (SqliteQuotaLimiter in @rulvar/store-sqlite) instead.
2822
+ */
2823
+ declare function memoryQuotaLimiter(rules: readonly QuotaRule[], options?: {
2824
+ now?: () => number;
2825
+ }): MemoryQuotaLimiter;
2826
+ /** createEngine quota config: the limiter plus its engine-scoped knobs. */
2827
+ interface EngineQuotaConfig {
2828
+ limiter: QuotaLimiter;
2829
+ /** Stamped on every reservation of this engine's runs. */
2830
+ tenant?: string;
2831
+ /**
2832
+ * What a limiter infrastructure FAILURE (reserve throwing) means:
2833
+ * 'deny' (default, fail closed) converts it into a retryable
2834
+ * transport-class denial; 'allow' logs a warning and dispatches
2835
+ * without a reservation. A limiter DENIAL is unaffected by this
2836
+ * knob. reconcile failures only ever warn.
2837
+ */
2838
+ onLimiterError?: "deny" | "allow";
2839
+ }
2840
+ /** The resolved engine-side quota runtime threaded into every run. */
2841
+ interface EngineQuotaRuntime {
2842
+ limiter: QuotaLimiter;
2843
+ tenant?: string;
2844
+ onLimiterError: "deny" | "allow";
2845
+ }
2846
+ /**
2847
+ * Validates createEngine's quota config as a typed ConfigError before
2848
+ * any run could dispatch under a malformed limiter (the intake
2849
+ * discipline every engine option follows).
2850
+ */
2851
+ declare function validateEngineQuotaConfig(config: EngineQuotaConfig | undefined, site?: string): void;
2852
+ //#endregion
2670
2853
  //#region src/model/floors.d.ts
2671
2854
  /** An explicit allowlist and denylist; deny wins over allow. */
2672
2855
  type ModelListConstraint = {
@@ -3773,6 +3956,24 @@ interface RunAgentOptions<S extends SchemaSpec = JsonSchema> {
3773
3956
  * key's queue without a slot (v1.34.0 review P2-4).
3774
3957
  */
3775
3958
  providerSlot?: <T>(key: string, fn: () => Promise<T>, signal?: AbortSignal) => Promise<T>;
3959
+ /**
3960
+ * The shared quota limiter hook (RV-215): consulted before EVERY
3961
+ * live wire dispatch (initial attempts, transport retries, and
3962
+ * failover takeovers alike, in every phase). A denial becomes a
3963
+ * synthetic rate-limit-class WireError the retry and failover
3964
+ * engine treats exactly like a provider 429, except no wire call
3965
+ * was paid: retryAfterMs drives the interruptible backoff, attempts
3966
+ * stay bounded by RetryPolicy, and exhaustion fails over (the
3967
+ * takeover reserves under its own model). Granted reservations are
3968
+ * reconciled with the attempt's actual usage after the outcome
3969
+ * settles. Live-only by construction: replayed calls never reach
3970
+ * this seam, and nothing here is journaled.
3971
+ */
3972
+ quota?: {
3973
+ reserve: (request: QuotaReservationRequest) => Promise<QuotaDecision>;
3974
+ reconcile: (reservationId: string, usage: Usage) => Promise<void>; /** Limiter infrastructure failure policy; a denial is unaffected. */
3975
+ onLimiterError: "deny" | "allow";
3976
+ };
3776
3977
  /** The resolved toolset; absent = no tools declared. */
3777
3978
  tools?: ToolRuntime;
3778
3979
  /**
@@ -5201,6 +5402,18 @@ interface CreateEngineOptions {
5201
5402
  perRun?: number; /** Per-adapter-id caps; unlimited unless configured (Appendix A; M4-T07). */
5202
5403
  perProvider?: Record<string, number>;
5203
5404
  };
5405
+ /**
5406
+ * The shared quota limiter (RV-215): a QuotaLimiter implementation
5407
+ * consulted before every live wire dispatch of every run, plus the
5408
+ * engine's tenant dimension and the limiter failure policy. Engines
5409
+ * and processes that share one limiter (or one limiter storage,
5410
+ * e.g. SqliteQuotaLimiter in @rulvar/store-sqlite over one database
5411
+ * file) enforce one global quota; a denial rides the provider-429
5412
+ * retry and failover machinery without paying a wire call. Absent =
5413
+ * no shared quota (Appendix A: an embeddable library must not
5414
+ * surprise-throttle hosts).
5415
+ */
5416
+ quota?: EngineQuotaConfig;
5204
5417
  /** Versioned price table; wins over caps.pricing (M4-T06). */
5205
5418
  pricing?: PriceTable;
5206
5419
  /**
@@ -6889,6 +7102,13 @@ interface RunInternals {
6889
7102
  };
6890
7103
  /** Engine-scoped per-provider keyed limiter (M4-T07). */
6891
7104
  providerLimiter?: KeyedLimiter;
7105
+ /**
7106
+ * The shared quota limiter runtime (RV-215): the configured
7107
+ * QuotaLimiter with the engine's tenant and failure policy
7108
+ * resolved. Threaded into every live wire dispatch of every run;
7109
+ * absent = no shared quota, byte-identical to before the feature.
7110
+ */
7111
+ quota?: EngineQuotaRuntime;
6892
7112
  /** The configured price table's version; pinned in decision entries (M4-T06). */
6893
7113
  pricingVersion?: string;
6894
7114
  /** budgetDefaults.flatReserveUsd; last resort of the reserve formula. */
@@ -8091,4 +8311,4 @@ interface SandboxBridge {
8091
8311
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
8092
8312
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
8093
8313
  //#endregion
8094
- 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, 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, 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, QualityFloors, 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, 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, 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, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
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 };
package/dist/index.js CHANGED
@@ -4340,11 +4340,13 @@ function buildAbandonFold(entries) {
4340
4340
  return isCovered(entry);
4341
4341
  } };
4342
4342
  }
4343
- function applyRule(rule, op) {
4343
+ function applyRule(rule, op, runSettledOk) {
4344
4344
  const terminal = op.terminal ?? op.running;
4345
4345
  switch (rule) {
4346
4346
  case "replay": return "replay";
4347
- case "memoize-limit": return terminal.memoizeOutcome ?? op.running.memoizeOutcome ?? false ? "replay" : "rerun";
4347
+ case "memoize-limit":
4348
+ if (terminal.memoizeOutcome ?? op.running.memoizeOutcome ?? false) return "replay";
4349
+ return runSettledOk ? "replay" : "rerun";
4348
4350
  case "memoize-task-error":
4349
4351
  if (!(terminal.memoizeOutcome ?? op.running.memoizeOutcome ?? false) || terminal.error === void 0) return "rerun";
4350
4352
  return classifyAgentError(agentErrorFromWireSafe(terminal)) === "task" ? "replay" : "rerun";
@@ -4381,17 +4383,18 @@ function replayDisposition(entry, fold, options) {
4381
4383
  if (options?.invalidated?.has(entry.seq) === true) return "rerun";
4382
4384
  const deriver = options?.registry?.get(entry.hashVersion) ?? deriverV2;
4383
4385
  const status = (options?.terminal ?? entry).status;
4384
- return applyRule(deriver.dispositionTable[status], op);
4386
+ return applyRule(deriver.dispositionTable[status], op, options?.runSettledOk ?? false);
4385
4387
  }
4386
4388
  /**
4387
4389
  * Adapts the predicate to the matcher's disposition hook: two-phase
4388
4390
  * operations dispatch on their terminal, single-phase on themselves.
4389
4391
  */
4390
- function dispositionHook(fold, registry, invalidated) {
4392
+ function dispositionHook(fold, registry, invalidated, options) {
4391
4393
  return (op) => replayDisposition(op.running, fold, {
4392
4394
  registry,
4393
4395
  ...op.terminal === void 0 ? {} : { terminal: op.terminal },
4394
- ...invalidated === void 0 ? {} : { invalidated }
4396
+ ...invalidated === void 0 ? {} : { invalidated },
4397
+ ...options?.runSettledOk === void 0 ? {} : { runSettledOk: options.runSettledOk }
4395
4398
  });
4396
4399
  }
4397
4400
  //#endregion
@@ -7924,9 +7927,10 @@ var Semaphore = class {
7924
7927
  * ride RetryPolicy; hosts with known tier limits opt in per adapter id
7925
7928
  * via createEngine concurrency.perProvider.
7926
7929
  *
7927
- * There is deliberately NO distributed cross-process limiter: two
7928
- * processes sharing one API key coordinate nothing here (a
7929
- * process-global limiter is an open question).
7930
+ * This keyed limiter bounds PARALLELISM inside one engine only. Two
7931
+ * processes sharing one API key coordinate through the QuotaLimiter
7932
+ * SPI instead (RV-215, createEngine `quota`): rate and volume live
7933
+ * there, in shared storage; in-flight slots live here.
7930
7934
  */
7931
7935
  var KeyedLimiter = class {
7932
7936
  semaphores = /* @__PURE__ */ new Map();
@@ -8127,6 +8131,223 @@ function liftRetainedParts(providerMetadata, adapter) {
8127
8131
  }));
8128
8132
  }
8129
8133
  //#endregion
8134
+ //#region src/model/quota.ts
8135
+ /**
8136
+ * Quota rules and the in-process reference QuotaLimiter (RV-215).
8137
+ * The rule model is shared by every reference implementation
8138
+ * (memoryQuotaLimiter here, SqliteQuotaLimiter in
8139
+ * @rulvar/store-sqlite): fixed one-minute windows aligned to the
8140
+ * epoch, admission at reservation time, reconciliation to actual
8141
+ * usage inside the same window. The hard guarantee is on
8142
+ * `requestsPerMinute` (every wire attempt is exactly one request);
8143
+ * `tokensPerMinute` admits on the heuristic estimate and settles to
8144
+ * actual usage, so token windows are approximate at admission and
8145
+ * exact at settlement.
8146
+ *
8147
+ * Docs: https://docs.rulvar.com/guide/model-routing
8148
+ */
8149
+ /**
8150
+ * Captured at module load, before the InProcessRunner's
8151
+ * nondeterminism guard can patch the global: the limiter's clock is
8152
+ * engine infrastructure on the live-only dispatch path and must never
8153
+ * be blamed on workflow code.
8154
+ */
8155
+ const nativeNow = Date.now;
8156
+ /** The fixed accounting window every PerMinute cap counts over. */
8157
+ const QUOTA_WINDOW_MS = 6e4;
8158
+ /**
8159
+ * Validates a quota rule set as a typed ConfigError before any
8160
+ * limiter can admit under it: a non-array or empty set, a rule
8161
+ * without a cap, a malformed dimension, or a malformed cap all fail
8162
+ * loud at construction. Shared by every reference implementation.
8163
+ */
8164
+ function validateQuotaRules(rules, site = "quota rules") {
8165
+ const raw = rules;
8166
+ if (!Array.isArray(raw)) throw new ConfigError(`${site} must be an array of QuotaRule objects`);
8167
+ if (raw.length === 0) throw new ConfigError(`${site} must contain at least one rule`);
8168
+ raw.forEach((entry, index) => {
8169
+ const at = `${site}[${String(index)}]`;
8170
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) throw new ConfigError(`${at} must be a QuotaRule object`);
8171
+ const rule = entry;
8172
+ for (const dimension of [
8173
+ "provider",
8174
+ "model",
8175
+ "tenant"
8176
+ ]) {
8177
+ const value = rule[dimension];
8178
+ if (value !== void 0 && (typeof value !== "string" || value === "")) throw new ConfigError(`${at}.${dimension} must be a nonempty string when given`);
8179
+ }
8180
+ if (rule.requestsPerMinute === void 0 && rule.tokensPerMinute === void 0) throw new ConfigError(`${at} must set requestsPerMinute or tokensPerMinute (or both)`);
8181
+ for (const cap of ["requestsPerMinute", "tokensPerMinute"]) if (rule[cap] !== void 0) requirePositiveInteger(rule[cap], `${at}.${cap}`);
8182
+ });
8183
+ }
8184
+ /** True when every dimension the rule pins matches the request. */
8185
+ function quotaRuleMatches(rule, request) {
8186
+ return (rule.provider === void 0 || rule.provider === request.provider) && (rule.model === void 0 || rule.model === request.model) && (rule.tenant === void 0 || rule.tenant === request.tenant);
8187
+ }
8188
+ /** The tokens a reservation is admitted under: input estimate plus the output cap. */
8189
+ function quotaEstimateTokens(request) {
8190
+ return request.estimate.inputTokens + (request.estimate.maxOutputTokens ?? 0);
8191
+ }
8192
+ /** The tokens a settled attempt actually consumed. */
8193
+ function quotaActualTokens(usage) {
8194
+ return usage.inputTokens + usage.outputTokens;
8195
+ }
8196
+ /**
8197
+ * One rule's admission verdict against its current-window counters,
8198
+ * the pure decision both reference implementations share. A denial
8199
+ * carries the window remainder as retryAfterMs, except when the
8200
+ * estimate alone can never fit the token cap: that denial says
8201
+ * retryAfterMs 0 (retry immediately), so the caller's bounded
8202
+ * attempts exhaust without waiting and failover gets its chance.
8203
+ */
8204
+ function quotaRuleAdmission(rule, counters, estimate, msUntilWindowEnd) {
8205
+ if (rule.requestsPerMinute !== void 0 && counters.requests + estimate.requests > rule.requestsPerMinute) return {
8206
+ admit: false,
8207
+ retryAfterMs: msUntilWindowEnd,
8208
+ reason: `requestsPerMinute ${String(rule.requestsPerMinute)} exhausted`
8209
+ };
8210
+ if (rule.tokensPerMinute !== void 0) {
8211
+ if (estimate.tokens > rule.tokensPerMinute) return {
8212
+ admit: false,
8213
+ retryAfterMs: 0,
8214
+ reason: `the estimate of ${String(estimate.tokens)} tokens can never fit tokensPerMinute ${String(rule.tokensPerMinute)}`
8215
+ };
8216
+ if (counters.tokens + estimate.tokens > rule.tokensPerMinute) return {
8217
+ admit: false,
8218
+ retryAfterMs: msUntilWindowEnd,
8219
+ reason: `tokensPerMinute ${String(rule.tokensPerMinute)} exhausted`
8220
+ };
8221
+ }
8222
+ return { admit: true };
8223
+ }
8224
+ /**
8225
+ * Folds one more failing rule into the decision the caller returns:
8226
+ * the wait is the LONGEST failing horizon (every matching rule must
8227
+ * admit), and the FIRST failing rule names the denial.
8228
+ */
8229
+ function mergeQuotaDenial(current, next) {
8230
+ if (current === void 0) return {
8231
+ retryAfterMs: next.retryAfterMs,
8232
+ reason: next.reason
8233
+ };
8234
+ return next.retryAfterMs > current.retryAfterMs ? {
8235
+ retryAfterMs: next.retryAfterMs,
8236
+ reason: current.reason
8237
+ } : current;
8238
+ }
8239
+ /**
8240
+ * The in-process reference QuotaLimiter: fixed epoch-aligned
8241
+ * one-minute windows over the shared rule model. Coordinates every
8242
+ * engine that shares THIS instance inside one process; processes
8243
+ * coordinate through a shared-storage implementation of the same SPI
8244
+ * (SqliteQuotaLimiter in @rulvar/store-sqlite) instead.
8245
+ */
8246
+ function memoryQuotaLimiter(rules, options = {}) {
8247
+ validateQuotaRules(rules, "memoryQuotaLimiter rules");
8248
+ const now = options.now ?? (() => nativeNow());
8249
+ const buckets = /* @__PURE__ */ new Map();
8250
+ const reservations = /* @__PURE__ */ new Map();
8251
+ let nextReservation = 0;
8252
+ const windowStartAt = (at) => at - at % QUOTA_WINDOW_MS;
8253
+ const bucketFor = (ruleIndex, windowStart) => {
8254
+ let bucket = buckets.get(ruleIndex);
8255
+ if (bucket === void 0 || bucket.windowStart !== windowStart) {
8256
+ bucket = {
8257
+ windowStart,
8258
+ requests: 0,
8259
+ tokens: 0
8260
+ };
8261
+ buckets.set(ruleIndex, bucket);
8262
+ }
8263
+ return bucket;
8264
+ };
8265
+ const prune = (windowStart) => {
8266
+ for (const [id, reservation] of reservations) if (reservation.windowStart < windowStart) reservations.delete(id);
8267
+ };
8268
+ return {
8269
+ reserve(request) {
8270
+ const at = now();
8271
+ const windowStart = windowStartAt(at);
8272
+ prune(windowStart);
8273
+ const estimateTokens = quotaEstimateTokens(request);
8274
+ const msUntilWindowEnd = windowStart + QUOTA_WINDOW_MS - at;
8275
+ const matched = [];
8276
+ let denial;
8277
+ rules.forEach((rule, index) => {
8278
+ if (!quotaRuleMatches(rule, request)) return;
8279
+ matched.push(index);
8280
+ const verdict = quotaRuleAdmission(rule, bucketFor(index, windowStart), {
8281
+ requests: request.estimate.requests,
8282
+ tokens: estimateTokens
8283
+ }, msUntilWindowEnd);
8284
+ if (!verdict.admit) denial = mergeQuotaDenial(denial, verdict);
8285
+ });
8286
+ if (denial !== void 0) return Promise.resolve({
8287
+ granted: false,
8288
+ ...denial
8289
+ });
8290
+ for (const index of matched) {
8291
+ const bucket = bucketFor(index, windowStart);
8292
+ bucket.requests += request.estimate.requests;
8293
+ bucket.tokens += estimateTokens;
8294
+ }
8295
+ nextReservation += 1;
8296
+ const reservationId = `mq-${String(nextReservation)}`;
8297
+ reservations.set(reservationId, {
8298
+ windowStart,
8299
+ estimateTokens,
8300
+ ruleIndexes: matched
8301
+ });
8302
+ return Promise.resolve({
8303
+ granted: true,
8304
+ reservationId
8305
+ });
8306
+ },
8307
+ reconcile(reservationId, usage) {
8308
+ const reservation = reservations.get(reservationId);
8309
+ if (reservation === void 0) return Promise.resolve();
8310
+ reservations.delete(reservationId);
8311
+ const windowStart = windowStartAt(now());
8312
+ if (reservation.windowStart !== windowStart) return Promise.resolve();
8313
+ const delta = quotaActualTokens(usage) - reservation.estimateTokens;
8314
+ for (const index of reservation.ruleIndexes) {
8315
+ const bucket = buckets.get(index);
8316
+ if (bucket !== void 0 && bucket.windowStart === windowStart) bucket.tokens = Math.max(0, bucket.tokens + delta);
8317
+ }
8318
+ return Promise.resolve();
8319
+ },
8320
+ snapshot() {
8321
+ const windowStart = windowStartAt(now());
8322
+ return rules.map((rule, index) => {
8323
+ const bucket = buckets.get(index);
8324
+ const current = bucket !== void 0 && bucket.windowStart === windowStart;
8325
+ return {
8326
+ rule,
8327
+ windowStart,
8328
+ requests: current ? bucket.requests : 0,
8329
+ tokens: current ? bucket.tokens : 0
8330
+ };
8331
+ });
8332
+ }
8333
+ };
8334
+ }
8335
+ /**
8336
+ * Validates createEngine's quota config as a typed ConfigError before
8337
+ * any run could dispatch under a malformed limiter (the intake
8338
+ * discipline every engine option follows).
8339
+ */
8340
+ function validateEngineQuotaConfig(config, site = "createEngine quota") {
8341
+ if (config === void 0) return;
8342
+ const raw = config;
8343
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new ConfigError(`${site} must be an object with a limiter`);
8344
+ const candidate = raw;
8345
+ const limiter = candidate.limiter;
8346
+ if (typeof limiter !== "object" || limiter === null || typeof limiter.reserve !== "function" || typeof limiter.reconcile !== "function") throw new ConfigError(`${site}.limiter must implement QuotaLimiter (reserve and reconcile functions)`);
8347
+ if (candidate.tenant !== void 0 && (typeof candidate.tenant !== "string" || candidate.tenant === "")) throw new ConfigError(`${site}.tenant must be a nonempty string when given`);
8348
+ if (candidate.onLimiterError !== void 0 && candidate.onLimiterError !== "deny" && candidate.onLimiterError !== "allow") throw new ConfigError(`${site}.onLimiterError must be 'deny' or 'allow' when given`);
8349
+ }
8350
+ //#endregion
8130
8351
  //#region src/model/retry.ts
8131
8352
  /**
8132
8353
  * Transport RetryPolicy (M4-T05): retries live UNDER the journal. A
@@ -10311,12 +10532,74 @@ async function runAgent(options) {
10311
10532
  const target = site.chain[site.cursor.index] ?? site.chain[0];
10312
10533
  let tries = 0;
10313
10534
  inner: for (;;) {
10535
+ let reservationId;
10536
+ const quotaDeniedOutcome = (denial) => ({
10537
+ turn: {
10538
+ text: "",
10539
+ toolCalls: []
10540
+ },
10541
+ usage: ZERO_USAGE$1,
10542
+ reported: ZERO_USAGE$1,
10543
+ usageApprox: false,
10544
+ quotaDenied: true,
10545
+ wireError: {
10546
+ code: denial.infrastructure === void 0 ? "rate-limit" : "quota-limiter",
10547
+ message: denial.infrastructure ?? `the shared quota limiter denied ${target.resolved.ref}` + (denial.reason === void 0 ? "" : `: ${denial.reason}`),
10548
+ retryable: true,
10549
+ data: {
10550
+ kind: denial.infrastructure === void 0 ? "rate-limit" : "transport",
10551
+ source: "quota-limiter",
10552
+ ...denial.retryAfterMs === void 0 ? {} : { retryAfterMs: denial.retryAfterMs },
10553
+ ...denial.reason === void 0 ? {} : { reason: denial.reason }
10554
+ }
10555
+ }
10556
+ });
10557
+ const dispatchWithQuota = async (quota) => {
10558
+ const req = site.requestFor(target);
10559
+ let decision;
10560
+ try {
10561
+ decision = await quota.reserve({
10562
+ provider: target.adapter.id,
10563
+ model: target.resolved.model,
10564
+ estimate: {
10565
+ requests: 1,
10566
+ inputTokens: estimateInputTokens(req.messages),
10567
+ ...req.maxOutputTokens === void 0 ? {} : { maxOutputTokens: req.maxOutputTokens }
10568
+ }
10569
+ });
10570
+ } catch (thrown) {
10571
+ const detail = thrown instanceof Error ? thrown.message : String(thrown);
10572
+ if (quota.onLimiterError === "allow") {
10573
+ events?.emit({
10574
+ type: "log",
10575
+ level: "warn",
10576
+ msg: `the shared quota limiter failed; dispatching ${target.resolved.ref} without a reservation (onLimiterError 'allow'): ${detail}`
10577
+ });
10578
+ return streamTurn(target.adapter, req, site.streamOptionsFor(target));
10579
+ }
10580
+ return quotaDeniedOutcome({ infrastructure: `the shared quota limiter failed (onLimiterError 'deny'): ${detail}` });
10581
+ }
10582
+ if (!decision.granted) return quotaDeniedOutcome(decision);
10583
+ reservationId = decision.reservationId;
10584
+ return streamTurn(target.adapter, req, site.streamOptionsFor(target));
10585
+ };
10314
10586
  const dispatch = () => {
10315
10587
  const aborted = abortKind();
10316
- return aborted === void 0 ? streamTurn(target.adapter, site.requestFor(target), site.streamOptionsFor(target)) : Promise.resolve(abortedOutcome(aborted));
10588
+ if (aborted !== void 0) return Promise.resolve(abortedOutcome(aborted));
10589
+ return options.quota === void 0 ? streamTurn(target.adapter, site.requestFor(target), site.streamOptionsFor(target)) : dispatchWithQuota(options.quota);
10317
10590
  };
10318
10591
  const outcome = await (options.providerSlot === void 0 ? dispatch() : options.providerSlot(target.adapter.id, dispatch, options.signal));
10319
- recordUsage(outcome.usage, outcome.reported, target.adapter.id, target.resolved.ref, site.role, outcome.usageViolation);
10592
+ if (reservationId !== void 0 && options.quota !== void 0) try {
10593
+ await options.quota.reconcile(reservationId, outcome.usage);
10594
+ } catch (thrown) {
10595
+ const detail = thrown instanceof Error ? thrown.message : String(thrown);
10596
+ events?.emit({
10597
+ type: "log",
10598
+ level: "warn",
10599
+ msg: `the shared quota limiter failed to reconcile a reservation: ${detail}`
10600
+ });
10601
+ }
10602
+ if (outcome.quotaDenied !== true) recordUsage(outcome.usage, outcome.reported, target.adapter.id, target.resolved.ref, site.role, outcome.usageViolation);
10320
10603
  tries += 1;
10321
10604
  const retryClass = outcome.aborted === "idle" ? "transport" : outcome.wireError === void 0 ? void 0 : retryClassOf(outcome.wireError);
10322
10605
  if (retryClass === void 0) return {
@@ -13251,6 +13534,18 @@ function createCtx(internals, rootWorkflow) {
13251
13534
  if (profile?.compaction !== void 0) runAgentOptions.compaction = profile.compaction;
13252
13535
  if (loopFallbacks.length > 0) runAgentOptions.fallbacks = loopFallbacks;
13253
13536
  if (retryPolicy !== void 0) runAgentOptions.retry = { policy: retryPolicy };
13537
+ if (internals.quota !== void 0) {
13538
+ const quota = internals.quota;
13539
+ runAgentOptions.quota = {
13540
+ reserve: (request) => quota.limiter.reserve({
13541
+ ...request,
13542
+ runId: internals.runId,
13543
+ ...quota.tenant === void 0 ? {} : { tenant: quota.tenant }
13544
+ }),
13545
+ reconcile: (reservationId, usage) => quota.limiter.reconcile(reservationId, usage),
13546
+ onLimiterError: quota.onLimiterError
13547
+ };
13548
+ }
13254
13549
  if (internals.providerLimiter !== void 0) {
13255
13550
  const limiter = internals.providerLimiter;
13256
13551
  runAgentOptions.providerSlot = (key, fn, signal) => limiter.withSlot(key, fn, () => internals.events.emit({
@@ -16322,6 +16617,12 @@ function createEngine(options) {
16322
16617
  if (profile.compaction?.threshold !== void 0) requireFraction(profile.compaction.threshold, `createEngine defaults.profiles['${name}'].compaction.threshold`);
16323
16618
  }
16324
16619
  validateDeterminismConfig(options.determinism);
16620
+ validateEngineQuotaConfig(options.quota);
16621
+ const quotaRuntime = options.quota === void 0 ? void 0 : {
16622
+ limiter: options.quota.limiter,
16623
+ ...options.quota.tenant === void 0 ? {} : { tenant: options.quota.tenant },
16624
+ onLimiterError: options.quota.onLimiterError ?? "deny"
16625
+ };
16325
16626
  const knowledgeStore = options.stores?.modelKnowledge;
16326
16627
  const knowledge = knowledgeStore === void 0 ? void 0 : { current: () => knowledgeStore.current() };
16327
16628
  const runner = new InProcessRunner(options.onEscalation === void 0 ? void 0 : { onEscalation: options.onEscalation });
@@ -16386,8 +16687,9 @@ function createEngine(options) {
16386
16687
  strict: resumeCtx?.strict ?? false
16387
16688
  });
16388
16689
  for (const seqToInvalidate of invalidated) replayer.invalidate(seqToInvalidate);
16389
- replayer.setDisposition(dispositionHook(replayer.fold.abandonFold, registry, replayer.invalidatedSeqs));
16390
- replayer.setAliasDisposition(dispositionHook({ isAbandoned: () => false }, registry, replayer.invalidatedSeqs));
16690
+ const runSettledOk = resumeCtx !== void 0 && lastRunSettle(resumeCtx.priorEntries)?.runStatus === "ok";
16691
+ replayer.setDisposition(dispositionHook(replayer.fold.abandonFold, registry, replayer.invalidatedSeqs, { runSettledOk }));
16692
+ replayer.setAliasDisposition(dispositionHook({ isAbandoned: () => false }, registry, replayer.invalidatedSeqs, { runSettledOk }));
16391
16693
  if (resumeCtx !== void 0) {
16392
16694
  const prior = replayer.ledger();
16393
16695
  budgetSeed = {
@@ -16428,6 +16730,7 @@ function createEngine(options) {
16428
16730
  admission,
16429
16731
  semaphore: new Semaphore(options.concurrency?.perRun ?? 12),
16430
16732
  providerLimiter,
16733
+ ...quotaRuntime === void 0 ? {} : { quota: quotaRuntime },
16431
16734
  ...options.pricing === void 0 ? {} : { pricingVersion: options.pricing.pricingVersion },
16432
16735
  ...options.budgetDefaults?.flatReserveUsd === void 0 ? {} : { flatReserveUsd: options.budgetDefaults.flatReserveUsd },
16433
16736
  ...defaults.roleFloors === void 0 ? {} : { floors: defaults.roleFloors },
@@ -17102,4 +17405,4 @@ function createSandboxBridge(ctx, options) {
17102
17405
  };
17103
17406
  }
17104
17407
  //#endregion
17105
- 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, 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, 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, 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, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.55.0",
3
+ "version": "1.57.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",