@rulvar/core 1.113.0 → 1.115.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
@@ -3130,6 +3130,17 @@ declare const QUOTA_WINDOW_MS = 6e4;
3130
3130
  * from each of them. The counters are rule-scoped: one rule matching
3131
3131
  * two models pools them under one cap; write one rule per model for
3132
3132
  * per-model buckets.
3133
+ *
3134
+ * Window semantics, named as the deliberate compromise it is (RV708):
3135
+ * every PerMinute cap counts over FIXED epoch-aligned 60 s windows
3136
+ * ({@link QUOTA_WINDOW_MS}), not a sliding minute. Each fixed window
3137
+ * enforces its cap exactly, and a burst placed astride a boundary can
3138
+ * therefore consume up to TWO caps inside one sliding 60 s; that
3139
+ * bounded burst is the price of cross-process parity (every reference
3140
+ * limiter in every process computes the same window from the same
3141
+ * clock with no shared sliding state), and provider-side minute
3142
+ * windows are themselves fuzzy. Size caps with the boundary burst in
3143
+ * mind; the semantics are pinned as intended, not scheduled to change.
3133
3144
  */
3134
3145
  interface QuotaRule {
3135
3146
  /** Adapter id, as in `concurrency.perProvider` keys. */
@@ -4609,6 +4620,20 @@ interface BudgetHooks {
4609
4620
  * grant against it.
4610
4621
  */
4611
4622
  remainingUsd?: () => number | undefined;
4623
+ /**
4624
+ * The in-flight exposure admission (RV711), wired only when the cap
4625
+ * is configured. Called synchronously right before each provider
4626
+ * dispatch attempt with the attempt's own request estimate: the
4627
+ * serving model, the estimated prompt tokens, and the planned
4628
+ * worst-case output tokens (the request's effective maxOutputTokens,
4629
+ * else the model's declared output cap). Throws BudgetExhaustedError
4630
+ * (data.reason 'in-flight-exposure') to refuse the dispatch typed,
4631
+ * on the same surface as the layer-2b output bound; returns the
4632
+ * release closure the loop calls once the attempt settles, so the
4633
+ * reservation lives exactly as long as the wire call it covers.
4634
+ * Undefined result = nothing reserved (the cap resolved inert).
4635
+ */
4636
+ admitTurnExposure?: (servedBy: ModelRef, estimatedInputTokens: number, plannedOutputTokens: number) => (() => void) | undefined;
4612
4637
  /** Live usage accounting; layer 3 may respond by aborting `signal`. */
4613
4638
  onUsage(usage: Usage, servedBy: ModelRef): void;
4614
4639
  /** Layer 3: the ceiling AbortSignal. */
@@ -4761,6 +4786,18 @@ interface RunAgentOptions<S extends SchemaSpec = JsonSchema> {
4761
4786
  fallbacks?: PhaseTarget[];
4762
4787
  };
4763
4788
  /**
4789
+ * Opt-in policy-facts digest (RV709): when true AND a finalize
4790
+ * invocation fires, one additional REQUEST-ONLY user message
4791
+ * precedes the synthesis instruction, carrying the deterministic
4792
+ * runtime facts the loop observed (quota denials and recoveries,
4793
+ * tool budget pressure, the finalization window, recorded spend with
4794
+ * its cost basis), so the final model can cite the run's own live
4795
+ * evidence instead of underclaiming it. Never touches the durable
4796
+ * transcript, never enters spawn identity; unset keeps the finalize
4797
+ * request byte identical.
4798
+ */
4799
+ policyFacts?: boolean;
4800
+ /**
4764
4801
  * Summarize invocation target for compaction (M4-T03): resolved
4765
4802
  * through the chain with role 'summarize', falling back to the loop
4766
4803
  * model when routing resolves nothing. Compaction
@@ -5328,6 +5365,14 @@ type Spend = {
5328
5365
  };
5329
5366
  /** Last resort of the admission reserve formula. */
5330
5367
  declare const DEFAULT_FLAT_RESERVE_USD = .5;
5368
+ /**
5369
+ * The message prefix of an in-flight exposure refusal (RV711): the
5370
+ * single producer is reserveTurnExposure below, and the ctx layer's
5371
+ * uniform budget rethrow keys on it to carry the refusal through with
5372
+ * its own honest arithmetic instead of claiming a ceiling crossed
5373
+ * (no account closes on a transient refusal).
5374
+ */
5375
+ declare const IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX = "in flight exposure cap reached";
5331
5376
  /** The run-root account scope. */
5332
5377
  declare const ROOT_ACCOUNT = "run";
5333
5378
  /**
@@ -5387,6 +5432,11 @@ interface BudgetExhaustionDiagnostics {
5387
5432
  declare class RunBudget {
5388
5433
  /** B0; immutable after start. Undefined means no USD ceiling. */
5389
5434
  readonly ceilingUsd?: number;
5435
+ /**
5436
+ * The opt-in in-flight exposure cap (RV711). Undefined means the
5437
+ * reservation surface is inert and reserveTurnExposure never binds.
5438
+ */
5439
+ readonly maxInFlightExposureUsd?: number;
5390
5440
  private readonly lifetimeSpawnCap;
5391
5441
  private readonly events?;
5392
5442
  private readonly priceUsd?;
@@ -5395,12 +5445,15 @@ declare class RunBudget {
5395
5445
  private usageInternal;
5396
5446
  private agentsSpawnedInternal;
5397
5447
  private exhaustedInternal;
5448
+ /** Live dispatch estimates held by reserveTurnExposure (RV711). */
5449
+ private inFlightExposureUsd;
5398
5450
  /** Models already warned about; the warning fires once per model per run. */
5399
5451
  private readonly unpricedWarned;
5400
5452
  /** Models whose price function already returned an invalid USD once. */
5401
5453
  private readonly invalidPriceWarned;
5402
5454
  constructor(options: {
5403
- ceilingUsd?: number;
5455
+ ceilingUsd?: number; /** The opt-in in-flight exposure cap (RV711); see reserveTurnExposure. */
5456
+ maxInFlightExposureUsd?: number;
5404
5457
  lifetimeSpawnCap?: number;
5405
5458
  events?: RuntimeEventSink;
5406
5459
  priceUsd?: (servedBy: ModelRef, usage: Usage) => number | undefined; /** Raw price-row resolution for the layer-2b output bound. */
@@ -5529,6 +5582,32 @@ declare class RunBudget {
5529
5582
  releaseSynthesisReserve(scope: string): void;
5530
5583
  /** The reserve is replaced by real spend when the spawn settles. */
5531
5584
  releaseReserve(reserveUsd: number, accountScope?: string): void;
5585
+ /**
5586
+ * The in-flight exposure reservation (RV711). The per-turn guard
5587
+ * below checks money already SPENT, so N concurrent turns each pass
5588
+ * it before any settles and together can cross the ceiling by up to
5589
+ * one whole turn each; this is the opt-in bound on that hole. The
5590
+ * caller reserves the attempt's own worst-case estimate (the prompt
5591
+ * estimate plus the planned output allowance, priced by the SAME
5592
+ * price rows as the layer-2b clamp) right before the wire call and
5593
+ * releases at the attempt's settle, so the reservation lives exactly
5594
+ * as long as the exposure it covers. The admission refuses, typed
5595
+ * and without waiting, when spent + the named reserves (finalize and
5596
+ * synthesis money is promised elsewhere) + live reservations + this
5597
+ * estimate does not fit the cap; an exact fill admits, mirroring
5598
+ * admitSpawn, and a full cap refuses even a zero estimate. A refusal
5599
+ * is TRANSIENT (in-flight money returns at settle), so it never
5600
+ * marks the run exhausted and never severs a stream. A model without
5601
+ * a price row reserves zero, exactly as it debits zero (the
5602
+ * once-per-model unpriced warning covers that hole). While an
5603
+ * attempt streams, its usage debits spentUsd with the reservation
5604
+ * still live, briefly counting the same money twice: conservative in
5605
+ * the safe direction, gone at release. Returns undefined (fully
5606
+ * inert) when the cap is not configured; layer-1 spawn reserves
5607
+ * (committedReserveUsd) stay out of the formula, because a child's
5608
+ * lifetime reserve and its own turn exposure would double-count.
5609
+ */
5610
+ reserveTurnExposure(servedBy: ModelRef, estimatedInputTokens: number, plannedOutputTokens: number): (() => void) | undefined;
5532
5611
  /** Layer 2: the per-turn guard. A turn that would cross any ceiling in the chain is not dispatched. */
5533
5612
  beforeTurn(accountScope?: string): void;
5534
5613
  /**
@@ -6510,6 +6589,28 @@ interface RunOptions {
6510
6589
  * concurrent agent. Contract: https://docs.rulvar.com/guide/budgets.
6511
6590
  */
6512
6591
  budgetUsd?: number;
6592
+ /**
6593
+ * The opt-in in-flight exposure cap (RV711): bounds spent money plus
6594
+ * the summed worst-case estimates of live dispatches. The per-turn
6595
+ * guard checks money already SPENT, so under `budgetUsd` alone N
6596
+ * concurrent turns each pass it before any settles and together can
6597
+ * cross the ceiling by up to one whole turn each (preflight's
6598
+ * 'overshoot-exposure' finding prices that hole). With the cap, the
6599
+ * admission holds each turn's own estimate (the prompt estimate plus
6600
+ * the request's output allowance, priced by the same rows as
6601
+ * settlement) from right before the provider call until the attempt
6602
+ * settles, and the dispatch whose estimate does not fit
6603
+ * spent + finalize/synthesis reserves + live estimates is refused
6604
+ * with a typed BudgetExhaustedError (data.reason
6605
+ * 'in-flight-exposure') instead of waiting; the refused agent
6606
+ * settles as a budget error. Worst concurrent overshoot past the cap
6607
+ * is thereby the estimate error of the in-flight turns, not one
6608
+ * whole turn per agent. Absent by default: wire traffic, journals,
6609
+ * and hooks stay byte-identical. Operational and per-invocation like
6610
+ * `limits`: not recorded in RunMeta, so a resumed segment runs
6611
+ * without it.
6612
+ */
6613
+ maxInFlightExposureUsd?: number;
6513
6614
  /** Run-level defaults merged over engine defaults. */
6514
6615
  limits?: UsageLimits;
6515
6616
  /**
@@ -7962,6 +8063,18 @@ interface OrchestrateSynthesis {
7962
8063
  /** Extra deterministic instruction lines appended to the synthesis prompt. */
7963
8064
  instructions?: string;
7964
8065
  /**
8066
+ * Opt-in policy-facts line in the 'single' synthesis prompt (RV709):
8067
+ * a deterministic digest of the settled children's durable
8068
+ * tool-budget facts (statuses, extension grants, finalization
8069
+ * windows and reserves), so the composing model can cite the run's
8070
+ * own observed evidence instead of underclaiming it. Folded ONLY
8071
+ * from replay-stable material (the settled results the journal
8072
+ * replays verbatim), so a resumed synthesis re-derives identical
8073
+ * prompt bytes; off by default, and the prompt stays byte identical
8074
+ * when unset (prompt bytes are journal identity).
8075
+ */
8076
+ policyFacts?: boolean;
8077
+ /**
7965
8078
  * Admission estimate for the synthesize invocation, like
7966
8079
  * AgentOpts.estCost: under a tight orchestrator cap the default
7967
8080
  * reserve (full maxOutputTokens pricing) can refuse the dispatch; an
@@ -9895,8 +10008,8 @@ interface PreflightOrchestratorSpec {
9895
10008
  interface PreflightInput {
9896
10009
  /** The same object createEngine would receive (adapters used for pure caps() only). */
9897
10010
  engine?: Partial<Pick<CreateEngineOptions, "adapters" | "defaults" | "budgetDefaults" | "concurrency" | "quota" | "pricing">>;
9898
- /** The RunOptions slice: the run ceiling and run-level limits. */
9899
- run?: Pick<RunOptions, "budgetUsd" | "limits">;
10011
+ /** The RunOptions slice: the ceiling, run-level limits, and the RV711 exposure cap. */
10012
+ run?: Pick<RunOptions, "budgetUsd" | "limits" | "maxInFlightExposureUsd">;
9900
10013
  /** Present when the run is a dynamic orchestration. */
9901
10014
  orchestrator?: PreflightOrchestratorSpec;
9902
10015
  /** The declared first spawn wave, in admission order. */
@@ -10565,6 +10678,52 @@ interface CriticalPath {
10565
10678
  synthesisShare?: number;
10566
10679
  /** Settled non-coordination agent spans that anchored the fan-in. */
10567
10680
  workerSpans: number;
10681
+ /** The RV710 decomposition of the window; present with postFanInMs. */
10682
+ postFanIn?: PostFanInBreakdown;
10683
+ }
10684
+ /**
10685
+ * Where the post-fan-in interval actually went (RV710): the eleventh
10686
+ * comparison experiment measured 45.5 percent of wall sitting after
10687
+ * fan-in with zero synthesis share and nothing to name it. The
10688
+ * decomposition is a pure fold over the SAME vocabulary, no new event
10689
+ * types: model activations and tool executions of coordination spans
10690
+ * (spans whose agent:start role is 'orchestrate') are reconstructed
10691
+ * from their end events' (ts, durationMs) and clipped to the
10692
+ * [last worker settle, run:end] window, and completed 'synthesize'
10693
+ * spans are clipped the same way. The coordinator's draft and repair
10694
+ * thinking lands in the model bucket; child-result pagination and the
10695
+ * finish exchanges (host validators run inside the finish tool's
10696
+ * measured window) land in the tool buckets under their own names; the
10697
+ * residue is what no recorded interval covers: scheduling gaps,
10698
+ * journal writes, park-to-wake latency. Live fidelity only, exactly
10699
+ * like the wall numbers around it: a replayed stream re-stamps
10700
+ * emission times and carries durationMs 0, so its decomposition is
10701
+ * degenerate. Buckets are clipped SUMS (two concurrent coordination
10702
+ * spans, or duration-clock skew against emission stamps, can
10703
+ * overlap-count); coveredMs is the exact interval union, so residueMs
10704
+ * is never understated by an overlap. End events whose span never
10705
+ * started in the stream (a consumer attached mid-stream) cannot be
10706
+ * attributed and are skipped, never guessed at.
10707
+ */
10708
+ interface PostFanInBreakdown {
10709
+ /** Model activations of coordination spans inside the window. */
10710
+ coordinationModelMs: number;
10711
+ /** Tool executions of coordination spans inside the window, summed. */
10712
+ coordinationToolMs: number;
10713
+ /**
10714
+ * The same tool time keyed by tool name. A zero-duration execution
10715
+ * inside the window still registers its name: sub-millisecond tools
10716
+ * round to 0 on the wall clock but did run here.
10717
+ */
10718
+ coordinationToolMsByName: Record<string, number>;
10719
+ /** Completed 'synthesize' span wall clipped to the window. */
10720
+ synthesisMs: number;
10721
+ /** Union length of every covered interval above. */
10722
+ coveredMs: number;
10723
+ /** postFanInMs minus coveredMs, floored at zero. */
10724
+ residueMs: number;
10725
+ /** residueMs / postFanInMs when the window is longer than zero. */
10726
+ residueShare?: number;
10568
10727
  }
10569
10728
  declare function reduceCriticalPath(events: Iterable<WorkflowEvent>): CriticalPath;
10570
10729
  //#endregion
@@ -10640,4 +10799,4 @@ interface SandboxBridge {
10640
10799
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
10641
10800
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
10642
10801
  //#endregion
10643
- 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 };
10802
+ 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
@@ -11113,6 +11113,8 @@ async function runAgent(options) {
11113
11113
  let invocationCounter = 0;
11114
11114
  let transportRetries = 0;
11115
11115
  let schemaRecoveredTerminalExchanges = 0;
11116
+ let quotaDenials = 0;
11117
+ let quotaRecoveries = 0;
11116
11118
  const rateLimitObservations = /* @__PURE__ */ new Map();
11117
11119
  const roleUsageSnapshot = (role) => {
11118
11120
  const snapshot = /* @__PURE__ */ new Map();
@@ -12012,11 +12014,24 @@ async function runAgent(options) {
12012
12014
  }
12013
12015
  };
12014
12016
  const dispatchPhase = async (site) => {
12017
+ let deniedEpisode = false;
12015
12018
  for (;;) {
12016
12019
  const target = site.chain[site.cursor.index] ?? site.chain[0];
12017
12020
  let tries = 0;
12018
12021
  inner: for (;;) {
12019
12022
  let reservationId;
12023
+ let releaseExposure;
12024
+ const admitExposure = (req) => {
12025
+ const admit = options.budget?.admitTurnExposure;
12026
+ if (admit === void 0) return;
12027
+ let planned = req.maxOutputTokens;
12028
+ if (planned === void 0) try {
12029
+ planned = target.adapter.caps(target.resolved.model).maxOutputTokens;
12030
+ } catch {
12031
+ planned = 0;
12032
+ }
12033
+ releaseExposure = admit(target.resolved.ref, estimateInputTokens(req.messages), planned);
12034
+ };
12020
12035
  const quotaDeniedOutcome = (denial) => ({
12021
12036
  turn: {
12022
12037
  text: "",
@@ -12040,6 +12055,7 @@ async function runAgent(options) {
12040
12055
  });
12041
12056
  const dispatchWithQuota = async (quota) => {
12042
12057
  const req = site.requestFor(target);
12058
+ admitExposure(req);
12043
12059
  let decision;
12044
12060
  try {
12045
12061
  decision = await quota.reserve({
@@ -12070,9 +12086,19 @@ async function runAgent(options) {
12070
12086
  const dispatch = () => {
12071
12087
  const aborted = abortKind();
12072
12088
  if (aborted !== void 0) return Promise.resolve(abortedOutcome(aborted));
12073
- return options.quota === void 0 ? streamTurn(target.adapter, site.requestFor(target), site.streamOptionsFor(target)) : dispatchWithQuota(options.quota);
12089
+ if (options.quota === void 0) {
12090
+ const req = site.requestFor(target);
12091
+ admitExposure(req);
12092
+ return streamTurn(target.adapter, req, site.streamOptionsFor(target));
12093
+ }
12094
+ return dispatchWithQuota(options.quota);
12074
12095
  };
12075
- const outcome = await (options.providerSlot === void 0 ? dispatch() : options.providerSlot(target.adapter.id, dispatch, options.signal));
12096
+ let outcome;
12097
+ try {
12098
+ outcome = await (options.providerSlot === void 0 ? dispatch() : options.providerSlot(target.adapter.id, dispatch, options.signal));
12099
+ } finally {
12100
+ releaseExposure?.();
12101
+ }
12076
12102
  if (reservationId !== void 0 && options.quota !== void 0) try {
12077
12103
  await options.quota.reconcile(reservationId, outcome.usage);
12078
12104
  } catch (thrown) {
@@ -12083,6 +12109,13 @@ async function runAgent(options) {
12083
12109
  msg: `the shared quota limiter failed to reconcile a reservation: ${detail}`
12084
12110
  });
12085
12111
  }
12112
+ if (outcome.quotaDenied === true) {
12113
+ quotaDenials += 1;
12114
+ deniedEpisode = true;
12115
+ } else if (deniedEpisode && outcome.neverDispatched !== true) {
12116
+ quotaRecoveries += 1;
12117
+ deniedEpisode = false;
12118
+ }
12086
12119
  if (outcome.quotaDenied !== true && outcome.neverDispatched !== true) {
12087
12120
  const accounted = recordUsage(outcome.usage, outcome.reported, target.adapter.id, target.resolved.ref, site.role, outcome.usageViolation);
12088
12121
  const namespace = outcome.providerMetadata?.[target.adapter.id];
@@ -12685,13 +12718,37 @@ async function runAgent(options) {
12685
12718
  }
12686
12719
  if (proceed) {
12687
12720
  turns += 1;
12688
- const synthesisMessages = [...messages, {
12689
- role: "user",
12690
- parts: [{
12691
- type: "text",
12692
- text: FINALIZE_SYNTHESIS_INSTRUCTION
12693
- }]
12694
- }];
12721
+ const policyFactsLines = () => {
12722
+ const lines = ["POLICY FACTS (request-only runtime digest): deterministic facts this run observed; cite the ones your answer relies on."];
12723
+ if (options.quota !== void 0) lines.push(`quota: ${String(quotaDenials)} denial(s), ${String(quotaRecoveries)} recovered`);
12724
+ if (limits.maxToolCalls !== void 0 || limits.toolUnits !== void 0 || extension !== void 0) {
12725
+ const cap = effectiveMaxToolCalls();
12726
+ let budgetLine = `tool budget: ${String(toolCallsUsed)}${cap === void 0 ? "" : ` of ${String(cap)}`} calls used`;
12727
+ if (extension !== void 0) budgetLine += `; extensions granted: ${String(extensionGrants)}`;
12728
+ lines.push(budgetLine);
12729
+ }
12730
+ if (finalizationWindow !== void 0) lines.push(`finalization window: ${windowEntered ? "entered" : "not entered"}`);
12731
+ const spend = recordedSpend();
12732
+ lines.push(`recorded spend: $${spend.usd.toFixed(4)} (${spend.basis})` + (spend.basis === "aggregate-estimate" ? "; per-call records did not cover all usage, treat the number as an estimate" : ""));
12733
+ return lines;
12734
+ };
12735
+ const synthesisMessages = [
12736
+ ...messages,
12737
+ ...options.policyFacts === true ? [{
12738
+ role: "user",
12739
+ parts: [{
12740
+ type: "text",
12741
+ text: policyFactsLines().join("\n")
12742
+ }]
12743
+ }] : [],
12744
+ {
12745
+ role: "user",
12746
+ parts: [{
12747
+ type: "text",
12748
+ text: FINALIZE_SYNTHESIS_INSTRUCTION
12749
+ }]
12750
+ }
12751
+ ];
12695
12752
  let finalizeDispatch;
12696
12753
  try {
12697
12754
  finalizeDispatch = await dispatchPhase({
@@ -13004,6 +13061,14 @@ async function runAgent(options) {
13004
13061
  */
13005
13062
  /** Last resort of the admission reserve formula. */
13006
13063
  const DEFAULT_FLAT_RESERVE_USD = .5;
13064
+ /**
13065
+ * The message prefix of an in-flight exposure refusal (RV711): the
13066
+ * single producer is reserveTurnExposure below, and the ctx layer's
13067
+ * uniform budget rethrow keys on it to carry the refusal through with
13068
+ * its own honest arithmetic instead of claiming a ceiling crossed
13069
+ * (no account closes on a transient refusal).
13070
+ */
13071
+ const IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX = "in flight exposure cap reached";
13007
13072
  /** The run-root account scope. */
13008
13073
  const ROOT_ACCOUNT = "run";
13009
13074
  const ZERO_USAGE = {
@@ -13054,6 +13119,11 @@ function admissionReserveUsd(options) {
13054
13119
  var RunBudget = class {
13055
13120
  /** B0; immutable after start. Undefined means no USD ceiling. */
13056
13121
  ceilingUsd;
13122
+ /**
13123
+ * The opt-in in-flight exposure cap (RV711). Undefined means the
13124
+ * reservation surface is inert and reserveTurnExposure never binds.
13125
+ */
13126
+ maxInFlightExposureUsd;
13057
13127
  lifetimeSpawnCap;
13058
13128
  events;
13059
13129
  priceUsd;
@@ -13062,6 +13132,8 @@ var RunBudget = class {
13062
13132
  usageInternal = { ...ZERO_USAGE };
13063
13133
  agentsSpawnedInternal = 0;
13064
13134
  exhaustedInternal = false;
13135
+ /** Live dispatch estimates held by reserveTurnExposure (RV711). */
13136
+ inFlightExposureUsd = 0;
13065
13137
  /** Models already warned about; the warning fires once per model per run. */
13066
13138
  unpricedWarned = /* @__PURE__ */ new Set();
13067
13139
  /** Models whose price function already returned an invalid USD once. */
@@ -13071,6 +13143,10 @@ var RunBudget = class {
13071
13143
  requireValidCeiling(options.ceilingUsd, "budget ceiling");
13072
13144
  this.ceilingUsd = options.ceilingUsd;
13073
13145
  }
13146
+ if (options.maxInFlightExposureUsd !== void 0) {
13147
+ requireValidCeiling(options.maxInFlightExposureUsd, "maxInFlightExposureUsd");
13148
+ this.maxInFlightExposureUsd = options.maxInFlightExposureUsd;
13149
+ }
13074
13150
  this.lifetimeSpawnCap = options.lifetimeSpawnCap ?? 500;
13075
13151
  if (options.events !== void 0) this.events = options.events;
13076
13152
  if (options.priceUsd !== void 0) this.priceUsd = options.priceUsd;
@@ -13350,6 +13426,59 @@ var RunBudget = class {
13350
13426
  for (const account of this.chainOf(accountScope)) account.committedReserveUsd = Math.max(0, account.committedReserveUsd - reserveUsd);
13351
13427
  this.emitUpdate();
13352
13428
  }
13429
+ /**
13430
+ * The in-flight exposure reservation (RV711). The per-turn guard
13431
+ * below checks money already SPENT, so N concurrent turns each pass
13432
+ * it before any settles and together can cross the ceiling by up to
13433
+ * one whole turn each; this is the opt-in bound on that hole. The
13434
+ * caller reserves the attempt's own worst-case estimate (the prompt
13435
+ * estimate plus the planned output allowance, priced by the SAME
13436
+ * price rows as the layer-2b clamp) right before the wire call and
13437
+ * releases at the attempt's settle, so the reservation lives exactly
13438
+ * as long as the exposure it covers. The admission refuses, typed
13439
+ * and without waiting, when spent + the named reserves (finalize and
13440
+ * synthesis money is promised elsewhere) + live reservations + this
13441
+ * estimate does not fit the cap; an exact fill admits, mirroring
13442
+ * admitSpawn, and a full cap refuses even a zero estimate. A refusal
13443
+ * is TRANSIENT (in-flight money returns at settle), so it never
13444
+ * marks the run exhausted and never severs a stream. A model without
13445
+ * a price row reserves zero, exactly as it debits zero (the
13446
+ * once-per-model unpriced warning covers that hole). While an
13447
+ * attempt streams, its usage debits spentUsd with the reservation
13448
+ * still live, briefly counting the same money twice: conservative in
13449
+ * the safe direction, gone at release. Returns undefined (fully
13450
+ * inert) when the cap is not configured; layer-1 spawn reserves
13451
+ * (committedReserveUsd) stay out of the formula, because a child's
13452
+ * lifetime reserve and its own turn exposure would double-count.
13453
+ */
13454
+ reserveTurnExposure(servedBy, estimatedInputTokens, plannedOutputTokens) {
13455
+ const cap = this.maxInFlightExposureUsd;
13456
+ if (cap === void 0) return;
13457
+ const pricing = this.pricingOf?.(servedBy);
13458
+ const rawEstimate = pricing === void 0 ? 0 : priceUsdOf(pricing, {
13459
+ inputTokens: Math.max(0, estimatedInputTokens),
13460
+ outputTokens: Math.max(0, plannedOutputTokens),
13461
+ cacheReadTokens: 0,
13462
+ cacheWriteTokens: 0
13463
+ });
13464
+ const estimateUsd = Number.isFinite(rawEstimate) && rawEstimate > 0 ? rawEstimate : 0;
13465
+ const root = this.root;
13466
+ const committed = root.spentUsd + root.finalizeReserveUsd + root.synthesisReserveUsd + this.inFlightExposureUsd;
13467
+ 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: {
13468
+ reason: "in-flight-exposure",
13469
+ capUsd: cap,
13470
+ spentUsd: root.spentUsd,
13471
+ inFlightUsd: this.inFlightExposureUsd,
13472
+ estimateUsd
13473
+ } });
13474
+ this.inFlightExposureUsd += estimateUsd;
13475
+ let released = false;
13476
+ return () => {
13477
+ if (released) return;
13478
+ released = true;
13479
+ this.inFlightExposureUsd = Math.max(0, this.inFlightExposureUsd - estimateUsd);
13480
+ };
13481
+ }
13353
13482
  /** Layer 2: the per-turn guard. A turn that would cross any ceiling in the chain is not dispatched. */
13354
13483
  beforeTurn(accountScope = "run") {
13355
13484
  for (const account of this.chainOf(accountScope)) if (account.ceilingUsd !== void 0 && account.spentUsd >= account.ceilingUsd) {
@@ -15202,6 +15331,7 @@ function createCtx(internals, rootWorkflow) {
15202
15331
  beforeTurn: () => internals.budget.beforeTurn(budgetAccount),
15203
15332
  maxAffordableOutputTokens: (servedBy, estimatedInputTokens) => internals.budget.maxAffordableOutputTokens(servedBy, estimatedInputTokens, budgetAccount),
15204
15333
  remainingUsd: () => internals.budget.remainingUsd(budgetAccount),
15334
+ ...internals.budget.maxInFlightExposureUsd === void 0 ? {} : { admitTurnExposure: (servedBy, estimatedInputTokens, plannedOutputTokens) => internals.budget.reserveTurnExposure(servedBy, estimatedInputTokens, plannedOutputTokens) },
15205
15335
  onUsage: (usage, servedBy) => internals.budget.onUsage(usage, servedBy, budgetAccount),
15206
15336
  signal: budgetAccount === "run" ? internals.budget.signal : AbortSignal.any([internals.budget.signal, internals.budget.signalOf(budgetAccount)].filter((signal) => signal !== void 0))
15207
15337
  },
@@ -15546,6 +15676,12 @@ function createCtx(internals, rootWorkflow) {
15546
15676
  bump(internals.cost.byPhase, state.phase ?? "", usd);
15547
15677
  bump(internals.cost.byAgentType, agentType, usd);
15548
15678
  if (result.error?.kind === "budget" || internals.budget.exhausted && result.status !== "ok") {
15679
+ if (!internals.budget.exhausted && result.errorMessage !== void 0 && result.errorMessage.startsWith("in flight exposure cap reached")) throw new BudgetExhaustedError(result.errorMessage, { data: {
15680
+ scope: state.scope,
15681
+ entryRef: terminal.seq,
15682
+ source: "in-flight-exposure",
15683
+ reason: "in-flight-exposure"
15684
+ } });
15549
15685
  const diagnostics = internals.budget.exhaustionDiagnostics(state.budgetScope ?? "run");
15550
15686
  const crossed = diagnostics.crossed;
15551
15687
  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`);
@@ -17384,6 +17520,8 @@ function validateOrchestrateOptions(opts) {
17384
17520
  ].includes(synthesis.effort)) throw new ConfigError(`orchestrate synthesis.effort must be one of 'low' | 'medium' | 'high' | 'xhigh' | 'max'; got ${JSON.stringify(synthesis.effort)}`);
17385
17521
  if (synthesis.limits !== void 0) validateUsageLimits(synthesis.limits, "orchestrate synthesis.limits");
17386
17522
  if (synthesis.instructions !== void 0 && typeof synthesis.instructions !== "string") throw new ConfigError(`orchestrate synthesis.instructions must be a string; got ${typeof synthesis.instructions}`);
17523
+ const facts = synthesis;
17524
+ if (facts.policyFacts !== void 0 && typeof facts.policyFacts !== "boolean") throw new ConfigError(`orchestrate synthesis.policyFacts must be a boolean; got ${typeof facts.policyFacts}`);
17387
17525
  if (synthesis.estCost !== void 0) requireNonNegativeNumber(synthesis.estCost, "orchestrate synthesis.estCost");
17388
17526
  }
17389
17527
  const spec = opts.budget;
@@ -18922,6 +19060,26 @@ function makeOrchestratorWorkflow(goal, opts) {
18922
19060
  ...repeatedClaims === void 0 ? [] : ["Repeated claims across children were deduplicated before this prompt: only the first occurrence of each repeated line remains in the digest, and the REPEATED CLAIMS index below lists each one with its reporters."],
18923
19061
  ...spec.instructions === void 0 ? [] : [spec.instructions],
18924
19062
  ...finishValidationPromptLines(validationSpec),
19063
+ ...spec.policyFacts === true ? [(() => {
19064
+ const byStatus = {};
19065
+ let extensionsGranted = 0;
19066
+ let windowsEntered = 0;
19067
+ let reservesUsed = 0;
19068
+ for (const [, record] of settledEntries) {
19069
+ const settled = record.settled;
19070
+ byStatus[settled.status] = (byStatus[settled.status] ?? 0) + 1;
19071
+ extensionsGranted += settled.toolBudget?.extensionsGranted ?? 0;
19072
+ if (settled.toolBudget?.finalizationWindowEntered === true) windowsEntered += 1;
19073
+ if (settled.toolBudget?.finalizationReserveUsed === true) reservesUsed += 1;
19074
+ }
19075
+ return `POLICY FACTS: ${JSON.stringify({
19076
+ children: settledEntries.length,
19077
+ byStatus: Object.fromEntries(Object.keys(byStatus).sort().map((status) => [status, byStatus[status]])),
19078
+ extensionsGranted,
19079
+ finalizationWindowsEntered: windowsEntered,
19080
+ finalizationReservesUsed: reservesUsed
19081
+ })}`;
19082
+ })()] : [],
18925
19083
  `GOAL: ${goal}`,
18926
19084
  `DRAFT: ${draftJson}`,
18927
19085
  `DIGEST: ${digestJson}`,
@@ -19377,6 +19535,7 @@ function preflightEstimate(input) {
19377
19535
  const defaults = engine.defaults ?? {};
19378
19536
  if (defaults.limits !== void 0) validateUsageLimits(defaults.limits, "preflight.engine.defaults.limits");
19379
19537
  if (input.run?.limits !== void 0) validateUsageLimits(input.run.limits, "preflight.run.limits");
19538
+ if (input.run?.maxInFlightExposureUsd !== void 0) requireNonNegativeNumber(input.run.maxInFlightExposureUsd, "preflight.run.maxInFlightExposureUsd");
19380
19539
  if (input.orchestrator?.limits !== void 0) validateUsageLimits(input.orchestrator.limits, "preflight.orchestrator.limits");
19381
19540
  const findings = [];
19382
19541
  const say = (finding) => {
@@ -19944,6 +20103,12 @@ function preflightEstimate(input) {
19944
20103
  code: "overshoot-exposure",
19945
20104
  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`
19946
20105
  });
20106
+ const exposureCapUsd = input.run?.maxInFlightExposureUsd;
20107
+ if (exposureCapUsd !== void 0) say({
20108
+ severity: "info",
20109
+ code: "in-flight-exposure-cap",
20110
+ 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`
20111
+ });
19947
20112
  const quotaConfigured = engine.quota !== void 0;
19948
20113
  if (!quotaConfigured && maxInFlight > 1 && units.length > 0) say({
19949
20114
  severity: "info",
@@ -20550,6 +20715,21 @@ function reduceInvocationTable(events) {
20550
20715
  totalCostUsd
20551
20716
  };
20552
20717
  }
20718
+ /** Total length of the union of possibly overlapping intervals. */
20719
+ function unionLength(intervals) {
20720
+ const positive = intervals.filter((interval) => interval.to > interval.from);
20721
+ if (positive.length === 0) return 0;
20722
+ const sorted = [...positive].sort((a, b) => a.from - b.from);
20723
+ let total = 0;
20724
+ let from = sorted[0]?.from ?? 0;
20725
+ let to = sorted[0]?.to ?? 0;
20726
+ for (const interval of sorted.slice(1)) if (interval.from > to) {
20727
+ total += to - from;
20728
+ from = interval.from;
20729
+ to = interval.to;
20730
+ } else if (interval.to > to) to = interval.to;
20731
+ return total + (to - from);
20732
+ }
20553
20733
  function reduceCriticalPath(events) {
20554
20734
  let runStart;
20555
20735
  let runEnd;
@@ -20557,6 +20737,10 @@ function reduceCriticalPath(events) {
20557
20737
  let lastWorkerEnd;
20558
20738
  let workerSpans = 0;
20559
20739
  let synthesisMs = 0;
20740
+ const coordinationModel = [];
20741
+ const coordinationTools = [];
20742
+ const synthesisSpans = [];
20743
+ const spanOf = (durationMs) => Number.isFinite(durationMs) && durationMs > 0 ? durationMs : 0;
20560
20744
  for (const event of events) {
20561
20745
  const at = Date.parse(event.ts);
20562
20746
  if (!Number.isFinite(at)) continue;
@@ -20573,11 +20757,29 @@ function reduceCriticalPath(events) {
20573
20757
  at
20574
20758
  });
20575
20759
  break;
20760
+ case "agent:phase:end":
20761
+ if (startBySpan.get(event.spanId)?.role === "orchestrate") coordinationModel.push({
20762
+ from: at - spanOf(event.durationMs),
20763
+ to: at
20764
+ });
20765
+ break;
20766
+ case "tool:end":
20767
+ if (startBySpan.get(event.spanId)?.role === "orchestrate") coordinationTools.push({
20768
+ name: event.toolName,
20769
+ from: at - spanOf(event.durationMs),
20770
+ to: at
20771
+ });
20772
+ break;
20576
20773
  case "agent:end": {
20577
20774
  const started = startBySpan.get(event.spanId);
20578
20775
  if (started === void 0) break;
20579
- if (started.role === "synthesize") synthesisMs += Math.max(0, at - started.at);
20580
- else if (started.role !== "orchestrate") {
20776
+ if (started.role === "synthesize") {
20777
+ synthesisMs += Math.max(0, at - started.at);
20778
+ synthesisSpans.push({
20779
+ from: started.at,
20780
+ to: at
20781
+ });
20782
+ } else if (started.role !== "orchestrate") {
20581
20783
  workerSpans += 1;
20582
20784
  lastWorkerEnd = lastWorkerEnd === void 0 ? at : Math.max(lastWorkerEnd, at);
20583
20785
  }
@@ -20591,7 +20793,44 @@ function reduceCriticalPath(events) {
20591
20793
  workerSpans
20592
20794
  };
20593
20795
  if (runStart !== void 0 && runEnd !== void 0) path.runWallMs = Math.max(0, runEnd - runStart);
20594
- if (runEnd !== void 0 && lastWorkerEnd !== void 0) path.postFanInMs = Math.max(0, runEnd - lastWorkerEnd);
20796
+ if (runEnd !== void 0 && lastWorkerEnd !== void 0) {
20797
+ path.postFanInMs = Math.max(0, runEnd - lastWorkerEnd);
20798
+ const windowFrom = Math.min(lastWorkerEnd, runEnd);
20799
+ const windowTo = runEnd;
20800
+ const clip = (interval) => {
20801
+ if (interval.to < windowFrom || interval.from > windowTo) return;
20802
+ return {
20803
+ from: Math.max(interval.from, windowFrom),
20804
+ to: Math.min(interval.to, windowTo)
20805
+ };
20806
+ };
20807
+ const modelClipped = coordinationModel.map(clip).filter((interval) => interval !== void 0);
20808
+ const synthesisClipped = synthesisSpans.map(clip).filter((interval) => interval !== void 0);
20809
+ const byName = {};
20810
+ const toolsClipped = [];
20811
+ for (const interval of coordinationTools) {
20812
+ const clipped = clip(interval);
20813
+ if (clipped === void 0) continue;
20814
+ byName[interval.name] = (byName[interval.name] ?? 0) + (clipped.to - clipped.from);
20815
+ toolsClipped.push(clipped);
20816
+ }
20817
+ const lengthOf = (intervals) => intervals.reduce((sum, interval) => sum + (interval.to - interval.from), 0);
20818
+ const coveredMs = unionLength([
20819
+ ...modelClipped,
20820
+ ...toolsClipped,
20821
+ ...synthesisClipped
20822
+ ]);
20823
+ const breakdown = {
20824
+ coordinationModelMs: lengthOf(modelClipped),
20825
+ coordinationToolMs: lengthOf(toolsClipped),
20826
+ coordinationToolMsByName: byName,
20827
+ synthesisMs: lengthOf(synthesisClipped),
20828
+ coveredMs,
20829
+ residueMs: Math.max(0, path.postFanInMs - coveredMs)
20830
+ };
20831
+ if (path.postFanInMs > 0) breakdown.residueShare = breakdown.residueMs / path.postFanInMs;
20832
+ path.postFanIn = breakdown;
20833
+ }
20595
20834
  if (path.runWallMs !== void 0 && path.runWallMs > 0) {
20596
20835
  if (path.postFanInMs !== void 0) path.postFanInShare = path.postFanInMs / path.runWallMs;
20597
20836
  path.synthesisShare = synthesisMs / path.runWallMs;
@@ -21047,6 +21286,7 @@ function createEngine(options) {
21047
21286
  function run(wf, args, opts, resumeCtx) {
21048
21287
  if (wf.kind !== "workflow" && wf.kind !== "compiled-workflow") throw new ConfigError("engine.run accepts in-process Workflow values or compileScript CompiledWorkflow values");
21049
21288
  if (opts?.budgetUsd !== void 0) requireNonNegativeNumber(opts.budgetUsd, "RunOptions.budgetUsd");
21289
+ if (opts?.maxInFlightExposureUsd !== void 0) requireNonNegativeNumber(opts.maxInFlightExposureUsd, "RunOptions.maxInFlightExposureUsd");
21050
21290
  if (opts?.limits !== void 0) validateUsageLimits(opts.limits, "RunOptions.limits");
21051
21291
  const deadlineAtMs = opts?.deadlineAt === void 0 ? void 0 : parseDeadlineAt(opts.deadlineAt);
21052
21292
  const compiled = wf.kind === "compiled-workflow" ? wf : void 0;
@@ -21074,6 +21314,7 @@ function createEngine(options) {
21074
21314
  const ceilingUsd = opts?.budgetUsd ?? resumeCtx?.budgetUsd;
21075
21315
  const makeBudget = () => new RunBudget({
21076
21316
  ...ceilingUsd === void 0 ? {} : { ceilingUsd },
21317
+ ...opts?.maxInFlightExposureUsd === void 0 ? {} : { maxInFlightExposureUsd: opts.maxInFlightExposureUsd },
21077
21318
  lifetimeSpawnCap: options.budgetDefaults?.lifetimeSpawnCap ?? 500,
21078
21319
  events: { emit: (body) => bus.emit(body, rootSpanId) },
21079
21320
  priceUsd,
@@ -21958,4 +22199,4 @@ function createSandboxBridge(ctx, options) {
21958
22199
  };
21959
22200
  }
21960
22201
  //#endregion
21961
- 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 };
22202
+ 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.113.0",
3
+ "version": "1.115.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",