@rulvar/core 1.40.0 → 1.42.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
@@ -5002,6 +5005,57 @@ interface TaskDigest {
5002
5005
  costUsd: number;
5003
5006
  artifactsIndex: string[];
5004
5007
  }
5008
+ /**
5009
+ * One page of a settled child's FULL output, returned by the opt-in
5010
+ * `get_child_result` tool. The digest is a wake signal truncated to 400
5011
+ * characters; this is the whole evidence, paged so a large result can be
5012
+ * read without overflowing the orchestrator's context in one call
5013
+ * (v1.40.0 improvement plan, the narrow RV-201 slice). The content is a
5014
+ * deterministic serialization of the child's `output` (the raw string
5015
+ * when the output IS a string, else its JCS-independent `JSON.stringify`)
5016
+ * for a settled ok child, or the child's `errorMessage` otherwise, so the
5017
+ * orchestrator can read WHY a child failed as readily as what it
5018
+ * produced. Everything here is a pure read of already durable journal
5019
+ * state, so a resume reproduces it with no new spend.
5020
+ */
5021
+ interface ChildResultPage {
5022
+ handle: number;
5023
+ status: string;
5024
+ /** Length of the whole serialized result, in characters. */
5025
+ totalChars: number;
5026
+ /** The character offset this page starts at, counted from zero. */
5027
+ offset: number;
5028
+ /** The page: `content.length` is at most the requested (clamped) maxChars. */
5029
+ content: string;
5030
+ /** True when more characters remain past this page; call again with a higher offset. */
5031
+ hasMore: boolean;
5032
+ /** The child's artifacts, id and kind, so the model knows what `read_child_artifact` can fetch. */
5033
+ artifacts: Array<{
5034
+ id: string;
5035
+ kind: string;
5036
+ label?: string;
5037
+ }>;
5038
+ }
5039
+ /**
5040
+ * One page of a settled child's artifact CONTENT, returned by the opt-in
5041
+ * `read_child_artifact` tool. Inline artifact `data` serializes to a
5042
+ * string; an offloaded artifact (a TranscriptStore `ref`) is fetched and
5043
+ * decoded as UTF-8; a `patch` artifact with only a changed file list
5044
+ * carries that list in `files` and empty content. Paged and pure exactly
5045
+ * like {@link ChildResultPage}.
5046
+ */
5047
+ interface ChildArtifactPage {
5048
+ handle: number;
5049
+ artifactId: string;
5050
+ kind: string;
5051
+ label?: string;
5052
+ totalChars: number;
5053
+ offset: number;
5054
+ content: string;
5055
+ hasMore: boolean;
5056
+ /** The changed file list for a `patch` artifact; absent otherwise. */
5057
+ files?: string[];
5058
+ }
5005
5059
  /** One spawned child tracked by the orchestrator runtime. */
5006
5060
  interface SpawnRecord {
5007
5061
  handle: number;
@@ -5044,6 +5098,16 @@ interface OrchestratorRuntime {
5044
5098
  }>;
5045
5099
  /** Sleep until a coalesced WakeDigest (M6-T09). */
5046
5100
  waitForEvents(triggers: unknown): Promise<unknown>;
5101
+ /** A page of a settled child's full output; opt-in `get_child_result` (RV-201). */
5102
+ getChildResult(handle: number, opts?: {
5103
+ offset?: number;
5104
+ maxChars?: number;
5105
+ }): Promise<ChildResultPage>;
5106
+ /** A page of a settled child's artifact content; opt-in `read_child_artifact` (RV-201). */
5107
+ readChildArtifact(handle: number, artifactId: string, opts?: {
5108
+ offset?: number;
5109
+ maxChars?: number;
5110
+ }): Promise<ChildArtifactPage>;
5047
5111
  }
5048
5112
  /**
5049
5113
  * The committed WakeDigest render budget (Appendix A: 400
@@ -5403,6 +5467,34 @@ interface OrchestratorBudgetSpec {
5403
5467
  atCap?: "finish-with-partial" | "fail-run";
5404
5468
  }
5405
5469
  /** Options for orchestrate(engine, goal, o?). */
5470
+ /**
5471
+ * The opt-in child completion policy (the v1.40.0 improvement plan's
5472
+ * completion contract): run status 'ok' alone never proves the children
5473
+ * succeeded, because the model may call finish after any mix of child
5474
+ * outcomes. When acceptance is set, the policy is evaluated exactly when
5475
+ * the model's finish validates, the verdict is journaled as ONE decision
5476
+ * entry (so a resume rolls the SAME verdict forward, immune to drift of
5477
+ * the live options), and the workflow result becomes the acceptance
5478
+ * envelope { result, completion, childStatusCounts, degradedReasons }. A
5479
+ * violated policy fails the run with the typed FailRunError (code
5480
+ * 'fail_run', data.source 'orchestrator_acceptance') instead of settling
5481
+ * ok. A budget cap settle keeps its atCap policy: the cap partial is
5482
+ * already visible as run status 'exhausted' or the typed fail run error,
5483
+ * never a plain ok, so acceptance does not judge it again.
5484
+ */
5485
+ interface OrchestrateAcceptance {
5486
+ /**
5487
+ * 'all-ok' requires EVERY spawned child to have settled 'ok' when
5488
+ * finish validates: a child still running counts against the policy,
5489
+ * and so does a deliberately cancelled straggler (spawn nothing you do
5490
+ * not need to succeed; zero spawned children are vacuously complete).
5491
+ * { minSuccessful: N } requires at least N children settled 'ok' and
5492
+ * reports every other child in degradedReasons.
5493
+ */
5494
+ childPolicy: "all-ok" | {
5495
+ minSuccessful: number;
5496
+ };
5497
+ }
5406
5498
  interface OrchestrateOptions {
5407
5499
  model?: ModelSpec;
5408
5500
  /** Registered profile names to advertise; default: every profile. */
@@ -5434,6 +5526,20 @@ interface OrchestrateOptions {
5434
5526
  * participates in the mandatory quiescence trigger.
5435
5527
  */
5436
5528
  extension?: OrchestratorExtension;
5529
+ /** The opt in child completion policy; see {@link OrchestrateAcceptance}. */
5530
+ acceptance?: OrchestrateAcceptance;
5531
+ /**
5532
+ * Opt in to the evidence tools `get_child_result` and
5533
+ * `read_child_artifact` (the v1.40.0 improvement plan's narrow RV-201
5534
+ * slice). The digest an await returns is a wake signal truncated to 400
5535
+ * characters; with this set, the orchestrator can page a settled
5536
+ * child's FULL output and its artifact contents, both pure reads of
5537
+ * durable journal state. Adding the tools changes the orchestrator
5538
+ * toolset hash by design (exactly like the extension's plan tools), so
5539
+ * leave it off and the default toolset, and every frozen cassette, stay
5540
+ * unchanged.
5541
+ */
5542
+ exposeChildResultTools?: boolean;
5437
5543
  }
5438
5544
  declare const ORCHESTRATE_WORKFLOW_NAME = "rulvar-orchestrate";
5439
5545
  /**
@@ -6740,6 +6846,13 @@ declare const PARALLEL_AGENTS_SCHEMA: SchemaSpec;
6740
6846
  declare const AWAIT_SCHEMA: SchemaSpec;
6741
6847
  /** The cancel_agent parameter schema. */
6742
6848
  declare const CANCEL_AGENT_SCHEMA: SchemaSpec;
6849
+ /** Default and hard-max characters per child-result / artifact page. */
6850
+ declare const DEFAULT_CHILD_RESULT_PAGE_CHARS = 4e3;
6851
+ declare const MAX_CHILD_RESULT_PAGE_CHARS = 2e4;
6852
+ declare const GET_CHILD_RESULT_SCHEMA: SchemaSpec;
6853
+ declare const READ_CHILD_ARTIFACT_SCHEMA: SchemaSpec;
6854
+ declare const GET_CHILD_RESULT_TOOL_NAME = "get_child_result";
6855
+ declare const READ_CHILD_ARTIFACT_TOOL_NAME = "read_child_artifact";
6743
6856
  /** finish; result validates against the declared output schema. */
6744
6857
  declare const FINISH_SCHEMA: SchemaSpec;
6745
6858
  declare const FINISH_TOOL_NAME = "finish";
@@ -6766,7 +6879,9 @@ interface SpawnAgentParams {
6766
6879
  * rides the spawn tools' descriptions so both modes speak one agent
6767
6880
  * vocabulary (M6-T04).
6768
6881
  */
6769
- declare function buildOrchestratorTools(runtime: OrchestratorRuntime, profileCardText: string): ToolDef[];
6882
+ declare function buildOrchestratorTools(runtime: OrchestratorRuntime, profileCardText: string, options?: {
6883
+ childResultTools?: boolean;
6884
+ }): ToolDef[];
6770
6885
  //#endregion
6771
6886
  //#region src/engine/events.d.ts
6772
6887
  /**
@@ -6924,4 +7039,4 @@ interface SandboxBridge {
6924
7039
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
6925
7040
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
6926
7041
  //#endregion
6927
- 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 };
7042
+ 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, 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_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, 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, 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
@@ -10765,6 +10768,46 @@ const CANCEL_AGENT_SCHEMA = {
10765
10768
  reason: { type: "string" }
10766
10769
  }
10767
10770
  };
10771
+ /** Default and hard-max characters per child-result / artifact page. */
10772
+ const DEFAULT_CHILD_RESULT_PAGE_CHARS = 4e3;
10773
+ const MAX_CHILD_RESULT_PAGE_CHARS = 2e4;
10774
+ const PAGING_PROPS = {
10775
+ offset: {
10776
+ type: "integer",
10777
+ minimum: 0
10778
+ },
10779
+ maxChars: {
10780
+ type: "integer",
10781
+ minimum: 1
10782
+ }
10783
+ };
10784
+ const GET_CHILD_RESULT_SCHEMA = {
10785
+ type: "object",
10786
+ additionalProperties: false,
10787
+ required: ["handle"],
10788
+ properties: {
10789
+ handle: {
10790
+ type: "integer",
10791
+ minimum: 1
10792
+ },
10793
+ ...PAGING_PROPS
10794
+ }
10795
+ };
10796
+ const READ_CHILD_ARTIFACT_SCHEMA = {
10797
+ type: "object",
10798
+ additionalProperties: false,
10799
+ required: ["handle", "artifactId"],
10800
+ properties: {
10801
+ handle: {
10802
+ type: "integer",
10803
+ minimum: 1
10804
+ },
10805
+ artifactId: { type: "string" },
10806
+ ...PAGING_PROPS
10807
+ }
10808
+ };
10809
+ const GET_CHILD_RESULT_TOOL_NAME = "get_child_result";
10810
+ const READ_CHILD_ARTIFACT_TOOL_NAME = "read_child_artifact";
10768
10811
  /** finish; result validates against the declared output schema. */
10769
10812
  const FINISH_SCHEMA = {
10770
10813
  type: "object",
@@ -10781,64 +10824,95 @@ const FINISH_TOOL_NAME = "finish";
10781
10824
  * rides the spawn tools' descriptions so both modes speak one agent
10782
10825
  * vocabulary (M6-T04).
10783
10826
  */
10784
- function buildOrchestratorTools(runtime, profileCardText) {
10785
- return [
10786
- tool({
10787
- name: "spawn_agent",
10788
- description: `Admit and schedule one child agent. ${profileCardText}`,
10789
- parameters: SPAWN_AGENT_SCHEMA,
10790
- execute: (input) => runtime.spawn(input)
10791
- }),
10792
- tool({
10793
- name: "parallel_agents",
10794
- description: "Admit and schedule several children at once (submission order).",
10795
- parameters: PARALLEL_AGENTS_SCHEMA,
10796
- execute: async (input) => {
10797
- const tasks = input.tasks;
10798
- const handles = [];
10799
- for (const task of tasks) {
10800
- const spawned = await runtime.spawn(task);
10801
- handles.push(spawned.handle);
10802
- }
10803
- return { handles };
10804
- }
10805
- }),
10806
- tool({
10807
- name: "await_any",
10808
- description: "Wait for the FIRST of the handles to settle; returns its TaskDigest.",
10809
- parameters: AWAIT_SCHEMA,
10810
- execute: (input) => runtime.awaitAny(input.handles)
10811
- }),
10812
- tool({
10813
- name: "await_all",
10814
- description: "Wait for ALL handles to settle; returns their TaskDigests in handle order.",
10815
- parameters: AWAIT_SCHEMA,
10816
- execute: (input) => runtime.awaitAll(input.handles)
10817
- }),
10818
- tool({
10819
- name: "cancel_agent",
10820
- description: "Cancel an in-flight child. Cancellation is caller intent: the entry journals cancelled and reruns on a later resume unless covered by abandon (M7).",
10821
- parameters: CANCEL_AGENT_SCHEMA,
10822
- execute: (input) => {
10823
- const params = input;
10824
- return runtime.cancel(params.handle, params.reason);
10825
- }
10826
- }),
10827
- tool({
10828
- name: WAIT_FOR_EVENTS_TOOL_NAME,
10829
- description: "Sleep until a coalesced WakeDigest: quiescence (always armed), child_terminal, escalation, or budget_threshold at 50/80 percent. A trigger set that can never fire is a typed error.",
10830
- parameters: WAIT_FOR_EVENTS_SCHEMA,
10831
- execute: (input) => runtime.waitForEvents(input.triggers)
10832
- }),
10833
- tool({
10834
- name: FINISH_TOOL_NAME,
10835
- description: "Terminate the orchestration with a result (run outcome ok).",
10836
- parameters: FINISH_SCHEMA,
10837
- execute: () => {
10838
- throw new Error("finish is intercepted by the agent runtime, never executed");
10839
- }
10840
- })
10827
+ function buildOrchestratorTools(runtime, profileCardText, options) {
10828
+ const spawnAgent = tool({
10829
+ name: "spawn_agent",
10830
+ description: `Admit and schedule one child agent. ${profileCardText}`,
10831
+ parameters: SPAWN_AGENT_SCHEMA,
10832
+ execute: (input) => runtime.spawn(input)
10833
+ });
10834
+ const parallelAgents = tool({
10835
+ name: "parallel_agents",
10836
+ description: "Admit and schedule several children at once (submission order).",
10837
+ parameters: PARALLEL_AGENTS_SCHEMA,
10838
+ execute: async (input) => {
10839
+ const tasks = input.tasks;
10840
+ const handles = [];
10841
+ for (const task of tasks) {
10842
+ const spawned = await runtime.spawn(task);
10843
+ handles.push(spawned.handle);
10844
+ }
10845
+ return { handles };
10846
+ }
10847
+ });
10848
+ const awaitAny = tool({
10849
+ name: "await_any",
10850
+ description: "Wait for the FIRST of the handles to settle; returns its TaskDigest.",
10851
+ parameters: AWAIT_SCHEMA,
10852
+ execute: (input) => runtime.awaitAny(input.handles)
10853
+ });
10854
+ const awaitAll = tool({
10855
+ name: "await_all",
10856
+ description: "Wait for ALL handles to settle; returns their TaskDigests in handle order.",
10857
+ parameters: AWAIT_SCHEMA,
10858
+ execute: (input) => runtime.awaitAll(input.handles)
10859
+ });
10860
+ const cancelAgent = tool({
10861
+ name: "cancel_agent",
10862
+ description: "Cancel an in-flight child. Cancellation is caller intent: the entry journals cancelled and reruns on a later resume unless covered by abandon (M7).",
10863
+ parameters: CANCEL_AGENT_SCHEMA,
10864
+ execute: (input) => {
10865
+ const params = input;
10866
+ return runtime.cancel(params.handle, params.reason);
10867
+ }
10868
+ });
10869
+ const waitForEvents = tool({
10870
+ name: WAIT_FOR_EVENTS_TOOL_NAME,
10871
+ description: "Sleep until a coalesced WakeDigest: quiescence (always armed), child_terminal, escalation, or budget_threshold at 50/80 percent. A trigger set that can never fire is a typed error.",
10872
+ parameters: WAIT_FOR_EVENTS_SCHEMA,
10873
+ execute: (input) => runtime.waitForEvents(input.triggers)
10874
+ });
10875
+ const finish = tool({
10876
+ name: FINISH_TOOL_NAME,
10877
+ description: "Terminate the orchestration with a result (run outcome ok).",
10878
+ parameters: FINISH_SCHEMA,
10879
+ execute: () => {
10880
+ throw new Error("finish is intercepted by the agent runtime, never executed");
10881
+ }
10882
+ });
10883
+ const tools = [
10884
+ spawnAgent,
10885
+ parallelAgents,
10886
+ awaitAny,
10887
+ awaitAll,
10888
+ cancelAgent,
10889
+ waitForEvents
10841
10890
  ];
10891
+ if (options?.childResultTools === true) tools.push(tool({
10892
+ name: GET_CHILD_RESULT_TOOL_NAME,
10893
+ description: "Read a page of a SETTLED child's FULL output (the digest is truncated to 400 chars). Pages with offset and maxChars; the reply reports totalChars and hasMore.",
10894
+ parameters: GET_CHILD_RESULT_SCHEMA,
10895
+ execute: (input) => {
10896
+ const p = input;
10897
+ return runtime.getChildResult(p.handle, {
10898
+ offset: p.offset,
10899
+ maxChars: p.maxChars
10900
+ });
10901
+ }
10902
+ }), tool({
10903
+ name: READ_CHILD_ARTIFACT_TOOL_NAME,
10904
+ description: "Read a page of a SETTLED child's artifact content by id (ids come from get_child_result or a digest). Pages with offset and maxChars.",
10905
+ parameters: READ_CHILD_ARTIFACT_SCHEMA,
10906
+ execute: (input) => {
10907
+ const p = input;
10908
+ return runtime.readChildArtifact(p.handle, p.artifactId, {
10909
+ offset: p.offset,
10910
+ maxChars: p.maxChars
10911
+ });
10912
+ }
10913
+ }));
10914
+ tools.push(finish);
10915
+ return tools;
10842
10916
  }
10843
10917
  //#endregion
10844
10918
  //#region src/engine/internal.ts
@@ -12477,6 +12551,29 @@ async function executeWorkflow(internals, wf, args) {
12477
12551
  */
12478
12552
  const ORCHESTRATE_WORKFLOW_NAME = "rulvar-orchestrate";
12479
12553
  /**
12554
+ * One page of a string, for the child result evidence tools: maxChars is
12555
+ * clamped to [1, MAX] and offset to [0, length], so a hostile or absent
12556
+ * paging argument can never throw or read past the end. The window is measured in
12557
+ * UTF-16 code units, the same unit the model counts, so hasMore and the
12558
+ * next offset are exact.
12559
+ */
12560
+ function pageOf(content, rawOffset, rawMaxChars) {
12561
+ const totalChars = content.length;
12562
+ const offset = Math.min(Math.max(0, Math.trunc(rawOffset ?? 0)), totalChars);
12563
+ const end = Math.min(offset + Math.min(Math.max(1, Math.trunc(rawMaxChars ?? 4e3)), MAX_CHILD_RESULT_PAGE_CHARS), totalChars);
12564
+ return {
12565
+ totalChars,
12566
+ offset,
12567
+ content: content.slice(offset, end),
12568
+ hasMore: end < totalChars
12569
+ };
12570
+ }
12571
+ /** The serialized full result of a settled child: the raw string, or JSON. */
12572
+ function serializeChildOutput(result) {
12573
+ if (result.status !== "ok") return result.errorMessage ?? `terminal status ${result.status}`;
12574
+ return typeof result.output === "string" ? result.output : JSON.stringify(result.output ?? null);
12575
+ }
12576
+ /**
12480
12577
  * The orchestrate intake gate (v1.35.0 review P2-2): every numeric
12481
12578
  * option and the atCap literal validate SYNCHRONOUSLY at workflow
12482
12579
  * construction, shared by both surfaces (the top level orchestrate() throws
@@ -12490,6 +12587,12 @@ function validateOrchestrateOptions(opts) {
12490
12587
  if (opts === void 0) return;
12491
12588
  if (opts.maxSpawns !== void 0) requireNonNegativeInteger(opts.maxSpawns, "orchestrate maxSpawns");
12492
12589
  if (opts.renderBudgetChars !== void 0) requireNonNegativeInteger(opts.renderBudgetChars, "orchestrate renderBudgetChars");
12590
+ if (opts.acceptance !== void 0) {
12591
+ const policy = opts.acceptance.childPolicy;
12592
+ const minSuccessful = typeof policy === "object" && policy !== null && !Array.isArray(policy) ? policy.minSuccessful : void 0;
12593
+ if (policy !== "all-ok" && minSuccessful === void 0) throw new ConfigError(`orchestrate acceptance.childPolicy must be 'all-ok' or { minSuccessful: N }; got ${JSON.stringify(policy)}`);
12594
+ if (policy !== "all-ok") requirePositiveInteger(minSuccessful, "orchestrate acceptance.childPolicy.minSuccessful");
12595
+ }
12493
12596
  const spec = opts.budget;
12494
12597
  if (spec === void 0) return;
12495
12598
  if (spec.capUsd !== void 0) requireNonNegativeNumber(spec.capUsd, "orchestrate budget.capUsd");
@@ -13231,6 +13334,48 @@ function makeOrchestratorWorkflow(goal, opts) {
13231
13334
  async cancel(handle, reason) {
13232
13335
  await recoveryDone;
13233
13336
  return cancelByHandle(handle, reason);
13337
+ },
13338
+ async getChildResult(handle, opts) {
13339
+ await recoveryDone;
13340
+ const record = records.get(handle);
13341
+ if (record === void 0) throw new ConfigError(`get_child_result: unknown handle ${String(handle)}`);
13342
+ const settled = record.settled;
13343
+ if (settled === void 0) throw new ConfigError(`get_child_result: child ${String(handle)} has not settled; await it first`);
13344
+ const page = pageOf(serializeChildOutput(settled), opts?.offset, opts?.maxChars);
13345
+ return {
13346
+ handle,
13347
+ status: settled.status,
13348
+ ...page,
13349
+ artifacts: (settled.artifacts ?? []).map((artifact) => ({
13350
+ id: artifact.id,
13351
+ kind: artifact.kind,
13352
+ ...artifact.label === void 0 ? {} : { label: artifact.label }
13353
+ }))
13354
+ };
13355
+ },
13356
+ async readChildArtifact(handle, artifactId, opts) {
13357
+ await recoveryDone;
13358
+ const record = records.get(handle);
13359
+ if (record === void 0) throw new ConfigError(`read_child_artifact: unknown handle ${String(handle)}`);
13360
+ const settled = record.settled;
13361
+ if (settled === void 0) throw new ConfigError(`read_child_artifact: child ${String(handle)} has not settled; await it first`);
13362
+ const artifact = (settled.artifacts ?? []).find((a) => a.id === artifactId);
13363
+ if (artifact === void 0) throw new ConfigError(`read_child_artifact: child ${String(handle)} has no artifact '${artifactId}'`);
13364
+ let raw = "";
13365
+ if (artifact.data !== void 0) raw = typeof artifact.data === "string" ? artifact.data : JSON.stringify(artifact.data);
13366
+ else if (artifact.ref !== void 0) {
13367
+ const blob = await internals.transcripts.get(artifact.ref);
13368
+ raw = blob === null ? "" : new TextDecoder().decode(blob);
13369
+ }
13370
+ const page = pageOf(raw, opts?.offset, opts?.maxChars);
13371
+ return {
13372
+ handle,
13373
+ artifactId,
13374
+ kind: artifact.kind,
13375
+ ...artifact.label === void 0 ? {} : { label: artifact.label },
13376
+ ...page,
13377
+ ...artifact.files === void 0 ? {} : { files: artifact.files }
13378
+ };
13234
13379
  }
13235
13380
  };
13236
13381
  if (extension?.boot !== void 0) await extension.boot(io);
@@ -13306,7 +13451,7 @@ function makeOrchestratorWorkflow(goal, opts) {
13306
13451
  const agentOpts = {
13307
13452
  role: "orchestrate",
13308
13453
  result: "full",
13309
- tools: [...buildOrchestratorTools(orchestratorRuntime, fullCardText), ...extension?.tools(io) ?? []],
13454
+ tools: [...buildOrchestratorTools(orchestratorRuntime, fullCardText, { childResultTools: opts?.exposeChildResultTools === true }), ...extension?.tools(io) ?? []],
13310
13455
  ...capState === void 0 ? {} : { estCost: capState.effectiveCapUsd - (orchestratorAccount === void 0 ? 0 : internals.budget.accountView(orchestratorAccount)?.finalizeReserveUsd ?? 0) },
13311
13456
  ...opts?.model === void 0 ? {} : { model: opts.model },
13312
13457
  ...opts?.limits === void 0 ? {} : { limits: opts.limits },
@@ -13417,7 +13562,55 @@ function makeOrchestratorWorkflow(goal, opts) {
13417
13562
  if (capDecisionRef !== void 0) return await settleCapOutcome();
13418
13563
  if (orchestratorAccount !== void 0) internals.cost.orchestrator.spentUsd = internals.budget.accountView(orchestratorAccount)?.spentUsd ?? 0;
13419
13564
  if (result.status !== "ok") throw new ConfigError(`the orchestrator agent terminated with status '${result.status}'` + (result.errorMessage === void 0 ? "" : `: ${result.errorMessage}`));
13420
- return result.output;
13565
+ if (opts?.acceptance === void 0) return result.output;
13566
+ const acceptanceKey = "acceptance";
13567
+ const priorAcceptance = internals.replayer.snapshot().find((entry) => entry.kind === "decision" && entry.scope === callingState.scope && entry.key === acceptanceKey);
13568
+ let decision;
13569
+ if (priorAcceptance !== void 0) decision = priorAcceptance.value;
13570
+ else {
13571
+ const childStatusCounts = {};
13572
+ const degradedReasons = [];
13573
+ const sortedRecords = [...records.values()].sort((a, b) => a.spawnOrdinal - b.spawnOrdinal);
13574
+ for (const record of sortedRecords) {
13575
+ const status = record.settled?.status ?? "running";
13576
+ childStatusCounts[status] = (childStatusCounts[status] ?? 0) + 1;
13577
+ if (status !== "ok") degradedReasons.push(status === "running" ? `child ${record.nodeId} was still running when finish validated` : `child ${record.nodeId} settled '${status}'`);
13578
+ }
13579
+ const childPolicy = opts.acceptance.childPolicy;
13580
+ const accepted = childPolicy === "all-ok" ? degradedReasons.length === 0 : (childStatusCounts.ok ?? 0) >= childPolicy.minSuccessful;
13581
+ decision = {
13582
+ decisionType: "orchestrator_acceptance",
13583
+ verdict: accepted ? "accepted" : "rejected",
13584
+ completion: !accepted ? "rejected" : degradedReasons.length === 0 ? "complete" : "partial",
13585
+ childPolicy,
13586
+ childStatusCounts,
13587
+ degradedReasons
13588
+ };
13589
+ await internals.replayer.appendSinglePhase({
13590
+ scope: callingState.scope,
13591
+ key: acceptanceKey,
13592
+ kind: "decision",
13593
+ status: "ok",
13594
+ spanId: internals.spans.mint(callingState.spanId),
13595
+ site: "orchestrator-acceptance",
13596
+ value: decision
13597
+ });
13598
+ }
13599
+ if (decision.verdict === "rejected") {
13600
+ const required = decision.childPolicy === "all-ok" ? "every child ok" : `at least ${String(decision.childPolicy.minSuccessful)} children ok`;
13601
+ 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: {
13602
+ source: "orchestrator_acceptance",
13603
+ childPolicy: decision.childPolicy,
13604
+ childStatusCounts: decision.childStatusCounts,
13605
+ degradedReasons: decision.degradedReasons
13606
+ } });
13607
+ }
13608
+ return {
13609
+ result: result.output,
13610
+ completion: decision.completion,
13611
+ childStatusCounts: decision.childStatusCounts,
13612
+ degradedReasons: decision.degradedReasons
13613
+ };
13421
13614
  });
13422
13615
  }
13423
13616
  /**
@@ -14589,4 +14782,4 @@ function createSandboxBridge(ctx, options) {
14589
14782
  };
14590
14783
  }
14591
14784
  //#endregion
14592
- 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, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, 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, 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 };
14785
+ 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_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, 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, 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, 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.40.0",
3
+ "version": "1.42.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",