@rulvar/core 1.58.0 → 1.59.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
@@ -1514,8 +1514,12 @@ interface ToolContext {
1514
1514
  }
1515
1515
  /**
1516
1516
  * Where execute runs. A declared capability consumed by dispatch and
1517
- * policy; only 'inprocess' is enforced in v1, subprocess/container remain
1518
- * declared capability while the executor design stays an open question.
1517
+ * policy. 'inprocess' runs the tool's `execute` closure in the engine
1518
+ * process (full host capabilities, an execution convenience). A
1519
+ * non-inprocess tag routes dispatch through the engine's registered
1520
+ * ToolExecutorProvider (RV-216) instead, so the tool's work runs out of
1521
+ * process under host-owned isolation; the shipped reference adapters live
1522
+ * in `@rulvar/executor`. The tag never enters toolsetHash.
1519
1523
  */
1520
1524
  type ToolExecutor = "inprocess" | "subprocess" | "container";
1521
1525
  /**
@@ -1533,6 +1537,14 @@ interface ToolDef<S extends SchemaSpec = SchemaSpec> {
1533
1537
  readonly version?: string;
1534
1538
  /** Default 'inprocess'. */
1535
1539
  readonly executor: ToolExecutor;
1540
+ /**
1541
+ * Opaque policy data for a non-inprocess executor: what THIS tool's
1542
+ * declared executor should run (for a subprocess adapter, the command
1543
+ * and its argv). Never identity: excluded from toolsetHash exactly like
1544
+ * `executor` and `risk`, and ignored for 'inprocess'. The engine passes
1545
+ * it verbatim to the ToolExecutorProvider (RV-216).
1546
+ */
1547
+ readonly executorSpec?: Json;
1536
1548
  /** Default false; the terminal permission default asks when true. */
1537
1549
  readonly needsApproval: boolean;
1538
1550
  readonly risk?: ToolRisk;
@@ -1775,6 +1787,67 @@ interface QuotaLimiter {
1775
1787
  reconcile(reservationId: string, usage: Usage): Promise<void>;
1776
1788
  }
1777
1789
  //#endregion
1790
+ //#region src/l0/spi/executor.d.ts
1791
+ /** The non-inprocess executor tags a provider can be registered under. */
1792
+ type IsolatedExecutorTag = Exclude<ToolExecutor, "inprocess">;
1793
+ /**
1794
+ * The per-call context handed to a ToolExecutorProvider. It carries the
1795
+ * tool span (so provider telemetry nests under the run tree), the
1796
+ * cancellation signal, and a stable idempotency key.
1797
+ */
1798
+ interface IsolatedExecContext {
1799
+ runId: string;
1800
+ /** The tool span, minted under the agent span exactly like inprocess. */
1801
+ spanId: string;
1802
+ agentType: string;
1803
+ /**
1804
+ * Stable identity of THIS logical tool call: identical
1805
+ * (runId, tool, args) always derive the same key, so a provider whose
1806
+ * work has external side effects can fold an at-least-once retry into
1807
+ * effectively-once. A rerun of the same call after a mid-flight crash
1808
+ * reuses the key; a different call never collides.
1809
+ */
1810
+ idempotencyKey: string;
1811
+ /** Fires on cancellation, a budget ceiling, or UsageLimits expiry. */
1812
+ signal: AbortSignal;
1813
+ /** Emits telemetry log events under the tool span; never journals. */
1814
+ log(level: "debug" | "info" | "warn" | "error", msg: string, data?: Json): void;
1815
+ }
1816
+ /** One out-of-process tool dispatch. */
1817
+ interface IsolatedExecRequest {
1818
+ /** The declared executor tag ('subprocess' | 'container'). */
1819
+ executor: IsolatedExecutorTag;
1820
+ /** The tool contract name. */
1821
+ tool: string;
1822
+ /** The validated arguments, after the permission chain rewrote them. */
1823
+ args: Json;
1824
+ /**
1825
+ * The tool's `executorSpec`: opaque host data telling THIS provider
1826
+ * what to run (for a subprocess adapter, the command and its argv).
1827
+ * Never identity; the engine passes it through verbatim.
1828
+ */
1829
+ spec: Json;
1830
+ ctx: IsolatedExecContext;
1831
+ }
1832
+ /**
1833
+ * The isolated tool executor seam. A provider runs one dispatch to its
1834
+ * JSON result. A thrown error becomes the call's error tool result, never
1835
+ * a run abort: an executor failure (non-zero exit, timeout kill,
1836
+ * unparseable output, infrastructure error) is surfaced to the model
1837
+ * exactly like any other tool error, so the loop can react and the run
1838
+ * stays durable.
1839
+ */
1840
+ interface ToolExecutorProvider {
1841
+ /** Runs one dispatch to its JSON result; throws to signal tool failure. */
1842
+ run(request: IsolatedExecRequest): Promise<Json>;
1843
+ }
1844
+ /**
1845
+ * The engine's executor registry: at most one provider per non-inprocess
1846
+ * tag. A tool whose `executor` tag is absent here fails typed at spawn
1847
+ * time, before any provider or model call.
1848
+ */
1849
+ type ExecutorRegistry = Partial<Record<IsolatedExecutorTag, ToolExecutorProvider>>;
1850
+ //#endregion
1778
1851
  //#region src/knowledge/decay.d.ts
1779
1852
  /**
1780
1853
  * The asymmetric TTL table:
@@ -4003,6 +4076,14 @@ interface ToolRuntime {
4003
4076
  contextFor(toolName: string): ToolContext;
4004
4077
  /** Permission chain evaluation (M3-T03); absent = every call allowed. */
4005
4078
  permission?: (call: ToolCallRequest) => Promise<PermissionGate>;
4079
+ /**
4080
+ * Runs a non-inprocess tool out of process through the engine's
4081
+ * registered ToolExecutorProvider (RV-216). Present whenever the frozen
4082
+ * toolset holds any non-inprocess tool; the ctx layer mints the tool
4083
+ * span and idempotency key and wires the provider. A throw becomes the
4084
+ * call's error tool result exactly like an inprocess execute throw.
4085
+ */
4086
+ executeExternal?: (def: ToolDef, args: Json) => Promise<unknown>;
4006
4087
  }
4007
4088
  /** One serving target of a phase: the primary or a failover fallback. */
4008
4089
  interface PhaseTarget {
@@ -4309,7 +4390,7 @@ declare function emptyToolset(): ResolvedToolset;
4309
4390
  * without one, string entries fail with the same unknown-name error as
4310
4391
  * a miss, so nothing outside the declared registry is ever reachable.
4311
4392
  */
4312
- declare function resolveToolset(specs: ToolsOption | undefined, session: ToolSourceSession, toolsets?: Record<string, ToolsOption>): Promise<ResolvedToolset>;
4393
+ declare function resolveToolset(specs: ToolsOption | undefined, session: ToolSourceSession, toolsets?: Record<string, ToolsOption>, executors?: ReadonlySet<string>): Promise<ResolvedToolset>;
4313
4394
  //#endregion
4314
4395
  //#region src/journal/termination.d.ts
4315
4396
  /** The frozen limits vector written into termination.init. */
@@ -5510,6 +5591,19 @@ interface CreateEngineOptions {
5510
5591
  sandbox?: ScriptRunner;
5511
5592
  };
5512
5593
  /**
5594
+ * Isolated tool executors (RV-216): one ToolExecutorProvider per
5595
+ * non-inprocess `executor` tag. A tool declaring `executor: 'subprocess'`
5596
+ * or `'container'` dispatches through the matching provider, so its work
5597
+ * runs OUT of the engine process under host-owned isolation instead of
5598
+ * as an inprocess closure with full host capabilities. The shipped
5599
+ * reference adapters (subprocessExecutor, containerExecutor) live in
5600
+ * `@rulvar/executor`. Absent = only inprocess tools are accepted, and a
5601
+ * non-inprocess tag is a typed ConfigError at spawn time. In-process
5602
+ * tools stay ordinary function calls: never a sandbox for hostile or
5603
+ * model-generated code.
5604
+ */
5605
+ executors?: ExecutorRegistry;
5606
+ /**
5513
5607
  * The InProcessRunner escalation hook:
5514
5608
  * receives escalated results when the call form cannot carry them; the
5515
5609
  * returned decision is journaled as the authoritative
@@ -7261,6 +7355,14 @@ interface RunInternals {
7261
7355
  /** The worktree lifecycle provider. */
7262
7356
  isolation?: IsolationProvider;
7263
7357
  /**
7358
+ * Isolated tool executors (RV-216): the ToolExecutorProvider registry
7359
+ * from createEngine, keyed by non-inprocess executor tag. A tool
7360
+ * declaring such a tag dispatches through the matching provider instead
7361
+ * of running its inprocess closure; absent means only inprocess tools
7362
+ * are accepted.
7363
+ */
7364
+ executors?: ExecutorRegistry;
7365
+ /**
7264
7366
  * The ModelKnowledge runtime handle (M10-T03): current()
7265
7367
  * only, commit physically absent. Present only when the engine was
7266
7368
  * given stores.modelKnowledge; absent means the feature is off and
@@ -7438,6 +7540,8 @@ interface ToolInit<S extends SchemaSpec> {
7438
7540
  version?: string;
7439
7541
  /** Default 'inprocess'. */
7440
7542
  executor?: ToolExecutor;
7543
+ /** Opaque data for a non-inprocess executor (RV-216); never identity. */
7544
+ executorSpec?: Json;
7441
7545
  /** Default false. */
7442
7546
  needsApproval?: boolean;
7443
7547
  /** Policy metadata; never identity. */
@@ -8484,4 +8588,4 @@ interface SandboxBridge {
8484
8588
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
8485
8589
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
8486
8590
  //#endregion
8487
- export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, type AdaptiveEvents, AdmissionController, AdmissionDecision, AdmissionRejectedError, AdmissionStatsBefore, AdmitLineage, AdmitRejectReason, AdmitSpec, AdmitVerdict, AgentCallError, AgentError, type AgentEvents, AgentIdentityInput, type AgentInvocationRow, AgentOpts, AgentProfile, AgentProfilePermissions, AgentProfileTemplateOptions, AgentResult, AgentResultMeta, AgentStatus, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, AuditCategory, AuditRecord, AuditRunsOptions, BUDGET_ABORT_REASON, BaseAppend, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildIdentityInput, ChildResultPage, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DataKeyProvider, DebitResult, DeclaredLadder, DedupIndex, DedupNote, DedupedClaims, DerivedKey, DeriverRegistry, type DeterminismConfig, DeterminismError, type DeterminismEvents, type DeterminismMode, DispositionRule, DispositionTable, DonorCandidate, DonorRef, DroppedItem, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EffectiveUsageLimits, Effort, Engine, EngineDefaults, EngineQuotaConfig, EngineQuotaRuntime, EntryKind, EntryRef, EntryStatus, EnvelopeEncryption, EnvelopeEncryptionOptions, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, type ExplorationSummary, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, FinishValidationChild, FinishValidationInput, FinishValidationSpec, FinishValidationVerdict, FinishValidator, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, IncrementalSynthesisResult, InvalidResolutionError, InvocationRole, type InvocationTable, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JOURNAL_ENVELOPE_MARKER, 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, MemoryQuotaLimiter, type MetaLookupStore, type ModelCaps, ModelChoice, type ModelClaim, ModelEpochInputs, type ModelKnowledgeHandle, type ModelKnowledgeStore, ModelListConstraint, ModelRef, ModelRetry, ModelSpec, Msg, NoProgressDetector, NodeId, NodeLinkValue, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OnEscalation, OperationDisposition, OrchestrateAcceptance, OrchestrateOptions, OrchestrateSynthesis, OrchestratorBudgetSpec, OrchestratorCapConfigError, OrchestratorExtension, OrchestratorExtensionIO, OrchestratorRuntime, Out, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, Part, PendingExternal, PendingToolTurn, PermissionConfig, PermissionGate, PermissionHook, PermissionPreset, PermissionRule, PermissionVerdict, type PhaseRow, PhaseTarget, PipelineCollected, PipelineOpts, PlanInvariantError, PriceTable, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, QUOTA_WINDOW_MS, QualityFloors, QuotaCounters, type QuotaDecision, type QuotaEstimate, type QuotaLimiter, type QuotaReservationRequest, QuotaRule, QuotaWindowSnapshot, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, RandIdentityInput, RandPayload, ReconcileOptions, ReconcileResult, RefEntryAppender, RefEntryClassification, RefusalInfo, RepeatedClaim, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, RepositoryResearchToolset, RepositoryResearchToolsetOptions, ResearchAgentProfileOptions, ResearchAgentProfileResult, ResearchEvidenceEntry, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunAuditVerdict, RunBudget, RunEventSink, RunExport, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStateAudit, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, SecretMasker, Semaphore, SerializationHook, Settled, ShellPatternRules, ShellSegment, ShellVerdict, SinglePhaseAppend, SpanMinter, SpanRegistry, SpawnAdmissionValue, SpawnAgentParams, SpawnKey, SpawnLineage, SpawnLineageOpt, SpawnOrigin, SpawnRecord, Spend, Stage, type StandardJSONSchemaV1, type StandardSchemaV1, StepIdentityInput, StructuredOutputTier, SuspendedAppend, SuspensionState, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, TerminalPatch, TerminationAccount, TerminationAccountSnapshot, TerminationDeniedValue, TerminationDeniedWriter, TerminationInitValue, TerminationLimits, TerminationResource, ToolCallRequest, ToolChoice, type ToolContext, ToolContextSeed, ToolContract, type ToolDef, type ToolEvents, type ToolExecutor, ToolInit, type ToolRisk, ToolRuntime, type ToolSource, type ToolSourceSession, ToolsOption, TranscriptSerializationHook, type TranscriptStore, TriggerClass, TtlState, Usage, UsageLimits, UsageSlice, VerifiedRecommendation, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, WakeBudgetBlock, WakeDigest, WakeTrigger, WireError, Workflow, WorkflowCallOpts, type WorkflowEvent, type WorkflowEventBody, WorkflowRegistry, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, identityJcs, implementationAgentProfile, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceAuditTrail, reduceCriticalPath, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
8591
+ export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, type AdaptiveEvents, AdmissionController, AdmissionDecision, AdmissionRejectedError, AdmissionStatsBefore, AdmitLineage, AdmitRejectReason, AdmitSpec, AdmitVerdict, AgentCallError, AgentError, type AgentEvents, AgentIdentityInput, type AgentInvocationRow, AgentOpts, AgentProfile, AgentProfilePermissions, AgentProfileTemplateOptions, AgentResult, AgentResultMeta, AgentStatus, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, AuditCategory, AuditRecord, AuditRunsOptions, BUDGET_ABORT_REASON, BaseAppend, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildIdentityInput, ChildResultPage, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DataKeyProvider, DebitResult, DeclaredLadder, DedupIndex, DedupNote, DedupedClaims, DerivedKey, DeriverRegistry, type DeterminismConfig, DeterminismError, type DeterminismEvents, type DeterminismMode, DispositionRule, DispositionTable, DonorCandidate, DonorRef, DroppedItem, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EffectiveUsageLimits, Effort, Engine, EngineDefaults, EngineQuotaConfig, EngineQuotaRuntime, EntryKind, EntryRef, EntryStatus, EnvelopeEncryption, EnvelopeEncryptionOptions, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, type ExecutorRegistry, type ExplorationSummary, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, FinishValidationChild, FinishValidationInput, FinishValidationSpec, FinishValidationVerdict, FinishValidator, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, IncrementalSynthesisResult, InvalidResolutionError, InvocationRole, type InvocationTable, type IsolatedExecContext, type IsolatedExecRequest, type IsolatedExecutorTag, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JOURNAL_ENVELOPE_MARKER, 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, MemoryQuotaLimiter, type MetaLookupStore, type ModelCaps, ModelChoice, type ModelClaim, ModelEpochInputs, type ModelKnowledgeHandle, type ModelKnowledgeStore, ModelListConstraint, ModelRef, ModelRetry, ModelSpec, Msg, NoProgressDetector, NodeId, NodeLinkValue, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OnEscalation, OperationDisposition, OrchestrateAcceptance, OrchestrateOptions, OrchestrateSynthesis, OrchestratorBudgetSpec, OrchestratorCapConfigError, OrchestratorExtension, OrchestratorExtensionIO, OrchestratorRuntime, Out, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, Part, PendingExternal, PendingToolTurn, PermissionConfig, PermissionGate, PermissionHook, PermissionPreset, PermissionRule, PermissionVerdict, type PhaseRow, PhaseTarget, PipelineCollected, PipelineOpts, PlanInvariantError, PriceTable, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, QUOTA_WINDOW_MS, QualityFloors, QuotaCounters, type QuotaDecision, type QuotaEstimate, type QuotaLimiter, type QuotaReservationRequest, QuotaRule, QuotaWindowSnapshot, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, RandIdentityInput, RandPayload, ReconcileOptions, ReconcileResult, RefEntryAppender, RefEntryClassification, RefusalInfo, RepeatedClaim, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, RepositoryResearchToolset, RepositoryResearchToolsetOptions, ResearchAgentProfileOptions, ResearchAgentProfileResult, ResearchEvidenceEntry, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunAuditVerdict, RunBudget, RunEventSink, RunExport, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStateAudit, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, SecretMasker, 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, type ToolExecutorProvider, ToolInit, type ToolRisk, ToolRuntime, type ToolSource, type ToolSourceSession, ToolsOption, TranscriptSerializationHook, type TranscriptStore, TriggerClass, TtlState, Usage, UsageLimits, UsageSlice, VerifiedRecommendation, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, WakeBudgetBlock, WakeDigest, WakeTrigger, WireError, Workflow, WorkflowCallOpts, type WorkflowEvent, type WorkflowEventBody, WorkflowRegistry, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, identityJcs, implementationAgentProfile, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceAuditTrail, reduceCriticalPath, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/dist/index.js CHANGED
@@ -3234,6 +3234,7 @@ function tool(init) {
3234
3234
  executor: init.executor ?? "inprocess",
3235
3235
  needsApproval: init.needsApproval ?? false,
3236
3236
  ...init.version === void 0 ? {} : { version: init.version },
3237
+ ...init.executorSpec === void 0 ? {} : { executorSpec: init.executorSpec },
3237
3238
  ...init.risk === void 0 ? {} : { risk: init.risk },
3238
3239
  execute: init.execute
3239
3240
  };
@@ -3288,7 +3289,7 @@ function isToolDef(spec) {
3288
3289
  * without one, string entries fail with the same unknown-name error as
3289
3290
  * a miss, so nothing outside the declared registry is ever reachable.
3290
3291
  */
3291
- async function resolveToolset(specs, session, toolsets) {
3292
+ async function resolveToolset(specs, session, toolsets, executors) {
3292
3293
  if (specs === void 0 || specs.length === 0) return emptyToolset();
3293
3294
  const tools = [];
3294
3295
  for (const spec of specs) {
@@ -3315,7 +3316,7 @@ async function resolveToolset(specs, session, toolsets) {
3315
3316
  for (const def of tools) {
3316
3317
  if (!TOOL_NAME_PATTERN.test(def.name)) throw new ConfigError(`imported tool name '${def.name}' must match ^[a-zA-Z0-9_-]{1,64}$; namespace it with the source prefix option`);
3317
3318
  if (seen.has(def.name)) throw new ConfigError(`duplicate tool name '${def.name}' in one toolset; disambiguate with the MCP prefix option`);
3318
- if (def.executor !== "inprocess") throw new ConfigError(`tool '${def.name}' declares executor '${def.executor}', but this engine implements only 'inprocess' in v1`);
3319
+ if (def.executor !== "inprocess" && !(executors?.has(def.executor) ?? false)) throw new ConfigError(`tool '${def.name}' declares executor '${def.executor}', but no such executor is registered; register one via createEngine({ executors }) (https://docs.rulvar.com/guide/isolated-executor)`);
3319
3320
  seen.set(def.name, def);
3320
3321
  }
3321
3322
  const contracts = tools.map((def) => toolContract(def));
@@ -10367,7 +10368,10 @@ async function executeToolCall(options) {
10367
10368
  issues: validation.issues.map((issue) => issue.message)
10368
10369
  }, "error");
10369
10370
  try {
10370
- const value = await def.execute(validation.value, runtime.contextFor(call.name));
10371
+ let value;
10372
+ if (def.executor === "inprocess") value = await def.execute(validation.value, runtime.contextFor(call.name));
10373
+ else if (runtime.executeExternal !== void 0) value = await runtime.executeExternal(def, validation.value);
10374
+ else return finish({ error: `tool '${call.name}' declares executor '${def.executor}' but no executor is registered` }, "error");
10371
10375
  const serialized = toJournalValue(value === void 0 ? null : value, `tool '${call.name}'`);
10372
10376
  options.retryCounts.delete(call.name);
10373
10377
  return finish(serialized, "ok");
@@ -13122,6 +13126,33 @@ function setLongTimeout(onDue, dueAtMs, now = Date.now) {
13122
13126
  } };
13123
13127
  }
13124
13128
  //#endregion
13129
+ //#region src/runtime/executor.ts
13130
+ /**
13131
+ * Isolated-executor dispatch helpers (RV-216). The engine routes a
13132
+ * non-inprocess tool call through the registered ToolExecutorProvider;
13133
+ * this module derives the stable per-call idempotency key the provider
13134
+ * receives, so an at-least-once retry of a side-effecting tool can be
13135
+ * folded into effectively-once.
13136
+ *
13137
+ * Public contract: https://docs.rulvar.com/guide/isolated-executor.
13138
+ */
13139
+ /**
13140
+ * Derives the idempotency key for one isolated tool dispatch. The key is
13141
+ * a pure function of the run, the tool name, and the JCS-canonical
13142
+ * arguments, so the same logical call always yields the same key
13143
+ * (byte-identical reruns dedupe) and distinct calls never collide. The
13144
+ * key never enters run identity; it exists only for the provider's own
13145
+ * side-effect deduplication.
13146
+ */
13147
+ function deriveExecIdempotencyKey(runId, tool, args) {
13148
+ const canonical = jcsSerialize({
13149
+ runId,
13150
+ tool,
13151
+ args
13152
+ });
13153
+ return createHash("sha256").update(canonical, "utf8").digest("hex");
13154
+ }
13155
+ //#endregion
13125
13156
  //#region src/engine/ctx.ts
13126
13157
  /**
13127
13158
  * Ctx primitives (M1-T07) plus the parallel/pipeline composition semantics
@@ -13393,7 +13424,7 @@ function createCtx(internals, rootWorkflow) {
13393
13424
  if (escalation.flavor === "B" && escalation.deadlineMs === void 0) throw new ConfigError("escalation flavor 'B' requires an explicit deadlineMs");
13394
13425
  }
13395
13426
  const declaredTools = opts.tools ?? profile?.tools ?? [];
13396
- const toolset = await resolveToolset(escalation === void 0 ? declaredTools : [...declaredTools, escalateTool()], { runId: internals.runId }, internals.defaults.toolsets);
13427
+ const toolset = await resolveToolset(escalation === void 0 ? declaredTools : [...declaredTools, escalateTool()], { runId: internals.runId }, internals.defaults.toolsets, internals.executors === void 0 ? void 0 : new Set(Object.keys(internals.executors)));
13397
13428
  const layers = [
13398
13429
  callLayer,
13399
13430
  profileLayer,
@@ -13915,6 +13946,38 @@ function createCtx(internals, rootWorkflow) {
13915
13946
  };
13916
13947
  }
13917
13948
  };
13949
+ if (internals.executors !== void 0) {
13950
+ const executors = internals.executors;
13951
+ toolRuntime.executeExternal = async (def, args) => {
13952
+ const tag = def.executor;
13953
+ const provider = executors[tag];
13954
+ if (provider === void 0) throw new ConfigError(`no executor registered for '${def.executor}'; register one via createEngine({ executors }) (https://docs.rulvar.com/guide/isolated-executor)`);
13955
+ const toolSpanId = internals.spans.mint(spanId);
13956
+ return provider.run({
13957
+ executor: tag,
13958
+ tool: def.name,
13959
+ args,
13960
+ spec: def.executorSpec ?? null,
13961
+ ctx: {
13962
+ runId: internals.runId,
13963
+ spanId: toolSpanId,
13964
+ agentType,
13965
+ idempotencyKey: deriveExecIdempotencyKey(internals.runId, def.name, args),
13966
+ signal: toolSignal,
13967
+ log: (level, msg, data) => internals.events.emit(data === void 0 ? {
13968
+ type: "log",
13969
+ level,
13970
+ msg
13971
+ } : {
13972
+ type: "log",
13973
+ level,
13974
+ msg,
13975
+ data
13976
+ }, toolSpanId)
13977
+ }
13978
+ });
13979
+ };
13980
+ }
13918
13981
  }
13919
13982
  const runAgentOptions = {
13920
13983
  prompt,
@@ -17196,6 +17259,7 @@ function createEngine(options) {
17196
17259
  pricingOf,
17197
17260
  runSignal: controller.signal,
17198
17261
  ...defaults.isolation === void 0 ? {} : { isolation: defaults.isolation },
17262
+ ...options.executors === void 0 ? {} : { executors: options.executors },
17199
17263
  ...options.onEscalation === void 0 ? {} : { onEscalation: options.onEscalation },
17200
17264
  external,
17201
17265
  mintTranscriptRef: () => `${runId}/t${transcriptCounter++}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.58.0",
3
+ "version": "1.59.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",