@rulvar/core 1.179.0 → 1.181.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
@@ -11957,6 +11957,214 @@ declare function invoiceFromJournal(entries: readonly JournalEntry[], priceUsd:
11957
11957
  pricing?: InvoicePricingProvenance;
11958
11958
  }): InvoiceExport;
11959
11959
  //#endregion
11960
+ //#region src/engine/reconcile-statement.d.ts
11961
+ /** The four billing components a provider statement itemizes. */
11962
+ type BillingComponent = "input" | "cached-input" | "cache-write" | "output";
11963
+ /**
11964
+ * One normalized per-request row of a usage/billing export. `usd` is
11965
+ * the row's billed dollars where the export carries amounts;
11966
+ * `componentsUsd` its per-component split where it carries one; `usage`
11967
+ * the provider-reported token counts where it carries those. A row must
11968
+ * carry at least one of the three, and every row needs the provider's
11969
+ * response id, the join key.
11970
+ */
11971
+ interface StatementRequestRow {
11972
+ responseId: string;
11973
+ /** Provider-side model name (without the adapter prefix); optional. */
11974
+ model?: string;
11975
+ usd?: number;
11976
+ componentsUsd?: Partial<Record<BillingComponent, number>>;
11977
+ usage?: {
11978
+ inputTokens?: number;
11979
+ cachedInputTokens?: number;
11980
+ cacheWriteTokens?: number;
11981
+ outputTokens?: number;
11982
+ };
11983
+ }
11984
+ /** One per-model per-component total: the Spend categories shape. */
11985
+ interface StatementCategoryRow {
11986
+ model: string;
11987
+ component: BillingComponent;
11988
+ usd: number;
11989
+ }
11990
+ /** A normalized provider export: never a headline total. */
11991
+ type ProviderStatement = {
11992
+ kind: "requests";
11993
+ rows: readonly StatementRequestRow[];
11994
+ } | {
11995
+ kind: "categories";
11996
+ rows: readonly StatementCategoryRow[];
11997
+ };
11998
+ interface ReconcileStatementOptions {
11999
+ /** Our rate card, the same resolution the engine prices with. */
12000
+ pricingOf: (servedBy: ModelRef) => Pricing | undefined;
12001
+ /**
12002
+ * Per-component divergence threshold in USD. The default 0.005
12003
+ * absorbs the dashboard's 3-decimal rounding (at most 0.0005 per
12004
+ * figure) with an order of margin, while any real rate-card
12005
+ * divergence on a run worth reconciling sits orders above it.
12006
+ */
12007
+ componentToleranceUsd?: number;
12008
+ /**
12009
+ * Totals threshold for a per-request export that carries row dollars
12010
+ * but no per-component split; default 0.01.
12011
+ */
12012
+ totalToleranceUsd?: number;
12013
+ /** Provider-side model name of a served ref; default strips the adapter prefix. */
12014
+ modelOf?: (servedBy: ModelRef) => string;
12015
+ /**
12016
+ * How provider-reported token counts weigh on the verdict (RV903).
12017
+ * 'verdict' (default): any token disagreement between the export and
12018
+ * our recorded usage is a divergence, because our counts ARE the
12019
+ * provider's own wire-reported numbers, so an export that disagrees
12020
+ * with them describes a different request than the wire served, and
12021
+ * dollars derived from either cannot be trusted to mean the same
12022
+ * thing. 'informational' preserves the pre-v1.126 dollar-only
12023
+ * verdict for exports whose token semantics legitimately differ from
12024
+ * the wire's (a different cache accounting, rounded aggregates):
12025
+ * mismatches are still counted and sampled, but only dollar deltas
12026
+ * decide.
12027
+ */
12028
+ tokenComparison?: "verdict" | "informational";
12029
+ }
12030
+ /** One (model, component) line of the reconciliation. */
12031
+ interface ComponentDelta {
12032
+ model: string;
12033
+ component: BillingComponent;
12034
+ /** Our token base for the component, from the invoice rows' usage. */
12035
+ ourTokens: number;
12036
+ /** Our dollars, from the shared price decomposition (priceComponentsOf). */
12037
+ ourUsd: number;
12038
+ /** The statement's dollars; absent when the export does not carry this line. */
12039
+ statementUsd?: number;
12040
+ deltaUsd?: number;
12041
+ /** statementUsd over ourTokens, per MTok: the rate the provider ACTUALLY applied. */
12042
+ impliedUsdPerMTok?: number;
12043
+ /** ourUsd over ourTokens, per MTok: our effective rate over the same base, tier mix included. */
12044
+ effectiveUsdPerMTok?: number;
12045
+ divergent: boolean;
12046
+ }
12047
+ interface StatementCoverage {
12048
+ /** Invoice rows carrying usage or dollars: the billable set. */
12049
+ billableRows: number;
12050
+ rowsWithResponseId: number;
12051
+ /** Requests mode: rows the export covered. Categories mode: equals billableRows (totals claim the set). */
12052
+ matchedRows: number;
12053
+ unmatchedRows: number;
12054
+ /** First unmatched response ids (at most 20), requests mode. */
12055
+ unmatchedIdSample: string[];
12056
+ /** Statement rows matching nothing of ours: ids (requests) or model names (categories). */
12057
+ statementOnlyRows: number;
12058
+ statementOnlyIdSample: string[];
12059
+ complete: boolean;
12060
+ }
12061
+ interface StatementReconciliation {
12062
+ mode: "requests" | "categories";
12063
+ coverage: StatementCoverage;
12064
+ totals: {
12065
+ ourUsd: number;
12066
+ statementUsd?: number;
12067
+ deltaUsd?: number;
12068
+ };
12069
+ /** Every (model, component) line, models sorted, components in canonical order. */
12070
+ components: ComponentDelta[];
12071
+ /** The lines beyond tolerance, largest |delta| first: the named divergences. */
12072
+ divergent: ComponentDelta[];
12073
+ /**
12074
+ * Token disagreements between the export and our recorded usage
12075
+ * (requests mode). Under the default tokenComparison 'verdict' any
12076
+ * mismatch makes the verdict 'divergence'; under 'informational' the
12077
+ * count and sample still report, advisory only (RV903).
12078
+ */
12079
+ tokenMismatches: number;
12080
+ tokenMismatchSample: Array<{
12081
+ responseId: string;
12082
+ field: string;
12083
+ ours: number;
12084
+ statement: number;
12085
+ }>;
12086
+ /** Models the rate card does not cover: declared, excluded from divergence. */
12087
+ unpricedModels: string[];
12088
+ /** Rows whose usage the ledger never saw (usageUnknown): counted apart, never folded. */
12089
+ usageUnknownRows: number;
12090
+ componentToleranceUsd: number;
12091
+ verdict: "match" | "divergence" | "partial-coverage" | "no-overlap";
12092
+ /**
12093
+ * The settlement-grade composite, first class (RV1006): true exactly
12094
+ * when the verdict is 'match' AND coverage is complete AND no row's
12095
+ * usage is unknown AND no model went unpriced. A 'match' alone is
12096
+ * not enough: an export can cover every KNOWN row to the cent while
12097
+ * a usage-unknown attempt still holds unattributed money, and a safe
12098
+ * consumer must not assemble this predicate by hand. The last two
12099
+ * conditions overlap today's verdict semantics deliberately: the
12100
+ * predicate states the full contract so it cannot drift apart from
12101
+ * a future verdict refinement.
12102
+ */
12103
+ settleable: boolean;
12104
+ }
12105
+ /**
12106
+ * Reconciles the invoice against a normalized provider export. Pure and
12107
+ * journal-free; see the module doc for the contract. Throws a typed
12108
+ * ConfigError on inputs that cannot be evidence: an empty statement (a
12109
+ * headline total with no rows), a request row without a response id, a
12110
+ * duplicate response id (an ambiguous join), a request export whose
12111
+ * rows carry neither dollars, components, nor usage, any non-finite or
12112
+ * negative dollar amount, any non-integer or negative token count, a
12113
+ * non-finite or negative tolerance (RV903: a statement that cannot
12114
+ * be summed must refuse loudly, never verdict 'match' on NaN totals),
12115
+ * or a row whose usd and componentsUsd contradict each other beyond
12116
+ * totalToleranceUsd (RV1005: an internally contradictory export is
12117
+ * not evidence either).
12118
+ */
12119
+ declare function reconcileStatement(invoice: {
12120
+ rows: readonly InvoiceRow[];
12121
+ }, statement: ProviderStatement, options: ReconcileStatementOptions): StatementReconciliation;
12122
+ /**
12123
+ * Column mapping for {@link statementFromRows}: each field names the
12124
+ * KEY in the caller's raw rows that carries the value. Provider export
12125
+ * formats change without notice and differ per tenant surface (CSV
12126
+ * headers, JSON field names, locale-shaped numbers), so this module
12127
+ * deliberately ships NO per-provider schema knowledge: the caller
12128
+ * states the mapping in one place and the normalizer applies one
12129
+ * fail-closed validation to whatever the export actually contained,
12130
+ * naming the row and the column of anything that cannot be evidence.
12131
+ */
12132
+ interface StatementColumnMap {
12133
+ /** Key of the provider response id; required for `kind: 'requests'`. */
12134
+ responseId?: string;
12135
+ /** Key of the provider-side model name. */
12136
+ model?: string;
12137
+ /** Key of the row's billed dollars; for `kind: 'categories'` required. */
12138
+ usd?: string;
12139
+ /** Key of the billing component name; required for `kind: 'categories'`. */
12140
+ component?: string;
12141
+ /** Keys of the provider-reported token counts. */
12142
+ inputTokens?: string;
12143
+ cachedInputTokens?: string;
12144
+ cacheWriteTokens?: string;
12145
+ outputTokens?: string;
12146
+ /** Keys of a per-component dollar split, one column per component. */
12147
+ componentsUsd?: Partial<Record<BillingComponent, string>>;
12148
+ }
12149
+ /**
12150
+ * Normalizes raw keyed rows (a parsed CSV, a JSON export) into a
12151
+ * {@link ProviderStatement} under one explicit {@link StatementColumnMap}
12152
+ * (RV1703). Fail-closed at the cell: a mapped column whose value cannot
12153
+ * be evidence (a non-numeric dollar figure, a fractional or negative
12154
+ * token count, an empty response id, an unknown component name) refuses
12155
+ * typed with the row index and column name instead of flowing a NaN or
12156
+ * a guess into the reconciliation. Absent cells (missing key, null,
12157
+ * empty string) mean "the export does not carry this figure" and simply
12158
+ * omit the field; a requests row that ends up carrying no dollars, no
12159
+ * component split, and no usage at all is refused, because a row
12160
+ * without evidence cannot reconcile anything.
12161
+ */
12162
+ declare function statementFromRows(input: {
12163
+ kind: "requests" | "categories";
12164
+ rows: readonly Record<string, unknown>[];
12165
+ map: StatementColumnMap;
12166
+ }): ProviderStatement;
12167
+ //#endregion
11960
12168
  //#region src/engine/persisted-terminal.d.ts
11961
12169
  /**
11962
12170
  * Why no persisted terminal could be served. `unsettled`: the journal
@@ -12991,4 +13199,4 @@ interface SandboxBridge {
12991
13199
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
12992
13200
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
12993
13201
  //#endregion
12994
- export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, AcceptanceChildSummary, 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_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildExecutionFacts, ChildIdentityInput, ChildResultPage, CitationTarget, type ClaimClass, ClaimContradictionFinding, ClaimCoverageGrade, ClaimCoverageInput, type ClaimOp, ClaimPair, ClaimPairOptions, ClaimPairsFold, ClaimPoolReading, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, Contradiction, ContradictionClaim, ContradictionOptions, ContradictionSource, type CoreEvents, CostAttribution, CostAttributionFacts, type CostBasis, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, 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, DocumentedRates, 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_SECTIONAL_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, InvoiceCardinality, 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_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, 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, OrchestrateClaimConsistency, OrchestrateClaimConsistencyMeta, OrchestrateContradictions, OrchestrateContradictionsMeta, 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, PersistedTerminalRefusal, PersistedTerminalResult, type PhaseRow, PhaseTarget, PilotAgentProfileOptions, PilotAgentProfileResult, type PinnedPricingSegment, PipelineCollected, PipelineOpts, PlanInvariantError, type PostFanInBreakdown, PreflightAdmissionRow, PreflightFinding, PreflightInput, PreflightOrchestratorSpec, PreflightReport, PreflightSpawnReport, PreflightSpawnSpec, PreflightToolCeiling, PriceTable, PricedComponent, PricedComponents, 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_FACTS_ANCHOR, 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, RunFactPairOptions, RunFactPairsFold, RunFactsSheet, 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, type StreamHooks, StructuredOutputTier, SupersededError, SuspendedAppend, SuspensionState, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, type TerminalEnvelope, TerminalOutcomeFacts, 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, ToolsetAttestation, 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, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, 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, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatCharacterValidator, 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, pairDraftClaims, pairRunFactClaims, parallelScope, parseModelRef, parseScopePath, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, 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, spliceSections, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, terminalEnvelopeOf, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolContractHash, toolsetHash, ttlState, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
13202
+ export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, AcceptanceChildSummary, 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, BillingComponent, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildExecutionFacts, ChildIdentityInput, ChildResultPage, CitationTarget, type ClaimClass, ClaimContradictionFinding, ClaimCoverageGrade, ClaimCoverageInput, type ClaimOp, ClaimPair, ClaimPairOptions, ClaimPairsFold, ClaimPoolReading, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ComponentDelta, ConfigError, Contradiction, ContradictionClaim, ContradictionOptions, ContradictionSource, type CoreEvents, CostAttribution, CostAttributionFacts, type CostBasis, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, 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, DocumentedRates, 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_SECTIONAL_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, InvoiceCardinality, 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_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, 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, OrchestrateClaimConsistency, OrchestrateClaimConsistencyMeta, OrchestrateContradictions, OrchestrateContradictionsMeta, 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, PersistedTerminalRefusal, PersistedTerminalResult, type PhaseRow, PhaseTarget, PilotAgentProfileOptions, PilotAgentProfileResult, type PinnedPricingSegment, PipelineCollected, PipelineOpts, PlanInvariantError, type PostFanInBreakdown, PreflightAdmissionRow, PreflightFinding, PreflightInput, PreflightOrchestratorSpec, PreflightReport, PreflightSpawnReport, PreflightSpawnSpec, PreflightToolCeiling, PriceTable, PricedComponent, PricedComponents, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, ProviderCallRecord, ProviderStatement, 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_FACTS_ANCHOR, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, RandIdentityInput, RandPayload, RateLimitObservation, ReconcileOptions, ReconcileResult, ReconcileStatementOptions, 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, RunFactPairOptions, RunFactPairsFold, RunFactsSheet, 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, StatementCategoryRow, StatementColumnMap, StatementCoverage, StatementReconciliation, StatementRequestRow, StepIdentityInput, type StreamHooks, StructuredOutputTier, SupersededError, SuspendedAppend, SuspensionState, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, type TerminalEnvelope, TerminalOutcomeFacts, 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, ToolsetAttestation, 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, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, 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, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatCharacterValidator, 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, pairDraftClaims, pairRunFactClaims, parallelScope, parseModelRef, parseScopePath, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reconcileStatement, 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, spliceSections, statementFromRows, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, terminalEnvelopeOf, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolContractHash, toolsetHash, ttlState, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/dist/index.js CHANGED
@@ -14324,6 +14324,467 @@ function invoiceFromJournal(entries, priceUsd, options) {
14324
14324
  return invoice;
14325
14325
  }
14326
14326
  //#endregion
14327
+ //#region src/engine/reconcile-statement.ts
14328
+ /**
14329
+ * Provider statement reconciliation (RV812). The twelfth comparison
14330
+ * run's billing question was closed by hand: the dashboard's headline
14331
+ * said 4.45 then 4.77 USD against the settled 7.304885, and only the
14332
+ * per-component Spend categories screenshots proved the invoice right
14333
+ * to the cent while the headline turned out to be the dashboard's own
14334
+ * unconverged aggregate. This module is that investigation as a
14335
+ * machine, so the next such question closes with a report instead of
14336
+ * screenshots.
14337
+ *
14338
+ * It joins a NORMALIZED provider export against the machine-readable
14339
+ * invoice (`invoiceFromJournal`): per-request rows by response id, or
14340
+ * per-model per-component category totals (the Spend categories tab).
14341
+ * Headline aggregates are refused typed: an eventually-consistent
14342
+ * dashboard total is not evidence, per-component figures and usage
14343
+ * exports are. The report carries response-id coverage (a partially
14344
+ * delivered export must read as partial coverage, never as false
14345
+ * divergence), per-component deltas, and the implied actual rate of
14346
+ * every component, so a real divergence NAMES the rate-card line that
14347
+ * moved instead of printing one inexplicable total.
14348
+ *
14349
+ * The intake fails closed on numbers that cannot be evidence (RV903,
14350
+ * the thirteenth experiment's probes): non-finite or negative dollars,
14351
+ * non-integer or negative token counts, and non-finite or negative
14352
+ * tolerances refuse typed instead of flowing NaN through the sums to a
14353
+ * false 'match'. Provider-reported token disagreements decide the
14354
+ * verdict by default; `tokenComparison: 'informational'` restores the
14355
+ * dollar-only verdict for exports with legitimately different token
14356
+ * semantics.
14357
+ *
14358
+ * Sidecar only, like the v1.19.0 cache audit beside it: nothing here
14359
+ * reads or writes a journal, and the caller stores the report next to
14360
+ * the invoice it reconciles.
14361
+ */
14362
+ const COMPONENTS = [
14363
+ "input",
14364
+ "cached-input",
14365
+ "cache-write",
14366
+ "output"
14367
+ ];
14368
+ const SAMPLE_CAP = 20;
14369
+ const emptySums = () => ({
14370
+ tokens: {
14371
+ input: 0,
14372
+ "cached-input": 0,
14373
+ "cache-write": 0,
14374
+ output: 0
14375
+ },
14376
+ usd: {
14377
+ input: 0,
14378
+ "cached-input": 0,
14379
+ "cache-write": 0,
14380
+ output: 0
14381
+ }
14382
+ });
14383
+ const defaultModelOf = (servedBy) => {
14384
+ const colon = servedBy.indexOf(":");
14385
+ return colon === -1 ? servedBy : servedBy.slice(colon + 1);
14386
+ };
14387
+ /**
14388
+ * A statement dollar amount must be a finite nonnegative number
14389
+ * (RV903). The thirteenth experiment's probe fed `usd: NaN` and got
14390
+ * verdict 'match' with NaN totals: NaN flowed through the sums and
14391
+ * `Math.abs(NaN) > tolerance` is false, so the divergence check
14392
+ * silently disarmed. Negative amounts are refused too: provider
14393
+ * credits and adjustments are real, but they are not per-request or
14394
+ * per-component BILLING evidence, and folding them into the join would
14395
+ * let an adjustment mask a rate divergence of the same size.
14396
+ */
14397
+ function assertStatementUsd(where, field, value) {
14398
+ if (!Number.isFinite(value)) throw new ConfigError(`statement reconciliation refused: ${where} carries ${field} ${String(value)}, which cannot be summed; a statement whose dollars are not finite is not evidence`);
14399
+ if (value < 0) throw new ConfigError(`statement reconciliation refused: ${where} carries negative ${field} ${String(value)}; credits and adjustments reconcile separately, never as negative statement rows`);
14400
+ }
14401
+ /** A provider-reported token count must be a nonnegative integer (RV903). */
14402
+ function assertTokenCount(where, field, value) {
14403
+ if (!Number.isInteger(value) || value < 0) throw new ConfigError(`statement reconciliation refused: ${where} carries ${field} ${String(value)}; provider-reported token counts are nonnegative integers`);
14404
+ }
14405
+ /**
14406
+ * Reconciles the invoice against a normalized provider export. Pure and
14407
+ * journal-free; see the module doc for the contract. Throws a typed
14408
+ * ConfigError on inputs that cannot be evidence: an empty statement (a
14409
+ * headline total with no rows), a request row without a response id, a
14410
+ * duplicate response id (an ambiguous join), a request export whose
14411
+ * rows carry neither dollars, components, nor usage, any non-finite or
14412
+ * negative dollar amount, any non-integer or negative token count, a
14413
+ * non-finite or negative tolerance (RV903: a statement that cannot
14414
+ * be summed must refuse loudly, never verdict 'match' on NaN totals),
14415
+ * or a row whose usd and componentsUsd contradict each other beyond
14416
+ * totalToleranceUsd (RV1005: an internally contradictory export is
14417
+ * not evidence either).
14418
+ */
14419
+ function reconcileStatement(invoice, statement, options) {
14420
+ for (const [name, value] of [["componentToleranceUsd", options.componentToleranceUsd], ["totalToleranceUsd", options.totalToleranceUsd]]) if (value !== void 0 && (!Number.isFinite(value) || value < 0)) throw new ConfigError(`statement reconciliation refused: ${name} ${String(value)} is not a finite nonnegative dollar tolerance`);
14421
+ const componentToleranceUsd = options.componentToleranceUsd ?? .005;
14422
+ const totalToleranceUsd = options.totalToleranceUsd ?? .01;
14423
+ const modelOf = options.modelOf ?? defaultModelOf;
14424
+ const tokenComparison = options.tokenComparison ?? "verdict";
14425
+ if (statement.rows.length === 0) throw new ConfigError("statement reconciliation refused: the statement carries no rows. A headline total is not evidence (dashboard aggregates are eventually consistent); export per-request rows or per-component categories and reconcile those");
14426
+ const billable = [];
14427
+ let usageUnknownRows = 0;
14428
+ for (const row of invoice.rows) {
14429
+ if (row.usageUnknown === true) {
14430
+ usageUnknownRows += 1;
14431
+ continue;
14432
+ }
14433
+ billable.push(row);
14434
+ }
14435
+ let covered = billable;
14436
+ let matchedRows;
14437
+ let unmatchedRows = 0;
14438
+ const unmatchedIdSample = [];
14439
+ let statementOnlyRows = 0;
14440
+ const statementOnlyIdSample = [];
14441
+ let statementTotalUsd;
14442
+ let statementComponents;
14443
+ let matchedStatementRows = 0;
14444
+ let matchedUsdRows = 0;
14445
+ let tokenMismatches = 0;
14446
+ let partialOverlap = false;
14447
+ const tokenMismatchSample = [];
14448
+ const rowsWithResponseId = billable.filter((row) => row.responseId !== void 0).length;
14449
+ if (statement.kind === "requests") {
14450
+ const byId = /* @__PURE__ */ new Map();
14451
+ let carriesAnything = false;
14452
+ for (const row of statement.rows) {
14453
+ if (row.responseId === "") throw new ConfigError("statement reconciliation refused: a per-request export row has no response id, the join key; normalize the export or reconcile per-component categories instead");
14454
+ if (byId.has(row.responseId)) throw new ConfigError(`statement reconciliation refused: duplicate response id '${row.responseId}' in the export makes the join ambiguous`);
14455
+ const where = `row '${row.responseId}'`;
14456
+ if (row.usd !== void 0) assertStatementUsd(where, "usd", row.usd);
14457
+ if (row.componentsUsd !== void 0) {
14458
+ let componentsSum = 0;
14459
+ let componentsSeen = 0;
14460
+ for (const component of COMPONENTS) {
14461
+ const usd = row.componentsUsd[component];
14462
+ if (usd !== void 0) {
14463
+ assertStatementUsd(where, `componentsUsd.${component}`, usd);
14464
+ componentsSum += usd;
14465
+ componentsSeen += 1;
14466
+ }
14467
+ }
14468
+ if (componentsSeen === 0) throw new ConfigError(`statement reconciliation refused: ${where} declares componentsUsd with no component figures; an empty object is not evidence: drop the field or export the split`);
14469
+ if (row.usd !== void 0 && componentsSeen > 0 && Math.abs(row.usd - componentsSum) > totalToleranceUsd) throw new ConfigError(`statement reconciliation refused: ${where} carries usd ${String(row.usd)} and a component split summing to ${String(componentsSum)}, claims that contradict each other beyond the ${String(totalToleranceUsd)} totals tolerance; an export whose own total disagrees with its own components is not evidence: normalize it to one dollar claim per row or fix the export`);
14470
+ }
14471
+ if (row.usage !== void 0) {
14472
+ let usageSeen = 0;
14473
+ for (const field of [
14474
+ "inputTokens",
14475
+ "cachedInputTokens",
14476
+ "cacheWriteTokens",
14477
+ "outputTokens"
14478
+ ]) {
14479
+ const count = row.usage[field];
14480
+ if (count !== void 0) {
14481
+ assertTokenCount(where, `usage.${field}`, count);
14482
+ usageSeen += 1;
14483
+ }
14484
+ }
14485
+ if (usageSeen === 0) throw new ConfigError(`statement reconciliation refused: ${where} declares usage with no token counts; an empty object is not evidence: drop the field or export the counts`);
14486
+ }
14487
+ byId.set(row.responseId, row);
14488
+ if (row.usd !== void 0 || row.componentsUsd !== void 0 || row.usage !== void 0) carriesAnything = true;
14489
+ }
14490
+ if (!carriesAnything) throw new ConfigError("statement reconciliation refused: no export row carries dollars, components, or usage; there is nothing to reconcile against");
14491
+ const matched = [];
14492
+ const matchedStatement = /* @__PURE__ */ new Set();
14493
+ const partialSegmentIds = /* @__PURE__ */ new Set();
14494
+ for (const row of billable) {
14495
+ const rowIds = row.wireResponseIds !== void 0 && row.wireResponseIds.length > 0 ? row.wireResponseIds : row.responseId === void 0 ? [] : [row.responseId];
14496
+ const hits = rowIds.map((id) => byId.get(id)).filter((hit) => hit !== void 0);
14497
+ if (rowIds.length === 0 || hits.length !== rowIds.length) {
14498
+ unmatchedRows += 1;
14499
+ if (row.responseId !== void 0 && unmatchedIdSample.length < SAMPLE_CAP) unmatchedIdSample.push(row.responseId);
14500
+ for (const hit of hits) {
14501
+ partialSegmentIds.add(hit.responseId);
14502
+ partialOverlap = true;
14503
+ }
14504
+ continue;
14505
+ }
14506
+ for (const hit of hits) matchedStatement.add(hit.responseId);
14507
+ matched.push(row);
14508
+ if (hits.length > 0 && hits.every((hit) => hit.usage !== void 0)) {
14509
+ const fields = [
14510
+ ["inputTokens", row.usage.inputTokens],
14511
+ ["cachedInputTokens", row.usage.cacheReadTokens],
14512
+ ["cacheWriteTokens", row.usage.cacheWriteTokens],
14513
+ ["outputTokens", row.usage.outputTokens]
14514
+ ];
14515
+ for (const [field, ours] of fields) {
14516
+ let sum = 0;
14517
+ let present = 0;
14518
+ for (const hit of hits) {
14519
+ const value = hit.usage?.[field];
14520
+ if (value !== void 0) {
14521
+ sum += value;
14522
+ present += 1;
14523
+ }
14524
+ }
14525
+ if (present === hits.length && sum !== ours) {
14526
+ tokenMismatches += 1;
14527
+ if (tokenMismatchSample.length < SAMPLE_CAP) tokenMismatchSample.push({
14528
+ responseId: row.responseId ?? rowIds[0] ?? "",
14529
+ field,
14530
+ ours,
14531
+ statement: sum
14532
+ });
14533
+ }
14534
+ }
14535
+ }
14536
+ }
14537
+ for (const row of statement.rows) if (!matchedStatement.has(row.responseId) && !partialSegmentIds.has(row.responseId)) {
14538
+ statementOnlyRows += 1;
14539
+ if (statementOnlyIdSample.length < SAMPLE_CAP) statementOnlyIdSample.push(row.responseId);
14540
+ }
14541
+ covered = matched;
14542
+ matchedRows = matched.length;
14543
+ let totalSeen = false;
14544
+ let total = 0;
14545
+ statementComponents = /* @__PURE__ */ new Map();
14546
+ for (const row of statement.rows) {
14547
+ if (!matchedStatement.has(row.responseId)) continue;
14548
+ matchedStatementRows += 1;
14549
+ if (row.usd !== void 0) {
14550
+ matchedUsdRows += 1;
14551
+ totalSeen = true;
14552
+ total += row.usd;
14553
+ }
14554
+ if (row.componentsUsd !== void 0) {
14555
+ const model = row.model ?? "";
14556
+ const sums = statementComponents.get(model) ?? {};
14557
+ for (const component of COMPONENTS) {
14558
+ const usd = row.componentsUsd[component];
14559
+ if (usd !== void 0) sums[component] = (sums[component] ?? 0) + usd;
14560
+ }
14561
+ statementComponents.set(model, sums);
14562
+ }
14563
+ }
14564
+ if (totalSeen) statementTotalUsd = total;
14565
+ if (statementComponents.size === 0) statementComponents = void 0;
14566
+ } else {
14567
+ statementComponents = /* @__PURE__ */ new Map();
14568
+ let total = 0;
14569
+ for (const row of statement.rows) {
14570
+ assertStatementUsd(`category row '${row.model}' ${row.component}`, "usd", row.usd);
14571
+ const sums = statementComponents.get(row.model) ?? {};
14572
+ sums[row.component] = (sums[row.component] ?? 0) + row.usd;
14573
+ statementComponents.set(row.model, sums);
14574
+ total += row.usd;
14575
+ }
14576
+ statementTotalUsd = total;
14577
+ matchedRows = billable.length;
14578
+ }
14579
+ const ourByModel = /* @__PURE__ */ new Map();
14580
+ const unpricedModels = /* @__PURE__ */ new Set();
14581
+ let ourUsd = 0;
14582
+ for (const row of covered) {
14583
+ const model = modelOf(row.servedBy);
14584
+ const pricing = options.pricingOf(row.servedBy);
14585
+ if (pricing === void 0) {
14586
+ unpricedModels.add(model);
14587
+ continue;
14588
+ }
14589
+ const parts = priceComponentsOf(pricing, row.usage);
14590
+ const sums = ourByModel.get(model) ?? emptySums();
14591
+ const byName = [
14592
+ ["input", parts.input],
14593
+ ["cached-input", parts.cachedInput],
14594
+ ["cache-write", parts.cacheWrite],
14595
+ ["output", parts.output]
14596
+ ];
14597
+ for (const [component, part] of byName) {
14598
+ sums.tokens[component] += part.tokens;
14599
+ sums.usd[component] += part.usd;
14600
+ }
14601
+ ourByModel.set(model, sums);
14602
+ }
14603
+ for (const sums of ourByModel.values()) for (const component of COMPONENTS) ourUsd += sums.usd[component];
14604
+ if (statement.kind === "categories") {
14605
+ for (const model of statementComponents?.keys() ?? []) if (!ourByModel.has(model) && !unpricedModels.has(model)) {
14606
+ statementOnlyRows += 1;
14607
+ if (statementOnlyIdSample.length < SAMPLE_CAP) statementOnlyIdSample.push(model);
14608
+ }
14609
+ }
14610
+ const components = [];
14611
+ const ourLines = statement.kind === "requests" && statementComponents?.has("") === true ? /* @__PURE__ */ new Map([["", [...ourByModel.values()].reduce((acc, sums) => {
14612
+ for (const component of COMPONENTS) {
14613
+ acc.tokens[component] += sums.tokens[component];
14614
+ acc.usd[component] += sums.usd[component];
14615
+ }
14616
+ return acc;
14617
+ }, emptySums())]]) : ourByModel;
14618
+ for (const model of [...ourLines.keys()].sort()) {
14619
+ const sums = ourLines.get(model);
14620
+ if (sums === void 0) continue;
14621
+ for (const component of COMPONENTS) {
14622
+ const ourTokens = sums.tokens[component];
14623
+ const ours = sums.usd[component];
14624
+ const statementUsd = statementComponents?.get(model)?.[component];
14625
+ const line = {
14626
+ model,
14627
+ component,
14628
+ ourTokens,
14629
+ ourUsd: ours,
14630
+ divergent: false
14631
+ };
14632
+ if (statementUsd !== void 0) {
14633
+ line.statementUsd = statementUsd;
14634
+ line.deltaUsd = statementUsd - ours;
14635
+ line.divergent = Math.abs(line.deltaUsd) > componentToleranceUsd;
14636
+ }
14637
+ if (ourTokens > 0) {
14638
+ line.effectiveUsdPerMTok = ours / (ourTokens / 1e6);
14639
+ if (statementUsd !== void 0) line.impliedUsdPerMTok = statementUsd / (ourTokens / 1e6);
14640
+ }
14641
+ components.push(line);
14642
+ }
14643
+ }
14644
+ const divergent = components.filter((line) => line.divergent).sort((a, b) => Math.abs(b.deltaUsd ?? 0) - Math.abs(a.deltaUsd ?? 0));
14645
+ const totalsDelta = statementTotalUsd === void 0 ? void 0 : statementTotalUsd - ourUsd;
14646
+ const totalsDivergent = unpricedModels.size === 0 && (statement.kind === "requests" ? matchedUsdRows === matchedStatementRows : statementOnlyRows === 0 && components.every((line) => line.statementUsd !== void 0)) && totalsDelta !== void 0 && Math.abs(totalsDelta) > totalToleranceUsd;
14647
+ const coverageComplete = unmatchedRows === 0 && statementOnlyRows === 0 && unpricedModels.size === 0 && (statement.kind === "categories" || matchedRows === rowsWithResponseId && rowsWithResponseId === billable.length) && (statement.kind === "requests" || components.every((line) => line.statementUsd !== void 0));
14648
+ const tokensDivergent = tokenComparison === "verdict" && tokenMismatches > 0;
14649
+ let verdict;
14650
+ if (divergent.length > 0 || totalsDivergent || tokensDivergent) verdict = "divergence";
14651
+ else if (matchedRows === 0 && !partialOverlap) verdict = "no-overlap";
14652
+ else if (!coverageComplete) verdict = "partial-coverage";
14653
+ else verdict = "match";
14654
+ return {
14655
+ mode: statement.kind,
14656
+ coverage: {
14657
+ billableRows: billable.length,
14658
+ rowsWithResponseId,
14659
+ matchedRows,
14660
+ unmatchedRows,
14661
+ unmatchedIdSample,
14662
+ statementOnlyRows,
14663
+ statementOnlyIdSample,
14664
+ complete: coverageComplete
14665
+ },
14666
+ totals: {
14667
+ ourUsd,
14668
+ ...statementTotalUsd === void 0 ? {} : { statementUsd: statementTotalUsd },
14669
+ ...totalsDelta === void 0 ? {} : { deltaUsd: totalsDelta }
14670
+ },
14671
+ components,
14672
+ divergent,
14673
+ tokenMismatches,
14674
+ tokenMismatchSample,
14675
+ unpricedModels: [...unpricedModels].sort(),
14676
+ usageUnknownRows,
14677
+ componentToleranceUsd,
14678
+ verdict,
14679
+ settleable: verdict === "match" && coverageComplete && usageUnknownRows === 0 && unpricedModels.size === 0
14680
+ };
14681
+ }
14682
+ /** A cell that is absent by export convention: missing, null, or ''. */
14683
+ const absentCell = (value) => value === void 0 || value === null || typeof value === "string" && value.trim() === "";
14684
+ const stringAt = (row, column, rowIndex) => {
14685
+ const value = row[column];
14686
+ if (absentCell(value)) return;
14687
+ if (typeof value !== "string" || value.trim() === "") throw new ConfigError(`statement row ${String(rowIndex)} column '${column}' must be a non-empty string, got ${JSON.stringify(value)}`);
14688
+ return value.trim();
14689
+ };
14690
+ const dollarsAt = (row, column, rowIndex) => {
14691
+ const value = row[column];
14692
+ if (absentCell(value)) return;
14693
+ const parsed = typeof value === "number" ? value : Number(String(value).trim());
14694
+ if (!Number.isFinite(parsed) || parsed < 0) throw new ConfigError(`statement row ${String(rowIndex)} column '${column}' must be finite non-negative dollars, got ${JSON.stringify(value)}`);
14695
+ return parsed;
14696
+ };
14697
+ const tokensAt = (row, column, rowIndex) => {
14698
+ const value = row[column];
14699
+ if (absentCell(value)) return;
14700
+ const parsed = typeof value === "number" ? value : Number(String(value).trim());
14701
+ if (!Number.isInteger(parsed) || parsed < 0) throw new ConfigError(`statement row ${String(rowIndex)} column '${column}' must be a non-negative integer token count, got ${JSON.stringify(value)}`);
14702
+ return parsed;
14703
+ };
14704
+ /**
14705
+ * Normalizes raw keyed rows (a parsed CSV, a JSON export) into a
14706
+ * {@link ProviderStatement} under one explicit {@link StatementColumnMap}
14707
+ * (RV1703). Fail-closed at the cell: a mapped column whose value cannot
14708
+ * be evidence (a non-numeric dollar figure, a fractional or negative
14709
+ * token count, an empty response id, an unknown component name) refuses
14710
+ * typed with the row index and column name instead of flowing a NaN or
14711
+ * a guess into the reconciliation. Absent cells (missing key, null,
14712
+ * empty string) mean "the export does not carry this figure" and simply
14713
+ * omit the field; a requests row that ends up carrying no dollars, no
14714
+ * component split, and no usage at all is refused, because a row
14715
+ * without evidence cannot reconcile anything.
14716
+ */
14717
+ function statementFromRows(input) {
14718
+ const { kind, rows, map } = input;
14719
+ if (kind === "categories") {
14720
+ for (const key of [
14721
+ "model",
14722
+ "component",
14723
+ "usd"
14724
+ ]) if (map[key] === void 0) throw new ConfigError(`statementFromRows kind 'categories' requires map.${key}`);
14725
+ return {
14726
+ kind: "categories",
14727
+ rows: rows.map((row, index) => {
14728
+ const model = stringAt(row, map.model, index);
14729
+ const componentRaw = stringAt(row, map.component, index);
14730
+ const usd = dollarsAt(row, map.usd, index);
14731
+ if (model === void 0 || componentRaw === void 0 || usd === void 0) throw new ConfigError(`statement row ${String(index)} must carry model, component, and usd for a categories statement`);
14732
+ const component = COMPONENTS.find((name) => name === componentRaw);
14733
+ if (component === void 0) throw new ConfigError(`statement row ${String(index)} names unknown component '${componentRaw}'; expected one of ${COMPONENTS.join(", ")}`);
14734
+ return {
14735
+ model,
14736
+ component,
14737
+ usd
14738
+ };
14739
+ })
14740
+ };
14741
+ }
14742
+ if (map.responseId === void 0) throw new ConfigError("statementFromRows kind 'requests' requires map.responseId");
14743
+ return {
14744
+ kind: "requests",
14745
+ rows: rows.map((row, index) => {
14746
+ const responseId = stringAt(row, map.responseId, index);
14747
+ if (responseId === void 0) throw new ConfigError(`statement row ${String(index)} carries no response id in column '${map.responseId}', the join key`);
14748
+ const model = map.model === void 0 ? void 0 : stringAt(row, map.model, index);
14749
+ const usd = map.usd === void 0 ? void 0 : dollarsAt(row, map.usd, index);
14750
+ let componentsUsd;
14751
+ if (map.componentsUsd !== void 0) for (const component of COMPONENTS) {
14752
+ const column = map.componentsUsd[component];
14753
+ if (column === void 0) continue;
14754
+ const cell = dollarsAt(row, column, index);
14755
+ if (cell === void 0) continue;
14756
+ componentsUsd = {
14757
+ ...componentsUsd ?? {},
14758
+ [component]: cell
14759
+ };
14760
+ }
14761
+ const usage = {};
14762
+ const tokenColumns = [
14763
+ ["inputTokens", map.inputTokens],
14764
+ ["cachedInputTokens", map.cachedInputTokens],
14765
+ ["cacheWriteTokens", map.cacheWriteTokens],
14766
+ ["outputTokens", map.outputTokens]
14767
+ ];
14768
+ let usageSeen = false;
14769
+ for (const [field, column] of tokenColumns) {
14770
+ if (column === void 0) continue;
14771
+ const cell = tokensAt(row, column, index);
14772
+ if (cell === void 0) continue;
14773
+ usage[field] = cell;
14774
+ usageSeen = true;
14775
+ }
14776
+ if (usd === void 0 && componentsUsd === void 0 && !usageSeen) throw new ConfigError(`statement row ${String(index)} ('${responseId}') carries no dollars, no component split, and no usage under the given map; a row without evidence cannot reconcile`);
14777
+ return {
14778
+ responseId,
14779
+ ...model === void 0 ? {} : { model },
14780
+ ...usd === void 0 ? {} : { usd },
14781
+ ...componentsUsd === void 0 ? {} : { componentsUsd },
14782
+ ...usageSeen ? { usage } : {}
14783
+ };
14784
+ })
14785
+ };
14786
+ }
14787
+ //#endregion
14327
14788
  //#region src/engine/persisted-terminal.ts
14328
14789
  const REFUSAL_MESSAGES = {
14329
14790
  unsettled: "no run settle is journaled for this run: nothing durable records a terminal",
@@ -25423,4 +25884,4 @@ function createSandboxBridge(ctx, options) {
25423
25884
  };
25424
25885
  }
25425
25886
  //#endregion
25426
- export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, 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_SECTIONAL_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_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, 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_FACTS_ANCHOR, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, SupersededError, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, 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, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatCharacterValidator, 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, pairDraftClaims, pairRunFactClaims, parallelScope, parseModelRef, parseScopePath, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, 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, spliceSections, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, terminalEnvelopeOf, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolContractHash, toolsetHash, ttlState, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
25887
+ export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, 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_SECTIONAL_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_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, 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_FACTS_ANCHOR, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, SupersededError, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, 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, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatCharacterValidator, 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, pairDraftClaims, pairRunFactClaims, parallelScope, parseModelRef, parseScopePath, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reconcileStatement, 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, spliceSections, statementFromRows, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, terminalEnvelopeOf, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolContractHash, toolsetHash, ttlState, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.179.0",
3
+ "version": "1.181.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",