@rulvar/core 1.107.0 → 1.109.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
@@ -5973,7 +5973,11 @@ declare class AdmissionController {
5973
5973
  * Folds the per-run attribution buckets into the normative CostReport.
5974
5974
  * Live attribution buckets never see abandoned subtrees, so a host
5975
5975
  * that tracked abandoned spend itself passes it as `abandoned`;
5976
- * omitted, the report shows a gross equal to the net.
5976
+ * omitted, the report shows a gross equal to the net. Non-finite
5977
+ * numbers anywhere in the inputs are a typed refusal (RV705): this
5978
+ * exported builder is the same public surface as
5979
+ * {@link costReportFromJournal} and holds the same RV610 doctrine,
5980
+ * instead of letting an Infinity or NaN serialize into null downstream.
5977
5981
  */
5978
5982
  declare function buildCostReport(attribution: CostAttribution, totalUsd: number, abandoned?: CostReport["abandoned"]): CostReport;
5979
5983
  /**
@@ -9430,6 +9434,13 @@ declare class JsonlFileStore implements MetaLookupStore {
9430
9434
  private metaPath;
9431
9435
  append(runId: string, e: JournalEntry): Promise<void>;
9432
9436
  load(runId: string): Promise<JournalEntry[]>;
9437
+ /**
9438
+ * Restores the trailing '\n' of a parseable-but-unterminated tail
9439
+ * (RV701). One byte appended in place terminates the record exactly
9440
+ * where the crash left it; the file's bytes before it stay untouched.
9441
+ * No-op on a missing, empty, or already-terminated journal.
9442
+ */
9443
+ private terminateUnterminatedTail;
9433
9444
  private repairTornTail;
9434
9445
  putMeta(m: RunMeta): Promise<void>;
9435
9446
  getMeta(runId: string): Promise<RunMeta | undefined>;
@@ -9468,6 +9479,27 @@ interface AppliedPricingRow {
9468
9479
  model: ModelRef;
9469
9480
  rates: Pricing;
9470
9481
  }
9482
+ /**
9483
+ * One pin's coverage (RV611): the run-settle that recorded it, the seq
9484
+ * range it settled FIRST, and exactly the version and rows it pinned.
9485
+ * The whole array is the per-segment provenance a single last-pin
9486
+ * version used to hide: an invoice folded over a rotation can now say
9487
+ * every table version that priced it, with the boundary seqs.
9488
+ */
9489
+ interface PinnedPricingSegment {
9490
+ /**
9491
+ * The first seq this pin covers: the previous pin's settle seq, 0 for
9492
+ * the first pin. Rows with `fromSeq <= seq < settleSeq` price under
9493
+ * this pin in the seq-aware fold.
9494
+ */
9495
+ fromSeq: number;
9496
+ /** The pinning run-settle's own seq (the exclusive upper bound). */
9497
+ settleSeq: number;
9498
+ /** The PriceTable version THIS settle pinned; absent for caps-only rows. */
9499
+ pricingVersion?: string;
9500
+ /** The applied rows THIS settle pinned. */
9501
+ rows: AppliedPricingRow[];
9502
+ }
9471
9503
  /** What `journalPricingSnapshot` rebuilds from a pinned run settle. */
9472
9504
  interface JournalPricingSnapshot {
9473
9505
  /** The PriceTable version of the LAST pin; absent for caps-only rows. */
@@ -9481,6 +9513,13 @@ interface JournalPricingSnapshot {
9481
9513
  */
9482
9514
  pinnedThroughSeq: number;
9483
9515
  /**
9516
+ * Every pin in journal order (RV611): boundaries, versions, and rows,
9517
+ * not only the last. This is the honest provenance for a fold across
9518
+ * a price-table rotation: consumers exporting `pricingVersion` alone
9519
+ * silently hid that different segments priced under different tables.
9520
+ */
9521
+ segments: PinnedPricingSegment[];
9522
+ /**
9484
9523
  * Prices usage with the PINNED rows only: a model absent from the
9485
9524
  * snapshot folds as unpriced (surfaced, never a silent zero), exactly
9486
9525
  * the honesty contract of the live fold. With a `seq`, the row is
@@ -9491,6 +9530,24 @@ interface JournalPricingSnapshot {
9491
9530
  * historical behavior.
9492
9531
  */
9493
9532
  priceUsd: (servedBy: ModelRef, usage: Usage, seq?: number) => number | undefined;
9533
+ /**
9534
+ * THE composition the engine's outcome mirror applies at settle
9535
+ * (RV611), exported so stored consumers (the CLI cost and invoice
9536
+ * views, the server cost endpoint) fold exactly like the engine
9537
+ * instead of passing the raw snapshot: a pin-covered row (`seq <
9538
+ * pinnedThroughSeq`) prices under the pin of its own segment; the
9539
+ * tail past the last pin (a segment journaled but not yet settled,
9540
+ * the crashed-mid-flight shape) and seq-less calls price at `current`
9541
+ * alone, exactly like the live debits that tail will settle with,
9542
+ * never silently at the last pin's rates. Two deliberate fallbacks,
9543
+ * both documented rather than hidden: a covered model its covering
9544
+ * pin missed back-reprices at the LAST pin when that pin names it
9545
+ * (the journal never recorded what those debits actually cost), and
9546
+ * otherwise falls to `current` (today's table may know a model the
9547
+ * run's tables never priced); a model neither names folds as
9548
+ * unpriced, surfaced, never a silent zero.
9549
+ */
9550
+ composedPriceUsd: (current: (servedBy: ModelRef, usage: Usage) => number | undefined) => (servedBy: ModelRef, usage: Usage, seq?: number) => number | undefined;
9494
9551
  }
9495
9552
  /**
9496
9553
  * The read side. Every settling segment pins the union it applied, and
@@ -9558,17 +9615,34 @@ interface InvoiceRow {
9558
9615
  reconciliation: InvoiceReconciliation;
9559
9616
  }
9560
9617
  /**
9561
- * Where the fold's rates came from (RV407): `snapshot` says the caller
9562
- * priced with the run-settle pin (`journalPricingSnapshot`), so these
9563
- * numbers are stable against later table updates; `current-table` says
9564
- * the live table priced it, the historical behavior. Attached by the
9565
- * caller, who is the one that chose.
9618
+ * Where the fold's rates came from (RV407): `composed` says the caller
9619
+ * priced with the snapshot's `composedPriceUsd` (RV611), the engine's
9620
+ * own composition, so pin-covered rows reproduce the settled numbers
9621
+ * and anything past the last pin priced at the caller's current table;
9622
+ * `snapshot` says the caller priced with the raw pinned rows alone
9623
+ * (the pre-RV611 label); `current-table` says the live table priced
9624
+ * it, the historical behavior for journals without a pin. Attached by
9625
+ * the caller, who is the one that chose.
9566
9626
  */
9567
9627
  interface InvoicePricingProvenance {
9568
- source: "snapshot" | "current-table";
9628
+ source: "snapshot" | "current-table" | "composed";
9569
9629
  pricingVersion?: string | undefined;
9570
9630
  /** The pinned rows the fold used; present on snapshot-priced exports. */
9571
9631
  rows?: AppliedPricingRow[] | undefined;
9632
+ /**
9633
+ * Per-pin coverage (RV611): every settled segment's version and rows
9634
+ * with its seq boundaries, not only the last. A fold across a
9635
+ * price-table rotation used to export one `pricingVersion` while its
9636
+ * rows priced under several; this array is the honest declaration.
9637
+ */
9638
+ segments?: PinnedPricingSegment[] | undefined;
9639
+ /**
9640
+ * On `composed` exports: the last pin's settle seq. Rows at or past
9641
+ * it (a segment journaled but not yet settled) priced at the current
9642
+ * table, not any pin; each row's `entrySeq` locates it against this
9643
+ * bound.
9644
+ */
9645
+ pinnedThroughSeq?: number | undefined;
9572
9646
  }
9573
9647
  /** The machine-readable invoice: rows plus the ledger totals. */
9574
9648
  interface InvoiceExport {
@@ -10483,4 +10557,4 @@ interface SandboxBridge {
10483
10557
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
10484
10558
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
10485
10559
  //#endregion
10486
- 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, 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, 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 };
10560
+ 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, 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 };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createCipheriv, createDecipheriv, createHash, createHmac, getRandomValues, hkdfSync, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
- import { appendFileSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { appendFileSync, closeSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import path, { dirname, join, resolve, sep } from "node:path";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client";
5
5
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
@@ -8080,7 +8080,13 @@ async function reconcileRunMeta(store, runId, opts) {
8080
8080
  *
8081
8081
  * Contract (DEF-4 tightening):
8082
8082
  * - A1 atomicity: a torn trailing line (crash mid-append) is never
8083
- * visible in load; it is dropped and overwritten by the next append.
8083
+ * visible in load; the incomplete fragment is dropped and overwritten
8084
+ * by the next append. Whole records on that line are data, never
8085
+ * fragment (RV701): a crash that persisted every JSON byte but not
8086
+ * the '\n' leaves a parseable tail that load serves and append
8087
+ * terminates before writing, and repair salvages complete records a
8088
+ * glued line carries instead of discarding the line, so an entry a
8089
+ * load has served can never be un-served by a later repair.
8084
8090
  * - A2 total per-run order: load returns append order, stable across
8085
8091
  * calls (the kernel's per-run queue serializes appends).
8086
8092
  * - A3 read-your-writes: append resolves after the line is written.
@@ -8097,6 +8103,62 @@ function safeName(runId) {
8097
8103
  if (!/^[A-Za-z0-9._-]+$/.test(runId)) throw new JournalOrderViolation(`JsonlFileStore: runId '${runId}' is not filesystem-safe ([A-Za-z0-9._-] only)`);
8098
8104
  return runId;
8099
8105
  }
8106
+ /**
8107
+ * Whole JSON values glued on one line, split apart without parser
8108
+ * ambiguity (RV701): depth is tracked outside string literals only, and
8109
+ * every candidate must still round-trip JSON.parse. A line that is not a
8110
+ * clean concatenation from its first byte salvages its whole prefix
8111
+ * values and returns everything after them as the torn fragment, so the
8112
+ * caller keeps accepted records and drops exactly the unacknowledged
8113
+ * tail a crash tore.
8114
+ */
8115
+ function splitConcatenatedJson(line) {
8116
+ const whole = [];
8117
+ let start = 0;
8118
+ let depth = 0;
8119
+ let inString = false;
8120
+ let escaped = false;
8121
+ for (let i = 0; i < line.length; i += 1) {
8122
+ const ch = line[i];
8123
+ if (inString) {
8124
+ if (escaped) escaped = false;
8125
+ else if (ch === "\\") escaped = true;
8126
+ else if (ch === "\"") inString = false;
8127
+ continue;
8128
+ }
8129
+ if (ch === "\"") {
8130
+ inString = true;
8131
+ continue;
8132
+ }
8133
+ if (ch === "{" || ch === "[") {
8134
+ depth += 1;
8135
+ continue;
8136
+ }
8137
+ if (ch === "}" || ch === "]") {
8138
+ depth -= 1;
8139
+ if (depth < 0) return {
8140
+ whole,
8141
+ fragment: line.slice(start)
8142
+ };
8143
+ if (depth === 0) {
8144
+ const candidate = line.slice(start, i + 1);
8145
+ try {
8146
+ whole.push(JSON.parse(candidate));
8147
+ } catch {
8148
+ return {
8149
+ whole,
8150
+ fragment: line.slice(start)
8151
+ };
8152
+ }
8153
+ start = i + 1;
8154
+ }
8155
+ }
8156
+ }
8157
+ return {
8158
+ whole,
8159
+ fragment: line.slice(start)
8160
+ };
8161
+ }
8100
8162
  var JsonlFileStore = class {
8101
8163
  dir;
8102
8164
  /**
@@ -8119,6 +8181,7 @@ var JsonlFileStore = class {
8119
8181
  let tail = this.lastSeq.get(runId);
8120
8182
  if (tail === void 0) {
8121
8183
  const existing = await this.load(runId);
8184
+ this.terminateUnterminatedTail(runId);
8122
8185
  const last = existing[existing.length - 1];
8123
8186
  tail = last !== void 0 && Number.isFinite(last.seq) ? last.seq : Number.NEGATIVE_INFINITY;
8124
8187
  this.lastSeq.set(runId, tail);
@@ -8144,6 +8207,7 @@ var JsonlFileStore = class {
8144
8207
  entries.push(JSON.parse(line));
8145
8208
  } catch (thrown) {
8146
8209
  if (lines.slice(i + 1).every((rest) => rest === "")) {
8210
+ for (const value of splitConcatenatedJson(line).whole) entries.push(value);
8147
8211
  this.repairTornTail(runId, entries);
8148
8212
  break;
8149
8213
  }
@@ -8152,6 +8216,34 @@ var JsonlFileStore = class {
8152
8216
  }
8153
8217
  return entries;
8154
8218
  }
8219
+ /**
8220
+ * Restores the trailing '\n' of a parseable-but-unterminated tail
8221
+ * (RV701). One byte appended in place terminates the record exactly
8222
+ * where the crash left it; the file's bytes before it stay untouched.
8223
+ * No-op on a missing, empty, or already-terminated journal.
8224
+ */
8225
+ terminateUnterminatedTail(runId) {
8226
+ const path = this.journalPath(runId);
8227
+ let fd;
8228
+ try {
8229
+ fd = openSync(path, "r");
8230
+ } catch (thrown) {
8231
+ if (thrown.code === "ENOENT") return;
8232
+ throw thrown;
8233
+ }
8234
+ let needsNewline = false;
8235
+ try {
8236
+ const size = fstatSync(fd).size;
8237
+ if (size > 0) {
8238
+ const lastByte = /* @__PURE__ */ new Uint8Array(1);
8239
+ readSync(fd, lastByte, 0, 1, size - 1);
8240
+ needsNewline = lastByte[0] !== 10;
8241
+ }
8242
+ } finally {
8243
+ closeSync(fd);
8244
+ }
8245
+ if (needsNewline) appendFileSync(path, "\n", "utf8");
8246
+ }
8155
8247
  repairTornTail(runId, whole) {
8156
8248
  const path = this.journalPath(runId);
8157
8249
  const temp = `${path}.tmp`;
@@ -8308,7 +8400,11 @@ function isOrchestratorAccount(scope) {
8308
8400
  * Folds the per-run attribution buckets into the normative CostReport.
8309
8401
  * Live attribution buckets never see abandoned subtrees, so a host
8310
8402
  * that tracked abandoned spend itself passes it as `abandoned`;
8311
- * omitted, the report shows a gross equal to the net.
8403
+ * omitted, the report shows a gross equal to the net. Non-finite
8404
+ * numbers anywhere in the inputs are a typed refusal (RV705): this
8405
+ * exported builder is the same public surface as
8406
+ * {@link costReportFromJournal} and holds the same RV610 doctrine,
8407
+ * instead of letting an Infinity or NaN serialize into null downstream.
8312
8408
  */
8313
8409
  function buildCostReport(attribution, totalUsd, abandoned = {
8314
8410
  usd: 0,
@@ -8322,7 +8418,7 @@ function buildCostReport(attribution, totalUsd, abandoned = {
8322
8418
  forcedFinish: false,
8323
8419
  reserveUsedUsd: 0
8324
8420
  };
8325
- return {
8421
+ const report = {
8326
8422
  totalUsd,
8327
8423
  grossUsd: totalUsd + abandoned.usd,
8328
8424
  abandoned,
@@ -8336,6 +8432,8 @@ function buildCostReport(attribution, totalUsd, abandoned = {
8336
8432
  },
8337
8433
  unpriced: attribution.unpriced
8338
8434
  };
8435
+ requireFiniteNumbersDeep(report, "costReport");
8436
+ return report;
8339
8437
  }
8340
8438
  /**
8341
8439
  * The pure journal fold: the complete CostReport from terminal entries,
@@ -8801,39 +8899,44 @@ function pinnedRows(value) {
8801
8899
  */
8802
8900
  function journalPricingSnapshot(entries) {
8803
8901
  const pins = [];
8804
- let last;
8805
8902
  for (const entry of entries) {
8806
8903
  if (entry?.kind !== "decision") continue;
8807
8904
  const value = entry.value;
8808
8905
  if (value?.decisionType !== "run_settle") continue;
8809
8906
  const rows = pinnedRows(value);
8810
8907
  if (rows === void 0) continue;
8811
- const byModel = new Map(rows.map((row) => [row.model, row.rates]));
8812
8908
  pins.push({
8813
8909
  seq: entry.seq,
8814
- byModel
8815
- });
8816
- last = {
8910
+ byModel: new Map(rows.map((row) => [row.model, row.rates])),
8817
8911
  rows,
8818
- byModel,
8819
8912
  ...typeof value.pricingVersion === "string" ? { pricingVersion: value.pricingVersion } : {}
8820
- };
8913
+ });
8821
8914
  }
8915
+ const last = pins[pins.length - 1];
8822
8916
  if (last === void 0) return;
8823
8917
  const lastByModel = last.byModel;
8918
+ const pinnedThroughSeq = last.seq;
8824
8919
  const ratesFor = (servedBy, seq) => {
8825
8920
  if (seq === void 0) return lastByModel.get(servedBy);
8826
8921
  for (const pin of pins) if (pin.seq > seq) return pin.byModel.get(servedBy) ?? lastByModel.get(servedBy);
8827
8922
  return lastByModel.get(servedBy);
8828
8923
  };
8924
+ const priceUsd = (servedBy, usage, seq) => {
8925
+ const rates = ratesFor(servedBy, seq);
8926
+ return rates === void 0 ? void 0 : priceUsdOf(rates, usage);
8927
+ };
8829
8928
  return {
8830
8929
  ...last.pricingVersion === void 0 ? {} : { pricingVersion: last.pricingVersion },
8831
8930
  rows: last.rows,
8832
- pinnedThroughSeq: pins[pins.length - 1]?.seq ?? 0,
8833
- priceUsd: (servedBy, usage, seq) => {
8834
- const rates = ratesFor(servedBy, seq);
8835
- return rates === void 0 ? void 0 : priceUsdOf(rates, usage);
8836
- }
8931
+ pinnedThroughSeq,
8932
+ segments: pins.map((pin, index) => ({
8933
+ fromSeq: index === 0 ? 0 : pins[index - 1]?.seq ?? 0,
8934
+ settleSeq: pin.seq,
8935
+ ...pin.pricingVersion === void 0 ? {} : { pricingVersion: pin.pricingVersion },
8936
+ rows: pin.rows
8937
+ })),
8938
+ priceUsd,
8939
+ composedPriceUsd: (current) => (servedBy, usage, seq) => seq !== void 0 && seq < pinnedThroughSeq ? priceUsd(servedBy, usage, seq) ?? current(servedBy, usage) : current(servedBy, usage)
8837
8940
  };
8838
8941
  }
8839
8942
  //#endregion
@@ -21154,7 +21257,7 @@ function createEngine(options) {
21154
21257
  }
21155
21258
  const ledger = replayer.ledger();
21156
21259
  const pinned = journalPricingSnapshot(replayer.snapshot());
21157
- const mirrorPriceUsd = (servedBy, usage, seq) => pinned !== void 0 && seq !== void 0 && seq < pinned.pinnedThroughSeq ? pinned.priceUsd(servedBy, usage, seq) ?? priceUsd(servedBy, usage) : priceUsd(servedBy, usage);
21260
+ const mirrorPriceUsd = pinned === void 0 ? (servedBy, usage) => priceUsd(servedBy, usage) : pinned.composedPriceUsd((servedBy, usage) => priceUsd(servedBy, usage));
21158
21261
  const outcome = {
21159
21262
  status,
21160
21263
  dropped: internals.dropped,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.107.0",
3
+ "version": "1.109.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",