@rulvar/core 1.114.0 → 1.116.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
@@ -2973,7 +2973,10 @@ declare class Replayer {
2973
2973
  appendSuspended(input: SuspendedAppend): Promise<JournalEntry>;
2974
2974
  /**
2975
2975
  * The budget ledger fold: usage sums over terminal entries once, never twice; agentsSpawned
2976
- * counts agent dispatches.
2976
+ * counts agent dispatches. Dollars fold on the settled billing basis
2977
+ * (RV801): per provider call where the entry's records cover its
2978
+ * usage, the per-slice aggregate otherwise, the same basis as the
2979
+ * CostReport and the invoice.
2977
2980
  */
2978
2981
  ledger(): Ledger;
2979
2982
  /** Read-only view of the appended entries, in per-run total order. */
@@ -4620,6 +4623,20 @@ interface BudgetHooks {
4620
4623
  * grant against it.
4621
4624
  */
4622
4625
  remainingUsd?: () => number | undefined;
4626
+ /**
4627
+ * The in-flight exposure admission (RV711), wired only when the cap
4628
+ * is configured. Called synchronously right before each provider
4629
+ * dispatch attempt with the attempt's own request estimate: the
4630
+ * serving model, the estimated prompt tokens, and the planned
4631
+ * worst-case output tokens (the request's effective maxOutputTokens,
4632
+ * else the model's declared output cap). Throws BudgetExhaustedError
4633
+ * (data.reason 'in-flight-exposure') to refuse the dispatch typed,
4634
+ * on the same surface as the layer-2b output bound; returns the
4635
+ * release closure the loop calls once the attempt settles, so the
4636
+ * reservation lives exactly as long as the wire call it covers.
4637
+ * Undefined result = nothing reserved (the cap resolved inert).
4638
+ */
4639
+ admitTurnExposure?: (servedBy: ModelRef, estimatedInputTokens: number, plannedOutputTokens: number) => (() => void) | undefined;
4623
4640
  /** Live usage accounting; layer 3 may respond by aborting `signal`. */
4624
4641
  onUsage(usage: Usage, servedBy: ModelRef): void;
4625
4642
  /** Layer 3: the ceiling AbortSignal. */
@@ -5351,6 +5368,14 @@ type Spend = {
5351
5368
  };
5352
5369
  /** Last resort of the admission reserve formula. */
5353
5370
  declare const DEFAULT_FLAT_RESERVE_USD = .5;
5371
+ /**
5372
+ * The message prefix of an in-flight exposure refusal (RV711): the
5373
+ * single producer is reserveTurnExposure below, and the ctx layer's
5374
+ * uniform budget rethrow keys on it to carry the refusal through with
5375
+ * its own honest arithmetic instead of claiming a ceiling crossed
5376
+ * (no account closes on a transient refusal).
5377
+ */
5378
+ declare const IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX = "in flight exposure cap reached";
5354
5379
  /** The run-root account scope. */
5355
5380
  declare const ROOT_ACCOUNT = "run";
5356
5381
  /**
@@ -5410,6 +5435,11 @@ interface BudgetExhaustionDiagnostics {
5410
5435
  declare class RunBudget {
5411
5436
  /** B0; immutable after start. Undefined means no USD ceiling. */
5412
5437
  readonly ceilingUsd?: number;
5438
+ /**
5439
+ * The opt-in in-flight exposure cap (RV711). Undefined means the
5440
+ * reservation surface is inert and reserveTurnExposure never binds.
5441
+ */
5442
+ readonly maxInFlightExposureUsd?: number;
5413
5443
  private readonly lifetimeSpawnCap;
5414
5444
  private readonly events?;
5415
5445
  private readonly priceUsd?;
@@ -5418,18 +5448,22 @@ declare class RunBudget {
5418
5448
  private usageInternal;
5419
5449
  private agentsSpawnedInternal;
5420
5450
  private exhaustedInternal;
5451
+ /** Live dispatch estimates held by reserveTurnExposure (RV711). */
5452
+ private inFlightExposureUsd;
5421
5453
  /** Models already warned about; the warning fires once per model per run. */
5422
5454
  private readonly unpricedWarned;
5423
5455
  /** Models whose price function already returned an invalid USD once. */
5424
5456
  private readonly invalidPriceWarned;
5425
5457
  constructor(options: {
5426
- ceilingUsd?: number;
5458
+ ceilingUsd?: number; /** The opt-in in-flight exposure cap (RV711); see reserveTurnExposure. */
5459
+ maxInFlightExposureUsd?: number;
5427
5460
  lifetimeSpawnCap?: number;
5428
5461
  events?: RuntimeEventSink;
5429
5462
  priceUsd?: (servedBy: ModelRef, usage: Usage) => number | undefined; /** Raw price-row resolution for the layer-2b output bound. */
5430
5463
  pricingOf?: (servedBy: ModelRef) => Pricing | undefined;
5431
5464
  /**
5432
- * The resume ledger fold: spend is never
5465
+ * The resume seed, folded from the persisted journal (the settled
5466
+ * per-call fold, RV801): spend is never
5433
5467
  * reset and never double-counted; replayed entries are already inside
5434
5468
  * this seed and add no increments.
5435
5469
  */
@@ -5552,6 +5586,32 @@ declare class RunBudget {
5552
5586
  releaseSynthesisReserve(scope: string): void;
5553
5587
  /** The reserve is replaced by real spend when the spawn settles. */
5554
5588
  releaseReserve(reserveUsd: number, accountScope?: string): void;
5589
+ /**
5590
+ * The in-flight exposure reservation (RV711). The per-turn guard
5591
+ * below checks money already SPENT, so N concurrent turns each pass
5592
+ * it before any settles and together can cross the ceiling by up to
5593
+ * one whole turn each; this is the opt-in bound on that hole. The
5594
+ * caller reserves the attempt's own worst-case estimate (the prompt
5595
+ * estimate plus the planned output allowance, priced by the SAME
5596
+ * price rows as the layer-2b clamp) right before the wire call and
5597
+ * releases at the attempt's settle, so the reservation lives exactly
5598
+ * as long as the exposure it covers. The admission refuses, typed
5599
+ * and without waiting, when spent + the named reserves (finalize and
5600
+ * synthesis money is promised elsewhere) + live reservations + this
5601
+ * estimate does not fit the cap; an exact fill admits, mirroring
5602
+ * admitSpawn, and a full cap refuses even a zero estimate. A refusal
5603
+ * is TRANSIENT (in-flight money returns at settle), so it never
5604
+ * marks the run exhausted and never severs a stream. A model without
5605
+ * a price row reserves zero, exactly as it debits zero (the
5606
+ * once-per-model unpriced warning covers that hole). While an
5607
+ * attempt streams, its usage debits spentUsd with the reservation
5608
+ * still live, briefly counting the same money twice: conservative in
5609
+ * the safe direction, gone at release. Returns undefined (fully
5610
+ * inert) when the cap is not configured; layer-1 spawn reserves
5611
+ * (committedReserveUsd) stay out of the formula, because a child's
5612
+ * lifetime reserve and its own turn exposure would double-count.
5613
+ */
5614
+ reserveTurnExposure(servedBy: ModelRef, estimatedInputTokens: number, plannedOutputTokens: number): (() => void) | undefined;
5555
5615
  /** Layer 2: the per-turn guard. A turn that would cross any ceiling in the chain is not dispatched. */
5556
5616
  beforeTurn(accountScope?: string): void;
5557
5617
  /**
@@ -6533,6 +6593,28 @@ interface RunOptions {
6533
6593
  * concurrent agent. Contract: https://docs.rulvar.com/guide/budgets.
6534
6594
  */
6535
6595
  budgetUsd?: number;
6596
+ /**
6597
+ * The opt-in in-flight exposure cap (RV711): bounds spent money plus
6598
+ * the summed worst-case estimates of live dispatches. The per-turn
6599
+ * guard checks money already SPENT, so under `budgetUsd` alone N
6600
+ * concurrent turns each pass it before any settles and together can
6601
+ * cross the ceiling by up to one whole turn each (preflight's
6602
+ * 'overshoot-exposure' finding prices that hole). With the cap, the
6603
+ * admission holds each turn's own estimate (the prompt estimate plus
6604
+ * the request's output allowance, priced by the same rows as
6605
+ * settlement) from right before the provider call until the attempt
6606
+ * settles, and the dispatch whose estimate does not fit
6607
+ * spent + finalize/synthesis reserves + live estimates is refused
6608
+ * with a typed BudgetExhaustedError (data.reason
6609
+ * 'in-flight-exposure') instead of waiting; the refused agent
6610
+ * settles as a budget error. Worst concurrent overshoot past the cap
6611
+ * is thereby the estimate error of the in-flight turns, not one
6612
+ * whole turn per agent. Absent by default: wire traffic, journals,
6613
+ * and hooks stay byte-identical. Operational and per-invocation like
6614
+ * `limits`: not recorded in RunMeta, so a resumed segment runs
6615
+ * without it.
6616
+ */
6617
+ maxInFlightExposureUsd?: number;
6536
6618
  /** Run-level defaults merged over engine defaults. */
6537
6619
  limits?: UsageLimits;
6538
6620
  /**
@@ -9930,8 +10012,8 @@ interface PreflightOrchestratorSpec {
9930
10012
  interface PreflightInput {
9931
10013
  /** The same object createEngine would receive (adapters used for pure caps() only). */
9932
10014
  engine?: Partial<Pick<CreateEngineOptions, "adapters" | "defaults" | "budgetDefaults" | "concurrency" | "quota" | "pricing">>;
9933
- /** The RunOptions slice: the run ceiling and run-level limits. */
9934
- run?: Pick<RunOptions, "budgetUsd" | "limits">;
10015
+ /** The RunOptions slice: the ceiling, run-level limits, and the RV711 exposure cap. */
10016
+ run?: Pick<RunOptions, "budgetUsd" | "limits" | "maxInFlightExposureUsd">;
9935
10017
  /** Present when the run is a dynamic orchestration. */
9936
10018
  orchestrator?: PreflightOrchestratorSpec;
9937
10019
  /** The declared first spawn wave, in admission order. */
@@ -10600,6 +10682,52 @@ interface CriticalPath {
10600
10682
  synthesisShare?: number;
10601
10683
  /** Settled non-coordination agent spans that anchored the fan-in. */
10602
10684
  workerSpans: number;
10685
+ /** The RV710 decomposition of the window; present with postFanInMs. */
10686
+ postFanIn?: PostFanInBreakdown;
10687
+ }
10688
+ /**
10689
+ * Where the post-fan-in interval actually went (RV710): the eleventh
10690
+ * comparison experiment measured 45.5 percent of wall sitting after
10691
+ * fan-in with zero synthesis share and nothing to name it. The
10692
+ * decomposition is a pure fold over the SAME vocabulary, no new event
10693
+ * types: model activations and tool executions of coordination spans
10694
+ * (spans whose agent:start role is 'orchestrate') are reconstructed
10695
+ * from their end events' (ts, durationMs) and clipped to the
10696
+ * [last worker settle, run:end] window, and completed 'synthesize'
10697
+ * spans are clipped the same way. The coordinator's draft and repair
10698
+ * thinking lands in the model bucket; child-result pagination and the
10699
+ * finish exchanges (host validators run inside the finish tool's
10700
+ * measured window) land in the tool buckets under their own names; the
10701
+ * residue is what no recorded interval covers: scheduling gaps,
10702
+ * journal writes, park-to-wake latency. Live fidelity only, exactly
10703
+ * like the wall numbers around it: a replayed stream re-stamps
10704
+ * emission times and carries durationMs 0, so its decomposition is
10705
+ * degenerate. Buckets are clipped SUMS (two concurrent coordination
10706
+ * spans, or duration-clock skew against emission stamps, can
10707
+ * overlap-count); coveredMs is the exact interval union, so residueMs
10708
+ * is never understated by an overlap. End events whose span never
10709
+ * started in the stream (a consumer attached mid-stream) cannot be
10710
+ * attributed and are skipped, never guessed at.
10711
+ */
10712
+ interface PostFanInBreakdown {
10713
+ /** Model activations of coordination spans inside the window. */
10714
+ coordinationModelMs: number;
10715
+ /** Tool executions of coordination spans inside the window, summed. */
10716
+ coordinationToolMs: number;
10717
+ /**
10718
+ * The same tool time keyed by tool name. A zero-duration execution
10719
+ * inside the window still registers its name: sub-millisecond tools
10720
+ * round to 0 on the wall clock but did run here.
10721
+ */
10722
+ coordinationToolMsByName: Record<string, number>;
10723
+ /** Completed 'synthesize' span wall clipped to the window. */
10724
+ synthesisMs: number;
10725
+ /** Union length of every covered interval above. */
10726
+ coveredMs: number;
10727
+ /** postFanInMs minus coveredMs, floored at zero. */
10728
+ residueMs: number;
10729
+ /** residueMs / postFanInMs when the window is longer than zero. */
10730
+ residueShare?: number;
10603
10731
  }
10604
10732
  declare function reduceCriticalPath(events: Iterable<WorkflowEvent>): CriticalPath;
10605
10733
  //#endregion
@@ -10675,4 +10803,4 @@ interface SandboxBridge {
10675
10803
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
10676
10804
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
10677
10805
  //#endregion
10678
- 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, type AppliedPricingRow, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, AuditCategory, AuditRecord, AuditRunsOptions, BUDGET_ABORT_REASON, BaseAppend, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildIdentityInput, ChildResultPage, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, type CostBasis, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DataKeyProvider, DebitResult, DeclaredLadder, DedupIndex, DedupNote, DedupedClaims, DerivedKey, DeriverRegistry, type DeterminismConfig, DeterminismError, type DeterminismEvents, type DeterminismMode, DispositionRule, DispositionTable, DonorCandidate, DonorRef, DroppedItem, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EffectiveUsageLimits, Effort, Engine, EngineDefaults, EngineQuotaConfig, EngineQuotaRuntime, EntryBillingFold, EntryBillingUnit, EntryKind, EntryRef, EntryStatus, EnvelopeEncryption, EnvelopeEncryptionOptions, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, EvidenceContract, type EvidenceRef, type ExecKeyDerivation, type ExecutorRegistry, type ExplorationSummary, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FencedCodeMode, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, type FinalizationWindowBudget, FinishContract, FinishContractCitations, FinishContractGoldenReject, FinishContractManifest, FinishInfo, FinishSelfTestFailure, FinishSelfTestFixtures, FinishSelfTestReport, 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, InvoiceExport, InvoicePricingProvenance, InvoiceReconciliation, InvoiceRow, type IsolatedExecContext, type IsolatedExecRequest, type IsolatedExecutorTag, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JOURNAL_ENVELOPE_MARKER, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, type JournalPricingSnapshot, JournalSerializationContext, 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, MAX_TIMER_DELAY_MS, 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, OrchestrateSynthesisSkipReason, 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, type PinnedPricingSegment, PipelineCollected, PipelineOpts, PlanInvariantError, PreflightAdmissionRow, PreflightFinding, PreflightInput, PreflightOrchestratorSpec, PreflightReport, PreflightSpawnReport, PreflightSpawnSpec, PreflightToolCeiling, PriceTable, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, ProviderCallRecord, 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, RateLimitObservation, ReconcileOptions, ReconcileResult, RefEntryAppender, RefEntryClassification, RefusalInfo, RepeatedClaim, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, RepositoryResearchToolset, RepositoryResearchToolsetOptions, ResearchAgentProfileOptions, ResearchAgentProfileResult, ResearchEvidenceEntry, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunAuditVerdict, RunBudget, RunEventSink, RunExport, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStateAudit, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, SecretMasker, SectionMatchMode, Semaphore, SerializationHook, Settled, SettlementError, 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, type ToolBudgetSummary, ToolCallRequest, ToolChoice, type ToolContext, ToolContextSeed, ToolContract, type ToolDef, type ToolEvents, type ToolExecutor, type ToolExecutorProvider, ToolInit, type ToolRisk, ToolRuntime, type ToolSource, type ToolSourceSession, ToolsOption, TranscriptSerializationHook, type TranscriptStore, TriggerClass, TtlState, Usage, UsageLimits, UsageSlice, VerifiedRecommendation, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, WakeBudgetBlock, WakeDigest, WakeTrigger, WireError, Workflow, WorkflowCallOpts, type WorkflowEvent, type WorkflowEventBody, WorkflowRegistry, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, finishContract, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, preflightEstimate, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceAuditTrail, reduceCriticalPath, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, sectionCitationsValidator, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, stripFencedBlocks, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
10806
+ 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, type AppliedPricingRow, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, AuditCategory, AuditRecord, AuditRunsOptions, BUDGET_ABORT_REASON, BaseAppend, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildIdentityInput, ChildResultPage, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, type CostBasis, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DataKeyProvider, DebitResult, DeclaredLadder, DedupIndex, DedupNote, DedupedClaims, DerivedKey, DeriverRegistry, type DeterminismConfig, DeterminismError, type DeterminismEvents, type DeterminismMode, DispositionRule, DispositionTable, DonorCandidate, DonorRef, DroppedItem, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EffectiveUsageLimits, Effort, Engine, EngineDefaults, EngineQuotaConfig, EngineQuotaRuntime, EntryBillingFold, EntryBillingUnit, EntryKind, EntryRef, EntryStatus, EnvelopeEncryption, EnvelopeEncryptionOptions, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, EvidenceContract, type EvidenceRef, type ExecKeyDerivation, type ExecutorRegistry, type ExplorationSummary, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FencedCodeMode, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, type FinalizationWindowBudget, FinishContract, FinishContractCitations, FinishContractGoldenReject, FinishContractManifest, FinishInfo, FinishSelfTestFailure, FinishSelfTestFixtures, FinishSelfTestReport, 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, IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, IncrementalSynthesisResult, InvalidResolutionError, InvocationRole, type InvocationTable, InvoiceExport, InvoicePricingProvenance, InvoiceReconciliation, InvoiceRow, type IsolatedExecContext, type IsolatedExecRequest, type IsolatedExecutorTag, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JOURNAL_ENVELOPE_MARKER, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, type JournalPricingSnapshot, JournalSerializationContext, 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, MAX_TIMER_DELAY_MS, 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, OrchestrateSynthesisSkipReason, 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, type PinnedPricingSegment, PipelineCollected, PipelineOpts, PlanInvariantError, type PostFanInBreakdown, PreflightAdmissionRow, PreflightFinding, PreflightInput, PreflightOrchestratorSpec, PreflightReport, PreflightSpawnReport, PreflightSpawnSpec, PreflightToolCeiling, PriceTable, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, ProviderCallRecord, 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, RateLimitObservation, ReconcileOptions, ReconcileResult, RefEntryAppender, RefEntryClassification, RefusalInfo, RepeatedClaim, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, RepositoryResearchToolset, RepositoryResearchToolsetOptions, ResearchAgentProfileOptions, ResearchAgentProfileResult, ResearchEvidenceEntry, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunAuditVerdict, RunBudget, RunEventSink, RunExport, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStateAudit, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, SecretMasker, SectionMatchMode, Semaphore, SerializationHook, Settled, SettlementError, 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, type ToolBudgetSummary, ToolCallRequest, ToolChoice, type ToolContext, ToolContextSeed, ToolContract, type ToolDef, type ToolEvents, type ToolExecutor, type ToolExecutorProvider, ToolInit, type ToolRisk, ToolRuntime, type ToolSource, type ToolSourceSession, ToolsOption, TranscriptSerializationHook, type TranscriptStore, TriggerClass, TtlState, Usage, UsageLimits, UsageSlice, VerifiedRecommendation, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, WakeBudgetBlock, WakeDigest, WakeTrigger, WireError, Workflow, WorkflowCallOpts, type WorkflowEvent, type WorkflowEventBody, WorkflowRegistry, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, finishContract, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, preflightEstimate, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceAuditTrail, reduceCriticalPath, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, sectionCitationsValidator, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, stripFencedBlocks, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/dist/index.js CHANGED
@@ -7258,7 +7258,10 @@ var Replayer = class {
7258
7258
  }
7259
7259
  /**
7260
7260
  * The budget ledger fold: usage sums over terminal entries once, never twice; agentsSpawned
7261
- * counts agent dispatches.
7261
+ * counts agent dispatches. Dollars fold on the settled billing basis
7262
+ * (RV801): per provider call where the entry's records cover its
7263
+ * usage, the per-slice aggregate otherwise, the same basis as the
7264
+ * CostReport and the invoice.
7262
7265
  */
7263
7266
  ledger() {
7264
7267
  const usage = {
@@ -7280,7 +7283,7 @@ var Replayer = class {
7280
7283
  usage.cacheReadTokens += entry.usage.cacheReadTokens;
7281
7284
  usage.cacheWriteTokens += entry.usage.cacheWriteTokens;
7282
7285
  reasoning += entry.usage.reasoningTokens ?? 0;
7283
- if (this.priceUsd !== void 0) usd += priceEntryUsage(entry, this.priceUsd).usd;
7286
+ if (this.priceUsd !== void 0) usd += priceEntryBilling(entry, this.priceUsd).usd;
7284
7287
  }
7285
7288
  if (reasoning > 0) usage.reasoningTokens = reasoning;
7286
7289
  return {
@@ -12020,6 +12023,18 @@ async function runAgent(options) {
12020
12023
  let tries = 0;
12021
12024
  inner: for (;;) {
12022
12025
  let reservationId;
12026
+ let releaseExposure;
12027
+ const admitExposure = (req) => {
12028
+ const admit = options.budget?.admitTurnExposure;
12029
+ if (admit === void 0) return;
12030
+ let planned = req.maxOutputTokens;
12031
+ if (planned === void 0) try {
12032
+ planned = target.adapter.caps(target.resolved.model).maxOutputTokens;
12033
+ } catch {
12034
+ planned = 0;
12035
+ }
12036
+ releaseExposure = admit(target.resolved.ref, estimateInputTokens(req.messages), planned);
12037
+ };
12023
12038
  const quotaDeniedOutcome = (denial) => ({
12024
12039
  turn: {
12025
12040
  text: "",
@@ -12043,6 +12058,7 @@ async function runAgent(options) {
12043
12058
  });
12044
12059
  const dispatchWithQuota = async (quota) => {
12045
12060
  const req = site.requestFor(target);
12061
+ admitExposure(req);
12046
12062
  let decision;
12047
12063
  try {
12048
12064
  decision = await quota.reserve({
@@ -12073,9 +12089,19 @@ async function runAgent(options) {
12073
12089
  const dispatch = () => {
12074
12090
  const aborted = abortKind();
12075
12091
  if (aborted !== void 0) return Promise.resolve(abortedOutcome(aborted));
12076
- return options.quota === void 0 ? streamTurn(target.adapter, site.requestFor(target), site.streamOptionsFor(target)) : dispatchWithQuota(options.quota);
12092
+ if (options.quota === void 0) {
12093
+ const req = site.requestFor(target);
12094
+ admitExposure(req);
12095
+ return streamTurn(target.adapter, req, site.streamOptionsFor(target));
12096
+ }
12097
+ return dispatchWithQuota(options.quota);
12077
12098
  };
12078
- const outcome = await (options.providerSlot === void 0 ? dispatch() : options.providerSlot(target.adapter.id, dispatch, options.signal));
12099
+ let outcome;
12100
+ try {
12101
+ outcome = await (options.providerSlot === void 0 ? dispatch() : options.providerSlot(target.adapter.id, dispatch, options.signal));
12102
+ } finally {
12103
+ releaseExposure?.();
12104
+ }
12079
12105
  if (reservationId !== void 0 && options.quota !== void 0) try {
12080
12106
  await options.quota.reconcile(reservationId, outcome.usage);
12081
12107
  } catch (thrown) {
@@ -13030,14 +13056,24 @@ async function runAgent(options) {
13030
13056
  * account and plan/NodeId accounts). A child's spend propagates to ALL
13031
13057
  * ancestors up to the run root; the root ceiling remains the true
13032
13058
  * invariant. Sub-account spend is per-process state: on resume the root
13033
- * is seeded from the ledger fold while sub-accounts restart empty (their
13034
- * reserves are recovered from spawn-admission decision entries); the
13035
- * per-account historical fold completes with DEF-7 in M7.
13059
+ * is seeded from the settled journal fold (the per-call billing basis
13060
+ * and per-segment pricing pins of outcome.cost.totalUsd, RV801) while
13061
+ * sub-accounts restart empty (their reserves are recovered from
13062
+ * spawn-admission decision entries); the per-account historical fold
13063
+ * completes with DEF-7 in M7.
13036
13064
  *
13037
13065
  * Full contract: https://docs.rulvar.com/guide/budgets
13038
13066
  */
13039
13067
  /** Last resort of the admission reserve formula. */
13040
13068
  const DEFAULT_FLAT_RESERVE_USD = .5;
13069
+ /**
13070
+ * The message prefix of an in-flight exposure refusal (RV711): the
13071
+ * single producer is reserveTurnExposure below, and the ctx layer's
13072
+ * uniform budget rethrow keys on it to carry the refusal through with
13073
+ * its own honest arithmetic instead of claiming a ceiling crossed
13074
+ * (no account closes on a transient refusal).
13075
+ */
13076
+ const IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX = "in flight exposure cap reached";
13041
13077
  /** The run-root account scope. */
13042
13078
  const ROOT_ACCOUNT = "run";
13043
13079
  const ZERO_USAGE = {
@@ -13088,6 +13124,11 @@ function admissionReserveUsd(options) {
13088
13124
  var RunBudget = class {
13089
13125
  /** B0; immutable after start. Undefined means no USD ceiling. */
13090
13126
  ceilingUsd;
13127
+ /**
13128
+ * The opt-in in-flight exposure cap (RV711). Undefined means the
13129
+ * reservation surface is inert and reserveTurnExposure never binds.
13130
+ */
13131
+ maxInFlightExposureUsd;
13091
13132
  lifetimeSpawnCap;
13092
13133
  events;
13093
13134
  priceUsd;
@@ -13096,6 +13137,8 @@ var RunBudget = class {
13096
13137
  usageInternal = { ...ZERO_USAGE };
13097
13138
  agentsSpawnedInternal = 0;
13098
13139
  exhaustedInternal = false;
13140
+ /** Live dispatch estimates held by reserveTurnExposure (RV711). */
13141
+ inFlightExposureUsd = 0;
13099
13142
  /** Models already warned about; the warning fires once per model per run. */
13100
13143
  unpricedWarned = /* @__PURE__ */ new Set();
13101
13144
  /** Models whose price function already returned an invalid USD once. */
@@ -13105,6 +13148,10 @@ var RunBudget = class {
13105
13148
  requireValidCeiling(options.ceilingUsd, "budget ceiling");
13106
13149
  this.ceilingUsd = options.ceilingUsd;
13107
13150
  }
13151
+ if (options.maxInFlightExposureUsd !== void 0) {
13152
+ requireValidCeiling(options.maxInFlightExposureUsd, "maxInFlightExposureUsd");
13153
+ this.maxInFlightExposureUsd = options.maxInFlightExposureUsd;
13154
+ }
13108
13155
  this.lifetimeSpawnCap = options.lifetimeSpawnCap ?? 500;
13109
13156
  if (options.events !== void 0) this.events = options.events;
13110
13157
  if (options.priceUsd !== void 0) this.priceUsd = options.priceUsd;
@@ -13384,6 +13431,59 @@ var RunBudget = class {
13384
13431
  for (const account of this.chainOf(accountScope)) account.committedReserveUsd = Math.max(0, account.committedReserveUsd - reserveUsd);
13385
13432
  this.emitUpdate();
13386
13433
  }
13434
+ /**
13435
+ * The in-flight exposure reservation (RV711). The per-turn guard
13436
+ * below checks money already SPENT, so N concurrent turns each pass
13437
+ * it before any settles and together can cross the ceiling by up to
13438
+ * one whole turn each; this is the opt-in bound on that hole. The
13439
+ * caller reserves the attempt's own worst-case estimate (the prompt
13440
+ * estimate plus the planned output allowance, priced by the SAME
13441
+ * price rows as the layer-2b clamp) right before the wire call and
13442
+ * releases at the attempt's settle, so the reservation lives exactly
13443
+ * as long as the exposure it covers. The admission refuses, typed
13444
+ * and without waiting, when spent + the named reserves (finalize and
13445
+ * synthesis money is promised elsewhere) + live reservations + this
13446
+ * estimate does not fit the cap; an exact fill admits, mirroring
13447
+ * admitSpawn, and a full cap refuses even a zero estimate. A refusal
13448
+ * is TRANSIENT (in-flight money returns at settle), so it never
13449
+ * marks the run exhausted and never severs a stream. A model without
13450
+ * a price row reserves zero, exactly as it debits zero (the
13451
+ * once-per-model unpriced warning covers that hole). While an
13452
+ * attempt streams, its usage debits spentUsd with the reservation
13453
+ * still live, briefly counting the same money twice: conservative in
13454
+ * the safe direction, gone at release. Returns undefined (fully
13455
+ * inert) when the cap is not configured; layer-1 spawn reserves
13456
+ * (committedReserveUsd) stay out of the formula, because a child's
13457
+ * lifetime reserve and its own turn exposure would double-count.
13458
+ */
13459
+ reserveTurnExposure(servedBy, estimatedInputTokens, plannedOutputTokens) {
13460
+ const cap = this.maxInFlightExposureUsd;
13461
+ if (cap === void 0) return;
13462
+ const pricing = this.pricingOf?.(servedBy);
13463
+ const rawEstimate = pricing === void 0 ? 0 : priceUsdOf(pricing, {
13464
+ inputTokens: Math.max(0, estimatedInputTokens),
13465
+ outputTokens: Math.max(0, plannedOutputTokens),
13466
+ cacheReadTokens: 0,
13467
+ cacheWriteTokens: 0
13468
+ });
13469
+ const estimateUsd = Number.isFinite(rawEstimate) && rawEstimate > 0 ? rawEstimate : 0;
13470
+ const root = this.root;
13471
+ const committed = root.spentUsd + root.finalizeReserveUsd + root.synthesisReserveUsd + this.inFlightExposureUsd;
13472
+ if (committed >= cap || committed + estimateUsd > cap) throw new BudgetExhaustedError(`${IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX}: spent ${root.spentUsd.toFixed(4)} USD plus reserves ${(root.finalizeReserveUsd + root.synthesisReserveUsd).toFixed(4)} USD plus live dispatch estimates ${this.inFlightExposureUsd.toFixed(4)} USD plus this turn's estimate ${estimateUsd.toFixed(4)} USD does not fit maxInFlightExposureUsd ${cap.toFixed(4)} USD; the dispatch was refused before any provider call`, { data: {
13473
+ reason: "in-flight-exposure",
13474
+ capUsd: cap,
13475
+ spentUsd: root.spentUsd,
13476
+ inFlightUsd: this.inFlightExposureUsd,
13477
+ estimateUsd
13478
+ } });
13479
+ this.inFlightExposureUsd += estimateUsd;
13480
+ let released = false;
13481
+ return () => {
13482
+ if (released) return;
13483
+ released = true;
13484
+ this.inFlightExposureUsd = Math.max(0, this.inFlightExposureUsd - estimateUsd);
13485
+ };
13486
+ }
13387
13487
  /** Layer 2: the per-turn guard. A turn that would cross any ceiling in the chain is not dispatched. */
13388
13488
  beforeTurn(accountScope = "run") {
13389
13489
  for (const account of this.chainOf(accountScope)) if (account.ceilingUsd !== void 0 && account.spentUsd >= account.ceilingUsd) {
@@ -15236,6 +15336,7 @@ function createCtx(internals, rootWorkflow) {
15236
15336
  beforeTurn: () => internals.budget.beforeTurn(budgetAccount),
15237
15337
  maxAffordableOutputTokens: (servedBy, estimatedInputTokens) => internals.budget.maxAffordableOutputTokens(servedBy, estimatedInputTokens, budgetAccount),
15238
15338
  remainingUsd: () => internals.budget.remainingUsd(budgetAccount),
15339
+ ...internals.budget.maxInFlightExposureUsd === void 0 ? {} : { admitTurnExposure: (servedBy, estimatedInputTokens, plannedOutputTokens) => internals.budget.reserveTurnExposure(servedBy, estimatedInputTokens, plannedOutputTokens) },
15239
15340
  onUsage: (usage, servedBy) => internals.budget.onUsage(usage, servedBy, budgetAccount),
15240
15341
  signal: budgetAccount === "run" ? internals.budget.signal : AbortSignal.any([internals.budget.signal, internals.budget.signalOf(budgetAccount)].filter((signal) => signal !== void 0))
15241
15342
  },
@@ -15580,6 +15681,12 @@ function createCtx(internals, rootWorkflow) {
15580
15681
  bump(internals.cost.byPhase, state.phase ?? "", usd);
15581
15682
  bump(internals.cost.byAgentType, agentType, usd);
15582
15683
  if (result.error?.kind === "budget" || internals.budget.exhausted && result.status !== "ok") {
15684
+ if (!internals.budget.exhausted && result.errorMessage !== void 0 && result.errorMessage.startsWith("in flight exposure cap reached")) throw new BudgetExhaustedError(result.errorMessage, { data: {
15685
+ scope: state.scope,
15686
+ entryRef: terminal.seq,
15687
+ source: "in-flight-exposure",
15688
+ reason: "in-flight-exposure"
15689
+ } });
15583
15690
  const diagnostics = internals.budget.exhaustionDiagnostics(state.budgetScope ?? "run");
15584
15691
  const crossed = diagnostics.crossed;
15585
15692
  const rootSuffix = `run root: spent ${diagnostics.root.spentUsd.toFixed(4)}` + (diagnostics.root.ceilingUsd === void 0 ? " USD, no ceiling" : ` of ${diagnostics.root.ceilingUsd.toFixed(4)} USD`);
@@ -19433,6 +19540,7 @@ function preflightEstimate(input) {
19433
19540
  const defaults = engine.defaults ?? {};
19434
19541
  if (defaults.limits !== void 0) validateUsageLimits(defaults.limits, "preflight.engine.defaults.limits");
19435
19542
  if (input.run?.limits !== void 0) validateUsageLimits(input.run.limits, "preflight.run.limits");
19543
+ if (input.run?.maxInFlightExposureUsd !== void 0) requireNonNegativeNumber(input.run.maxInFlightExposureUsd, "preflight.run.maxInFlightExposureUsd");
19436
19544
  if (input.orchestrator?.limits !== void 0) validateUsageLimits(input.orchestrator.limits, "preflight.orchestrator.limits");
19437
19545
  const findings = [];
19438
19546
  const say = (finding) => {
@@ -20000,6 +20108,12 @@ function preflightEstimate(input) {
20000
20108
  code: "overshoot-exposure",
20001
20109
  message: `past a ceiling crossing, up to ${String(Math.min(maxInFlight, units.length))} in-flight turns may still complete: at least ${overshootOneTurnFloorUsd.toFixed(4)} USD past the ${ceilingUsd.toFixed(4)} USD ceiling at the declared estimates, growing with prompt size`
20002
20110
  });
20111
+ const exposureCapUsd = input.run?.maxInFlightExposureUsd;
20112
+ if (exposureCapUsd !== void 0) say({
20113
+ severity: "info",
20114
+ code: "in-flight-exposure-cap",
20115
+ message: `RunOptions.maxInFlightExposureUsd ${exposureCapUsd.toFixed(4)} USD bounds spent money plus live dispatch estimates: a dispatch whose estimate does not fit is refused typed before the provider call, so the worst concurrent overshoot past the cap is the estimate error of the in-flight turns, not one whole turn per agent`
20116
+ });
20003
20117
  const quotaConfigured = engine.quota !== void 0;
20004
20118
  if (!quotaConfigured && maxInFlight > 1 && units.length > 0) say({
20005
20119
  severity: "info",
@@ -20606,6 +20720,21 @@ function reduceInvocationTable(events) {
20606
20720
  totalCostUsd
20607
20721
  };
20608
20722
  }
20723
+ /** Total length of the union of possibly overlapping intervals. */
20724
+ function unionLength(intervals) {
20725
+ const positive = intervals.filter((interval) => interval.to > interval.from);
20726
+ if (positive.length === 0) return 0;
20727
+ const sorted = [...positive].sort((a, b) => a.from - b.from);
20728
+ let total = 0;
20729
+ let from = sorted[0]?.from ?? 0;
20730
+ let to = sorted[0]?.to ?? 0;
20731
+ for (const interval of sorted.slice(1)) if (interval.from > to) {
20732
+ total += to - from;
20733
+ from = interval.from;
20734
+ to = interval.to;
20735
+ } else if (interval.to > to) to = interval.to;
20736
+ return total + (to - from);
20737
+ }
20609
20738
  function reduceCriticalPath(events) {
20610
20739
  let runStart;
20611
20740
  let runEnd;
@@ -20613,6 +20742,10 @@ function reduceCriticalPath(events) {
20613
20742
  let lastWorkerEnd;
20614
20743
  let workerSpans = 0;
20615
20744
  let synthesisMs = 0;
20745
+ const coordinationModel = [];
20746
+ const coordinationTools = [];
20747
+ const synthesisSpans = [];
20748
+ const spanOf = (durationMs) => Number.isFinite(durationMs) && durationMs > 0 ? durationMs : 0;
20616
20749
  for (const event of events) {
20617
20750
  const at = Date.parse(event.ts);
20618
20751
  if (!Number.isFinite(at)) continue;
@@ -20629,11 +20762,29 @@ function reduceCriticalPath(events) {
20629
20762
  at
20630
20763
  });
20631
20764
  break;
20765
+ case "agent:phase:end":
20766
+ if (startBySpan.get(event.spanId)?.role === "orchestrate") coordinationModel.push({
20767
+ from: at - spanOf(event.durationMs),
20768
+ to: at
20769
+ });
20770
+ break;
20771
+ case "tool:end":
20772
+ if (startBySpan.get(event.spanId)?.role === "orchestrate") coordinationTools.push({
20773
+ name: event.toolName,
20774
+ from: at - spanOf(event.durationMs),
20775
+ to: at
20776
+ });
20777
+ break;
20632
20778
  case "agent:end": {
20633
20779
  const started = startBySpan.get(event.spanId);
20634
20780
  if (started === void 0) break;
20635
- if (started.role === "synthesize") synthesisMs += Math.max(0, at - started.at);
20636
- else if (started.role !== "orchestrate") {
20781
+ if (started.role === "synthesize") {
20782
+ synthesisMs += Math.max(0, at - started.at);
20783
+ synthesisSpans.push({
20784
+ from: started.at,
20785
+ to: at
20786
+ });
20787
+ } else if (started.role !== "orchestrate") {
20637
20788
  workerSpans += 1;
20638
20789
  lastWorkerEnd = lastWorkerEnd === void 0 ? at : Math.max(lastWorkerEnd, at);
20639
20790
  }
@@ -20647,7 +20798,44 @@ function reduceCriticalPath(events) {
20647
20798
  workerSpans
20648
20799
  };
20649
20800
  if (runStart !== void 0 && runEnd !== void 0) path.runWallMs = Math.max(0, runEnd - runStart);
20650
- if (runEnd !== void 0 && lastWorkerEnd !== void 0) path.postFanInMs = Math.max(0, runEnd - lastWorkerEnd);
20801
+ if (runEnd !== void 0 && lastWorkerEnd !== void 0) {
20802
+ path.postFanInMs = Math.max(0, runEnd - lastWorkerEnd);
20803
+ const windowFrom = Math.min(lastWorkerEnd, runEnd);
20804
+ const windowTo = runEnd;
20805
+ const clip = (interval) => {
20806
+ if (interval.to < windowFrom || interval.from > windowTo) return;
20807
+ return {
20808
+ from: Math.max(interval.from, windowFrom),
20809
+ to: Math.min(interval.to, windowTo)
20810
+ };
20811
+ };
20812
+ const modelClipped = coordinationModel.map(clip).filter((interval) => interval !== void 0);
20813
+ const synthesisClipped = synthesisSpans.map(clip).filter((interval) => interval !== void 0);
20814
+ const byName = {};
20815
+ const toolsClipped = [];
20816
+ for (const interval of coordinationTools) {
20817
+ const clipped = clip(interval);
20818
+ if (clipped === void 0) continue;
20819
+ byName[interval.name] = (byName[interval.name] ?? 0) + (clipped.to - clipped.from);
20820
+ toolsClipped.push(clipped);
20821
+ }
20822
+ const lengthOf = (intervals) => intervals.reduce((sum, interval) => sum + (interval.to - interval.from), 0);
20823
+ const coveredMs = unionLength([
20824
+ ...modelClipped,
20825
+ ...toolsClipped,
20826
+ ...synthesisClipped
20827
+ ]);
20828
+ const breakdown = {
20829
+ coordinationModelMs: lengthOf(modelClipped),
20830
+ coordinationToolMs: lengthOf(toolsClipped),
20831
+ coordinationToolMsByName: byName,
20832
+ synthesisMs: lengthOf(synthesisClipped),
20833
+ coveredMs,
20834
+ residueMs: Math.max(0, path.postFanInMs - coveredMs)
20835
+ };
20836
+ if (path.postFanInMs > 0) breakdown.residueShare = breakdown.residueMs / path.postFanInMs;
20837
+ path.postFanIn = breakdown;
20838
+ }
20651
20839
  if (path.runWallMs !== void 0 && path.runWallMs > 0) {
20652
20840
  if (path.postFanInMs !== void 0) path.postFanInShare = path.postFanInMs / path.runWallMs;
20653
20841
  path.synthesisShare = synthesisMs / path.runWallMs;
@@ -21103,6 +21291,7 @@ function createEngine(options) {
21103
21291
  function run(wf, args, opts, resumeCtx) {
21104
21292
  if (wf.kind !== "workflow" && wf.kind !== "compiled-workflow") throw new ConfigError("engine.run accepts in-process Workflow values or compileScript CompiledWorkflow values");
21105
21293
  if (opts?.budgetUsd !== void 0) requireNonNegativeNumber(opts.budgetUsd, "RunOptions.budgetUsd");
21294
+ if (opts?.maxInFlightExposureUsd !== void 0) requireNonNegativeNumber(opts.maxInFlightExposureUsd, "RunOptions.maxInFlightExposureUsd");
21106
21295
  if (opts?.limits !== void 0) validateUsageLimits(opts.limits, "RunOptions.limits");
21107
21296
  const deadlineAtMs = opts?.deadlineAt === void 0 ? void 0 : parseDeadlineAt(opts.deadlineAt);
21108
21297
  const compiled = wf.kind === "compiled-workflow" ? wf : void 0;
@@ -21130,6 +21319,7 @@ function createEngine(options) {
21130
21319
  const ceilingUsd = opts?.budgetUsd ?? resumeCtx?.budgetUsd;
21131
21320
  const makeBudget = () => new RunBudget({
21132
21321
  ...ceilingUsd === void 0 ? {} : { ceilingUsd },
21322
+ ...opts?.maxInFlightExposureUsd === void 0 ? {} : { maxInFlightExposureUsd: opts.maxInFlightExposureUsd },
21133
21323
  lifetimeSpawnCap: options.budgetDefaults?.lifetimeSpawnCap ?? 500,
21134
21324
  events: { emit: (body) => bus.emit(body, rootSpanId) },
21135
21325
  priceUsd,
@@ -21158,8 +21348,10 @@ function createEngine(options) {
21158
21348
  replayer.setAliasDisposition(dispositionHook({ isAbandoned: () => false }, registry, replayer.invalidatedSeqs, { runSettledOk }));
21159
21349
  if (resumeCtx !== void 0) {
21160
21350
  const prior = replayer.ledger();
21351
+ const priorPinned = journalPricingSnapshot(replayer.snapshot());
21352
+ const priorPriceUsd = priorPinned === void 0 ? (servedBy, usage) => priceUsd(servedBy, usage) : priorPinned.composedPriceUsd((servedBy, usage) => priceUsd(servedBy, usage));
21161
21353
  budgetSeed = {
21162
- usd: prior.usd,
21354
+ usd: costReportFromJournal(replayer.snapshot(), priorPriceUsd).totalUsd,
21163
21355
  usage: prior.usage,
21164
21356
  agentsSpawned: prior.agentsSpawned
21165
21357
  };
@@ -21490,7 +21682,7 @@ function createEngine(options) {
21490
21682
  bus.emit({
21491
21683
  type: "run:end",
21492
21684
  status,
21493
- totalUsd: ledger.usd,
21685
+ totalUsd: outcome.cost.totalUsd,
21494
21686
  ...outcome.cost.usageApprox === true ? { usageApprox: true } : {},
21495
21687
  ...lifted === void 0 ? {} : lifted
21496
21688
  }, rootSpanId);
@@ -22014,4 +22206,4 @@ function createSandboxBridge(ctx, options) {
22014
22206
  };
22015
22207
  }
22016
22208
  //#endregion
22017
- 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_CITATION_SAMPLE, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GitWorktreeProvider, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JOURNAL_ENVELOPE_MARKER, JournalCompatibilityError, JournalMatcher, JournalMissError, JournalOrderViolation, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, MAX_TIMER_DELAY_MS, 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, SettlementError, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, finishContract, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, preflightEstimate, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceAuditTrail, reduceCriticalPath, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, sectionCitationsValidator, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, stripFencedBlocks, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
22209
+ 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_CITATION_SAMPLE, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, 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, IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JOURNAL_ENVELOPE_MARKER, JournalCompatibilityError, JournalMatcher, JournalMissError, JournalOrderViolation, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, MAX_TIMER_DELAY_MS, 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, SettlementError, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, finishContract, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, preflightEstimate, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceAuditTrail, reduceCriticalPath, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, sectionCitationsValidator, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, stripFencedBlocks, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.114.0",
3
+ "version": "1.116.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",