@rulvar/core 1.39.0 → 1.41.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
@@ -193,8 +193,11 @@ declare class BudgetExhaustedError extends RulvarError {
193
193
  /**
194
194
  * A declared fail-run policy engaged and closed the run as a failure
195
195
  * (v1.35.0 review P2-1): `budget.atCap: 'fail-run'` after the journaled
196
- * orchestrator cap decision, or `guards.fallback: 'fail-run'` after the
197
- * journaled guard verdict. The run outcome is 'error' with this code;
196
+ * orchestrator cap decision, `guards.fallback: 'fail-run'` after the
197
+ * journaled guard verdict, or a violated orchestrate acceptance policy
198
+ * after the journaled acceptance decision (`data.source`
199
+ * 'orchestrator_acceptance', with the child status counts and degraded
200
+ * reasons in `data`). The run outcome is 'error' with this code;
198
201
  * `data.source` names the policy ('orchestrator_budget_cap' or
199
202
  * 'plan_guards') and `data` carries the decision entry reference, so the
200
203
  * outcome is a pure roll forward of the journal on resume: no second
@@ -4303,6 +4306,14 @@ type CoreEvents = {
4303
4306
  type: "run:end";
4304
4307
  status: "ok" | "error" | "cancelled" | "exhausted" | "suspended";
4305
4308
  totalUsd: number;
4309
+ /**
4310
+ * Present and true when any priced usage folded into totalUsd is
4311
+ * approximate (a transport cut, a stream the ceiling severed, or an
4312
+ * abort left a turn's usage estimated rather than reported by the
4313
+ * provider), so totalUsd is a lower bound estimate, never an exact
4314
+ * charge. Absent means every contributing turn reported exact usage.
4315
+ */
4316
+ usageApprox?: boolean;
4306
4317
  } | {
4307
4318
  type: "phase:start";
4308
4319
  phase: string;
@@ -4356,6 +4367,14 @@ type AgentEvents = {
4356
4367
  usage: Usage;
4357
4368
  costUsd: number;
4358
4369
  entryRef: number;
4370
+ /**
4371
+ * Present and true when this agent's usage is approximate rather
4372
+ * than reported by the provider (the turn was cut by a transport
4373
+ * failure, a ceiling that severed the stream, or an abort). Absent
4374
+ * means the provider reported the usage exactly. Mirrors the
4375
+ * terminal journal entry's usageApprox.
4376
+ */
4377
+ usageApprox?: boolean;
4359
4378
  } | {
4360
4379
  type: "agent:error";
4361
4380
  agentType: string;
@@ -4612,6 +4631,16 @@ interface CostReport {
4612
4631
  model: string;
4613
4632
  usage: Usage;
4614
4633
  }>;
4634
+ /**
4635
+ * Present and true when any terminal entry folded into totalUsd carried
4636
+ * approximate usage (a transport cut, a stream the ceiling severed, or
4637
+ * an abort estimated the turn instead of the provider reporting it), so
4638
+ * totalUsd is a lower bound estimate, never an exact charge. Absent
4639
+ * means every contributing entry reported exact usage. The field the
4640
+ * v1.39.0 review asked the report to raise so approximate cost is never
4641
+ * shown as though it were the provider invoice.
4642
+ */
4643
+ usageApprox?: boolean;
4615
4644
  }
4616
4645
  type RunOutcome<R> = {
4617
4646
  status: "ok" | "error" | "cancelled" | "exhausted" | "suspended";
@@ -5377,6 +5406,34 @@ interface OrchestratorBudgetSpec {
5377
5406
  atCap?: "finish-with-partial" | "fail-run";
5378
5407
  }
5379
5408
  /** Options for orchestrate(engine, goal, o?). */
5409
+ /**
5410
+ * The opt-in child completion policy (the v1.40.0 improvement plan's
5411
+ * completion contract): run status 'ok' alone never proves the children
5412
+ * succeeded, because the model may call finish after any mix of child
5413
+ * outcomes. When acceptance is set, the policy is evaluated exactly when
5414
+ * the model's finish validates, the verdict is journaled as ONE decision
5415
+ * entry (so a resume rolls the SAME verdict forward, immune to drift of
5416
+ * the live options), and the workflow result becomes the acceptance
5417
+ * envelope { result, completion, childStatusCounts, degradedReasons }. A
5418
+ * violated policy fails the run with the typed FailRunError (code
5419
+ * 'fail_run', data.source 'orchestrator_acceptance') instead of settling
5420
+ * ok. A budget cap settle keeps its atCap policy: the cap partial is
5421
+ * already visible as run status 'exhausted' or the typed fail run error,
5422
+ * never a plain ok, so acceptance does not judge it again.
5423
+ */
5424
+ interface OrchestrateAcceptance {
5425
+ /**
5426
+ * 'all-ok' requires EVERY spawned child to have settled 'ok' when
5427
+ * finish validates: a child still running counts against the policy,
5428
+ * and so does a deliberately cancelled straggler (spawn nothing you do
5429
+ * not need to succeed; zero spawned children are vacuously complete).
5430
+ * { minSuccessful: N } requires at least N children settled 'ok' and
5431
+ * reports every other child in degradedReasons.
5432
+ */
5433
+ childPolicy: "all-ok" | {
5434
+ minSuccessful: number;
5435
+ };
5436
+ }
5380
5437
  interface OrchestrateOptions {
5381
5438
  model?: ModelSpec;
5382
5439
  /** Registered profile names to advertise; default: every profile. */
@@ -5408,6 +5465,8 @@ interface OrchestrateOptions {
5408
5465
  * participates in the mandatory quiescence trigger.
5409
5466
  */
5410
5467
  extension?: OrchestratorExtension;
5468
+ /** The opt in child completion policy; see {@link OrchestrateAcceptance}. */
5469
+ acceptance?: OrchestrateAcceptance;
5411
5470
  }
5412
5471
  declare const ORCHESTRATE_WORKFLOW_NAME = "rulvar-orchestrate";
5413
5472
  /**
@@ -6898,4 +6957,4 @@ interface SandboxBridge {
6898
6957
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
6899
6958
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
6900
6959
  //#endregion
6901
- 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, 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, 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, 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, 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, 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, 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, hasMetaLookup, hashRunArgs, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, metaMatchesFilter, 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, 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, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
6960
+ 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, 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, 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, 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, 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, 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, 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, hasMetaLookup, hashRunArgs, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, metaMatchesFilter, 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, 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, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/dist/index.js CHANGED
@@ -208,8 +208,11 @@ var BudgetExhaustedError = class extends RulvarError {
208
208
  /**
209
209
  * A declared fail-run policy engaged and closed the run as a failure
210
210
  * (v1.35.0 review P2-1): `budget.atCap: 'fail-run'` after the journaled
211
- * orchestrator cap decision, or `guards.fallback: 'fail-run'` after the
212
- * journaled guard verdict. The run outcome is 'error' with this code;
211
+ * orchestrator cap decision, `guards.fallback: 'fail-run'` after the
212
+ * journaled guard verdict, or a violated orchestrate acceptance policy
213
+ * after the journaled acceptance decision (`data.source`
214
+ * 'orchestrator_acceptance', with the child status counts and degraded
215
+ * reasons in `data`). The run outcome is 'error' with this code;
213
216
  * `data.source` names the policy ('orchestrator_budget_cap' or
214
217
  * 'plan_guards') and `data` carries the decision entry reference, so the
215
218
  * outcome is a pure roll forward of the journal on resume: no second
@@ -6799,6 +6802,7 @@ function costReportFromJournal(entries, priceUsd) {
6799
6802
  const byRole = emptyByRole();
6800
6803
  const unpriced = [];
6801
6804
  let totalUsd = 0;
6805
+ let usageApprox = false;
6802
6806
  let orchestratorSpentUsd = 0;
6803
6807
  let reserveUsedUsd = 0;
6804
6808
  let wakes = 0;
@@ -6815,6 +6819,7 @@ function costReportFromJournal(entries, priceUsd) {
6815
6819
  });
6816
6820
  for (const slice of priced.priced) byModel[slice.servedBy] = (byModel[slice.servedBy] ?? 0) + slice.usd;
6817
6821
  totalUsd += priced.usd;
6822
+ if (entry.usageApprox === true) usageApprox = true;
6818
6823
  const facts = entry.costAttribution;
6819
6824
  const phase = facts?.phase ?? "";
6820
6825
  byPhase[phase] = (byPhase[phase] ?? 0) + priced.usd;
@@ -6840,7 +6845,8 @@ function costReportFromJournal(entries, priceUsd) {
6840
6845
  forcedFinish,
6841
6846
  reserveUsedUsd
6842
6847
  },
6843
- unpriced
6848
+ unpriced,
6849
+ ...usageApprox ? { usageApprox: true } : {}
6844
6850
  };
6845
6851
  }
6846
6852
  //#endregion
@@ -11411,7 +11417,8 @@ function createCtx(internals, rootWorkflow) {
11411
11417
  status: result.status,
11412
11418
  usage,
11413
11419
  costUsd,
11414
- entryRef: terminal?.seq ?? matched.running.seq
11420
+ entryRef: terminal?.seq ?? matched.running.seq,
11421
+ ...terminal?.usageApprox === true ? { usageApprox: true } : {}
11415
11422
  }, spanId, true);
11416
11423
  for (const slice of replayPriced?.priced ?? []) bump(internals.cost.byModel, slice.servedBy, slice.usd);
11417
11424
  for (const slice of replayPriced?.unpriced ?? []) internals.cost.unpriced.push({
@@ -11866,7 +11873,8 @@ function createCtx(internals, rootWorkflow) {
11866
11873
  if (result.status === "escalated" && result.escalation !== void 0) terminalPatch.escalation = result.escalation;
11867
11874
  if (result.output !== null && result.status === "ok") terminalPatch.value = result.output;
11868
11875
  if (result.error !== void 0) terminalPatch.error = agentErrorToWire(result.error, result.errorMessage ?? `agent terminated with status ${result.status}`);
11869
- if (result.usageApprox === true) terminalPatch.usageApprox = true;
11876
+ const resultUsageApprox = result.usageApprox === true;
11877
+ if (resultUsageApprox) terminalPatch.usageApprox = true;
11870
11878
  if (result.artifacts !== void 0) terminalPatch.artifacts = result.artifacts;
11871
11879
  if (result.abortClass !== void 0) {
11872
11880
  terminalPatch.memoizeOutcome = true;
@@ -11891,7 +11899,8 @@ function createCtx(internals, rootWorkflow) {
11891
11899
  status: result.status,
11892
11900
  usage: result.usage,
11893
11901
  costUsd: result.costUsd,
11894
- entryRef: terminal.seq
11902
+ entryRef: terminal.seq,
11903
+ ...resultUsageApprox ? { usageApprox: true } : {}
11895
11904
  }, spanId);
11896
11905
  if (result.status === "escalated" && result.escalation !== void 0) {
11897
11906
  let decision = flavorBDecision;
@@ -12484,6 +12493,12 @@ function validateOrchestrateOptions(opts) {
12484
12493
  if (opts === void 0) return;
12485
12494
  if (opts.maxSpawns !== void 0) requireNonNegativeInteger(opts.maxSpawns, "orchestrate maxSpawns");
12486
12495
  if (opts.renderBudgetChars !== void 0) requireNonNegativeInteger(opts.renderBudgetChars, "orchestrate renderBudgetChars");
12496
+ if (opts.acceptance !== void 0) {
12497
+ const policy = opts.acceptance.childPolicy;
12498
+ const minSuccessful = typeof policy === "object" && policy !== null && !Array.isArray(policy) ? policy.minSuccessful : void 0;
12499
+ if (policy !== "all-ok" && minSuccessful === void 0) throw new ConfigError(`orchestrate acceptance.childPolicy must be 'all-ok' or { minSuccessful: N }; got ${JSON.stringify(policy)}`);
12500
+ if (policy !== "all-ok") requirePositiveInteger(minSuccessful, "orchestrate acceptance.childPolicy.minSuccessful");
12501
+ }
12487
12502
  const spec = opts.budget;
12488
12503
  if (spec === void 0) return;
12489
12504
  if (spec.capUsd !== void 0) requireNonNegativeNumber(spec.capUsd, "orchestrate budget.capUsd");
@@ -13411,7 +13426,55 @@ function makeOrchestratorWorkflow(goal, opts) {
13411
13426
  if (capDecisionRef !== void 0) return await settleCapOutcome();
13412
13427
  if (orchestratorAccount !== void 0) internals.cost.orchestrator.spentUsd = internals.budget.accountView(orchestratorAccount)?.spentUsd ?? 0;
13413
13428
  if (result.status !== "ok") throw new ConfigError(`the orchestrator agent terminated with status '${result.status}'` + (result.errorMessage === void 0 ? "" : `: ${result.errorMessage}`));
13414
- return result.output;
13429
+ if (opts?.acceptance === void 0) return result.output;
13430
+ const acceptanceKey = "acceptance";
13431
+ const priorAcceptance = internals.replayer.snapshot().find((entry) => entry.kind === "decision" && entry.scope === callingState.scope && entry.key === acceptanceKey);
13432
+ let decision;
13433
+ if (priorAcceptance !== void 0) decision = priorAcceptance.value;
13434
+ else {
13435
+ const childStatusCounts = {};
13436
+ const degradedReasons = [];
13437
+ const sortedRecords = [...records.values()].sort((a, b) => a.spawnOrdinal - b.spawnOrdinal);
13438
+ for (const record of sortedRecords) {
13439
+ const status = record.settled?.status ?? "running";
13440
+ childStatusCounts[status] = (childStatusCounts[status] ?? 0) + 1;
13441
+ if (status !== "ok") degradedReasons.push(status === "running" ? `child ${record.nodeId} was still running when finish validated` : `child ${record.nodeId} settled '${status}'`);
13442
+ }
13443
+ const childPolicy = opts.acceptance.childPolicy;
13444
+ const accepted = childPolicy === "all-ok" ? degradedReasons.length === 0 : (childStatusCounts.ok ?? 0) >= childPolicy.minSuccessful;
13445
+ decision = {
13446
+ decisionType: "orchestrator_acceptance",
13447
+ verdict: accepted ? "accepted" : "rejected",
13448
+ completion: !accepted ? "rejected" : degradedReasons.length === 0 ? "complete" : "partial",
13449
+ childPolicy,
13450
+ childStatusCounts,
13451
+ degradedReasons
13452
+ };
13453
+ await internals.replayer.appendSinglePhase({
13454
+ scope: callingState.scope,
13455
+ key: acceptanceKey,
13456
+ kind: "decision",
13457
+ status: "ok",
13458
+ spanId: internals.spans.mint(callingState.spanId),
13459
+ site: "orchestrator-acceptance",
13460
+ value: decision
13461
+ });
13462
+ }
13463
+ if (decision.verdict === "rejected") {
13464
+ const required = decision.childPolicy === "all-ok" ? "every child ok" : `at least ${String(decision.childPolicy.minSuccessful)} children ok`;
13465
+ throw new FailRunError(`the orchestrator acceptance policy rejected the finish: ${String(decision.childStatusCounts.ok ?? 0)} children settled 'ok' but the policy requires ${required}; degraded: ${decision.degradedReasons.join("; ")}`, { data: {
13466
+ source: "orchestrator_acceptance",
13467
+ childPolicy: decision.childPolicy,
13468
+ childStatusCounts: decision.childStatusCounts,
13469
+ degradedReasons: decision.degradedReasons
13470
+ } });
13471
+ }
13472
+ return {
13473
+ result: result.output,
13474
+ completion: decision.completion,
13475
+ childStatusCounts: decision.childStatusCounts,
13476
+ degradedReasons: decision.degradedReasons
13477
+ };
13415
13478
  });
13416
13479
  }
13417
13480
  /**
@@ -14110,7 +14173,8 @@ function createEngine(options) {
14110
14173
  bus.emit({
14111
14174
  type: "run:end",
14112
14175
  status,
14113
- totalUsd: ledger.usd
14176
+ totalUsd: ledger.usd,
14177
+ ...outcome.cost.usageApprox === true ? { usageApprox: true } : {}
14114
14178
  }, rootSpanId);
14115
14179
  bus.end();
14116
14180
  resumeCtx?.previewResolve({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.39.0",
3
+ "version": "1.41.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",