@rulvar/core 1.33.0 → 1.35.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 +78 -31
- package/dist/index.js +275 -52
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -2556,9 +2556,11 @@ declare class KeyedLimiter {
|
|
|
2556
2556
|
pending(key: string): number;
|
|
2557
2557
|
/**
|
|
2558
2558
|
* Runs `fn` under the key's semaphore; keys without a configured cap
|
|
2559
|
-
* run unlimited (no queueing, no overhead).
|
|
2559
|
+
* run unlimited (no queueing, no overhead). An aborted `signal` frees
|
|
2560
|
+
* a queued caller without a slot (the Semaphore contract), so run
|
|
2561
|
+
* cancellation drains provider queues too (v1.34.0 review P2-4).
|
|
2560
2562
|
*/
|
|
2561
|
-
withSlot<T>(key: string, fn: () => Promise<T>, onQueued?: () => void): Promise<T>;
|
|
2563
|
+
withSlot<T>(key: string, fn: () => Promise<T>, onQueued?: () => void, signal?: AbortSignal): Promise<T>;
|
|
2562
2564
|
}
|
|
2563
2565
|
//#endregion
|
|
2564
2566
|
//#region src/model/floors.d.ts
|
|
@@ -2881,15 +2883,6 @@ declare class NoProgressDetector {
|
|
|
2881
2883
|
}
|
|
2882
2884
|
//#endregion
|
|
2883
2885
|
//#region src/runtime/usage-limits.d.ts
|
|
2884
|
-
/**
|
|
2885
|
-
* UsageLimits (M1-T06): normative limit vocabulary and the per-spawn merge.
|
|
2886
|
-
*
|
|
2887
|
-
* Full contract: https://docs.rulvar.com/guide/agents. Expiry of maxTurns, maxToolCalls,
|
|
2888
|
-
* or timeoutMs produces the terminal status 'limit' (paid partial work);
|
|
2889
|
-
* streamIdleTimeoutMs expiry is a retryable transport-class AgentError,
|
|
2890
|
-
* never 'limit'. The run-level deadline is RunOptions.deadlineAt, not a
|
|
2891
|
-
* UsageLimits field.
|
|
2892
|
-
*/
|
|
2893
2886
|
interface UsageLimits {
|
|
2894
2887
|
/** Default 32. */
|
|
2895
2888
|
maxTurns?: number;
|
|
@@ -2924,6 +2917,19 @@ interface EffectiveUsageLimits {
|
|
|
2924
2917
|
* defaults.limits.
|
|
2925
2918
|
*/
|
|
2926
2919
|
declare function mergeUsageLimits(call?: UsageLimits, profile?: UsageLimits, engine?: UsageLimits): EffectiveUsageLimits;
|
|
2920
|
+
/**
|
|
2921
|
+
* Validates one UsageLimits layer at its intake boundary (v1.34.0
|
|
2922
|
+
* review P2-3): a malformed field (NaN, Infinity, a negative, a
|
|
2923
|
+
* fraction) is a typed ConfigError before the merge, before any journal
|
|
2924
|
+
* entry, and before any provider dispatch. `site` names the layer in the
|
|
2925
|
+
* error text (e.g. `RunOptions.limits`). Counts are positive integers
|
|
2926
|
+
* (maxToolCalls may be 0: a spawn that must not call tools).
|
|
2927
|
+
* streamIdleTimeoutMs is handed to setTimeout as-is, so it is bounded by
|
|
2928
|
+
* the Node timer maximum like RetryPolicy delays; timeoutMs is a
|
|
2929
|
+
* wall-clock comparison, so it has no upper bound. Every present field
|
|
2930
|
+
* is checked; absent fields keep their defaults.
|
|
2931
|
+
*/
|
|
2932
|
+
declare function validateUsageLimits(limits: UsageLimits, site: string): void;
|
|
2927
2933
|
//#endregion
|
|
2928
2934
|
//#region src/runtime/agent-loop.d.ts
|
|
2929
2935
|
type AgentStatus = "ok" | "error" | "limit" | "cancelled" | "skipped" | "escalated";
|
|
@@ -3111,8 +3117,10 @@ interface RunAgentOptions<S extends SchemaSpec = JsonSchema> {
|
|
|
3111
3117
|
/**
|
|
3112
3118
|
* Per-provider keyed limiter hook (M4-T07): wraps every wire dispatch
|
|
3113
3119
|
* under the serving adapter's key; absent = unlimited (Appendix A).
|
|
3120
|
+
* `signal` is the agent-level abort: an aborted caller leaves the
|
|
3121
|
+
* key's queue without a slot (v1.34.0 review P2-4).
|
|
3114
3122
|
*/
|
|
3115
|
-
providerSlot?: <T>(key: string, fn: () => Promise<T
|
|
3123
|
+
providerSlot?: <T>(key: string, fn: () => Promise<T>, signal?: AbortSignal) => Promise<T>;
|
|
3116
3124
|
/** The resolved toolset; absent = no tools declared. */
|
|
3117
3125
|
tools?: ToolRuntime;
|
|
3118
3126
|
/**
|
|
@@ -4799,7 +4807,17 @@ interface RunOptions {
|
|
|
4799
4807
|
budgetUsd?: number;
|
|
4800
4808
|
/** Run-level defaults merged over engine defaults. */
|
|
4801
4809
|
limits?: UsageLimits;
|
|
4802
|
-
/**
|
|
4810
|
+
/**
|
|
4811
|
+
* Run-level deadline: an ISO 8601 date-time with an explicit UTC
|
|
4812
|
+
* designator or offset (e.g. `2026-07-21T10:00:00Z` or
|
|
4813
|
+
* `2026-07-21T12:00:00+02:00`); crossing it cancels the run. Any
|
|
4814
|
+
* other string is a typed ConfigError thrown synchronously by
|
|
4815
|
+
* engine.run, before any journal entry or provider dispatch (v1.34.0
|
|
4816
|
+
* review P2-1). A deadline already in the past cancels immediately:
|
|
4817
|
+
* a crossed deadline is a valid deadline. Deadlines beyond the Node
|
|
4818
|
+
* timer maximum are honored through sliced timers, never truncated
|
|
4819
|
+
* (v1.34.0 review P2-2).
|
|
4820
|
+
*/
|
|
4803
4821
|
deadlineAt?: string;
|
|
4804
4822
|
name?: string;
|
|
4805
4823
|
tags?: string[];
|
|
@@ -5334,27 +5352,34 @@ declare function makeOrchestratorWorkflow(goal: string, opts?: OrchestrateOption
|
|
|
5334
5352
|
declare function orchestrate(engine: Engine, goal: string, opts?: OrchestrateOptions, runOptions?: RunOptions): RunHandle<unknown>;
|
|
5335
5353
|
//#endregion
|
|
5336
5354
|
//#region src/engine/scheduler.d.ts
|
|
5337
|
-
/**
|
|
5338
|
-
* Scheduler and concurrency (M1-T08): the per-run semaphore with a FIFO
|
|
5339
|
-
* queue (default 12 concurrent model calls). The engine lifetime spawn cap
|
|
5340
|
-
* is enforced by the budget layer at admission; parallel/pipeline
|
|
5341
|
-
* composition semantics live with ctx.
|
|
5342
|
-
* Per-provider concurrency keys land with M4.
|
|
5343
|
-
*/
|
|
5344
5355
|
/** FIFO semaphore; default per-run width is 12. */
|
|
5345
5356
|
declare const DEFAULT_PER_RUN_CONCURRENCY = 12;
|
|
5346
5357
|
declare class Semaphore {
|
|
5347
5358
|
private readonly limit;
|
|
5348
5359
|
private active;
|
|
5349
5360
|
private readonly waiters;
|
|
5361
|
+
/**
|
|
5362
|
+
* `limit` must be a positive integer: anything else (NaN included) is
|
|
5363
|
+
* a typed ConfigError. Before this gate a NaN limit made
|
|
5364
|
+
* `active < limit` permanently false, so the first acquire queued
|
|
5365
|
+
* forever and the run could not settle, not even through cancel()
|
|
5366
|
+
* (v1.34.0 review P2-4). Unlimited is expressed by not constructing a
|
|
5367
|
+
* semaphore, never by a sentinel limit.
|
|
5368
|
+
*/
|
|
5350
5369
|
constructor(limit: number);
|
|
5351
5370
|
get pending(): number;
|
|
5352
5371
|
/**
|
|
5353
5372
|
* Acquires a slot, resolving in FIFO order. `onQueued` fires only when
|
|
5354
5373
|
* the caller actually has to wait (feeds the agent:queued event).
|
|
5355
|
-
|
|
5356
|
-
|
|
5357
|
-
|
|
5374
|
+
* An aborted `signal` releases the caller from the queue without a
|
|
5375
|
+
* slot: the returned release is a no-op, the remaining waiters keep
|
|
5376
|
+
* their FIFO positions, and the caller proceeds to observe its own
|
|
5377
|
+
* aborted signal (the model layers refuse dispatch under an aborted
|
|
5378
|
+
* signal, so no provider call follows). Cancellation can therefore
|
|
5379
|
+
* always drain a queued run (v1.34.0 review P2-4).
|
|
5380
|
+
*/
|
|
5381
|
+
acquire(onQueued?: () => void, signal?: AbortSignal): Promise<() => void>;
|
|
5382
|
+
withSlot<T>(fn: () => Promise<T>, onQueued?: () => void, signal?: AbortSignal): Promise<T>;
|
|
5358
5383
|
private release;
|
|
5359
5384
|
}
|
|
5360
5385
|
//#endregion
|
|
@@ -6100,13 +6125,35 @@ interface McpConfig {
|
|
|
6100
6125
|
risk?: Record<string, ToolRisk>;
|
|
6101
6126
|
}
|
|
6102
6127
|
/**
|
|
6103
|
-
*
|
|
6104
|
-
*
|
|
6105
|
-
*
|
|
6106
|
-
*
|
|
6107
|
-
*
|
|
6108
|
-
|
|
6109
|
-
|
|
6128
|
+
* The ToolSource returned by {@link mcp}: the frozen ToolSource seam
|
|
6129
|
+
* plus the lifecycle the seam deliberately leaves to the host.
|
|
6130
|
+
* `close()` releases everything the source created on first use: the
|
|
6131
|
+
* SDK client, its transport, and, for stdio, the spawned child
|
|
6132
|
+
* process, without which a one shot host process cannot exit
|
|
6133
|
+
* naturally after a run, because the child and its pipes keep the
|
|
6134
|
+
* event loop alive (v1.33.0 review P2). It is idempotent, resolves
|
|
6135
|
+
* even when the connection never succeeded, and resets the source, so
|
|
6136
|
+
* a later `tools()` call connects afresh. The engine never closes a
|
|
6137
|
+
* source, because one source may serve many runs: the host owns the
|
|
6138
|
+
* lifecycle and should close once its runs have settled (closing
|
|
6139
|
+
* while a run is in flight fails that run's MCP tool calls).
|
|
6140
|
+
*/
|
|
6141
|
+
interface McpToolSource extends ToolSource {
|
|
6142
|
+
close(): Promise<void>;
|
|
6143
|
+
}
|
|
6144
|
+
/**
|
|
6145
|
+
* Imports MCP tools as a {@link McpToolSource}. The client connects
|
|
6146
|
+
* lazily on the first tools() call; tools/list is fetched with cursor
|
|
6147
|
+
* pagination until exhaustion and cached per session; a listChanged
|
|
6148
|
+
* notification invalidates the cache, affecting subsequently spawned
|
|
6149
|
+
* agents only (a spawn's toolset snapshot is immutable by
|
|
6150
|
+
* construction). The host owns the source's lifecycle: `close()`
|
|
6151
|
+
* releases the client, the transport, and the stdio child once the
|
|
6152
|
+
* runs using the source have settled; a one shot host should close in
|
|
6153
|
+
* a finally block, or its process never exits naturally (v1.33.0
|
|
6154
|
+
* review P2).
|
|
6155
|
+
*/
|
|
6156
|
+
declare function mcp(cfg: McpConfig): McpToolSource;
|
|
6110
6157
|
//#endregion
|
|
6111
6158
|
//#region src/tools/isolation.d.ts
|
|
6112
6159
|
/** Appendix A: the shared pin cap (park/unpark and retainWorktree). */
|
|
@@ -6732,4 +6779,4 @@ interface SandboxBridge {
|
|
|
6732
6779
|
declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
|
|
6733
6780
|
declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
|
|
6734
6781
|
//#endregion
|
|
6735
|
-
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, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, InvocationRole, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, JournalSerializationHook, type JournalStore, type Json, JsonSchema, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, type KbProposal, type KbProposalTrigger, KeyDeriver, KeyRing, KeyedLimiter, KnowledgeCasError, type KnowledgeSnapshot, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LadderSpec, type LeasableStore, type Lease, LeaseHeldError, Ledger, LineageCounters, LineageIndex, LineageRef, LineageRelation, LineageStats, LogicalTaskId, MASKED_SECRET, MAX_DEPTH_CEILING, MatchResult, McpConfig, MechanicalGateProfile, MechanicalGateVerdict, type 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, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
|
|
6782
|
+
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, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, InvocationRole, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, JournalSerializationHook, type JournalStore, type Json, JsonSchema, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, type KbProposal, type KbProposalTrigger, KeyDeriver, KeyRing, KeyedLimiter, KnowledgeCasError, type KnowledgeSnapshot, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LadderSpec, type LeasableStore, type Lease, LeaseHeldError, Ledger, LineageCounters, LineageIndex, LineageRef, LineageRelation, LineageStats, LogicalTaskId, MASKED_SECRET, MAX_DEPTH_CEILING, MatchResult, McpConfig, 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 };
|
package/dist/index.js
CHANGED
|
@@ -2893,11 +2893,16 @@ function errorText(result) {
|
|
|
2893
2893
|
return text === "" ? "MCP tool reported an error" : text;
|
|
2894
2894
|
}
|
|
2895
2895
|
/**
|
|
2896
|
-
* Imports MCP tools as a
|
|
2897
|
-
* first tools() call; tools/list is fetched with cursor
|
|
2898
|
-
* exhaustion and cached per session; a listChanged
|
|
2899
|
-
* invalidates the cache, affecting subsequently spawned
|
|
2900
|
-
* spawn's toolset snapshot is immutable by
|
|
2896
|
+
* Imports MCP tools as a {@link McpToolSource}. The client connects
|
|
2897
|
+
* lazily on the first tools() call; tools/list is fetched with cursor
|
|
2898
|
+
* pagination until exhaustion and cached per session; a listChanged
|
|
2899
|
+
* notification invalidates the cache, affecting subsequently spawned
|
|
2900
|
+
* agents only (a spawn's toolset snapshot is immutable by
|
|
2901
|
+
* construction). The host owns the source's lifecycle: `close()`
|
|
2902
|
+
* releases the client, the transport, and the stdio child once the
|
|
2903
|
+
* runs using the source have settled; a one shot host should close in
|
|
2904
|
+
* a finally block, or its process never exits naturally (v1.33.0
|
|
2905
|
+
* review P2).
|
|
2901
2906
|
*/
|
|
2902
2907
|
function mcp(cfg) {
|
|
2903
2908
|
validateConfig(cfg);
|
|
@@ -2908,19 +2913,24 @@ function mcp(cfg) {
|
|
|
2908
2913
|
name: "rulvar",
|
|
2909
2914
|
version: "1.0.0"
|
|
2910
2915
|
});
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2916
|
+
try {
|
|
2917
|
+
if (cfg.transport === "stdio") {
|
|
2918
|
+
const transport = new StdioClientTransport({
|
|
2919
|
+
command: cfg.command ?? "",
|
|
2920
|
+
...cfg.args === void 0 ? {} : { args: cfg.args }
|
|
2921
|
+
});
|
|
2922
|
+
await client.connect(transport);
|
|
2923
|
+
} else if (cfg.transport === "streamable-http") {
|
|
2924
|
+
const transport = new StreamableHTTPClientTransport(new URL(cfg.url ?? ""));
|
|
2925
|
+
await client.connect(transport);
|
|
2926
|
+
} else {
|
|
2927
|
+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
|
2928
|
+
await cfg.server.connect(serverTransport);
|
|
2929
|
+
await client.connect(clientTransport);
|
|
2930
|
+
}
|
|
2931
|
+
} catch (error) {
|
|
2932
|
+
await client.close().catch(() => void 0);
|
|
2933
|
+
throw error;
|
|
2924
2934
|
}
|
|
2925
2935
|
client.setNotificationHandler(ToolListChangedNotificationSchema, () => {
|
|
2926
2936
|
cache = void 0;
|
|
@@ -2980,6 +2990,19 @@ function mcp(cfg) {
|
|
|
2980
2990
|
const allowSet = cfg.allow === void 0 ? void 0 : new Set(cfg.allow);
|
|
2981
2991
|
cache = wireTools.filter((wire) => !denySet.has(wire.name) && (allowSet === void 0 || allowSet.has(wire.name))).map((wire) => toDef(client, wire));
|
|
2982
2992
|
return cache;
|
|
2993
|
+
},
|
|
2994
|
+
close: async () => {
|
|
2995
|
+
const pending = clientPromise;
|
|
2996
|
+
clientPromise = void 0;
|
|
2997
|
+
cache = void 0;
|
|
2998
|
+
if (pending === void 0) return;
|
|
2999
|
+
let client;
|
|
3000
|
+
try {
|
|
3001
|
+
client = await pending;
|
|
3002
|
+
} catch {
|
|
3003
|
+
return;
|
|
3004
|
+
}
|
|
3005
|
+
await client.close();
|
|
2983
3006
|
}
|
|
2984
3007
|
};
|
|
2985
3008
|
}
|
|
@@ -6735,6 +6758,51 @@ function tierWithinCaps(tier, caps) {
|
|
|
6735
6758
|
return TIER_ORDER[tier] <= TIER_ORDER[caps.structuredOutput];
|
|
6736
6759
|
}
|
|
6737
6760
|
//#endregion
|
|
6761
|
+
//#region src/l0/validate-numbers.ts
|
|
6762
|
+
/**
|
|
6763
|
+
* Shared numeric option validators (v1.34.0 review P2-3). Every public
|
|
6764
|
+
* numeric knob that shapes admission, limits, concurrency, or timers is
|
|
6765
|
+
* validated with these helpers at its intake boundary, so a malformed
|
|
6766
|
+
* value (NaN, Infinity, a negative, a fraction where an integer is
|
|
6767
|
+
* required) fails as a typed ConfigError before any journal entry,
|
|
6768
|
+
* worker, or provider dispatch. NaN needs dedicated handling because
|
|
6769
|
+
* every comparison with it is false: a hand-written range check in the
|
|
6770
|
+
* rejecting polarity (`value < min || value > max`) silently admits it.
|
|
6771
|
+
*/
|
|
6772
|
+
/**
|
|
6773
|
+
* The Node timer ceiling: setTimeout clamps any longer delay to 1 ms, so
|
|
6774
|
+
* a naive far-future timer fires immediately (v1.34.0 review P2-2).
|
|
6775
|
+
* Relative timer options are validated against this bound; absolute
|
|
6776
|
+
* deadlines use the sliced timer in long-timer.ts instead.
|
|
6777
|
+
*/
|
|
6778
|
+
const MAX_TIMER_DELAY_MS = 2147483647;
|
|
6779
|
+
function refuse(site, requirement, value) {
|
|
6780
|
+
throw new ConfigError(`${site} must be ${requirement}; got ${String(value)}`);
|
|
6781
|
+
}
|
|
6782
|
+
/** An integer >= 1 (counts, caps, and depths). */
|
|
6783
|
+
function requirePositiveInteger(value, site) {
|
|
6784
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1) refuse(site, "a positive integer", value);
|
|
6785
|
+
}
|
|
6786
|
+
/** An integer >= 0 (caps where zero means "none allowed"). */
|
|
6787
|
+
function requireNonNegativeInteger(value, site) {
|
|
6788
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) refuse(site, "a nonnegative integer", value);
|
|
6789
|
+
}
|
|
6790
|
+
/** A finite number >= 0 (USD amounts and reserves). */
|
|
6791
|
+
function requireNonNegativeNumber(value, site) {
|
|
6792
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) refuse(site, "a finite nonnegative number", value);
|
|
6793
|
+
}
|
|
6794
|
+
/** A finite fraction in (0, 1]. */
|
|
6795
|
+
function requireFraction(value, site) {
|
|
6796
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > 1) refuse(site, "a fraction in (0, 1]", value);
|
|
6797
|
+
}
|
|
6798
|
+
/**
|
|
6799
|
+
* A relative delay handed to setTimeout as-is: an integer within the
|
|
6800
|
+
* Node timer maximum, mirroring validateRetryPolicy's bound.
|
|
6801
|
+
*/
|
|
6802
|
+
function requireTimerDelayMs(value, site) {
|
|
6803
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 2147483647) refuse(site, "an integer between 1 and 2147483647 ms (the Node timer maximum)", value);
|
|
6804
|
+
}
|
|
6805
|
+
//#endregion
|
|
6738
6806
|
//#region src/engine/scheduler.ts
|
|
6739
6807
|
/**
|
|
6740
6808
|
* Scheduler and concurrency (M1-T08): the per-run semaphore with a FIFO
|
|
@@ -6749,8 +6817,17 @@ var Semaphore = class {
|
|
|
6749
6817
|
limit;
|
|
6750
6818
|
active = 0;
|
|
6751
6819
|
waiters = [];
|
|
6820
|
+
/**
|
|
6821
|
+
* `limit` must be a positive integer: anything else (NaN included) is
|
|
6822
|
+
* a typed ConfigError. Before this gate a NaN limit made
|
|
6823
|
+
* `active < limit` permanently false, so the first acquire queued
|
|
6824
|
+
* forever and the run could not settle, not even through cancel()
|
|
6825
|
+
* (v1.34.0 review P2-4). Unlimited is expressed by not constructing a
|
|
6826
|
+
* semaphore, never by a sentinel limit.
|
|
6827
|
+
*/
|
|
6752
6828
|
constructor(limit) {
|
|
6753
|
-
|
|
6829
|
+
requirePositiveInteger(limit, "Semaphore limit");
|
|
6830
|
+
this.limit = limit;
|
|
6754
6831
|
}
|
|
6755
6832
|
get pending() {
|
|
6756
6833
|
return this.waiters.length;
|
|
@@ -6758,21 +6835,50 @@ var Semaphore = class {
|
|
|
6758
6835
|
/**
|
|
6759
6836
|
* Acquires a slot, resolving in FIFO order. `onQueued` fires only when
|
|
6760
6837
|
* the caller actually has to wait (feeds the agent:queued event).
|
|
6838
|
+
* An aborted `signal` releases the caller from the queue without a
|
|
6839
|
+
* slot: the returned release is a no-op, the remaining waiters keep
|
|
6840
|
+
* their FIFO positions, and the caller proceeds to observe its own
|
|
6841
|
+
* aborted signal (the model layers refuse dispatch under an aborted
|
|
6842
|
+
* signal, so no provider call follows). Cancellation can therefore
|
|
6843
|
+
* always drain a queued run (v1.34.0 review P2-4).
|
|
6761
6844
|
*/
|
|
6762
|
-
async acquire(onQueued) {
|
|
6845
|
+
async acquire(onQueued, signal) {
|
|
6763
6846
|
if (this.active < this.limit) {
|
|
6764
6847
|
this.active += 1;
|
|
6765
6848
|
return () => this.release();
|
|
6766
6849
|
}
|
|
6850
|
+
if (signal?.aborted === true) return () => void 0;
|
|
6767
6851
|
onQueued?.();
|
|
6768
|
-
|
|
6769
|
-
|
|
6852
|
+
const waiter = {
|
|
6853
|
+
resolve: () => void 0,
|
|
6854
|
+
aborted: false
|
|
6855
|
+
};
|
|
6856
|
+
const wait = new Promise((resolve) => {
|
|
6857
|
+
waiter.resolve = resolve;
|
|
6770
6858
|
});
|
|
6859
|
+
this.waiters.push(waiter);
|
|
6860
|
+
let onAbort;
|
|
6861
|
+
if (signal !== void 0) {
|
|
6862
|
+
onAbort = () => {
|
|
6863
|
+
const index = this.waiters.indexOf(waiter);
|
|
6864
|
+
if (index === -1) return;
|
|
6865
|
+
this.waiters.splice(index, 1);
|
|
6866
|
+
waiter.aborted = true;
|
|
6867
|
+
waiter.resolve();
|
|
6868
|
+
};
|
|
6869
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
6870
|
+
}
|
|
6871
|
+
try {
|
|
6872
|
+
await wait;
|
|
6873
|
+
} finally {
|
|
6874
|
+
if (signal !== void 0 && onAbort !== void 0) signal.removeEventListener("abort", onAbort);
|
|
6875
|
+
}
|
|
6876
|
+
if (waiter.aborted) return () => void 0;
|
|
6771
6877
|
this.active += 1;
|
|
6772
6878
|
return () => this.release();
|
|
6773
6879
|
}
|
|
6774
|
-
async withSlot(fn, onQueued) {
|
|
6775
|
-
const release = await this.acquire(onQueued);
|
|
6880
|
+
async withSlot(fn, onQueued, signal) {
|
|
6881
|
+
const release = await this.acquire(onQueued, signal);
|
|
6776
6882
|
try {
|
|
6777
6883
|
return await fn();
|
|
6778
6884
|
} finally {
|
|
@@ -6782,7 +6888,7 @@ var Semaphore = class {
|
|
|
6782
6888
|
release() {
|
|
6783
6889
|
this.active -= 1;
|
|
6784
6890
|
const next = this.waiters.shift();
|
|
6785
|
-
if (next !== void 0) next();
|
|
6891
|
+
if (next !== void 0) next.resolve();
|
|
6786
6892
|
}
|
|
6787
6893
|
};
|
|
6788
6894
|
//#endregion
|
|
@@ -6811,12 +6917,14 @@ var KeyedLimiter = class {
|
|
|
6811
6917
|
}
|
|
6812
6918
|
/**
|
|
6813
6919
|
* Runs `fn` under the key's semaphore; keys without a configured cap
|
|
6814
|
-
* run unlimited (no queueing, no overhead).
|
|
6920
|
+
* run unlimited (no queueing, no overhead). An aborted `signal` frees
|
|
6921
|
+
* a queued caller without a slot (the Semaphore contract), so run
|
|
6922
|
+
* cancellation drains provider queues too (v1.34.0 review P2-4).
|
|
6815
6923
|
*/
|
|
6816
|
-
async withSlot(key, fn, onQueued) {
|
|
6924
|
+
async withSlot(key, fn, onQueued, signal) {
|
|
6817
6925
|
const semaphore = this.semaphores.get(key);
|
|
6818
6926
|
if (semaphore === void 0) return fn();
|
|
6819
|
-
return semaphore.withSlot(fn, onQueued);
|
|
6927
|
+
return semaphore.withSlot(fn, onQueued, signal);
|
|
6820
6928
|
}
|
|
6821
6929
|
};
|
|
6822
6930
|
//#endregion
|
|
@@ -7043,13 +7151,6 @@ function retryClassOf(error) {
|
|
|
7043
7151
|
if (kind === "overloaded") return "overloaded";
|
|
7044
7152
|
return "transport";
|
|
7045
7153
|
}
|
|
7046
|
-
/**
|
|
7047
|
-
* The largest delay a Node timer represents exactly (2^31 above that
|
|
7048
|
-
* a timer overflows and fires almost immediately); every returned
|
|
7049
|
-
* delay is clamped to it so a huge provider value can never turn
|
|
7050
|
-
* into an instant retry storm.
|
|
7051
|
-
*/
|
|
7052
|
-
const MAX_TIMER_DELAY_MS = 2147483647;
|
|
7053
7154
|
/** Bounds a delay to a finite nonnegative integer a Node timer can honor. */
|
|
7054
7155
|
function timerSafe(ms) {
|
|
7055
7156
|
if (!Number.isFinite(ms) || ms <= 0) return 0;
|
|
@@ -7105,7 +7206,7 @@ function validateRetryPolicy(policy, source = "retry") {
|
|
|
7105
7206
|
const backoff = candidate.backoff;
|
|
7106
7207
|
if (typeof backoff !== "object" || backoff === null || Array.isArray(backoff)) throw new ConfigError(`${source}: backoff must be an object with initialMs, factor, and maxMs; got ${renderConfigValue(backoff)}`);
|
|
7107
7208
|
const { initialMs, factor, maxMs, jitter } = backoff;
|
|
7108
|
-
for (const [field, value] of [["backoff.initialMs", initialMs], ["backoff.maxMs", maxMs]]) if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value >
|
|
7209
|
+
for (const [field, value] of [["backoff.initialMs", initialMs], ["backoff.maxMs", maxMs]]) if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value > 2147483647) fail(field, "must be an integer between 0 and 2147483647 ms (the Node timer maximum)", value);
|
|
7109
7210
|
if (typeof factor !== "number" || !Number.isFinite(factor) || factor <= 0) fail("backoff.factor", "must be a finite number above zero", factor);
|
|
7110
7211
|
if (jitter !== void 0 && typeof jitter !== "boolean") fail("backoff.jitter", "must be a boolean when given", jitter);
|
|
7111
7212
|
const retryOn = candidate.retryOn;
|
|
@@ -7494,6 +7595,15 @@ function ladderRungChoice(ladder, index) {
|
|
|
7494
7595
|
}
|
|
7495
7596
|
//#endregion
|
|
7496
7597
|
//#region src/runtime/usage-limits.ts
|
|
7598
|
+
/**
|
|
7599
|
+
* UsageLimits (M1-T06): normative limit vocabulary and the per-spawn merge.
|
|
7600
|
+
*
|
|
7601
|
+
* Full contract: https://docs.rulvar.com/guide/agents. Expiry of maxTurns, maxToolCalls,
|
|
7602
|
+
* or timeoutMs produces the terminal status 'limit' (paid partial work);
|
|
7603
|
+
* streamIdleTimeoutMs expiry is a retryable transport-class AgentError,
|
|
7604
|
+
* never 'limit'. The run-level deadline is RunOptions.deadlineAt, not a
|
|
7605
|
+
* UsageLimits field.
|
|
7606
|
+
*/
|
|
7497
7607
|
const DEFAULT_MAX_TURNS = 32;
|
|
7498
7608
|
const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 12e4;
|
|
7499
7609
|
/**
|
|
@@ -7516,6 +7626,26 @@ function mergeUsageLimits(call, profile, engine) {
|
|
|
7516
7626
|
if (noProgressTurns !== void 0) merged.noProgressTurns = noProgressTurns;
|
|
7517
7627
|
return merged;
|
|
7518
7628
|
}
|
|
7629
|
+
/**
|
|
7630
|
+
* Validates one UsageLimits layer at its intake boundary (v1.34.0
|
|
7631
|
+
* review P2-3): a malformed field (NaN, Infinity, a negative, a
|
|
7632
|
+
* fraction) is a typed ConfigError before the merge, before any journal
|
|
7633
|
+
* entry, and before any provider dispatch. `site` names the layer in the
|
|
7634
|
+
* error text (e.g. `RunOptions.limits`). Counts are positive integers
|
|
7635
|
+
* (maxToolCalls may be 0: a spawn that must not call tools).
|
|
7636
|
+
* streamIdleTimeoutMs is handed to setTimeout as-is, so it is bounded by
|
|
7637
|
+
* the Node timer maximum like RetryPolicy delays; timeoutMs is a
|
|
7638
|
+
* wall-clock comparison, so it has no upper bound. Every present field
|
|
7639
|
+
* is checked; absent fields keep their defaults.
|
|
7640
|
+
*/
|
|
7641
|
+
function validateUsageLimits(limits, site) {
|
|
7642
|
+
if (limits.maxTurns !== void 0) requirePositiveInteger(limits.maxTurns, `${site}.maxTurns`);
|
|
7643
|
+
if (limits.maxToolCalls !== void 0) requireNonNegativeInteger(limits.maxToolCalls, `${site}.maxToolCalls`);
|
|
7644
|
+
if (limits.maxOutputTokensPerTurn !== void 0) requirePositiveInteger(limits.maxOutputTokensPerTurn, `${site}.maxOutputTokensPerTurn`);
|
|
7645
|
+
if (limits.timeoutMs !== void 0) requirePositiveInteger(limits.timeoutMs, `${site}.timeoutMs`);
|
|
7646
|
+
if (limits.streamIdleTimeoutMs !== void 0) requireTimerDelayMs(limits.streamIdleTimeoutMs, `${site}.streamIdleTimeoutMs`);
|
|
7647
|
+
if (limits.noProgressTurns !== void 0) requirePositiveInteger(limits.noProgressTurns, `${site}.noProgressTurns`);
|
|
7648
|
+
}
|
|
7519
7649
|
//#endregion
|
|
7520
7650
|
//#region src/runtime/model-retry.ts
|
|
7521
7651
|
var ModelRetry = class extends Error {
|
|
@@ -8778,7 +8908,7 @@ async function runAgent(options) {
|
|
|
8778
8908
|
const aborted = abortKind();
|
|
8779
8909
|
return aborted === void 0 ? streamTurn(target.adapter, site.requestFor(target), site.streamOptionsFor(target)) : Promise.resolve(abortedOutcome(aborted));
|
|
8780
8910
|
};
|
|
8781
|
-
const outcome = await (options.providerSlot === void 0 ? dispatch() : options.providerSlot(target.adapter.id, dispatch));
|
|
8911
|
+
const outcome = await (options.providerSlot === void 0 ? dispatch() : options.providerSlot(target.adapter.id, dispatch, options.signal));
|
|
8782
8912
|
recordUsage(outcome.usage, outcome.reported, target.adapter.id, target.resolved.ref, site.role, outcome.usageViolation);
|
|
8783
8913
|
tries += 1;
|
|
8784
8914
|
const retryClass = outcome.aborted === "idle" ? "transport" : outcome.wireError === void 0 ? void 0 : retryClassOf(outcome.wireError);
|
|
@@ -9749,6 +9879,7 @@ var RunBudget = class {
|
|
|
9749
9879
|
* Also enforces the engine lifetime spawn cap.
|
|
9750
9880
|
*/
|
|
9751
9881
|
admitSpawn(reserveUsd, accountScope = "run") {
|
|
9882
|
+
requireNonNegativeNumber(reserveUsd, "the admission reserve (estCost or its fallbacks)");
|
|
9752
9883
|
if (this.agentsSpawnedInternal >= this.lifetimeSpawnCap) {
|
|
9753
9884
|
this.exhaustedInternal = true;
|
|
9754
9885
|
throw new BudgetExhaustedError(`engine lifetime spawn cap reached (${this.lifetimeSpawnCap} spawns per run; budgetDefaults.lifetimeSpawnCap)`, { data: { cap: this.lifetimeSpawnCap } });
|
|
@@ -9967,7 +10098,11 @@ var AdmissionController = class {
|
|
|
9967
10098
|
admittedTotal = 0;
|
|
9968
10099
|
constructor(options) {
|
|
9969
10100
|
const maxDepth = options.maxDepth ?? 1;
|
|
9970
|
-
if (maxDepth < 1 || maxDepth > 4) throw new ConfigError(`maxDepth ${String(maxDepth)} is outside [1, ${String(4)}] (default 1, hard ceiling 4)`);
|
|
10101
|
+
if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > 4) throw new ConfigError(`maxDepth ${String(maxDepth)} is outside [1, ${String(4)}] (default 1, hard ceiling 4)`);
|
|
10102
|
+
if (options.maxChildrenPerNode !== void 0) requirePositiveInteger(options.maxChildrenPerNode, "maxChildrenPerNode");
|
|
10103
|
+
if (options.childBudgetFraction !== void 0) requireFraction(options.childBudgetFraction, "childBudgetFraction");
|
|
10104
|
+
if (options.flatReserveUsd !== void 0) requireNonNegativeNumber(options.flatReserveUsd, "flatReserveUsd");
|
|
10105
|
+
if (options.maxTotalSpawns !== void 0) requirePositiveInteger(options.maxTotalSpawns, "maxTotalSpawns");
|
|
9971
10106
|
this.budget = options.budget;
|
|
9972
10107
|
this.maxDepth = maxDepth;
|
|
9973
10108
|
this.maxChildrenPerNode = options.maxChildrenPerNode ?? 16;
|
|
@@ -10594,6 +10729,45 @@ function emitSpawnRejected(events, input) {
|
|
|
10594
10729
|
}, input.spanId, input.replayed);
|
|
10595
10730
|
}
|
|
10596
10731
|
//#endregion
|
|
10732
|
+
//#region src/l0/long-timer.ts
|
|
10733
|
+
/**
|
|
10734
|
+
* Sliced timers for absolute wall-clock deadlines (v1.34.0 review P2-2).
|
|
10735
|
+
*
|
|
10736
|
+
* Node clamps a setTimeout delay above 2147483647 ms (about 24.8 days)
|
|
10737
|
+
* to 1 ms, so a naive timer for a far-future deadline fires immediately.
|
|
10738
|
+
* setLongTimeout never hands Node more than one MAX_TIMER_DELAY_MS
|
|
10739
|
+
* slice, re-checks the wall clock when a slice fires, and re-arms until
|
|
10740
|
+
* the clock actually reaches the deadline: firing a slice is never taken
|
|
10741
|
+
* as proof the deadline arrived. A deadline already in the past fires on
|
|
10742
|
+
* the next macrotask (delay 0), matching the plain setTimeout behavior
|
|
10743
|
+
* the callers had for near deadlines.
|
|
10744
|
+
*/
|
|
10745
|
+
/**
|
|
10746
|
+
* Schedules `onDue` for the absolute wall-clock instant `dueAtMs` as
|
|
10747
|
+
* reported by `now` (default Date.now), slicing delays beyond the Node
|
|
10748
|
+
* timer maximum.
|
|
10749
|
+
*/
|
|
10750
|
+
function setLongTimeout(onDue, dueAtMs, now = Date.now) {
|
|
10751
|
+
let handle;
|
|
10752
|
+
let cancelled = false;
|
|
10753
|
+
const arm = () => {
|
|
10754
|
+
const remaining = Math.max(0, dueAtMs - now());
|
|
10755
|
+
handle = setTimeout(() => {
|
|
10756
|
+
if (cancelled) return;
|
|
10757
|
+
if (now() >= dueAtMs) {
|
|
10758
|
+
onDue();
|
|
10759
|
+
return;
|
|
10760
|
+
}
|
|
10761
|
+
arm();
|
|
10762
|
+
}, Math.min(remaining, MAX_TIMER_DELAY_MS));
|
|
10763
|
+
};
|
|
10764
|
+
arm();
|
|
10765
|
+
return { cancel: () => {
|
|
10766
|
+
cancelled = true;
|
|
10767
|
+
if (handle !== void 0) clearTimeout(handle);
|
|
10768
|
+
} };
|
|
10769
|
+
}
|
|
10770
|
+
//#endregion
|
|
10597
10771
|
//#region src/engine/ctx.ts
|
|
10598
10772
|
/**
|
|
10599
10773
|
* Ctx primitives (M1-T07) plus the parallel/pipeline composition semantics
|
|
@@ -10859,6 +11033,7 @@ function createCtx(internals, rootWorkflow) {
|
|
|
10859
11033
|
const escalation = opts.escalation ?? profile?.escalation;
|
|
10860
11034
|
if (escalation !== void 0) {
|
|
10861
11035
|
if (escalation.flavor === "B" && escalation.deadlineMs === void 0) throw new ConfigError("flavor 'B' escalation requires an explicit deadlineMs: the suspension deadline has no engine default");
|
|
11036
|
+
if (escalation.deadlineMs !== void 0) requirePositiveInteger(escalation.deadlineMs, "escalation.deadlineMs");
|
|
10862
11037
|
if (opts.result !== "full" && internals.onEscalation === void 0) throw new ConfigError("a spawn that opts into escalation from a plain value-form call needs an onEscalation hook (or use result: 'full')");
|
|
10863
11038
|
if (escalation.flavor === "B" && escalation.deadlineMs === void 0) throw new ConfigError("escalation flavor 'B' requires an explicit deadlineMs");
|
|
10864
11039
|
}
|
|
@@ -10987,6 +11162,8 @@ function createCtx(internals, rootWorkflow) {
|
|
|
10987
11162
|
}
|
|
10988
11163
|
const retryPolicy = opts.retry ?? profile?.retry ?? internals.defaults.retry;
|
|
10989
11164
|
if (retryPolicy !== void 0) validateRetryPolicy(retryPolicy, opts.retry !== void 0 ? "the agent retry option" : profile?.retry !== void 0 ? `the retry of profile '${String(opts.agentType)}'` : "engine defaults.retry");
|
|
11165
|
+
if (opts.estCost !== void 0) requireNonNegativeNumber(opts.estCost, "the agent estCost option");
|
|
11166
|
+
if (opts.limits !== void 0) validateUsageLimits(opts.limits, "the agent limits option");
|
|
10990
11167
|
const identityInput = {
|
|
10991
11168
|
kind: "agent",
|
|
10992
11169
|
agentType,
|
|
@@ -11390,12 +11567,12 @@ function createCtx(internals, rootWorkflow) {
|
|
|
11390
11567
|
if (retryPolicy !== void 0) runAgentOptions.retry = { policy: retryPolicy };
|
|
11391
11568
|
if (internals.providerLimiter !== void 0) {
|
|
11392
11569
|
const limiter = internals.providerLimiter;
|
|
11393
|
-
runAgentOptions.providerSlot = (key, fn) => limiter.withSlot(key, fn, () => internals.events.emit({
|
|
11570
|
+
runAgentOptions.providerSlot = (key, fn, signal) => limiter.withSlot(key, fn, () => internals.events.emit({
|
|
11394
11571
|
type: "agent:queued",
|
|
11395
11572
|
agentType,
|
|
11396
11573
|
label: opts.label,
|
|
11397
11574
|
providerKey: key
|
|
11398
|
-
}, spanId));
|
|
11575
|
+
}, spanId), signal);
|
|
11399
11576
|
}
|
|
11400
11577
|
if (opts.stream !== void 0) runAgentOptions.stream = opts.stream;
|
|
11401
11578
|
if (opts.label !== void 0) runAgentOptions.label = opts.label;
|
|
@@ -11407,7 +11584,7 @@ function createCtx(internals, rootWorkflow) {
|
|
|
11407
11584
|
type: "agent:queued",
|
|
11408
11585
|
agentType,
|
|
11409
11586
|
label: opts.label
|
|
11410
|
-
}, spanId));
|
|
11587
|
+
}, spanId), branchOrRunSignal);
|
|
11411
11588
|
} finally {
|
|
11412
11589
|
exitActivity?.();
|
|
11413
11590
|
}
|
|
@@ -11433,13 +11610,12 @@ function createCtx(internals, rootWorkflow) {
|
|
|
11433
11610
|
entryRef: entry.seq
|
|
11434
11611
|
}, spanId, replayed);
|
|
11435
11612
|
const registry = internals.external;
|
|
11436
|
-
|
|
11437
|
-
timer = setTimeout(() => {
|
|
11613
|
+
timer = setLongTimeout(() => {
|
|
11438
11614
|
registry?.submitResolution(entry.seq, {
|
|
11439
11615
|
by: "timeout",
|
|
11440
11616
|
value: defaultDecision
|
|
11441
11617
|
}).catch(() => void 0);
|
|
11442
|
-
},
|
|
11618
|
+
}, Date.parse(entry.deadlineAt ?? "") || internals.now(), () => internals.now());
|
|
11443
11619
|
if (internals.onEscalation !== void 0) {
|
|
11444
11620
|
const preview = buildEscalationReport(request, result, void 0);
|
|
11445
11621
|
const previewResult = {
|
|
@@ -11453,7 +11629,7 @@ function createCtx(internals, rootWorkflow) {
|
|
|
11453
11629
|
}
|
|
11454
11630
|
}
|
|
11455
11631
|
});
|
|
11456
|
-
if (timer !== void 0)
|
|
11632
|
+
if (timer !== void 0) timer.cancel();
|
|
11457
11633
|
flavorBDecision = decisionOutcome.value;
|
|
11458
11634
|
}
|
|
11459
11635
|
if (acquired !== void 0) {
|
|
@@ -13302,6 +13478,36 @@ var InProcessRunner = class {
|
|
|
13302
13478
|
* ctx is created per run. engine.resume lands with the journal
|
|
13303
13479
|
* kernel in M2.
|
|
13304
13480
|
*/
|
|
13481
|
+
/**
|
|
13482
|
+
* The accepted RunOptions.deadlineAt grammar: an ISO 8601 calendar
|
|
13483
|
+
* date-time with minute precision at least, optional seconds and
|
|
13484
|
+
* fractional seconds, and a MANDATORY UTC designator or numeric offset.
|
|
13485
|
+
* Date.parse would accept far more (and would read an offset-less
|
|
13486
|
+
* date-time in the host's local zone, so the same string would mean a
|
|
13487
|
+
* different instant on different hosts); the grammar pins one meaning.
|
|
13488
|
+
*/
|
|
13489
|
+
const DEADLINE_AT_GRAMMAR = /^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
13490
|
+
/**
|
|
13491
|
+
* Typed refusal of a malformed deadlineAt (v1.34.0 review P2-1). The
|
|
13492
|
+
* calendar day is range-checked explicitly: V8's Date.parse silently
|
|
13493
|
+
* ROLLS an impossible ISO day into the next month (2026-02-30 parses as
|
|
13494
|
+
* 2026-03-02), so the finite check alone would accept a date the host
|
|
13495
|
+
* never wrote and cancel the run at a different instant.
|
|
13496
|
+
*/
|
|
13497
|
+
function parseDeadlineAt(value) {
|
|
13498
|
+
const parsed = Date.parse(value);
|
|
13499
|
+
const match = DEADLINE_AT_GRAMMAR.exec(value);
|
|
13500
|
+
const refuse = () => {
|
|
13501
|
+
throw new ConfigError(`RunOptions.deadlineAt must be an ISO 8601 date-time with an explicit UTC designator or offset (e.g. 2026-07-21T10:00:00Z or 2026-07-21T12:00:00+02:00); got '${value}'`);
|
|
13502
|
+
};
|
|
13503
|
+
if (match === null || !Number.isFinite(parsed)) refuse();
|
|
13504
|
+
const year = Number(match?.[1]);
|
|
13505
|
+
const month = Number(match?.[2]);
|
|
13506
|
+
const day = Number(match?.[3]);
|
|
13507
|
+
const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
13508
|
+
if (month < 1 || month > 12 || day < 1 || day > daysInMonth) refuse();
|
|
13509
|
+
return parsed;
|
|
13510
|
+
}
|
|
13305
13511
|
/** Content hash of an in-process workflow body (run-to-definition binding). */
|
|
13306
13512
|
function hashWorkflowBody(wf) {
|
|
13307
13513
|
return createHash("sha256").update(wf.body.toString(), "utf8").digest("hex");
|
|
@@ -13343,7 +13549,24 @@ function createEngine(options) {
|
|
|
13343
13549
|
const maskEvents = options.redaction?.maskEvents ?? true;
|
|
13344
13550
|
const defaults = options.defaults ?? {};
|
|
13345
13551
|
if (defaults.retry !== void 0) validateRetryPolicy(defaults.retry, "createEngine defaults.retry");
|
|
13346
|
-
|
|
13552
|
+
if (options.concurrency?.perRun !== void 0) requirePositiveInteger(options.concurrency.perRun, "createEngine concurrency.perRun");
|
|
13553
|
+
for (const [adapterId, cap] of Object.entries(options.concurrency?.perProvider ?? {})) requirePositiveInteger(cap, `createEngine concurrency.perProvider['${adapterId}']`);
|
|
13554
|
+
const budgetDefaults = options.budgetDefaults;
|
|
13555
|
+
if (budgetDefaults?.flatReserveUsd !== void 0) requireNonNegativeNumber(budgetDefaults.flatReserveUsd, "createEngine budgetDefaults.flatReserveUsd");
|
|
13556
|
+
if (budgetDefaults?.lifetimeSpawnCap !== void 0) requireNonNegativeInteger(budgetDefaults.lifetimeSpawnCap, "createEngine budgetDefaults.lifetimeSpawnCap");
|
|
13557
|
+
if (budgetDefaults?.childBudgetFraction !== void 0) requireFraction(budgetDefaults.childBudgetFraction, "createEngine budgetDefaults.childBudgetFraction");
|
|
13558
|
+
if (budgetDefaults?.maxDepth !== void 0) {
|
|
13559
|
+
requirePositiveInteger(budgetDefaults.maxDepth, "createEngine budgetDefaults.maxDepth");
|
|
13560
|
+
if (budgetDefaults.maxDepth > 4) throw new ConfigError(`createEngine budgetDefaults.maxDepth ${String(budgetDefaults.maxDepth)} is outside [1, ${String(4)}] (default 1, hard ceiling ${String(4)})`);
|
|
13561
|
+
}
|
|
13562
|
+
if (defaults.limits !== void 0) validateUsageLimits(defaults.limits, "createEngine defaults.limits");
|
|
13563
|
+
for (const [name, profile] of Object.entries(defaults.profiles ?? {})) {
|
|
13564
|
+
if (profile.retry !== void 0) validateRetryPolicy(profile.retry, `createEngine defaults.profiles['${name}'].retry`);
|
|
13565
|
+
if (profile.limits !== void 0) validateUsageLimits(profile.limits, `createEngine defaults.profiles['${name}'].limits`);
|
|
13566
|
+
if (profile.estCost !== void 0) requireNonNegativeNumber(profile.estCost, `createEngine defaults.profiles['${name}'].estCost`);
|
|
13567
|
+
if (profile.escalation?.deadlineMs !== void 0) requirePositiveInteger(profile.escalation.deadlineMs, `createEngine defaults.profiles['${name}'].escalation.deadlineMs`);
|
|
13568
|
+
if (profile.compaction?.threshold !== void 0) requireFraction(profile.compaction.threshold, `createEngine defaults.profiles['${name}'].compaction.threshold`);
|
|
13569
|
+
}
|
|
13347
13570
|
const knowledgeStore = options.stores?.modelKnowledge;
|
|
13348
13571
|
const knowledge = knowledgeStore === void 0 ? void 0 : { current: () => knowledgeStore.current() };
|
|
13349
13572
|
const runner = new InProcessRunner(options.onEscalation === void 0 ? void 0 : { onEscalation: options.onEscalation });
|
|
@@ -13362,6 +13585,9 @@ function createEngine(options) {
|
|
|
13362
13585
|
const activeSegments = /* @__PURE__ */ new Set();
|
|
13363
13586
|
function run(wf, args, opts, resumeCtx) {
|
|
13364
13587
|
if (wf.kind !== "workflow" && wf.kind !== "compiled-workflow") throw new ConfigError("engine.run accepts in-process Workflow values or compileScript CompiledWorkflow values");
|
|
13588
|
+
if (opts?.budgetUsd !== void 0) requireNonNegativeNumber(opts.budgetUsd, "RunOptions.budgetUsd");
|
|
13589
|
+
if (opts?.limits !== void 0) validateUsageLimits(opts.limits, "RunOptions.limits");
|
|
13590
|
+
const deadlineAtMs = opts?.deadlineAt === void 0 ? void 0 : parseDeadlineAt(opts.deadlineAt);
|
|
13365
13591
|
const compiled = wf.kind === "compiled-workflow" ? wf : void 0;
|
|
13366
13592
|
if (compiled !== void 0 && options.runners?.sandbox === void 0) throw new ConfigError("running a CompiledWorkflow requires a sandbox runner: pass createEngine({ runners: { sandbox: new WorkerSandboxRunner() } }) from @rulvar/planner ");
|
|
13367
13593
|
const runId = resumeCtx?.runId ?? opts?.runId ?? mintRunId();
|
|
@@ -13425,10 +13651,7 @@ function createEngine(options) {
|
|
|
13425
13651
|
if (opts?.signal !== void 0) if (opts.signal.aborted) requestCancel("host signal aborted");
|
|
13426
13652
|
else opts.signal.addEventListener("abort", () => requestCancel("host signal aborted"), { once: true });
|
|
13427
13653
|
let deadlineTimer;
|
|
13428
|
-
if (
|
|
13429
|
-
const delay = Date.parse(opts.deadlineAt) - realNow();
|
|
13430
|
-
deadlineTimer = setTimeout(() => requestCancel(`run deadline ${opts.deadlineAt} crossed`), Math.max(0, delay));
|
|
13431
|
-
}
|
|
13654
|
+
if (deadlineAtMs !== void 0) deadlineTimer = setLongTimeout(() => requestCancel(`run deadline ${opts?.deadlineAt ?? ""} crossed`), deadlineAtMs, realNow);
|
|
13432
13655
|
const budget = makeBudget();
|
|
13433
13656
|
const admission = new AdmissionController({
|
|
13434
13657
|
budget,
|
|
@@ -13606,7 +13829,7 @@ function createEngine(options) {
|
|
|
13606
13829
|
};
|
|
13607
13830
|
}
|
|
13608
13831
|
} finally {
|
|
13609
|
-
if (deadlineTimer !== void 0)
|
|
13832
|
+
if (deadlineTimer !== void 0) deadlineTimer.cancel();
|
|
13610
13833
|
external.close();
|
|
13611
13834
|
await replayer.flush().catch(() => void 0);
|
|
13612
13835
|
}
|
|
@@ -14096,4 +14319,4 @@ function createSandboxBridge(ctx, options) {
|
|
|
14096
14319
|
};
|
|
14097
14320
|
}
|
|
14098
14321
|
//#endregion
|
|
14099
|
-
export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DedupIndex, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FileModelKnowledgeStore, FileTranscriptStore, GitWorktreeProvider, INBOX_PROPOSAL_TTL_DAYS, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JournalCompatibilityError, JournalMatcher, JournalMissError, JournalOrderViolation, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_DEPTH_CEILING, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, PlanInvariantError, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, atCompactionThreshold, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, 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, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
|
|
14322
|
+
export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DedupIndex, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FileModelKnowledgeStore, FileTranscriptStore, GitWorktreeProvider, INBOX_PROPOSAL_TTL_DAYS, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JournalCompatibilityError, JournalMatcher, JournalMissError, JournalOrderViolation, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_DEPTH_CEILING, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, PlanInvariantError, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, atCompactionThreshold, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, 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.
|
|
3
|
+
"version": "1.35.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",
|