@rulvar/core 1.22.0 → 1.23.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
@@ -799,6 +799,18 @@ type RunMeta = {
799
799
  * resumed run to uncapped.
800
800
  */
801
801
  budgetUsd?: number;
802
+ /**
803
+ * Count of execution segments this run has STARTED (a fresh start
804
+ * writes 1; every resume writes prior + 1, durably, BEFORE the
805
+ * segment emits its first event). The engine derives each segment's
806
+ * WorkflowEvent seq and span-id base from it, which is what keeps
807
+ * `seq` strictly increasing and `spanId` unique per run across
808
+ * suspend/resume and process recreation, even after a crash-killed
809
+ * segment (v1.22.0 review P1-2). Stores must round-trip the field
810
+ * (the conformance kit checks); a store that drops it degrades a
811
+ * resumed run's telemetry counters to per-segment, never the journal.
812
+ */
813
+ segments?: number;
802
814
  };
803
815
  type RunFilter = {
804
816
  status?: string;
@@ -4310,7 +4322,14 @@ type AdaptiveEvents = {
4310
4322
  verdict: "admit" | "reuse_full" | "admit_graft";
4311
4323
  agentType: string;
4312
4324
  logicalTaskId: string;
4313
- spawnUnitsAfter: number;
4325
+ /**
4326
+ * Spawn-unit balance after the budget-layer debit. Present on
4327
+ * budget-layer admissions (the orchestrator spawn tools and
4328
+ * ctx.workflow children); absent on lineage-layer admissions
4329
+ * (ctx.agent roots), whose spawn-unit debit rides the dispatch
4330
+ * itself (v1.22.0 review P2-5).
4331
+ */
4332
+ spawnUnitsAfter?: number;
4314
4333
  } | {
4315
4334
  type: "spawn:rejected";
4316
4335
  /**
@@ -5085,7 +5104,14 @@ interface OrchestratorExtensionIO {
5085
5104
  /** Telemetry emission into the run event stream. */
5086
5105
  emit(event: {
5087
5106
  type: string;
5088
- } & Record<string, unknown>): void;
5107
+ } & Record<string, unknown>, options?: {
5108
+ /**
5109
+ * Marks the event as the replay of a journal-recovered decision
5110
+ * (the standard envelope flag), so extension surfaces can emit
5111
+ * recovered admissions honestly (v1.22.0 review P2-5).
5112
+ */
5113
+ replayed?: boolean;
5114
+ }): void;
5089
5115
  }
5090
5116
  /**
5091
5117
  * The extension contract. PlanRunner implements it in @rulvar/plan; the
@@ -6421,12 +6447,31 @@ declare function buildOrchestratorTools(runtime: OrchestratorRuntime, profileCar
6421
6447
  //#endregion
6422
6448
  //#region src/engine/events.d.ts
6423
6449
  /**
6450
+ * The distance between the telemetry counter bases of two consecutive
6451
+ * execution segments of one run: segment k of a run starts its event
6452
+ * `seq` and span counter at `k * EVENT_SEGMENT_STRIDE`. A single
6453
+ * segment would need over four billion events to reach the next base,
6454
+ * so `seq` stays strictly increasing and `spanId` unique across
6455
+ * suspend/resume and process recreation while remaining an ordinary
6456
+ * safe-integer number (v1.22.0 review P1-2). Informational for
6457
+ * consumers: treat `seq` as ordered and `spanId` as opaque, never
6458
+ * parse segment structure out of either.
6459
+ */
6460
+ declare const EVENT_SEGMENT_STRIDE: number;
6461
+ /**
6424
6462
  * Spans form a tree per run; spanId values are engine-minted opaque
6425
6463
  * strings, unique per run, pure telemetry, never identity.
6426
6464
  */
6427
6465
  declare class SpanRegistry {
6428
6466
  private readonly parents;
6429
6467
  private counter;
6468
+ constructor(options?: {
6469
+ /**
6470
+ * First counter value (default 0): the resumed-segment base that
6471
+ * keeps span ids unique per run across segments.
6472
+ */
6473
+ first?: number;
6474
+ });
6430
6475
  mint(parentSpanId?: string): string;
6431
6476
  parentOf(spanId: string): string | undefined;
6432
6477
  }
@@ -6455,14 +6500,25 @@ declare class EventBus {
6455
6500
  * identity by construction, so masking cannot perturb replay.
6456
6501
  */
6457
6502
  maskEvents?: boolean;
6503
+ /**
6504
+ * First seq value (default 0): the resumed-segment base that keeps
6505
+ * seq strictly increasing per run across segments (v1.22.0 review
6506
+ * P1-2).
6507
+ */
6508
+ firstSeq?: number;
6458
6509
  });
6459
6510
  emit(body: WorkflowEventBody, spanId: string, replayed?: boolean): WorkflowEvent;
6460
6511
  /**
6461
6512
  * A throwing on() listener is isolated (its work is best-effort
6462
6513
  * telemetry), and the failure surfaces ONCE as a warn log on this bus
6463
- * rather than propagating into the run. The guard is set before the
6464
- * warn is delivered, so a listener that also throws on the warn cannot
6465
- * re-arm the report or recurse.
6514
+ * rather than propagating into the run. The warn goes through emit()
6515
+ * itself, AFTER the triggering event's fan-out completed: it is
6516
+ * masked exactly like every other event (a secret-shaped fragment of
6517
+ * the listener's error message never reaches observers raw), its seq
6518
+ * is stamped at delivery, and every surface sees [event, warn] in
6519
+ * that order. The guard is set before the recursive emit, so a
6520
+ * listener that also throws on the warn cannot re-arm the report or
6521
+ * recurse (v1.22.0 review P2-1).
6466
6522
  */
6467
6523
  private reportListenerError;
6468
6524
  on<T extends WorkflowEvent["type"]>(type: T, cb: (event: Extract<WorkflowEvent, {
@@ -6535,6 +6591,14 @@ interface SandboxBridge {
6535
6591
  /** Releases the activity token and rejects outstanding thunks. */
6536
6592
  close(): void;
6537
6593
  }
6594
+ /**
6595
+ * The sanctioned JSON subset of AgentOpts a sandbox script may pass:
6596
+ * the planner-dialect allowlist. Exported as the single source both for
6597
+ * the runtime validator below and for the planner API card, so the two
6598
+ * can never drift (v1.22.0 review P2-4: the hand-maintained card had
6599
+ * silently fallen three options behind).
6600
+ */
6601
+ declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
6538
6602
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
6539
6603
  //#endregion
6540
- export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, type AdaptiveEvents, AdmissionController, AdmissionDecision, AdmissionRejectedError, AdmissionStatsBefore, AdmitLineage, AdmitRejectReason, AdmitSpec, AdmitVerdict, AgentCallError, AgentError, type AgentEvents, AgentIdentityInput, AgentOpts, AgentProfile, AgentProfilePermissions, AgentResult, AgentResultMeta, AgentStatus, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, BUDGET_ABORT_REASON, 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, ChildIdentityInput, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, CostReport, CreateEngineOptions, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, 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, DebitResult, DeclaredLadder, DedupIndex, DedupNote, DerivedKey, DeriverRegistry, DispositionRule, DispositionTable, DonorCandidate, DonorRef, DroppedItem, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EffectiveUsageLimits, Effort, Engine, EngineDefaults, EntryKind, EntryRef, EntryStatus, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, InvocationRole, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, 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_DEPTH_CEILING, MatchResult, McpConfig, MechanicalGateProfile, MechanicalGateVerdict, type ModelCaps, ModelChoice, type ModelClaim, ModelEpochInputs, type ModelKnowledgeHandle, type ModelKnowledgeStore, ModelListConstraint, ModelRef, ModelRetry, ModelSpec, Msg, NoProgressDetector, NodeId, NodeLinkValue, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OnEscalation, OperationDisposition, OrchestrateOptions, OrchestratorBudgetSpec, OrchestratorCapConfigError, OrchestratorExtension, OrchestratorExtensionIO, OrchestratorRuntime, Out, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, Part, PendingExternal, PendingToolTurn, PermissionConfig, PermissionGate, PermissionHook, PermissionPreset, PermissionRule, PermissionVerdict, PhaseTarget, PipelineCollected, PipelineOpts, PlanInvariantError, PriceTable, PricedUsage, type Pricing, type PricingTier, type ProviderAdapter, QualityFloors, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RandIdentityInput, RandPayload, RefEntryAppender, RefEntryClassification, RefusalInfo, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunBudget, RunEventSink, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStatus, RuntimeEventSink, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, Semaphore, SerializationHook, Settled, 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, ToolCallRequest, ToolChoice, type ToolContext, ToolContextSeed, ToolContract, type ToolDef, type ToolEvents, type ToolExecutor, 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, atCompactionThreshold, 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, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, readTerminationInit, registryKeyRing, remeasureQueue, replayDisposition, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateSchemaSpec, validateTerminationLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
6604
+ export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, type AdaptiveEvents, AdmissionController, AdmissionDecision, AdmissionRejectedError, AdmissionStatsBefore, AdmitLineage, AdmitRejectReason, AdmitSpec, AdmitVerdict, AgentCallError, AgentError, type AgentEvents, AgentIdentityInput, AgentOpts, AgentProfile, AgentProfilePermissions, AgentResult, AgentResultMeta, AgentStatus, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, BUDGET_ABORT_REASON, 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, ChildIdentityInput, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, CostReport, CreateEngineOptions, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, 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, DebitResult, DeclaredLadder, DedupIndex, DedupNote, DerivedKey, DeriverRegistry, 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, EntryKind, EntryRef, EntryStatus, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, InvocationRole, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, 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_DEPTH_CEILING, MatchResult, McpConfig, MechanicalGateProfile, MechanicalGateVerdict, type ModelCaps, ModelChoice, type ModelClaim, ModelEpochInputs, type ModelKnowledgeHandle, type ModelKnowledgeStore, ModelListConstraint, ModelRef, ModelRetry, ModelSpec, Msg, NoProgressDetector, NodeId, NodeLinkValue, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OnEscalation, OperationDisposition, OrchestrateOptions, OrchestratorBudgetSpec, OrchestratorCapConfigError, OrchestratorExtension, OrchestratorExtensionIO, OrchestratorRuntime, Out, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, Part, PendingExternal, PendingToolTurn, PermissionConfig, PermissionGate, PermissionHook, PermissionPreset, PermissionRule, PermissionVerdict, PhaseTarget, PipelineCollected, PipelineOpts, PlanInvariantError, PriceTable, PricedUsage, type Pricing, type PricingTier, type ProviderAdapter, QualityFloors, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RandIdentityInput, RandPayload, RefEntryAppender, RefEntryClassification, RefusalInfo, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunBudget, RunEventSink, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, Semaphore, SerializationHook, Settled, 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, ToolCallRequest, ToolChoice, type ToolContext, ToolContextSeed, ToolContract, type ToolDef, type ToolEvents, type ToolExecutor, 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, atCompactionThreshold, 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, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, readTerminationInit, registryKeyRing, remeasureQueue, replayDisposition, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateSchemaSpec, validateTerminationLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/dist/index.js CHANGED
@@ -5455,6 +5455,20 @@ var JournalMatcher = class {
5455
5455
  * Full contract: https://docs.rulvar.com/guide/journal; architecture
5456
5456
  * overview: https://docs.rulvar.com/guide/architecture.
5457
5457
  */
5458
+ /**
5459
+ * The ordinal-space map key: one composite per (scope, hashVersion, key).
5460
+ * `U+0000` separators built from escape sequences (never literal control
5461
+ * bytes in source), because scopes and keys are free-form strings and a
5462
+ * printable separator could alias two different pairs. Prior seeding and
5463
+ * mint() MUST both go through this helper: v1.22.0 shipped with two
5464
+ * hand-built variants whose separators differed (an invisible literal
5465
+ * NUL against a space), so resume seeding filled a bucket mint() never
5466
+ * read and every identical live operation after a resume re-minted
5467
+ * ordinal 0, duplicating the identity triple (v1.22.0 review P1-1).
5468
+ */
5469
+ function ordinalMapKey(scope, hashVersion, key) {
5470
+ return `${scope}\u0000${String(hashVersion)}\u0000${key}`;
5471
+ }
5458
5472
  /** Large-value soft warn threshold (committed for M2). */
5459
5473
  const LARGE_VALUE_WARN_BYTES = 262144;
5460
5474
  /**
@@ -5498,9 +5512,9 @@ var Replayer = class {
5498
5512
  this.entries.push(entry);
5499
5513
  if (entry.seq >= this.seq) this.seq = entry.seq + 1;
5500
5514
  if (entry.ref === void 0 && entry.kind !== "resolution" && entry.kind !== "abandon" && entry.hashVersion === 2) {
5501
- const ordinalKey = `${entry.scope} ${entry.hashVersion} ${entry.key}`;
5502
- const next = (this.ordinals.get(ordinalKey) ?? 0) + 1;
5503
- if (entry.ordinal + 1 > next - 1) this.ordinals.set(ordinalKey, entry.ordinal + 1);
5515
+ const ordinalKey = ordinalMapKey(entry.scope, entry.hashVersion, entry.key);
5516
+ const current = this.ordinals.get(ordinalKey) ?? 0;
5517
+ if (entry.ordinal + 1 > current) this.ordinals.set(ordinalKey, entry.ordinal + 1);
5504
5518
  }
5505
5519
  }
5506
5520
  }
@@ -5744,7 +5758,7 @@ var Replayer = class {
5744
5758
  await this.queue;
5745
5759
  }
5746
5760
  mint(scope, key, kind, status) {
5747
- const ordinalKey = `${scope}2${key}`;
5761
+ const ordinalKey = ordinalMapKey(scope, 2, key);
5748
5762
  const ordinal = this.ordinals.get(ordinalKey) ?? 0;
5749
5763
  this.ordinals.set(ordinalKey, ordinal + 1);
5750
5764
  const entry = {
@@ -5925,7 +5939,7 @@ var ExternalRegistry = class ExternalRegistry {
5925
5939
  * until a resolution wins the first-closing-wins fold.
5926
5940
  */
5927
5941
  async awaitExternal(scope, spanId, key, options) {
5928
- const scopeKey = `${scope}${key}`;
5942
+ const scopeKey = `${scope}\u0000${key}`;
5929
5943
  if (this.keysByScope.has(scopeKey)) throw new ConfigError(`duplicate awaitExternal key '${key}' in scope '${scope}'`);
5930
5944
  this.keysByScope.add(scopeKey);
5931
5945
  const identity = {
@@ -8242,7 +8256,7 @@ async function runAgent(options) {
8242
8256
  const primaryRole = options.role ?? "loop";
8243
8257
  const usageByPhaseModel = /* @__PURE__ */ new Map();
8244
8258
  const addPhaseUsage = (role, ref, usage) => {
8245
- const key = `${role}${ref}`;
8259
+ const key = `${role}\u0000${ref}`;
8246
8260
  const prior = usageByPhaseModel.get(key);
8247
8261
  usageByPhaseModel.set(key, {
8248
8262
  role,
@@ -10364,6 +10378,26 @@ function runtimeOf(ctx) {
10364
10378
  return runtime;
10365
10379
  }
10366
10380
  //#endregion
10381
+ //#region src/engine/spawn-events.ts
10382
+ function emitSpawnAdmitted(events, input) {
10383
+ events.emit({
10384
+ type: "spawn:admitted",
10385
+ entryRef: input.entryRef,
10386
+ verdict: input.verdict,
10387
+ agentType: input.agentType,
10388
+ logicalTaskId: input.logicalTaskId,
10389
+ ...input.spawnUnitsAfter === void 0 ? {} : { spawnUnitsAfter: input.spawnUnitsAfter }
10390
+ }, input.spanId, input.replayed);
10391
+ }
10392
+ function emitSpawnRejected(events, input) {
10393
+ events.emit({
10394
+ type: "spawn:rejected",
10395
+ ...input.entryRef === void 0 ? {} : { entryRef: input.entryRef },
10396
+ code: input.code,
10397
+ agentType: input.agentType
10398
+ }, input.spanId, input.replayed);
10399
+ }
10400
+ //#endregion
10367
10401
  //#region src/engine/ctx.ts
10368
10402
  /**
10369
10403
  * Ctx primitives (M1-T07) plus the parallel/pipeline composition semantics
@@ -10899,14 +10933,23 @@ function createCtx(internals, rootWorkflow) {
10899
10933
  claimed.add(prior.seq);
10900
10934
  const recorded = prior.value;
10901
10935
  if (recorded.reject !== void 0) {
10902
- internals.events.emit({
10903
- type: "spawn:rejected",
10936
+ emitSpawnRejected(internals.events, {
10904
10937
  entryRef: prior.seq,
10905
10938
  code: recorded.reject.code,
10906
- agentType
10907
- }, state.spanId, true);
10939
+ agentType,
10940
+ spanId: state.spanId,
10941
+ replayed: true
10942
+ });
10908
10943
  throw new AdmissionRejectedError(`lineage admission rejected agent spawn (${recorded.reject.code}; recorded verdict)`, { data: { reason: recorded.reject } });
10909
10944
  }
10945
+ emitSpawnAdmitted(internals.events, {
10946
+ entryRef: prior.seq,
10947
+ verdict: "admit",
10948
+ agentType,
10949
+ logicalTaskId: recorded.lineage?.logicalTaskId ?? "unknown",
10950
+ spanId: state.spanId,
10951
+ replayed: true
10952
+ });
10910
10953
  } else {
10911
10954
  const evaluated = admission.evaluateLineage({
10912
10955
  name: agentType,
@@ -10938,15 +10981,22 @@ function createCtx(internals, rootWorkflow) {
10938
10981
  value: decisionValue
10939
10982
  });
10940
10983
  if (evaluated.decision.kind === "reject") {
10941
- internals.events.emit({
10942
- type: "spawn:rejected",
10984
+ emitSpawnRejected(internals.events, {
10943
10985
  entryRef: decisionEntry.seq,
10944
10986
  code: evaluated.decision.reason.code,
10945
- agentType
10946
- }, state.spanId);
10987
+ agentType,
10988
+ spanId: state.spanId
10989
+ });
10947
10990
  throw new AdmissionRejectedError(`lineage admission rejected agent spawn (${evaluated.decision.reason.code})`, { data: { reason: evaluated.decision.reason } });
10948
10991
  }
10949
10992
  admission.registerLineageAdmit(evaluated.decision.lineage.logicalTaskId);
10993
+ emitSpawnAdmitted(internals.events, {
10994
+ entryRef: decisionEntry.seq,
10995
+ verdict: "admit",
10996
+ agentType,
10997
+ logicalTaskId: evaluated.decision.lineage.logicalTaskId,
10998
+ spanId: state.spanId
10999
+ });
10950
11000
  }
10951
11001
  }
10952
11002
  const adapter = adapterOf(loopResolved);
@@ -11506,7 +11556,7 @@ function createCtx(internals, rootWorkflow) {
11506
11556
  */
11507
11557
  const workflowOrdinals = /* @__PURE__ */ new Map();
11508
11558
  const nextWorkflowOrdinal = (scope, name) => {
11509
- const counterKey = `${scope}${name}`;
11559
+ const counterKey = `${scope}\u0000${name}`;
11510
11560
  const ordinal = workflowOrdinals.get(counterKey) ?? 0;
11511
11561
  workflowOrdinals.set(counterKey, ordinal + 1);
11512
11562
  return ordinal;
@@ -11587,8 +11637,12 @@ function createCtx(internals, rootWorkflow) {
11587
11637
  return value?.decisionType === "spawn-admission" && value.childScope === childScope;
11588
11638
  });
11589
11639
  let verdict;
11640
+ let decisionEntrySeq;
11641
+ let decisionReplayed = false;
11590
11642
  if (prior !== void 0) {
11591
11643
  verdict = prior.value.decision.verdict;
11644
+ decisionEntrySeq = prior.seq;
11645
+ decisionReplayed = true;
11592
11646
  if (verdict.kind !== "reject") admission.recoverInFlight(budgetAccount, verdict);
11593
11647
  } else {
11594
11648
  const decision = admission.admit({
@@ -11604,7 +11658,7 @@ function createCtx(internals, rootWorkflow) {
11604
11658
  }
11605
11659
  });
11606
11660
  verdict = decision.verdict;
11607
- await internals.replayer.appendSinglePhase({
11661
+ decisionEntrySeq = (await internals.replayer.appendSinglePhase({
11608
11662
  scope: state.scope,
11609
11663
  key: "",
11610
11664
  kind: "decision",
@@ -11618,10 +11672,28 @@ function createCtx(internals, rootWorkflow) {
11618
11672
  parentAccountScope: budgetAccount,
11619
11673
  decision
11620
11674
  }
11675
+ })).seq;
11676
+ }
11677
+ if (verdict.kind === "reject") {
11678
+ emitSpawnRejected(internals.events, {
11679
+ entryRef: decisionEntrySeq,
11680
+ code: verdict.reason.code,
11681
+ agentType: name,
11682
+ spanId,
11683
+ replayed: decisionReplayed ? true : void 0
11621
11684
  });
11685
+ throw rejectionError(verdict.reason, name);
11622
11686
  }
11623
- if (verdict.kind === "reject") throw rejectionError(verdict.reason, name);
11624
11687
  if (verdict.kind !== "admit") throw new ConfigError(`admission verdict '${verdict.kind}' has no producer before M7 (DEF-5)`);
11688
+ emitSpawnAdmitted(internals.events, {
11689
+ entryRef: decisionEntrySeq,
11690
+ verdict: verdict.kind,
11691
+ agentType: name,
11692
+ logicalTaskId: verdict.lineage.logicalTaskId,
11693
+ spawnUnitsAfter: verdict.spawnUnitsAfter,
11694
+ spanId,
11695
+ replayed: decisionReplayed ? true : void 0
11696
+ });
11625
11697
  const reserve = verdict.reserve;
11626
11698
  const openOptions = { parentScope: budgetAccount };
11627
11699
  if (reserve.childCeilingUsd !== void 0) {
@@ -12152,7 +12224,7 @@ function makeOrchestratorWorkflow(goal, opts) {
12152
12224
  },
12153
12225
  registerAlias: (donorScope, targetScope) => internals.replayer.registerAlias(donorScope, targetScope),
12154
12226
  priceUsd: (servedBy, usage) => servedBy === void 0 ? void 0 : internals.priceUsd(servedBy, usage),
12155
- emit: (event) => internals.events.emit(event, callingState.spanId)
12227
+ emit: (event, options) => internals.events.emit(event, callingState.spanId, options?.replayed)
12156
12228
  };
12157
12229
  const cancelByHandle = async (handle, _reason) => {
12158
12230
  const record = records.get(handle);
@@ -12196,15 +12268,31 @@ function makeOrchestratorWorkflow(goal, opts) {
12196
12268
  if (entry.kind !== "decision" || entry.scope !== callingState.scope) return false;
12197
12269
  const value = entry.value;
12198
12270
  return value?.decisionType === "spawn-admission" && (value.origin === "spawn_agent" || value.origin === "parallel_agents");
12199
- }).map((entry) => entry.value).sort((a, b) => a.spawnOrdinal - b.spawnOrdinal);
12200
- for (const value of admissions) {
12271
+ }).map((entry) => ({
12272
+ entrySeq: entry.seq,
12273
+ value: entry.value
12274
+ })).sort((a, b) => a.value.spawnOrdinal - b.value.spawnOrdinal);
12275
+ for (const { entrySeq, value } of admissions) {
12201
12276
  nextOrdinal = Math.max(nextOrdinal, value.spawnOrdinal + 1);
12202
12277
  const decision = value.decision;
12203
12278
  recoveredSpecByOrdinal.set(value.spawnOrdinal, value.spec);
12279
+ const recoveredAgentType = value.spec?.agentType ?? "unknown";
12204
12280
  if (decision.verdict.kind !== "admit") {
12205
- rejectedByOrdinal.set(value.spawnOrdinal, decision);
12281
+ rejectedByOrdinal.set(value.spawnOrdinal, {
12282
+ decision,
12283
+ entrySeq
12284
+ });
12206
12285
  continue;
12207
12286
  }
12287
+ emitSpawnAdmitted(internals.events, {
12288
+ entryRef: entrySeq,
12289
+ verdict: decision.verdict.kind,
12290
+ agentType: recoveredAgentType,
12291
+ logicalTaskId: decision.verdict.lineage.logicalTaskId,
12292
+ spawnUnitsAfter: decision.verdict.spawnUnitsAfter,
12293
+ spanId: callingState.spanId,
12294
+ replayed: true
12295
+ });
12208
12296
  admission.recoverChild(currentScope);
12209
12297
  const childScope = value.childScope ?? value.orchestratorScope;
12210
12298
  const record = await dispatchChild(value.spec, value.spawnOrdinal, {
@@ -12355,7 +12443,17 @@ function makeOrchestratorWorkflow(goal, opts) {
12355
12443
  const recovered = byOrdinal.get(spawnOrdinal);
12356
12444
  if (recovered !== void 0 && specMatches) return { handle: recovered.handle };
12357
12445
  const recoveredRejection = rejectedByOrdinal.get(spawnOrdinal);
12358
- if (recoveredRejection !== void 0 && specMatches) throw new AdmissionRejectedError(`admission rejected spawn ordinal ${String(spawnOrdinal)} (recovered verdict)`, { data: { decision: recoveredRejection } });
12446
+ if (recoveredRejection !== void 0 && specMatches) {
12447
+ const reason = recoveredRejection.decision.verdict;
12448
+ emitSpawnRejected(internals.events, {
12449
+ entryRef: recoveredRejection.entrySeq,
12450
+ code: reason.reason?.code ?? "unknown",
12451
+ agentType: params.agentType,
12452
+ spanId: callingState.spanId,
12453
+ replayed: true
12454
+ });
12455
+ throw new AdmissionRejectedError(`admission rejected spawn ordinal ${String(spawnOrdinal)} (recovered verdict)`, { data: { decision: recoveredRejection.decision } });
12456
+ }
12359
12457
  if (opts?.maxSpawns !== void 0 && spawnOrdinal >= opts.maxSpawns) {
12360
12458
  internals.events.emit({
12361
12459
  type: "spawn:rejected",
@@ -12407,24 +12505,27 @@ function makeOrchestratorWorkflow(goal, opts) {
12407
12505
  value: admissionValue
12408
12506
  });
12409
12507
  if (decision.verdict.kind === "reject") {
12410
- rejectedByOrdinal.set(spawnOrdinal, decision);
12411
- internals.events.emit({
12412
- type: "spawn:rejected",
12508
+ rejectedByOrdinal.set(spawnOrdinal, {
12509
+ decision,
12510
+ entrySeq: decisionEntry.seq
12511
+ });
12512
+ emitSpawnRejected(internals.events, {
12413
12513
  entryRef: decisionEntry.seq,
12414
12514
  code: decision.verdict.reason.code,
12415
- agentType: params.agentType
12416
- }, callingState.spanId);
12515
+ agentType: params.agentType,
12516
+ spanId: callingState.spanId
12517
+ });
12417
12518
  throw new AdmissionRejectedError(`admission rejected spawn_agent '${params.agentType}' (${decision.verdict.reason.code})`, { data: { reason: decision.verdict.reason } });
12418
12519
  }
12419
12520
  if (decision.verdict.kind !== "admit") throw new ConfigError(`admission verdict '${decision.verdict.kind}' has no producer before M7 (DEF-5)`);
12420
- internals.events.emit({
12421
- type: "spawn:admitted",
12521
+ emitSpawnAdmitted(internals.events, {
12422
12522
  entryRef: decisionEntry.seq,
12423
12523
  verdict: decision.verdict.kind,
12424
12524
  agentType: params.agentType,
12425
12525
  logicalTaskId: decision.verdict.lineage.logicalTaskId,
12426
- spawnUnitsAfter: decision.verdict.spawnUnitsAfter
12427
- }, callingState.spanId);
12526
+ spawnUnitsAfter: decision.verdict.spawnUnitsAfter,
12527
+ spanId: callingState.spanId
12528
+ });
12428
12529
  return { handle: (await dispatchChild(params, spawnOrdinal, {
12429
12530
  nodeId: decision.nodeId ?? "unknown",
12430
12531
  logicalTaskId: decision.verdict.lineage.logicalTaskId
@@ -12727,12 +12828,27 @@ function orchestrate(engine, goal, opts, runOptions) {
12727
12828
  * Full contract: https://docs.rulvar.com/guide/observability.
12728
12829
  */
12729
12830
  /**
12831
+ * The distance between the telemetry counter bases of two consecutive
12832
+ * execution segments of one run: segment k of a run starts its event
12833
+ * `seq` and span counter at `k * EVENT_SEGMENT_STRIDE`. A single
12834
+ * segment would need over four billion events to reach the next base,
12835
+ * so `seq` stays strictly increasing and `spanId` unique across
12836
+ * suspend/resume and process recreation while remaining an ordinary
12837
+ * safe-integer number (v1.22.0 review P1-2). Informational for
12838
+ * consumers: treat `seq` as ordered and `spanId` as opaque, never
12839
+ * parse segment structure out of either.
12840
+ */
12841
+ const EVENT_SEGMENT_STRIDE = 2 ** 32;
12842
+ /**
12730
12843
  * Spans form a tree per run; spanId values are engine-minted opaque
12731
12844
  * strings, unique per run, pure telemetry, never identity.
12732
12845
  */
12733
12846
  var SpanRegistry = class {
12734
12847
  parents = /* @__PURE__ */ new Map();
12735
- counter = 0;
12848
+ counter;
12849
+ constructor(options) {
12850
+ this.counter = options?.first ?? 0;
12851
+ }
12736
12852
  mint(parentSpanId) {
12737
12853
  const spanId = `s${this.counter++}`;
12738
12854
  if (parentSpanId !== void 0) this.parents.set(spanId, parentSpanId);
@@ -12754,7 +12870,7 @@ var EventBus = class {
12754
12870
  maskEvents;
12755
12871
  subscribers = /* @__PURE__ */ new Set();
12756
12872
  listeners = /* @__PURE__ */ new Set();
12757
- seq = 0;
12873
+ seq;
12758
12874
  ended = false;
12759
12875
  listenerErrorReported = false;
12760
12876
  constructor(options) {
@@ -12762,6 +12878,7 @@ var EventBus = class {
12762
12878
  this.spans = options.spans;
12763
12879
  this.now = options.now ?? realNow;
12764
12880
  this.maskEvents = options.maskEvents ?? true;
12881
+ this.seq = options.firstSeq ?? 0;
12765
12882
  }
12766
12883
  emit(body, spanId, replayed) {
12767
12884
  const parentSpanId = this.spans.parentOf(spanId);
@@ -12775,39 +12892,40 @@ var EventBus = class {
12775
12892
  ...replayed === true ? { replayed: true } : {},
12776
12893
  ...safeBody
12777
12894
  };
12895
+ let listenerFailure;
12896
+ let sawListenerFailure = false;
12778
12897
  for (const listener of this.listeners) try {
12779
12898
  listener(event);
12780
12899
  } catch (thrown) {
12781
- this.reportListenerError(thrown, spanId);
12900
+ if (!sawListenerFailure) {
12901
+ sawListenerFailure = true;
12902
+ listenerFailure = thrown;
12903
+ }
12782
12904
  }
12783
12905
  for (const subscriber of this.subscribers) subscriber.push(event);
12906
+ if (sawListenerFailure) this.reportListenerError(listenerFailure, spanId);
12784
12907
  return event;
12785
12908
  }
12786
12909
  /**
12787
12910
  * A throwing on() listener is isolated (its work is best-effort
12788
12911
  * telemetry), and the failure surfaces ONCE as a warn log on this bus
12789
- * rather than propagating into the run. The guard is set before the
12790
- * warn is delivered, so a listener that also throws on the warn cannot
12791
- * re-arm the report or recurse.
12912
+ * rather than propagating into the run. The warn goes through emit()
12913
+ * itself, AFTER the triggering event's fan-out completed: it is
12914
+ * masked exactly like every other event (a secret-shaped fragment of
12915
+ * the listener's error message never reaches observers raw), its seq
12916
+ * is stamped at delivery, and every surface sees [event, warn] in
12917
+ * that order. The guard is set before the recursive emit, so a
12918
+ * listener that also throws on the warn cannot re-arm the report or
12919
+ * recurse (v1.22.0 review P2-1).
12792
12920
  */
12793
12921
  reportListenerError(thrown, spanId) {
12794
12922
  if (this.listenerErrorReported) return;
12795
12923
  this.listenerErrorReported = true;
12796
- const parentSpanId = this.spans.parentOf(spanId);
12797
- const warn = {
12798
- runId: this.runId,
12799
- seq: this.seq++,
12800
- ts: new Date(this.now()).toISOString(),
12801
- spanId,
12802
- ...parentSpanId === void 0 ? {} : { parentSpanId },
12924
+ this.emit({
12803
12925
  type: "log",
12804
12926
  level: "warn",
12805
12927
  msg: "an event listener threw and was isolated so the run is unaffected: " + (thrown instanceof Error ? thrown.message : String(thrown))
12806
- };
12807
- for (const listener of this.listeners) try {
12808
- listener(warn);
12809
- } catch {}
12810
- for (const subscriber of this.subscribers) subscriber.push(warn);
12928
+ }, spanId);
12811
12929
  }
12812
12930
  on(type, cb) {
12813
12931
  const listener = (event) => {
@@ -13012,12 +13130,15 @@ function createEngine(options) {
13012
13130
  if (compiled !== void 0 && options.runners?.sandbox === void 0) throw new ConfigError("running a CompiledWorkflow requires a sandbox runner: pass createEngine({ runners: { sandbox: new WorkerSandboxRunner() } }) from @rulvar/planner ");
13013
13131
  const runId = resumeCtx?.runId ?? opts?.runId ?? mintRunId();
13014
13132
  const registry = buildDeriverRegistry(options.extraDerivers);
13015
- const spans = new SpanRegistry();
13133
+ const segmentsBefore = resumeCtx?.segmentsBefore ?? 0;
13134
+ const telemetryBase = segmentsBefore * EVENT_SEGMENT_STRIDE;
13135
+ const spans = new SpanRegistry({ first: telemetryBase });
13016
13136
  const bus = new EventBus({
13017
13137
  runId,
13018
13138
  spans,
13019
13139
  now: realNow,
13020
- maskEvents
13140
+ maskEvents,
13141
+ firstSeq: telemetryBase
13021
13142
  });
13022
13143
  const rootSpanId = spans.mint();
13023
13144
  let budgetSeed;
@@ -13096,7 +13217,7 @@ function createEngine(options) {
13096
13217
  ...options.budgetDefaults?.flatReserveUsd === void 0 ? {} : { flatReserveUsd: options.budgetDefaults.flatReserveUsd },
13097
13218
  ...defaults.roleFloors === void 0 ? {} : { floors: defaults.roleFloors },
13098
13219
  ...knowledge === void 0 ? {} : { knowledge },
13099
- events: { emit: (body, spanId) => bus.emit(body, spanId ?? rootSpanId) },
13220
+ events: { emit: (body, spanId, replayed) => bus.emit(body, spanId ?? rootSpanId, replayed) },
13100
13221
  spans,
13101
13222
  rootSpanId,
13102
13223
  transcripts,
@@ -13142,6 +13263,7 @@ function createEngine(options) {
13142
13263
  const putMeta = (status) => journal.putMeta({
13143
13264
  runId,
13144
13265
  status,
13266
+ segments: segmentsBefore + 1,
13145
13267
  updatedAt: new Date(realNow()).toISOString(),
13146
13268
  ...opts?.name === void 0 ? {} : { name: opts.name },
13147
13269
  ...opts?.tags === void 0 ? {} : { tags: opts.tags },
@@ -13329,6 +13451,7 @@ function createEngine(options) {
13329
13451
  invalidate: resumeOptions?.invalidate ?? [],
13330
13452
  ...resumeOptions?.lease === void 0 ? {} : { lease: resumeOptions.lease },
13331
13453
  ...typeof meta?.budgetUsd === "number" ? { budgetUsd: meta.budgetUsd } : {},
13454
+ segmentsBefore: typeof meta?.segments === "number" && meta.segments > 0 ? Math.floor(meta.segments) : 1,
13332
13455
  previewResolve
13333
13456
  });
13334
13457
  })();
@@ -13427,8 +13550,14 @@ function createEngine(options) {
13427
13550
  * exactly like an in-process one (the token is re-acquired BEFORE any
13428
13551
  * response is posted, closing the wake latency gap).
13429
13552
  */
13430
- /** The sanctioned JSON subset of AgentOpts a sandbox script may pass. */
13431
- const SANDBOX_AGENT_OPT_KEYS = /* @__PURE__ */ new Set([
13553
+ /**
13554
+ * The sanctioned JSON subset of AgentOpts a sandbox script may pass:
13555
+ * the planner-dialect allowlist. Exported as the single source both for
13556
+ * the runtime validator below and for the planner API card, so the two
13557
+ * can never drift (v1.22.0 review P2-4: the hand-maintained card had
13558
+ * silently fallen three options behind).
13559
+ */
13560
+ const SANDBOX_AGENT_OPT_KEYS = [
13432
13561
  "agentType",
13433
13562
  "model",
13434
13563
  "effort",
@@ -13445,7 +13574,8 @@ const SANDBOX_AGENT_OPT_KEYS = /* @__PURE__ */ new Set([
13445
13574
  "escalation",
13446
13575
  "fallback",
13447
13576
  "replay"
13448
- ]);
13577
+ ];
13578
+ const SANDBOX_AGENT_OPT_KEY_SET = new Set(SANDBOX_AGENT_OPT_KEYS);
13449
13579
  function asRecord(value, what) {
13450
13580
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ConfigError(`sandbox call ${what} must be a JSON object`);
13451
13581
  return value;
@@ -13519,7 +13649,7 @@ function createSandboxBridge(ctx, options) {
13519
13649
  const record = asRecord(params, "agent params");
13520
13650
  if (typeof record.prompt !== "string") throw new ConfigError("sandbox agent call requires a string prompt");
13521
13651
  const rawOpts = record.opts === void 0 ? {} : asRecord(record.opts, "agent options");
13522
- for (const key of Object.keys(rawOpts)) if (!SANDBOX_AGENT_OPT_KEYS.has(key)) throw new ConfigError(`sandbox agent option '${key}' is outside the sanctioned dialect; allowed: ` + [...SANDBOX_AGENT_OPT_KEYS].sort().join(", "));
13652
+ for (const key of Object.keys(rawOpts)) if (!SANDBOX_AGENT_OPT_KEY_SET.has(key)) throw new ConfigError(`sandbox agent option '${key}' is outside the sanctioned dialect; allowed: ` + [...SANDBOX_AGENT_OPT_KEYS].sort().join(", "));
13523
13653
  if (rawOpts.tools !== void 0) {
13524
13654
  const tools = rawOpts.tools;
13525
13655
  if (!(Array.isArray(tools) && tools.every((v) => typeof v === "string"))) throw new ConfigError("sandbox agent tools must be registered profile NAMES");
@@ -13682,4 +13812,4 @@ function createSandboxBridge(ctx, options) {
13682
13812
  };
13683
13813
  }
13684
13814
  //#endregion
13685
- export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, 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, DedupIndex, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FileModelKnowledgeStore, FileTranscriptStore, GitWorktreeProvider, INBOX_PROPOSAL_TTL_DAYS, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, 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_DEPTH_CEILING, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, PlanInvariantError, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, atCompactionThreshold, 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, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, readTerminationInit, registryKeyRing, remeasureQueue, replayDisposition, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateSchemaSpec, validateTerminationLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
13815
+ export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, 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, DedupIndex, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FileModelKnowledgeStore, FileTranscriptStore, GitWorktreeProvider, INBOX_PROPOSAL_TTL_DAYS, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, 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_DEPTH_CEILING, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, PlanInvariantError, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, atCompactionThreshold, 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, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, readTerminationInit, registryKeyRing, remeasureQueue, replayDisposition, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateSchemaSpec, validateTerminationLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.22.0",
3
+ "version": "1.23.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",