@rulvar/core 1.55.0 → 1.56.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:
@@ -2667,6 +2720,127 @@ declare class KeyedLimiter {
2667
2720
  withSlot<T>(key: string, fn: () => Promise<T>, onQueued?: () => void, signal?: AbortSignal): Promise<T>;
2668
2721
  }
2669
2722
  //#endregion
2723
+ //#region src/model/quota.d.ts
2724
+ /** The fixed accounting window every PerMinute cap counts over. */
2725
+ declare const QUOTA_WINDOW_MS = 6e4;
2726
+ /**
2727
+ * One shared-quota rule. The dimension fields select which requests
2728
+ * the rule governs (an absent dimension matches every value); EVERY
2729
+ * matching rule must admit a request, and a grant consumes capacity
2730
+ * from each of them. The counters are rule-scoped: one rule matching
2731
+ * two models pools them under one cap; write one rule per model for
2732
+ * per-model buckets.
2733
+ */
2734
+ interface QuotaRule {
2735
+ /** Adapter id, as in `concurrency.perProvider` keys. */
2736
+ provider?: string;
2737
+ model?: string;
2738
+ tenant?: string;
2739
+ /** Wire attempts admitted per window; the exact, hard cap. */
2740
+ requestsPerMinute?: number;
2741
+ /**
2742
+ * Input plus output tokens admitted per window: estimated at
2743
+ * admission, reconciled to actual usage.
2744
+ */
2745
+ tokensPerMinute?: number;
2746
+ }
2747
+ /**
2748
+ * Validates a quota rule set as a typed ConfigError before any
2749
+ * limiter can admit under it: a non-array or empty set, a rule
2750
+ * without a cap, a malformed dimension, or a malformed cap all fail
2751
+ * loud at construction. Shared by every reference implementation.
2752
+ */
2753
+ declare function validateQuotaRules(rules: readonly QuotaRule[], site?: string): void;
2754
+ /** True when every dimension the rule pins matches the request. */
2755
+ declare function quotaRuleMatches(rule: QuotaRule, request: QuotaReservationRequest): boolean;
2756
+ /** The tokens a reservation is admitted under: input estimate plus the output cap. */
2757
+ declare function quotaEstimateTokens(request: QuotaReservationRequest): number;
2758
+ /** The tokens a settled attempt actually consumed. */
2759
+ declare function quotaActualTokens(usage: Usage): number;
2760
+ /** Current-window counters of one rule bucket. */
2761
+ interface QuotaCounters {
2762
+ requests: number;
2763
+ tokens: number;
2764
+ }
2765
+ /**
2766
+ * One rule's admission verdict against its current-window counters,
2767
+ * the pure decision both reference implementations share. A denial
2768
+ * carries the window remainder as retryAfterMs, except when the
2769
+ * estimate alone can never fit the token cap: that denial says
2770
+ * retryAfterMs 0 (retry immediately), so the caller's bounded
2771
+ * attempts exhaust without waiting and failover gets its chance.
2772
+ */
2773
+ declare function quotaRuleAdmission(rule: QuotaRule, counters: QuotaCounters, estimate: QuotaCounters, msUntilWindowEnd: number): {
2774
+ admit: true;
2775
+ } | {
2776
+ admit: false;
2777
+ retryAfterMs: number;
2778
+ reason: string;
2779
+ };
2780
+ /**
2781
+ * Folds one more failing rule into the decision the caller returns:
2782
+ * the wait is the LONGEST failing horizon (every matching rule must
2783
+ * admit), and the FIRST failing rule names the denial.
2784
+ */
2785
+ declare function mergeQuotaDenial(current: {
2786
+ retryAfterMs: number;
2787
+ reason: string;
2788
+ } | undefined, next: {
2789
+ retryAfterMs: number;
2790
+ reason: string;
2791
+ }): {
2792
+ retryAfterMs: number;
2793
+ reason: string;
2794
+ };
2795
+ /** One rule's live counters, exposed by `snapshot()` for telemetry. */
2796
+ interface QuotaWindowSnapshot {
2797
+ rule: QuotaRule;
2798
+ windowStart: number;
2799
+ requests: number;
2800
+ tokens: number;
2801
+ }
2802
+ /** The in-process reference QuotaLimiter returned by memoryQuotaLimiter. */
2803
+ interface MemoryQuotaLimiter extends QuotaLimiter {
2804
+ /** Current-window counters per rule; rolled-over windows read as zero. */
2805
+ snapshot(): QuotaWindowSnapshot[];
2806
+ }
2807
+ /**
2808
+ * The in-process reference QuotaLimiter: fixed epoch-aligned
2809
+ * one-minute windows over the shared rule model. Coordinates every
2810
+ * engine that shares THIS instance inside one process; processes
2811
+ * coordinate through a shared-storage implementation of the same SPI
2812
+ * (SqliteQuotaLimiter in @rulvar/store-sqlite) instead.
2813
+ */
2814
+ declare function memoryQuotaLimiter(rules: readonly QuotaRule[], options?: {
2815
+ now?: () => number;
2816
+ }): MemoryQuotaLimiter;
2817
+ /** createEngine quota config: the limiter plus its engine-scoped knobs. */
2818
+ interface EngineQuotaConfig {
2819
+ limiter: QuotaLimiter;
2820
+ /** Stamped on every reservation of this engine's runs. */
2821
+ tenant?: string;
2822
+ /**
2823
+ * What a limiter infrastructure FAILURE (reserve throwing) means:
2824
+ * 'deny' (default, fail closed) converts it into a retryable
2825
+ * transport-class denial; 'allow' logs a warning and dispatches
2826
+ * without a reservation. A limiter DENIAL is unaffected by this
2827
+ * knob. reconcile failures only ever warn.
2828
+ */
2829
+ onLimiterError?: "deny" | "allow";
2830
+ }
2831
+ /** The resolved engine-side quota runtime threaded into every run. */
2832
+ interface EngineQuotaRuntime {
2833
+ limiter: QuotaLimiter;
2834
+ tenant?: string;
2835
+ onLimiterError: "deny" | "allow";
2836
+ }
2837
+ /**
2838
+ * Validates createEngine's quota config as a typed ConfigError before
2839
+ * any run could dispatch under a malformed limiter (the intake
2840
+ * discipline every engine option follows).
2841
+ */
2842
+ declare function validateEngineQuotaConfig(config: EngineQuotaConfig | undefined, site?: string): void;
2843
+ //#endregion
2670
2844
  //#region src/model/floors.d.ts
2671
2845
  /** An explicit allowlist and denylist; deny wins over allow. */
2672
2846
  type ModelListConstraint = {
@@ -3773,6 +3947,24 @@ interface RunAgentOptions<S extends SchemaSpec = JsonSchema> {
3773
3947
  * key's queue without a slot (v1.34.0 review P2-4).
3774
3948
  */
3775
3949
  providerSlot?: <T>(key: string, fn: () => Promise<T>, signal?: AbortSignal) => Promise<T>;
3950
+ /**
3951
+ * The shared quota limiter hook (RV-215): consulted before EVERY
3952
+ * live wire dispatch (initial attempts, transport retries, and
3953
+ * failover takeovers alike, in every phase). A denial becomes a
3954
+ * synthetic rate-limit-class WireError the retry and failover
3955
+ * engine treats exactly like a provider 429, except no wire call
3956
+ * was paid: retryAfterMs drives the interruptible backoff, attempts
3957
+ * stay bounded by RetryPolicy, and exhaustion fails over (the
3958
+ * takeover reserves under its own model). Granted reservations are
3959
+ * reconciled with the attempt's actual usage after the outcome
3960
+ * settles. Live-only by construction: replayed calls never reach
3961
+ * this seam, and nothing here is journaled.
3962
+ */
3963
+ quota?: {
3964
+ reserve: (request: QuotaReservationRequest) => Promise<QuotaDecision>;
3965
+ reconcile: (reservationId: string, usage: Usage) => Promise<void>; /** Limiter infrastructure failure policy; a denial is unaffected. */
3966
+ onLimiterError: "deny" | "allow";
3967
+ };
3776
3968
  /** The resolved toolset; absent = no tools declared. */
3777
3969
  tools?: ToolRuntime;
3778
3970
  /**
@@ -5201,6 +5393,18 @@ interface CreateEngineOptions {
5201
5393
  perRun?: number; /** Per-adapter-id caps; unlimited unless configured (Appendix A; M4-T07). */
5202
5394
  perProvider?: Record<string, number>;
5203
5395
  };
5396
+ /**
5397
+ * The shared quota limiter (RV-215): a QuotaLimiter implementation
5398
+ * consulted before every live wire dispatch of every run, plus the
5399
+ * engine's tenant dimension and the limiter failure policy. Engines
5400
+ * and processes that share one limiter (or one limiter storage,
5401
+ * e.g. SqliteQuotaLimiter in @rulvar/store-sqlite over one database
5402
+ * file) enforce one global quota; a denial rides the provider-429
5403
+ * retry and failover machinery without paying a wire call. Absent =
5404
+ * no shared quota (Appendix A: an embeddable library must not
5405
+ * surprise-throttle hosts).
5406
+ */
5407
+ quota?: EngineQuotaConfig;
5204
5408
  /** Versioned price table; wins over caps.pricing (M4-T06). */
5205
5409
  pricing?: PriceTable;
5206
5410
  /**
@@ -6889,6 +7093,13 @@ interface RunInternals {
6889
7093
  };
6890
7094
  /** Engine-scoped per-provider keyed limiter (M4-T07). */
6891
7095
  providerLimiter?: KeyedLimiter;
7096
+ /**
7097
+ * The shared quota limiter runtime (RV-215): the configured
7098
+ * QuotaLimiter with the engine's tenant and failure policy
7099
+ * resolved. Threaded into every live wire dispatch of every run;
7100
+ * absent = no shared quota, byte-identical to before the feature.
7101
+ */
7102
+ quota?: EngineQuotaRuntime;
6892
7103
  /** The configured price table's version; pinned in decision entries (M4-T06). */
6893
7104
  pricingVersion?: string;
6894
7105
  /** budgetDefaults.flatReserveUsd; last resort of the reserve formula. */
@@ -8091,4 +8302,4 @@ interface SandboxBridge {
8091
8302
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
8092
8303
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
8093
8304
  //#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 };
8305
+ 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
@@ -7924,9 +7924,10 @@ var Semaphore = class {
7924
7924
  * ride RetryPolicy; hosts with known tier limits opt in per adapter id
7925
7925
  * via createEngine concurrency.perProvider.
7926
7926
  *
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).
7927
+ * This keyed limiter bounds PARALLELISM inside one engine only. Two
7928
+ * processes sharing one API key coordinate through the QuotaLimiter
7929
+ * SPI instead (RV-215, createEngine `quota`): rate and volume live
7930
+ * there, in shared storage; in-flight slots live here.
7930
7931
  */
7931
7932
  var KeyedLimiter = class {
7932
7933
  semaphores = /* @__PURE__ */ new Map();
@@ -8127,6 +8128,223 @@ function liftRetainedParts(providerMetadata, adapter) {
8127
8128
  }));
8128
8129
  }
8129
8130
  //#endregion
8131
+ //#region src/model/quota.ts
8132
+ /**
8133
+ * Quota rules and the in-process reference QuotaLimiter (RV-215).
8134
+ * The rule model is shared by every reference implementation
8135
+ * (memoryQuotaLimiter here, SqliteQuotaLimiter in
8136
+ * @rulvar/store-sqlite): fixed one-minute windows aligned to the
8137
+ * epoch, admission at reservation time, reconciliation to actual
8138
+ * usage inside the same window. The hard guarantee is on
8139
+ * `requestsPerMinute` (every wire attempt is exactly one request);
8140
+ * `tokensPerMinute` admits on the heuristic estimate and settles to
8141
+ * actual usage, so token windows are approximate at admission and
8142
+ * exact at settlement.
8143
+ *
8144
+ * Docs: https://docs.rulvar.com/guide/model-routing
8145
+ */
8146
+ /**
8147
+ * Captured at module load, before the InProcessRunner's
8148
+ * nondeterminism guard can patch the global: the limiter's clock is
8149
+ * engine infrastructure on the live-only dispatch path and must never
8150
+ * be blamed on workflow code.
8151
+ */
8152
+ const nativeNow = Date.now;
8153
+ /** The fixed accounting window every PerMinute cap counts over. */
8154
+ const QUOTA_WINDOW_MS = 6e4;
8155
+ /**
8156
+ * Validates a quota rule set as a typed ConfigError before any
8157
+ * limiter can admit under it: a non-array or empty set, a rule
8158
+ * without a cap, a malformed dimension, or a malformed cap all fail
8159
+ * loud at construction. Shared by every reference implementation.
8160
+ */
8161
+ function validateQuotaRules(rules, site = "quota rules") {
8162
+ const raw = rules;
8163
+ if (!Array.isArray(raw)) throw new ConfigError(`${site} must be an array of QuotaRule objects`);
8164
+ if (raw.length === 0) throw new ConfigError(`${site} must contain at least one rule`);
8165
+ raw.forEach((entry, index) => {
8166
+ const at = `${site}[${String(index)}]`;
8167
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) throw new ConfigError(`${at} must be a QuotaRule object`);
8168
+ const rule = entry;
8169
+ for (const dimension of [
8170
+ "provider",
8171
+ "model",
8172
+ "tenant"
8173
+ ]) {
8174
+ const value = rule[dimension];
8175
+ if (value !== void 0 && (typeof value !== "string" || value === "")) throw new ConfigError(`${at}.${dimension} must be a nonempty string when given`);
8176
+ }
8177
+ if (rule.requestsPerMinute === void 0 && rule.tokensPerMinute === void 0) throw new ConfigError(`${at} must set requestsPerMinute or tokensPerMinute (or both)`);
8178
+ for (const cap of ["requestsPerMinute", "tokensPerMinute"]) if (rule[cap] !== void 0) requirePositiveInteger(rule[cap], `${at}.${cap}`);
8179
+ });
8180
+ }
8181
+ /** True when every dimension the rule pins matches the request. */
8182
+ function quotaRuleMatches(rule, request) {
8183
+ 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);
8184
+ }
8185
+ /** The tokens a reservation is admitted under: input estimate plus the output cap. */
8186
+ function quotaEstimateTokens(request) {
8187
+ return request.estimate.inputTokens + (request.estimate.maxOutputTokens ?? 0);
8188
+ }
8189
+ /** The tokens a settled attempt actually consumed. */
8190
+ function quotaActualTokens(usage) {
8191
+ return usage.inputTokens + usage.outputTokens;
8192
+ }
8193
+ /**
8194
+ * One rule's admission verdict against its current-window counters,
8195
+ * the pure decision both reference implementations share. A denial
8196
+ * carries the window remainder as retryAfterMs, except when the
8197
+ * estimate alone can never fit the token cap: that denial says
8198
+ * retryAfterMs 0 (retry immediately), so the caller's bounded
8199
+ * attempts exhaust without waiting and failover gets its chance.
8200
+ */
8201
+ function quotaRuleAdmission(rule, counters, estimate, msUntilWindowEnd) {
8202
+ if (rule.requestsPerMinute !== void 0 && counters.requests + estimate.requests > rule.requestsPerMinute) return {
8203
+ admit: false,
8204
+ retryAfterMs: msUntilWindowEnd,
8205
+ reason: `requestsPerMinute ${String(rule.requestsPerMinute)} exhausted`
8206
+ };
8207
+ if (rule.tokensPerMinute !== void 0) {
8208
+ if (estimate.tokens > rule.tokensPerMinute) return {
8209
+ admit: false,
8210
+ retryAfterMs: 0,
8211
+ reason: `the estimate of ${String(estimate.tokens)} tokens can never fit tokensPerMinute ${String(rule.tokensPerMinute)}`
8212
+ };
8213
+ if (counters.tokens + estimate.tokens > rule.tokensPerMinute) return {
8214
+ admit: false,
8215
+ retryAfterMs: msUntilWindowEnd,
8216
+ reason: `tokensPerMinute ${String(rule.tokensPerMinute)} exhausted`
8217
+ };
8218
+ }
8219
+ return { admit: true };
8220
+ }
8221
+ /**
8222
+ * Folds one more failing rule into the decision the caller returns:
8223
+ * the wait is the LONGEST failing horizon (every matching rule must
8224
+ * admit), and the FIRST failing rule names the denial.
8225
+ */
8226
+ function mergeQuotaDenial(current, next) {
8227
+ if (current === void 0) return {
8228
+ retryAfterMs: next.retryAfterMs,
8229
+ reason: next.reason
8230
+ };
8231
+ return next.retryAfterMs > current.retryAfterMs ? {
8232
+ retryAfterMs: next.retryAfterMs,
8233
+ reason: current.reason
8234
+ } : current;
8235
+ }
8236
+ /**
8237
+ * The in-process reference QuotaLimiter: fixed epoch-aligned
8238
+ * one-minute windows over the shared rule model. Coordinates every
8239
+ * engine that shares THIS instance inside one process; processes
8240
+ * coordinate through a shared-storage implementation of the same SPI
8241
+ * (SqliteQuotaLimiter in @rulvar/store-sqlite) instead.
8242
+ */
8243
+ function memoryQuotaLimiter(rules, options = {}) {
8244
+ validateQuotaRules(rules, "memoryQuotaLimiter rules");
8245
+ const now = options.now ?? (() => nativeNow());
8246
+ const buckets = /* @__PURE__ */ new Map();
8247
+ const reservations = /* @__PURE__ */ new Map();
8248
+ let nextReservation = 0;
8249
+ const windowStartAt = (at) => at - at % QUOTA_WINDOW_MS;
8250
+ const bucketFor = (ruleIndex, windowStart) => {
8251
+ let bucket = buckets.get(ruleIndex);
8252
+ if (bucket === void 0 || bucket.windowStart !== windowStart) {
8253
+ bucket = {
8254
+ windowStart,
8255
+ requests: 0,
8256
+ tokens: 0
8257
+ };
8258
+ buckets.set(ruleIndex, bucket);
8259
+ }
8260
+ return bucket;
8261
+ };
8262
+ const prune = (windowStart) => {
8263
+ for (const [id, reservation] of reservations) if (reservation.windowStart < windowStart) reservations.delete(id);
8264
+ };
8265
+ return {
8266
+ reserve(request) {
8267
+ const at = now();
8268
+ const windowStart = windowStartAt(at);
8269
+ prune(windowStart);
8270
+ const estimateTokens = quotaEstimateTokens(request);
8271
+ const msUntilWindowEnd = windowStart + QUOTA_WINDOW_MS - at;
8272
+ const matched = [];
8273
+ let denial;
8274
+ rules.forEach((rule, index) => {
8275
+ if (!quotaRuleMatches(rule, request)) return;
8276
+ matched.push(index);
8277
+ const verdict = quotaRuleAdmission(rule, bucketFor(index, windowStart), {
8278
+ requests: request.estimate.requests,
8279
+ tokens: estimateTokens
8280
+ }, msUntilWindowEnd);
8281
+ if (!verdict.admit) denial = mergeQuotaDenial(denial, verdict);
8282
+ });
8283
+ if (denial !== void 0) return Promise.resolve({
8284
+ granted: false,
8285
+ ...denial
8286
+ });
8287
+ for (const index of matched) {
8288
+ const bucket = bucketFor(index, windowStart);
8289
+ bucket.requests += request.estimate.requests;
8290
+ bucket.tokens += estimateTokens;
8291
+ }
8292
+ nextReservation += 1;
8293
+ const reservationId = `mq-${String(nextReservation)}`;
8294
+ reservations.set(reservationId, {
8295
+ windowStart,
8296
+ estimateTokens,
8297
+ ruleIndexes: matched
8298
+ });
8299
+ return Promise.resolve({
8300
+ granted: true,
8301
+ reservationId
8302
+ });
8303
+ },
8304
+ reconcile(reservationId, usage) {
8305
+ const reservation = reservations.get(reservationId);
8306
+ if (reservation === void 0) return Promise.resolve();
8307
+ reservations.delete(reservationId);
8308
+ const windowStart = windowStartAt(now());
8309
+ if (reservation.windowStart !== windowStart) return Promise.resolve();
8310
+ const delta = quotaActualTokens(usage) - reservation.estimateTokens;
8311
+ for (const index of reservation.ruleIndexes) {
8312
+ const bucket = buckets.get(index);
8313
+ if (bucket !== void 0 && bucket.windowStart === windowStart) bucket.tokens = Math.max(0, bucket.tokens + delta);
8314
+ }
8315
+ return Promise.resolve();
8316
+ },
8317
+ snapshot() {
8318
+ const windowStart = windowStartAt(now());
8319
+ return rules.map((rule, index) => {
8320
+ const bucket = buckets.get(index);
8321
+ const current = bucket !== void 0 && bucket.windowStart === windowStart;
8322
+ return {
8323
+ rule,
8324
+ windowStart,
8325
+ requests: current ? bucket.requests : 0,
8326
+ tokens: current ? bucket.tokens : 0
8327
+ };
8328
+ });
8329
+ }
8330
+ };
8331
+ }
8332
+ /**
8333
+ * Validates createEngine's quota config as a typed ConfigError before
8334
+ * any run could dispatch under a malformed limiter (the intake
8335
+ * discipline every engine option follows).
8336
+ */
8337
+ function validateEngineQuotaConfig(config, site = "createEngine quota") {
8338
+ if (config === void 0) return;
8339
+ const raw = config;
8340
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new ConfigError(`${site} must be an object with a limiter`);
8341
+ const candidate = raw;
8342
+ const limiter = candidate.limiter;
8343
+ 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)`);
8344
+ if (candidate.tenant !== void 0 && (typeof candidate.tenant !== "string" || candidate.tenant === "")) throw new ConfigError(`${site}.tenant must be a nonempty string when given`);
8345
+ if (candidate.onLimiterError !== void 0 && candidate.onLimiterError !== "deny" && candidate.onLimiterError !== "allow") throw new ConfigError(`${site}.onLimiterError must be 'deny' or 'allow' when given`);
8346
+ }
8347
+ //#endregion
8130
8348
  //#region src/model/retry.ts
8131
8349
  /**
8132
8350
  * Transport RetryPolicy (M4-T05): retries live UNDER the journal. A
@@ -10311,12 +10529,74 @@ async function runAgent(options) {
10311
10529
  const target = site.chain[site.cursor.index] ?? site.chain[0];
10312
10530
  let tries = 0;
10313
10531
  inner: for (;;) {
10532
+ let reservationId;
10533
+ const quotaDeniedOutcome = (denial) => ({
10534
+ turn: {
10535
+ text: "",
10536
+ toolCalls: []
10537
+ },
10538
+ usage: ZERO_USAGE$1,
10539
+ reported: ZERO_USAGE$1,
10540
+ usageApprox: false,
10541
+ quotaDenied: true,
10542
+ wireError: {
10543
+ code: denial.infrastructure === void 0 ? "rate-limit" : "quota-limiter",
10544
+ message: denial.infrastructure ?? `the shared quota limiter denied ${target.resolved.ref}` + (denial.reason === void 0 ? "" : `: ${denial.reason}`),
10545
+ retryable: true,
10546
+ data: {
10547
+ kind: denial.infrastructure === void 0 ? "rate-limit" : "transport",
10548
+ source: "quota-limiter",
10549
+ ...denial.retryAfterMs === void 0 ? {} : { retryAfterMs: denial.retryAfterMs },
10550
+ ...denial.reason === void 0 ? {} : { reason: denial.reason }
10551
+ }
10552
+ }
10553
+ });
10554
+ const dispatchWithQuota = async (quota) => {
10555
+ const req = site.requestFor(target);
10556
+ let decision;
10557
+ try {
10558
+ decision = await quota.reserve({
10559
+ provider: target.adapter.id,
10560
+ model: target.resolved.model,
10561
+ estimate: {
10562
+ requests: 1,
10563
+ inputTokens: estimateInputTokens(req.messages),
10564
+ ...req.maxOutputTokens === void 0 ? {} : { maxOutputTokens: req.maxOutputTokens }
10565
+ }
10566
+ });
10567
+ } catch (thrown) {
10568
+ const detail = thrown instanceof Error ? thrown.message : String(thrown);
10569
+ if (quota.onLimiterError === "allow") {
10570
+ events?.emit({
10571
+ type: "log",
10572
+ level: "warn",
10573
+ msg: `the shared quota limiter failed; dispatching ${target.resolved.ref} without a reservation (onLimiterError 'allow'): ${detail}`
10574
+ });
10575
+ return streamTurn(target.adapter, req, site.streamOptionsFor(target));
10576
+ }
10577
+ return quotaDeniedOutcome({ infrastructure: `the shared quota limiter failed (onLimiterError 'deny'): ${detail}` });
10578
+ }
10579
+ if (!decision.granted) return quotaDeniedOutcome(decision);
10580
+ reservationId = decision.reservationId;
10581
+ return streamTurn(target.adapter, req, site.streamOptionsFor(target));
10582
+ };
10314
10583
  const dispatch = () => {
10315
10584
  const aborted = abortKind();
10316
- return aborted === void 0 ? streamTurn(target.adapter, site.requestFor(target), site.streamOptionsFor(target)) : Promise.resolve(abortedOutcome(aborted));
10585
+ if (aborted !== void 0) return Promise.resolve(abortedOutcome(aborted));
10586
+ return options.quota === void 0 ? streamTurn(target.adapter, site.requestFor(target), site.streamOptionsFor(target)) : dispatchWithQuota(options.quota);
10317
10587
  };
10318
10588
  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);
10589
+ if (reservationId !== void 0 && options.quota !== void 0) try {
10590
+ await options.quota.reconcile(reservationId, outcome.usage);
10591
+ } catch (thrown) {
10592
+ const detail = thrown instanceof Error ? thrown.message : String(thrown);
10593
+ events?.emit({
10594
+ type: "log",
10595
+ level: "warn",
10596
+ msg: `the shared quota limiter failed to reconcile a reservation: ${detail}`
10597
+ });
10598
+ }
10599
+ if (outcome.quotaDenied !== true) recordUsage(outcome.usage, outcome.reported, target.adapter.id, target.resolved.ref, site.role, outcome.usageViolation);
10320
10600
  tries += 1;
10321
10601
  const retryClass = outcome.aborted === "idle" ? "transport" : outcome.wireError === void 0 ? void 0 : retryClassOf(outcome.wireError);
10322
10602
  if (retryClass === void 0) return {
@@ -13251,6 +13531,18 @@ function createCtx(internals, rootWorkflow) {
13251
13531
  if (profile?.compaction !== void 0) runAgentOptions.compaction = profile.compaction;
13252
13532
  if (loopFallbacks.length > 0) runAgentOptions.fallbacks = loopFallbacks;
13253
13533
  if (retryPolicy !== void 0) runAgentOptions.retry = { policy: retryPolicy };
13534
+ if (internals.quota !== void 0) {
13535
+ const quota = internals.quota;
13536
+ runAgentOptions.quota = {
13537
+ reserve: (request) => quota.limiter.reserve({
13538
+ ...request,
13539
+ runId: internals.runId,
13540
+ ...quota.tenant === void 0 ? {} : { tenant: quota.tenant }
13541
+ }),
13542
+ reconcile: (reservationId, usage) => quota.limiter.reconcile(reservationId, usage),
13543
+ onLimiterError: quota.onLimiterError
13544
+ };
13545
+ }
13254
13546
  if (internals.providerLimiter !== void 0) {
13255
13547
  const limiter = internals.providerLimiter;
13256
13548
  runAgentOptions.providerSlot = (key, fn, signal) => limiter.withSlot(key, fn, () => internals.events.emit({
@@ -16322,6 +16614,12 @@ function createEngine(options) {
16322
16614
  if (profile.compaction?.threshold !== void 0) requireFraction(profile.compaction.threshold, `createEngine defaults.profiles['${name}'].compaction.threshold`);
16323
16615
  }
16324
16616
  validateDeterminismConfig(options.determinism);
16617
+ validateEngineQuotaConfig(options.quota);
16618
+ const quotaRuntime = options.quota === void 0 ? void 0 : {
16619
+ limiter: options.quota.limiter,
16620
+ ...options.quota.tenant === void 0 ? {} : { tenant: options.quota.tenant },
16621
+ onLimiterError: options.quota.onLimiterError ?? "deny"
16622
+ };
16325
16623
  const knowledgeStore = options.stores?.modelKnowledge;
16326
16624
  const knowledge = knowledgeStore === void 0 ? void 0 : { current: () => knowledgeStore.current() };
16327
16625
  const runner = new InProcessRunner(options.onEscalation === void 0 ? void 0 : { onEscalation: options.onEscalation });
@@ -16428,6 +16726,7 @@ function createEngine(options) {
16428
16726
  admission,
16429
16727
  semaphore: new Semaphore(options.concurrency?.perRun ?? 12),
16430
16728
  providerLimiter,
16729
+ ...quotaRuntime === void 0 ? {} : { quota: quotaRuntime },
16431
16730
  ...options.pricing === void 0 ? {} : { pricingVersion: options.pricing.pricingVersion },
16432
16731
  ...options.budgetDefaults?.flatReserveUsd === void 0 ? {} : { flatReserveUsd: options.budgetDefaults.flatReserveUsd },
16433
16732
  ...defaults.roleFloors === void 0 ? {} : { floors: defaults.roleFloors },
@@ -17102,4 +17401,4 @@ function createSandboxBridge(ctx, options) {
17102
17401
  };
17103
17402
  }
17104
17403
  //#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 };
17404
+ 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.56.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",