@rulvar/core 1.47.0 → 1.49.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
@@ -3088,6 +3088,13 @@ interface AgentResult<T> {
3088
3088
  * cancellation or ordinary cap hits.
3089
3089
  */
3090
3090
  abortClass?: AbortClass;
3091
+ /**
3092
+ * Transport retries across the span's phase activations, present only
3093
+ * when greater than zero. Live telemetry only: the ctx layer surfaces
3094
+ * it as `agent:end` retryCount; it is never journaled, so a replayed
3095
+ * result omits it (absent means "zero or unknown").
3096
+ */
3097
+ transportRetries?: number;
3091
3098
  }
3092
3099
  type EscalatedResult<T> = AgentResult<T> & {
3093
3100
  status: "escalated";
@@ -4408,7 +4415,19 @@ type CoreEvents = {
4408
4415
  scope: string;
4409
4416
  status: string;
4410
4417
  };
4411
- /** Agent lifecycle. */
4418
+ /**
4419
+ * Agent lifecycle. One logical agent dispatch emits EXACTLY ONE
4420
+ * `agent:start`/`agent:end` pair on its span (the start carries the
4421
+ * primary role), and each model invocation phase inside the span
4422
+ * (`loop`, then possibly `summarize` activations, `finalize`,
4423
+ * `extract`) emits its own `agent:phase:start`/`agent:phase:end` pair,
4424
+ * so durations, per-phase usage, and attempts are derivable without
4425
+ * heuristics (the RV-207 event-model contract; before it, every phase
4426
+ * emitted an unpaired extra `agent:start` and consumers pairing starts
4427
+ * with the single end computed the LAST phase's duration as the
4428
+ * agent's). `reduceInvocationTable` is the official reducer over this
4429
+ * vocabulary.
4430
+ */
4412
4431
  type AgentEvents = {
4413
4432
  type: "agent:queued";
4414
4433
  agentType: string;
@@ -4419,6 +4438,39 @@ type AgentEvents = {
4419
4438
  label?: string;
4420
4439
  model: string;
4421
4440
  role: string;
4441
+ } | {
4442
+ type: "agent:phase:start";
4443
+ agentType: string;
4444
+ label?: string; /** The invocation role this phase activation runs as. */
4445
+ role: string; /** The model the activation resolved to (fallbacks may serve another; the end event reports the server). */
4446
+ model: string;
4447
+ /**
4448
+ * 1-based activation ordinal within the span, unique per
4449
+ * activation (a summarize that fires three times gets three
4450
+ * pairs). Key phases by (spanId, invocation).
4451
+ */
4452
+ invocation: number;
4453
+ } | {
4454
+ type: "agent:phase:end";
4455
+ agentType: string;
4456
+ label?: string;
4457
+ role: string; /** The model that actually served the activation's last attempt. */
4458
+ model: string;
4459
+ invocation: number;
4460
+ /**
4461
+ * Wall-clock activation duration. Live telemetry only: replayed
4462
+ * phase pairs (reconstructed from the terminal entry's usage
4463
+ * slices) carry 0.
4464
+ */
4465
+ durationMs: number; /** The usage this activation added to its (role, model) slices. */
4466
+ usage: Usage; /** That usage priced at each serving model's own rate. */
4467
+ costUsd: number;
4468
+ outcome: "ok" | "error";
4469
+ /**
4470
+ * Transport retries inside this activation. Present only when
4471
+ * greater than zero; live telemetry only (absent on replay).
4472
+ */
4473
+ retries?: number;
4422
4474
  } | {
4423
4475
  type: "agent:end";
4424
4476
  agentType: string;
@@ -4435,6 +4487,13 @@ type AgentEvents = {
4435
4487
  * terminal journal entry's usageApprox.
4436
4488
  */
4437
4489
  usageApprox?: boolean;
4490
+ /**
4491
+ * Total transport retries across the span's activations. Present
4492
+ * only when greater than zero; live telemetry only, never
4493
+ * journaled, so a replayed agent:end omits it (absent means "zero
4494
+ * or unknown").
4495
+ */
4496
+ retryCount?: number;
4438
4497
  } | {
4439
4498
  type: "agent:error";
4440
4499
  agentType: string;
@@ -7300,6 +7359,58 @@ declare class EventBus {
7300
7359
  iterate(): AsyncIterable<WorkflowEvent>;
7301
7360
  }
7302
7361
  //#endregion
7362
+ //#region src/l0/telemetry-reduce.d.ts
7363
+ /** One phase activation of one agent span. */
7364
+ interface PhaseRow {
7365
+ invocation: number;
7366
+ role: string;
7367
+ model: string;
7368
+ /** 0 until the end event arrives, and on replayed rows. */
7369
+ durationMs: number;
7370
+ usage: Usage;
7371
+ costUsd: number;
7372
+ outcome?: "ok" | "error";
7373
+ retries: number;
7374
+ replayed: boolean;
7375
+ /** True when the phase's end event never arrived. */
7376
+ open: boolean;
7377
+ }
7378
+ /** One logical agent span. */
7379
+ interface AgentInvocationRow {
7380
+ spanId: string;
7381
+ agentType: string;
7382
+ label?: string;
7383
+ /** The primary role from agent:start. */
7384
+ role?: string;
7385
+ /** From agent:end; absent while the span is open. */
7386
+ status?: string;
7387
+ usage: Usage;
7388
+ costUsd: number;
7389
+ usageApprox: boolean;
7390
+ retryCount: number;
7391
+ replayed: boolean;
7392
+ /** True when the span's agent:end never arrived. */
7393
+ open: boolean;
7394
+ phases: PhaseRow[];
7395
+ }
7396
+ /** The reduced table plus the per-role aggregate across every span. */
7397
+ interface InvocationTable {
7398
+ agents: AgentInvocationRow[];
7399
+ /** Aggregated over COMPLETED phase pairs, keyed by role. */
7400
+ byRole: Record<string, {
7401
+ usage: Usage;
7402
+ costUsd: number;
7403
+ }>;
7404
+ /** Sum of agent:end costUsd over settled spans. */
7405
+ totalCostUsd: number;
7406
+ }
7407
+ /**
7408
+ * Reduces one run's event stream (or any slice of it) to the invocation
7409
+ * table. Feed it the events in emission order; both a live stream and a
7410
+ * replayed one produce the same usage and cost columns.
7411
+ */
7412
+ declare function reduceInvocationTable(events: Iterable<WorkflowEvent>): InvocationTable;
7413
+ //#endregion
7303
7414
  //#region src/runner/sandbox-bridge.d.ts
7304
7415
  /** Methods a sandbox script may proxy to the host ctx. */
7305
7416
  type SandboxMethod = "agent" | "step" | "workflow" | "awaitExternal" | "parallel" | "pipeline" | "phase" | "budget.spent" | "budget.remaining";
@@ -7372,4 +7483,4 @@ interface SandboxBridge {
7372
7483
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
7373
7484
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
7374
7485
  //#endregion
7375
- 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, 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, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, 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, 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, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, FinishValidationChild, FinishValidationInput, FinishValidationSpec, FinishValidationVerdict, FinishValidator, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, 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_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, MatchResult, McpConfig, McpToolSource, MechanicalGateProfile, MechanicalGateVerdict, 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, 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, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, RandIdentityInput, RandPayload, ReconcileOptions, ReconcileResult, 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, RunAuditVerdict, RunBudget, RunEventSink, 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, 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, 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, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, 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, readRunMeta, readTerminationInit, reconcileRunMeta, registryKeyRing, remeasureQueue, replayDisposition, requiredFieldsValidator, requiredSectionsValidator, 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, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
7486
+ 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, AgentResult, AgentResultMeta, AgentStatus, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, 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, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, 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, 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, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, FinishValidationChild, FinishValidationInput, FinishValidationSpec, FinishValidationVerdict, FinishValidator, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, InvocationRole, type InvocationTable, 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_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, MatchResult, McpConfig, McpToolSource, MechanicalGateProfile, MechanicalGateVerdict, 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, OrchestratorBudgetSpec, OrchestratorCapConfigError, OrchestratorExtension, OrchestratorExtensionIO, OrchestratorRuntime, Out, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, Part, PendingExternal, PendingToolTurn, PermissionConfig, PermissionGate, PermissionHook, PermissionPreset, PermissionRule, PermissionVerdict, type PhaseRow, PhaseTarget, PipelineCollected, PipelineOpts, PlanInvariantError, PriceTable, PricedUsage, type Pricing, type PricingTier, type ProviderAdapter, QualityFloors, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, RandIdentityInput, RandPayload, ReconcileOptions, ReconcileResult, 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, RunAuditVerdict, RunBudget, RunEventSink, 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, 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, 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, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, 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, readRunMeta, readTerminationInit, reconcileRunMeta, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, requiredFieldsValidator, requiredSectionsValidator, 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, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/dist/index.js CHANGED
@@ -8515,7 +8515,7 @@ const ZERO_USAGE$1 = {
8515
8515
  cacheReadTokens: 0,
8516
8516
  cacheWriteTokens: 0
8517
8517
  };
8518
- function addUsage(total, turn) {
8518
+ function addUsage$1(total, turn) {
8519
8519
  const sum = {
8520
8520
  inputTokens: total.inputTokens + turn.inputTokens,
8521
8521
  outputTokens: total.outputTokens + turn.outputTokens,
@@ -8625,7 +8625,7 @@ async function streamTurn(adapter, req, options) {
8625
8625
  cacheWriteTokens: cleaned.cacheWriteTokens ?? 0
8626
8626
  };
8627
8627
  if (cleaned.reasoningTokens !== void 0) delta.reasoningTokens = cleaned.reasoningTokens;
8628
- reported = addUsage(reported, delta);
8628
+ reported = addUsage$1(reported, delta);
8629
8629
  options.onUsage?.(delta);
8630
8630
  break;
8631
8631
  }
@@ -8872,9 +8872,73 @@ async function runAgent(options) {
8872
8872
  usageByPhaseModel.set(key, {
8873
8873
  role,
8874
8874
  servedBy: ref,
8875
- usage: addUsage(prior?.usage ?? ZERO_USAGE$1, usage)
8875
+ usage: addUsage$1(prior?.usage ?? ZERO_USAGE$1, usage)
8876
8876
  });
8877
8877
  };
8878
+ let invocationCounter = 0;
8879
+ let transportRetries = 0;
8880
+ const roleUsageSnapshot = (role) => {
8881
+ const snapshot = /* @__PURE__ */ new Map();
8882
+ for (const [key, slice] of usageByPhaseModel) if (slice.role === role) snapshot.set(key, slice.usage);
8883
+ return snapshot;
8884
+ };
8885
+ const usageDelta = (after, before) => {
8886
+ const base = before ?? ZERO_USAGE$1;
8887
+ const delta = {
8888
+ inputTokens: Math.max(0, after.inputTokens - base.inputTokens),
8889
+ outputTokens: Math.max(0, after.outputTokens - base.outputTokens),
8890
+ cacheReadTokens: Math.max(0, after.cacheReadTokens - base.cacheReadTokens),
8891
+ cacheWriteTokens: Math.max(0, after.cacheWriteTokens - base.cacheWriteTokens)
8892
+ };
8893
+ const reasoning = (after.reasoningTokens ?? 0) - (base.reasoningTokens ?? 0);
8894
+ if (reasoning > 0) delta.reasoningTokens = reasoning;
8895
+ return delta;
8896
+ };
8897
+ const beginPhase = (role, model) => {
8898
+ invocationCounter += 1;
8899
+ events?.emit({
8900
+ type: "agent:phase:start",
8901
+ agentType,
8902
+ label: options.label,
8903
+ role,
8904
+ model,
8905
+ invocation: invocationCounter
8906
+ });
8907
+ return {
8908
+ invocation: invocationCounter,
8909
+ role,
8910
+ model,
8911
+ before: roleUsageSnapshot(role),
8912
+ startedAtMs: now(),
8913
+ retriesBefore: transportRetries
8914
+ };
8915
+ };
8916
+ const endPhase = (phase, outcome, servedModel) => {
8917
+ let phaseUsage = ZERO_USAGE$1;
8918
+ let phaseUsd = 0;
8919
+ for (const [key, slice] of usageByPhaseModel) {
8920
+ if (slice.role !== phase.role) continue;
8921
+ const delta = usageDelta(slice.usage, phase.before.get(key));
8922
+ phaseUsage = addUsage$1(phaseUsage, delta);
8923
+ const priced = options.priceUsd?.(slice.servedBy, delta) ?? 0;
8924
+ if (Number.isFinite(priced) && priced > 0) phaseUsd += priced;
8925
+ }
8926
+ const retries = transportRetries - phase.retriesBefore;
8927
+ events?.emit({
8928
+ type: "agent:phase:end",
8929
+ agentType,
8930
+ label: options.label,
8931
+ role: phase.role,
8932
+ model: servedModel ?? phase.model,
8933
+ invocation: phase.invocation,
8934
+ durationMs: Math.max(0, now() - phase.startedAtMs),
8935
+ usage: phaseUsage,
8936
+ costUsd: phaseUsd,
8937
+ outcome,
8938
+ ...retries > 0 ? { retries } : {}
8939
+ });
8940
+ };
8941
+ const phaseOutcome = () => status === "error" || status === "cancelled" ? "error" : "ok";
8878
8942
  let turns = 0;
8879
8943
  let schemaAttempts = 0;
8880
8944
  let output = null;
@@ -9181,6 +9245,7 @@ async function runAgent(options) {
9181
9245
  model: servedBy,
9182
9246
  role: primaryRole
9183
9247
  });
9248
+ const loopPhase = beginPhase(primaryRole, servedBy);
9184
9249
  let invariantViolation;
9185
9250
  const recordUsage = (usage, reported, adapterId, ref, role, streamViolation) => {
9186
9251
  if (streamViolation !== void 0) invariantViolation ??= `adapter '${adapterId}' violated the Usage invariant: ${streamViolation}`;
@@ -9188,7 +9253,7 @@ async function runAgent(options) {
9188
9253
  const violation = usageInvariantViolation(snapshot, adapterId);
9189
9254
  if (violation !== void 0) invariantViolation ??= violation;
9190
9255
  const safe = violation === void 0 ? snapshot : sanitizeUsage(snapshot);
9191
- totalUsage = addUsage(totalUsage, safe);
9256
+ totalUsage = addUsage$1(totalUsage, safe);
9192
9257
  addPhaseUsage(role, ref, safe);
9193
9258
  const remainder = {
9194
9259
  inputTokens: Math.max(0, safe.inputTokens - reported.inputTokens),
@@ -9290,13 +9355,16 @@ async function runAgent(options) {
9290
9355
  target
9291
9356
  };
9292
9357
  const retryAfter = (outcome.wireError?.data)?.retryAfterMs;
9293
- if (outcome.wireError !== void 0) events?.emit({
9294
- type: "agent:error",
9295
- agentType,
9296
- label: options.label,
9297
- error: outcome.wireError,
9298
- willRetry: true
9299
- });
9358
+ if (outcome.wireError !== void 0) {
9359
+ transportRetries += 1;
9360
+ events?.emit({
9361
+ type: "agent:error",
9362
+ agentType,
9363
+ label: options.label,
9364
+ error: outcome.wireError,
9365
+ willRetry: true
9366
+ });
9367
+ }
9300
9368
  await backoffWait(retryDelayMs(retryPolicy, tries - 1, typeof retryAfter === "number" ? retryAfter : void 0, retryRandom));
9301
9369
  const abortedAfter = abortKind();
9302
9370
  if (abortedAfter !== void 0) return {
@@ -9528,13 +9596,7 @@ async function runAgent(options) {
9528
9596
  ...options.compaction?.threshold === void 0 ? {} : { threshold: options.compaction.threshold }
9529
9597
  })) {
9530
9598
  const summarizeResolved = options.summarize.resolved;
9531
- events?.emit({
9532
- type: "agent:start",
9533
- agentType,
9534
- label: options.label,
9535
- model: summarizeResolved.ref,
9536
- role: "summarize"
9537
- });
9599
+ const summarizePhase = beginPhase("summarize", summarizeResolved.ref);
9538
9600
  for (const scrub of summarizeResolved.scrubs) events?.emit({
9539
9601
  type: "log",
9540
9602
  level: "warn",
@@ -9548,6 +9610,7 @@ async function runAgent(options) {
9548
9610
  kind: "budget",
9549
9611
  retryable: false
9550
9612
  };
9613
+ endPhase(summarizePhase, "error");
9551
9614
  break;
9552
9615
  }
9553
9616
  turns += 1;
@@ -9586,9 +9649,11 @@ async function runAgent(options) {
9586
9649
  retryable: false
9587
9650
  };
9588
9651
  errorMessage = thrown.message;
9652
+ endPhase(summarizePhase, "error");
9589
9653
  break;
9590
9654
  }
9591
- const { outcome: summary } = summaryDispatch;
9655
+ const { outcome: summary, target: summarizeTarget } = summaryDispatch;
9656
+ const summarizeServed = summarizeTarget.resolved.ref;
9592
9657
  usageApprox = usageApprox || summary.usageApprox;
9593
9658
  if (summary.aborted === "budget") {
9594
9659
  status = "cancelled";
@@ -9596,10 +9661,12 @@ async function runAgent(options) {
9596
9661
  kind: "budget",
9597
9662
  retryable: false
9598
9663
  };
9664
+ endPhase(summarizePhase, "error", summarizeServed);
9599
9665
  break;
9600
9666
  }
9601
9667
  if (summary.aborted === "external") {
9602
9668
  status = "cancelled";
9669
+ endPhase(summarizePhase, "error", summarizeServed);
9603
9670
  break;
9604
9671
  }
9605
9672
  if (summary.wireError !== void 0 || summary.aborted === "idle" || summary.turn.text.trim() === "") {
@@ -9609,6 +9676,7 @@ async function runAgent(options) {
9609
9676
  level: "warn",
9610
9677
  msg: "compaction disabled for this run: the summarize invocation " + (summary.wireError !== void 0 ? `failed (${summary.wireError.message})` : summary.aborted === "idle" ? "timed out" : "returned an empty summary")
9611
9678
  });
9679
+ endPhase(summarizePhase, "error", summarizeServed);
9612
9680
  } else {
9613
9681
  const compacted = compactMessages(messages, summary.turn.text);
9614
9682
  messages.length = 0;
@@ -9618,6 +9686,7 @@ async function runAgent(options) {
9618
9686
  inputTokens: 0,
9619
9687
  outputTokens: 0
9620
9688
  };
9689
+ endPhase(summarizePhase, "ok", summarizeServed);
9621
9690
  }
9622
9691
  }
9623
9692
  await saveBoundary();
@@ -9702,15 +9771,11 @@ async function runAgent(options) {
9702
9771
  await saveBoundary();
9703
9772
  continue loop;
9704
9773
  }
9774
+ endPhase(loopPhase, phaseOutcome(), servedBy);
9705
9775
  if (status === "ok" && !finishedViaTool && options.finalize !== void 0) {
9706
9776
  const finalizeResolved = options.finalize.resolved;
9707
- events?.emit({
9708
- type: "agent:start",
9709
- agentType,
9710
- label: options.label,
9711
- model: finalizeResolved.ref,
9712
- role: "finalize"
9713
- });
9777
+ const finalizePhase = beginPhase("finalize", finalizeResolved.ref);
9778
+ let finalizeServed;
9714
9779
  let proceed = true;
9715
9780
  try {
9716
9781
  options.budget?.beforeTurn();
@@ -9769,6 +9834,7 @@ async function runAgent(options) {
9769
9834
  }
9770
9835
  if (finalizeDispatch !== void 0) {
9771
9836
  const { outcome, target: finalizeTarget } = finalizeDispatch;
9837
+ finalizeServed = finalizeTarget.resolved.ref;
9772
9838
  usageApprox = usageApprox || outcome.usageApprox;
9773
9839
  messages.push(assistantMsg(outcome.turn, liftRetainedParts(outcome.providerMetadata, finalizeTarget.adapter)));
9774
9840
  if (invariantViolation !== void 0) {
@@ -9818,16 +9884,12 @@ async function runAgent(options) {
9818
9884
  }
9819
9885
  }
9820
9886
  }
9887
+ endPhase(finalizePhase, phaseOutcome(), finalizeServed);
9821
9888
  }
9822
9889
  if (status === "ok" && !finishedViaTool && separateExtract && options.extract !== void 0 && options.schema !== void 0) {
9823
9890
  const extractResolved = options.extract.resolved;
9824
- events?.emit({
9825
- type: "agent:start",
9826
- agentType,
9827
- label: options.label,
9828
- model: extractResolved.ref,
9829
- role: "extract"
9830
- });
9891
+ const extractPhase = beginPhase("extract", extractResolved.ref);
9892
+ let extractServed;
9831
9893
  const extractTierFor = (target) => selectStructuredOutputTier(target.adapter.caps(target.resolved.model), options.canonicalSchema ?? {});
9832
9894
  const extractChain = [{
9833
9895
  adapter: options.extract.adapter,
@@ -9891,6 +9953,7 @@ async function runAgent(options) {
9891
9953
  break;
9892
9954
  }
9893
9955
  const { outcome, target: extractTarget } = extractDispatch;
9956
+ extractServed = extractTarget.resolved.ref;
9894
9957
  usageApprox = usageApprox || outcome.usageApprox;
9895
9958
  if (invariantViolation !== void 0) {
9896
9959
  status = "error";
@@ -9944,6 +10007,7 @@ async function runAgent(options) {
9944
10007
  }
9945
10008
  }
9946
10009
  }
10010
+ endPhase(extractPhase, phaseOutcome(), extractServed);
9947
10011
  }
9948
10012
  let transcriptRef = "";
9949
10013
  if (options.transcript !== void 0) {
@@ -9967,6 +10031,7 @@ async function runAgent(options) {
9967
10031
  if (abortClass !== void 0) result.abortClass = abortClass;
9968
10032
  if (errorMessage !== void 0) result.errorMessage = errorMessage;
9969
10033
  if (usageApprox) result.usageApprox = true;
10034
+ if (transportRetries > 0) result.transportRetries = transportRetries;
9970
10035
  return result;
9971
10036
  }
9972
10037
  //#endregion
@@ -11833,6 +11898,29 @@ function createCtx(internals, rootWorkflow) {
11833
11898
  durationMs: 0
11834
11899
  }, spanId, true);
11835
11900
  }
11901
+ if (terminal !== void 0) entryUsageSlices(terminal).forEach((slice, index) => {
11902
+ const priced = internals.priceUsd(slice.servedBy, slice.usage) ?? 0;
11903
+ const sliceUsd = Number.isFinite(priced) && priced > 0 ? priced : 0;
11904
+ const common = {
11905
+ agentType,
11906
+ label: opts.label,
11907
+ role: slice.role ?? primaryRole,
11908
+ model: slice.servedBy,
11909
+ invocation: index + 1
11910
+ };
11911
+ internals.events.emit({
11912
+ type: "agent:phase:start",
11913
+ ...common
11914
+ }, spanId, true);
11915
+ internals.events.emit({
11916
+ type: "agent:phase:end",
11917
+ ...common,
11918
+ durationMs: 0,
11919
+ usage: slice.usage,
11920
+ costUsd: sliceUsd,
11921
+ outcome: terminal.status === "error" || terminal.status === "cancelled" ? "error" : "ok"
11922
+ }, spanId, true);
11923
+ });
11836
11924
  internals.events.emit({
11837
11925
  type: "agent:end",
11838
11926
  agentType,
@@ -12323,7 +12411,8 @@ function createCtx(internals, rootWorkflow) {
12323
12411
  usage: result.usage,
12324
12412
  costUsd: result.costUsd,
12325
12413
  entryRef: terminal.seq,
12326
- ...resultUsageApprox ? { usageApprox: true } : {}
12414
+ ...resultUsageApprox ? { usageApprox: true } : {},
12415
+ ...result.transportRetries !== void 0 && result.transportRetries > 0 ? { retryCount: result.transportRetries } : {}
12327
12416
  }, spanId);
12328
12417
  if (result.status === "escalated" && result.escalation !== void 0) {
12329
12418
  let decision = flavorBDecision;
@@ -14298,6 +14387,132 @@ var EventBus = class {
14298
14387
  }
14299
14388
  };
14300
14389
  //#endregion
14390
+ //#region src/l0/telemetry-reduce.ts
14391
+ const ZERO = {
14392
+ inputTokens: 0,
14393
+ outputTokens: 0,
14394
+ cacheReadTokens: 0,
14395
+ cacheWriteTokens: 0
14396
+ };
14397
+ function addUsage(a, b) {
14398
+ const sum = {
14399
+ inputTokens: a.inputTokens + b.inputTokens,
14400
+ outputTokens: a.outputTokens + b.outputTokens,
14401
+ cacheReadTokens: a.cacheReadTokens + b.cacheReadTokens,
14402
+ cacheWriteTokens: a.cacheWriteTokens + b.cacheWriteTokens
14403
+ };
14404
+ const reasoning = (a.reasoningTokens ?? 0) + (b.reasoningTokens ?? 0);
14405
+ if (reasoning > 0) sum.reasoningTokens = reasoning;
14406
+ return sum;
14407
+ }
14408
+ /**
14409
+ * Reduces one run's event stream (or any slice of it) to the invocation
14410
+ * table. Feed it the events in emission order; both a live stream and a
14411
+ * replayed one produce the same usage and cost columns.
14412
+ */
14413
+ function reduceInvocationTable(events) {
14414
+ const rows = /* @__PURE__ */ new Map();
14415
+ const order = [];
14416
+ const openPhases = /* @__PURE__ */ new Map();
14417
+ const byRole = {};
14418
+ let totalCostUsd = 0;
14419
+ const rowFor = (event) => {
14420
+ let row = rows.get(event.spanId);
14421
+ if (row === void 0) {
14422
+ row = {
14423
+ spanId: event.spanId,
14424
+ agentType: event.agentType,
14425
+ ...event.label === void 0 ? {} : { label: event.label },
14426
+ usage: ZERO,
14427
+ costUsd: 0,
14428
+ usageApprox: false,
14429
+ retryCount: 0,
14430
+ replayed: event.replayed === true,
14431
+ open: true,
14432
+ phases: []
14433
+ };
14434
+ rows.set(event.spanId, row);
14435
+ order.push(row);
14436
+ }
14437
+ return row;
14438
+ };
14439
+ for (const event of events) switch (event.type) {
14440
+ case "agent:start": {
14441
+ const row = rowFor(event);
14442
+ row.role = event.role;
14443
+ break;
14444
+ }
14445
+ case "agent:phase:start": {
14446
+ const row = rowFor(event);
14447
+ const phase = {
14448
+ invocation: event.invocation,
14449
+ role: event.role,
14450
+ model: event.model,
14451
+ durationMs: 0,
14452
+ usage: ZERO,
14453
+ costUsd: 0,
14454
+ retries: 0,
14455
+ replayed: event.replayed === true,
14456
+ open: true
14457
+ };
14458
+ row.phases.push(phase);
14459
+ openPhases.set(`${event.spanId}#${event.invocation}`, phase);
14460
+ break;
14461
+ }
14462
+ case "agent:phase:end": {
14463
+ const key = `${event.spanId}#${event.invocation}`;
14464
+ let phase = openPhases.get(key);
14465
+ if (phase === void 0) {
14466
+ phase = {
14467
+ invocation: event.invocation,
14468
+ role: event.role,
14469
+ model: event.model,
14470
+ durationMs: 0,
14471
+ usage: ZERO,
14472
+ costUsd: 0,
14473
+ retries: 0,
14474
+ replayed: event.replayed === true,
14475
+ open: true
14476
+ };
14477
+ rowFor(event).phases.push(phase);
14478
+ }
14479
+ openPhases.delete(key);
14480
+ phase.open = false;
14481
+ phase.role = event.role;
14482
+ phase.model = event.model;
14483
+ phase.durationMs = event.durationMs;
14484
+ phase.usage = event.usage;
14485
+ phase.costUsd = event.costUsd;
14486
+ phase.outcome = event.outcome;
14487
+ phase.retries = event.retries ?? 0;
14488
+ const bucket = byRole[event.role] ??= {
14489
+ usage: ZERO,
14490
+ costUsd: 0
14491
+ };
14492
+ bucket.usage = addUsage(bucket.usage, event.usage);
14493
+ bucket.costUsd += event.costUsd;
14494
+ break;
14495
+ }
14496
+ case "agent:end": {
14497
+ const row = rowFor(event);
14498
+ row.open = false;
14499
+ row.status = event.status;
14500
+ row.usage = event.usage;
14501
+ row.costUsd = event.costUsd;
14502
+ row.usageApprox = event.usageApprox === true;
14503
+ row.retryCount = event.retryCount ?? 0;
14504
+ totalCostUsd += event.costUsd;
14505
+ break;
14506
+ }
14507
+ default: break;
14508
+ }
14509
+ return {
14510
+ agents: order,
14511
+ byRole,
14512
+ totalCostUsd
14513
+ };
14514
+ }
14515
+ //#endregion
14301
14516
  //#region src/l0/run-id.ts
14302
14517
  /**
14303
14518
  * Run id containment (v1.36.0 review SEC-P1). A runId becomes both a
@@ -15296,4 +15511,4 @@ function createSandboxBridge(ctx, options) {
15296
15511
  };
15297
15512
  }
15298
15513
  //#endregion
15299
- export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, 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, DedupIndex, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GitWorktreeProvider, 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_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, PlanInvariantError, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, 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, readRunMeta, readTerminationInit, reconcileRunMeta, registryKeyRing, remeasureQueue, replayDisposition, requiredFieldsValidator, requiredSectionsValidator, 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, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
15514
+ export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, 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, DedupIndex, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GitWorktreeProvider, 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_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, PlanInvariantError, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, 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, readRunMeta, readTerminationInit, reconcileRunMeta, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, requiredFieldsValidator, requiredSectionsValidator, 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, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.47.0",
3
+ "version": "1.49.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",