@rulvar/core 1.114.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
@@ -4620,6 +4620,20 @@ interface BudgetHooks {
4620
4620
  * grant against it.
4621
4621
  */
4622
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;
4623
4637
  /** Live usage accounting; layer 3 may respond by aborting `signal`. */
4624
4638
  onUsage(usage: Usage, servedBy: ModelRef): void;
4625
4639
  /** Layer 3: the ceiling AbortSignal. */
@@ -5351,6 +5365,14 @@ type Spend = {
5351
5365
  };
5352
5366
  /** Last resort of the admission reserve formula. */
5353
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";
5354
5376
  /** The run-root account scope. */
5355
5377
  declare const ROOT_ACCOUNT = "run";
5356
5378
  /**
@@ -5410,6 +5432,11 @@ interface BudgetExhaustionDiagnostics {
5410
5432
  declare class RunBudget {
5411
5433
  /** B0; immutable after start. Undefined means no USD ceiling. */
5412
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;
5413
5440
  private readonly lifetimeSpawnCap;
5414
5441
  private readonly events?;
5415
5442
  private readonly priceUsd?;
@@ -5418,12 +5445,15 @@ declare class RunBudget {
5418
5445
  private usageInternal;
5419
5446
  private agentsSpawnedInternal;
5420
5447
  private exhaustedInternal;
5448
+ /** Live dispatch estimates held by reserveTurnExposure (RV711). */
5449
+ private inFlightExposureUsd;
5421
5450
  /** Models already warned about; the warning fires once per model per run. */
5422
5451
  private readonly unpricedWarned;
5423
5452
  /** Models whose price function already returned an invalid USD once. */
5424
5453
  private readonly invalidPriceWarned;
5425
5454
  constructor(options: {
5426
- ceilingUsd?: number;
5455
+ ceilingUsd?: number; /** The opt-in in-flight exposure cap (RV711); see reserveTurnExposure. */
5456
+ maxInFlightExposureUsd?: number;
5427
5457
  lifetimeSpawnCap?: number;
5428
5458
  events?: RuntimeEventSink;
5429
5459
  priceUsd?: (servedBy: ModelRef, usage: Usage) => number | undefined; /** Raw price-row resolution for the layer-2b output bound. */
@@ -5552,6 +5582,32 @@ declare class RunBudget {
5552
5582
  releaseSynthesisReserve(scope: string): void;
5553
5583
  /** The reserve is replaced by real spend when the spawn settles. */
5554
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;
5555
5611
  /** Layer 2: the per-turn guard. A turn that would cross any ceiling in the chain is not dispatched. */
5556
5612
  beforeTurn(accountScope?: string): void;
5557
5613
  /**
@@ -6533,6 +6589,28 @@ interface RunOptions {
6533
6589
  * concurrent agent. Contract: https://docs.rulvar.com/guide/budgets.
6534
6590
  */
6535
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;
6536
6614
  /** Run-level defaults merged over engine defaults. */
6537
6615
  limits?: UsageLimits;
6538
6616
  /**
@@ -9930,8 +10008,8 @@ interface PreflightOrchestratorSpec {
9930
10008
  interface PreflightInput {
9931
10009
  /** The same object createEngine would receive (adapters used for pure caps() only). */
9932
10010
  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">;
10011
+ /** The RunOptions slice: the ceiling, run-level limits, and the RV711 exposure cap. */
10012
+ run?: Pick<RunOptions, "budgetUsd" | "limits" | "maxInFlightExposureUsd">;
9935
10013
  /** Present when the run is a dynamic orchestration. */
9936
10014
  orchestrator?: PreflightOrchestratorSpec;
9937
10015
  /** The declared first spawn wave, in admission order. */
@@ -10600,6 +10678,52 @@ interface CriticalPath {
10600
10678
  synthesisShare?: number;
10601
10679
  /** Settled non-coordination agent spans that anchored the fan-in. */
10602
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;
10603
10727
  }
10604
10728
  declare function reduceCriticalPath(events: Iterable<WorkflowEvent>): CriticalPath;
10605
10729
  //#endregion
@@ -10675,4 +10799,4 @@ interface SandboxBridge {
10675
10799
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
10676
10800
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
10677
10801
  //#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 };
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
@@ -12020,6 +12020,18 @@ async function runAgent(options) {
12020
12020
  let tries = 0;
12021
12021
  inner: for (;;) {
12022
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
+ };
12023
12035
  const quotaDeniedOutcome = (denial) => ({
12024
12036
  turn: {
12025
12037
  text: "",
@@ -12043,6 +12055,7 @@ async function runAgent(options) {
12043
12055
  });
12044
12056
  const dispatchWithQuota = async (quota) => {
12045
12057
  const req = site.requestFor(target);
12058
+ admitExposure(req);
12046
12059
  let decision;
12047
12060
  try {
12048
12061
  decision = await quota.reserve({
@@ -12073,9 +12086,19 @@ async function runAgent(options) {
12073
12086
  const dispatch = () => {
12074
12087
  const aborted = abortKind();
12075
12088
  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);
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);
12077
12095
  };
12078
- 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
+ }
12079
12102
  if (reservationId !== void 0 && options.quota !== void 0) try {
12080
12103
  await options.quota.reconcile(reservationId, outcome.usage);
12081
12104
  } catch (thrown) {
@@ -13038,6 +13061,14 @@ async function runAgent(options) {
13038
13061
  */
13039
13062
  /** Last resort of the admission reserve formula. */
13040
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";
13041
13072
  /** The run-root account scope. */
13042
13073
  const ROOT_ACCOUNT = "run";
13043
13074
  const ZERO_USAGE = {
@@ -13088,6 +13119,11 @@ function admissionReserveUsd(options) {
13088
13119
  var RunBudget = class {
13089
13120
  /** B0; immutable after start. Undefined means no USD ceiling. */
13090
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;
13091
13127
  lifetimeSpawnCap;
13092
13128
  events;
13093
13129
  priceUsd;
@@ -13096,6 +13132,8 @@ var RunBudget = class {
13096
13132
  usageInternal = { ...ZERO_USAGE };
13097
13133
  agentsSpawnedInternal = 0;
13098
13134
  exhaustedInternal = false;
13135
+ /** Live dispatch estimates held by reserveTurnExposure (RV711). */
13136
+ inFlightExposureUsd = 0;
13099
13137
  /** Models already warned about; the warning fires once per model per run. */
13100
13138
  unpricedWarned = /* @__PURE__ */ new Set();
13101
13139
  /** Models whose price function already returned an invalid USD once. */
@@ -13105,6 +13143,10 @@ var RunBudget = class {
13105
13143
  requireValidCeiling(options.ceilingUsd, "budget ceiling");
13106
13144
  this.ceilingUsd = options.ceilingUsd;
13107
13145
  }
13146
+ if (options.maxInFlightExposureUsd !== void 0) {
13147
+ requireValidCeiling(options.maxInFlightExposureUsd, "maxInFlightExposureUsd");
13148
+ this.maxInFlightExposureUsd = options.maxInFlightExposureUsd;
13149
+ }
13108
13150
  this.lifetimeSpawnCap = options.lifetimeSpawnCap ?? 500;
13109
13151
  if (options.events !== void 0) this.events = options.events;
13110
13152
  if (options.priceUsd !== void 0) this.priceUsd = options.priceUsd;
@@ -13384,6 +13426,59 @@ var RunBudget = class {
13384
13426
  for (const account of this.chainOf(accountScope)) account.committedReserveUsd = Math.max(0, account.committedReserveUsd - reserveUsd);
13385
13427
  this.emitUpdate();
13386
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
+ }
13387
13482
  /** Layer 2: the per-turn guard. A turn that would cross any ceiling in the chain is not dispatched. */
13388
13483
  beforeTurn(accountScope = "run") {
13389
13484
  for (const account of this.chainOf(accountScope)) if (account.ceilingUsd !== void 0 && account.spentUsd >= account.ceilingUsd) {
@@ -15236,6 +15331,7 @@ function createCtx(internals, rootWorkflow) {
15236
15331
  beforeTurn: () => internals.budget.beforeTurn(budgetAccount),
15237
15332
  maxAffordableOutputTokens: (servedBy, estimatedInputTokens) => internals.budget.maxAffordableOutputTokens(servedBy, estimatedInputTokens, budgetAccount),
15238
15333
  remainingUsd: () => internals.budget.remainingUsd(budgetAccount),
15334
+ ...internals.budget.maxInFlightExposureUsd === void 0 ? {} : { admitTurnExposure: (servedBy, estimatedInputTokens, plannedOutputTokens) => internals.budget.reserveTurnExposure(servedBy, estimatedInputTokens, plannedOutputTokens) },
15239
15335
  onUsage: (usage, servedBy) => internals.budget.onUsage(usage, servedBy, budgetAccount),
15240
15336
  signal: budgetAccount === "run" ? internals.budget.signal : AbortSignal.any([internals.budget.signal, internals.budget.signalOf(budgetAccount)].filter((signal) => signal !== void 0))
15241
15337
  },
@@ -15580,6 +15676,12 @@ function createCtx(internals, rootWorkflow) {
15580
15676
  bump(internals.cost.byPhase, state.phase ?? "", usd);
15581
15677
  bump(internals.cost.byAgentType, agentType, usd);
15582
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
+ } });
15583
15685
  const diagnostics = internals.budget.exhaustionDiagnostics(state.budgetScope ?? "run");
15584
15686
  const crossed = diagnostics.crossed;
15585
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`);
@@ -19433,6 +19535,7 @@ function preflightEstimate(input) {
19433
19535
  const defaults = engine.defaults ?? {};
19434
19536
  if (defaults.limits !== void 0) validateUsageLimits(defaults.limits, "preflight.engine.defaults.limits");
19435
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");
19436
19539
  if (input.orchestrator?.limits !== void 0) validateUsageLimits(input.orchestrator.limits, "preflight.orchestrator.limits");
19437
19540
  const findings = [];
19438
19541
  const say = (finding) => {
@@ -20000,6 +20103,12 @@ function preflightEstimate(input) {
20000
20103
  code: "overshoot-exposure",
20001
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`
20002
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
+ });
20003
20112
  const quotaConfigured = engine.quota !== void 0;
20004
20113
  if (!quotaConfigured && maxInFlight > 1 && units.length > 0) say({
20005
20114
  severity: "info",
@@ -20606,6 +20715,21 @@ function reduceInvocationTable(events) {
20606
20715
  totalCostUsd
20607
20716
  };
20608
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
+ }
20609
20733
  function reduceCriticalPath(events) {
20610
20734
  let runStart;
20611
20735
  let runEnd;
@@ -20613,6 +20737,10 @@ function reduceCriticalPath(events) {
20613
20737
  let lastWorkerEnd;
20614
20738
  let workerSpans = 0;
20615
20739
  let synthesisMs = 0;
20740
+ const coordinationModel = [];
20741
+ const coordinationTools = [];
20742
+ const synthesisSpans = [];
20743
+ const spanOf = (durationMs) => Number.isFinite(durationMs) && durationMs > 0 ? durationMs : 0;
20616
20744
  for (const event of events) {
20617
20745
  const at = Date.parse(event.ts);
20618
20746
  if (!Number.isFinite(at)) continue;
@@ -20629,11 +20757,29 @@ function reduceCriticalPath(events) {
20629
20757
  at
20630
20758
  });
20631
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;
20632
20773
  case "agent:end": {
20633
20774
  const started = startBySpan.get(event.spanId);
20634
20775
  if (started === void 0) break;
20635
- if (started.role === "synthesize") synthesisMs += Math.max(0, at - started.at);
20636
- 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") {
20637
20783
  workerSpans += 1;
20638
20784
  lastWorkerEnd = lastWorkerEnd === void 0 ? at : Math.max(lastWorkerEnd, at);
20639
20785
  }
@@ -20647,7 +20793,44 @@ function reduceCriticalPath(events) {
20647
20793
  workerSpans
20648
20794
  };
20649
20795
  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);
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
+ }
20651
20834
  if (path.runWallMs !== void 0 && path.runWallMs > 0) {
20652
20835
  if (path.postFanInMs !== void 0) path.postFanInShare = path.postFanInMs / path.runWallMs;
20653
20836
  path.synthesisShare = synthesisMs / path.runWallMs;
@@ -21103,6 +21286,7 @@ function createEngine(options) {
21103
21286
  function run(wf, args, opts, resumeCtx) {
21104
21287
  if (wf.kind !== "workflow" && wf.kind !== "compiled-workflow") throw new ConfigError("engine.run accepts in-process Workflow values or compileScript CompiledWorkflow values");
21105
21288
  if (opts?.budgetUsd !== void 0) requireNonNegativeNumber(opts.budgetUsd, "RunOptions.budgetUsd");
21289
+ if (opts?.maxInFlightExposureUsd !== void 0) requireNonNegativeNumber(opts.maxInFlightExposureUsd, "RunOptions.maxInFlightExposureUsd");
21106
21290
  if (opts?.limits !== void 0) validateUsageLimits(opts.limits, "RunOptions.limits");
21107
21291
  const deadlineAtMs = opts?.deadlineAt === void 0 ? void 0 : parseDeadlineAt(opts.deadlineAt);
21108
21292
  const compiled = wf.kind === "compiled-workflow" ? wf : void 0;
@@ -21130,6 +21314,7 @@ function createEngine(options) {
21130
21314
  const ceilingUsd = opts?.budgetUsd ?? resumeCtx?.budgetUsd;
21131
21315
  const makeBudget = () => new RunBudget({
21132
21316
  ...ceilingUsd === void 0 ? {} : { ceilingUsd },
21317
+ ...opts?.maxInFlightExposureUsd === void 0 ? {} : { maxInFlightExposureUsd: opts.maxInFlightExposureUsd },
21133
21318
  lifetimeSpawnCap: options.budgetDefaults?.lifetimeSpawnCap ?? 500,
21134
21319
  events: { emit: (body) => bus.emit(body, rootSpanId) },
21135
21320
  priceUsd,
@@ -22014,4 +22199,4 @@ function createSandboxBridge(ctx, options) {
22014
22199
  };
22015
22200
  }
22016
22201
  //#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 };
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.114.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",