@rulvar/core 1.35.0 → 1.36.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 +125 -13
- package/dist/index.js +265 -105
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -28,7 +28,7 @@ type WireError = {
|
|
|
28
28
|
* 'agent' is carried by the AgentError value projection, not by a
|
|
29
29
|
* RulvarError subclass.
|
|
30
30
|
*/
|
|
31
|
-
type ErrorCode = "agent" | "config" | "non_serializable_value" | "script_rejected" | "journal_compat" | "invalid_resolution" | "journal_order_violation" | "plan_invariant" | "replay_plan_hash_mismatch" | "orchestrator_cap_config" | "journal_miss" | "budget_exhausted" | "admission_rejected" | "sandbox_limit" | "lease_held" | "knowledge_cas";
|
|
31
|
+
type ErrorCode = "agent" | "config" | "non_serializable_value" | "script_rejected" | "journal_compat" | "invalid_resolution" | "journal_order_violation" | "plan_invariant" | "replay_plan_hash_mismatch" | "orchestrator_cap_config" | "journal_miss" | "budget_exhausted" | "fail_run" | "admission_rejected" | "sandbox_limit" | "lease_held" | "knowledge_cas";
|
|
32
32
|
/** An alias for the registry type; both names are public. */
|
|
33
33
|
type RulvarErrorCode = ErrorCode;
|
|
34
34
|
/**
|
|
@@ -191,6 +191,23 @@ declare class BudgetExhaustedError extends RulvarError {
|
|
|
191
191
|
});
|
|
192
192
|
}
|
|
193
193
|
/**
|
|
194
|
+
* A declared fail-run policy engaged and closed the run as a failure
|
|
195
|
+
* (v1.35.0 review P2-1): `budget.atCap: 'fail-run'` after the journaled
|
|
196
|
+
* orchestrator cap decision, or `guards.fallback: 'fail-run'` after the
|
|
197
|
+
* journaled guard verdict. The run outcome is 'error' with this code;
|
|
198
|
+
* `data.source` names the policy ('orchestrator_budget_cap' or
|
|
199
|
+
* 'plan_guards') and `data` carries the decision entry reference, so the
|
|
200
|
+
* outcome is a pure roll forward of the journal on resume: no second
|
|
201
|
+
* decision, no model call, no spend.
|
|
202
|
+
*/
|
|
203
|
+
declare class FailRunError extends RulvarError {
|
|
204
|
+
readonly code = "fail_run";
|
|
205
|
+
constructor(message: string, opts?: {
|
|
206
|
+
data?: Json;
|
|
207
|
+
cause?: unknown;
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
194
211
|
* A structural admission rejection (maxDepth, maxChildrenPerNode,
|
|
195
212
|
* maxTotalSpawns) from the AdmissionController (M6-T06). The rejection verdict is embedded in
|
|
196
213
|
* the carrying spawn-admission decision entry and replays identically;
|
|
@@ -893,6 +910,14 @@ interface LeasableStore extends JournalStore {
|
|
|
893
910
|
acquire(runId: string, owner: string): Promise<Lease>;
|
|
894
911
|
renew(l: Lease): Promise<void>;
|
|
895
912
|
release(l: Lease): Promise<void>;
|
|
913
|
+
/**
|
|
914
|
+
* Optional TTL introspection (v1.35.0 review P2-4): the configured
|
|
915
|
+
* lease ttl in milliseconds. A store exposing it lets createWorker
|
|
916
|
+
* VERIFY at construction that the worker's renew cadence matches the
|
|
917
|
+
* store's expiry instead of trusting two config sources to agree;
|
|
918
|
+
* stores without it are accepted with the worker's own ttl.
|
|
919
|
+
*/
|
|
920
|
+
readonly leaseTtlMs?: number;
|
|
896
921
|
}
|
|
897
922
|
//#endregion
|
|
898
923
|
//#region src/l0/spi/transcript.d.ts
|
|
@@ -1667,7 +1692,13 @@ declare function applyClaimOps(claims: readonly ModelClaim[], ops: readonly Clai
|
|
|
1667
1692
|
interface FileModelKnowledgeStoreOptions {
|
|
1668
1693
|
/** Default './rulvar.models.json'. */
|
|
1669
1694
|
path?: string;
|
|
1670
|
-
/**
|
|
1695
|
+
/**
|
|
1696
|
+
* Active claims per (model, taskClass); default 8. A nonnegative
|
|
1697
|
+
* integer (zero refuses every active claim), validated at
|
|
1698
|
+
* construction: the enforcement compares `count > cap`, and every
|
|
1699
|
+
* comparison with NaN is false, so an unvalidated NaN or Infinity
|
|
1700
|
+
* silently disabled the cap (v1.35.0 review P2-5).
|
|
1701
|
+
*/
|
|
1671
1702
|
activeClaimsCap?: number;
|
|
1672
1703
|
}
|
|
1673
1704
|
declare class FileModelKnowledgeStore implements ModelKnowledgeStore {
|
|
@@ -2792,7 +2823,11 @@ interface EscalationOptions {
|
|
|
2792
2823
|
deadlineMs?: number;
|
|
2793
2824
|
/** Applied by the timeout resolution (by: 'timeout'); default accept. */
|
|
2794
2825
|
defaultDecision?: EscalationDecision;
|
|
2795
|
-
/**
|
|
2826
|
+
/**
|
|
2827
|
+
* In-run minimum spend before scope_bigger; default 0 (M3-T09). A
|
|
2828
|
+
* finite number >= 0, validated before any LLM call: the gate
|
|
2829
|
+
* compares spend against it, and a NaN would silently disable it.
|
|
2830
|
+
*/
|
|
2796
2831
|
minSpendUsd?: number;
|
|
2797
2832
|
}
|
|
2798
2833
|
/** The model-facing request: the report minus the runtime-filled fields. */
|
|
@@ -5244,6 +5279,18 @@ interface OrchestratorExtensionIO {
|
|
|
5244
5279
|
*/
|
|
5245
5280
|
replayed?: boolean;
|
|
5246
5281
|
}): void;
|
|
5282
|
+
/**
|
|
5283
|
+
* A deterministic run failure declared by the extension (v1.35.0 review P2-1):
|
|
5284
|
+
* the first call stores the error and aborts the orchestrator loop;
|
|
5285
|
+
* the orchestrate settle boundary rethrows it, so the run fails with
|
|
5286
|
+
* the given typed error instead of asking the model to finish. Later
|
|
5287
|
+
* calls do nothing. The intended producer is a journaled
|
|
5288
|
+
* policy verdict (the PlanRunner guards fallback 'fail-run'): boot
|
|
5289
|
+
* terminates again from the journal on resume, so the failure rolls
|
|
5290
|
+
* forward without another decision or model call. Optional so
|
|
5291
|
+
* IO implementations built before v1.36 keep compiling.
|
|
5292
|
+
*/
|
|
5293
|
+
terminate?(error: Error): void;
|
|
5247
5294
|
}
|
|
5248
5295
|
/**
|
|
5249
5296
|
* The extension contract. PlanRunner implements it in @rulvar/plan; the
|
|
@@ -5290,17 +5337,43 @@ interface OrchestratorExtension {
|
|
|
5290
5337
|
*/
|
|
5291
5338
|
interface OrchestratorBudgetSpec {
|
|
5292
5339
|
/**
|
|
5293
|
-
* Absolute bound in USD
|
|
5340
|
+
* Absolute bound in USD: a finite number >= 0, validated before any
|
|
5341
|
+
* journal entry or dispatch (a malformed value is a ConfigError). It
|
|
5342
|
+
* never REPLACES the fraction bound:
|
|
5294
5343
|
* effectiveCap = min(capUsd, (capFraction ?? 0.2) * ceiling), so an
|
|
5295
5344
|
* explicit capUsd larger than the default fraction of the run ceiling
|
|
5296
5345
|
* is still cut to that fraction (and a warn log says so). Pass
|
|
5297
5346
|
* capFraction: 1.0 to make capUsd the sole bound.
|
|
5298
5347
|
*/
|
|
5299
5348
|
capUsd?: number;
|
|
5300
|
-
/**
|
|
5349
|
+
/**
|
|
5350
|
+
* A fraction in (0, 1], default 0.2; effectiveCap = min of the given
|
|
5351
|
+
* bounds. Zero does not lift the cap (it would make every turn
|
|
5352
|
+
* unpayable): anything outside (0, 1] is a ConfigError before any
|
|
5353
|
+
* journal entry or dispatch.
|
|
5354
|
+
*/
|
|
5301
5355
|
capFraction?: number;
|
|
5356
|
+
/**
|
|
5357
|
+
* A finite number >= 0, validated before any journal entry or
|
|
5358
|
+
* dispatch. The reserve is SUBTRACTED from the soft boundary, so a
|
|
5359
|
+
* negative value would widen the cap instead of reserving.
|
|
5360
|
+
*/
|
|
5302
5361
|
finalizeReserveUsd?: number;
|
|
5362
|
+
/**
|
|
5363
|
+
* A positive integer, validated before any journal entry or dispatch:
|
|
5364
|
+
* the turn limit of the reserved final wake.
|
|
5365
|
+
*/
|
|
5303
5366
|
finalizeTurns?: number;
|
|
5367
|
+
/**
|
|
5368
|
+
* The policy at the cap, validated as exactly one of the two literals
|
|
5369
|
+
* even at a plain JS/JSON boundary. 'finish-with-partial' (default)
|
|
5370
|
+
* runs the reserved finalizer and returns its partial result with run
|
|
5371
|
+
* outcome 'ok'. 'fail-run' skips the finalizer entirely: the run
|
|
5372
|
+
* fails with outcome 'error' carrying FailRunError (code 'fail_run',
|
|
5373
|
+
* data.source 'orchestrator_budget_cap', data.capDecisionRef); resume
|
|
5374
|
+
* rolls the same failure forward from the journaled cap decision
|
|
5375
|
+
* without another model call.
|
|
5376
|
+
*/
|
|
5304
5377
|
atCap?: "finish-with-partial" | "fail-run";
|
|
5305
5378
|
}
|
|
5306
5379
|
/** Options for orchestrate(engine, goal, o?). */
|
|
@@ -5308,13 +5381,19 @@ interface OrchestrateOptions {
|
|
|
5308
5381
|
model?: ModelSpec;
|
|
5309
5382
|
/** Registered profile names to advertise; default: every profile. */
|
|
5310
5383
|
profiles?: string[];
|
|
5311
|
-
/**
|
|
5384
|
+
/**
|
|
5385
|
+
* Per-orchestrate spawn cap: a nonnegative integer (zero admits no
|
|
5386
|
+
* spawns), validated before any journal entry or dispatch. The engine
|
|
5387
|
+
* lifetime cap applies regardless.
|
|
5388
|
+
*/
|
|
5312
5389
|
maxSpawns?: number;
|
|
5313
5390
|
/** The orchestrator's own budget sub-account (cap enforcement layers only in M6). */
|
|
5314
5391
|
budget?: OrchestratorBudgetSpec;
|
|
5315
5392
|
/**
|
|
5316
|
-
* Deterministic digest render bound:
|
|
5317
|
-
*
|
|
5393
|
+
* Deterministic digest render bound: a nonnegative integer, validated
|
|
5394
|
+
* before any journal entry or dispatch. Each TaskDigest outputSummary
|
|
5395
|
+
* is truncated to AT MOST this many CHARACTERS, the truncation marker
|
|
5396
|
+
* included (a budget below 3 keeps the bound with a bare slice; the
|
|
5318
5397
|
* model-independent measure; OQ-04 closed at M10 entry). Default
|
|
5319
5398
|
* WAKE_SUMMARY_RENDER_BUDGET_CHARS.
|
|
5320
5399
|
*/
|
|
@@ -5384,6 +5463,20 @@ declare class Semaphore {
|
|
|
5384
5463
|
}
|
|
5385
5464
|
//#endregion
|
|
5386
5465
|
//#region src/engine/external.d.ts
|
|
5466
|
+
/**
|
|
5467
|
+
* The rejection carrier of an aborted flavor B decision wait (v1.35.0
|
|
5468
|
+
* review P1): the parked `awaitDecision` observes the branch/run
|
|
5469
|
+
* AbortSignal, releases its held activity, removes its waiter, and
|
|
5470
|
+
* rejects with this class so cancel, host abort, the run deadline, and
|
|
5471
|
+
* failed sibling aborts all settle the run in bounded time.
|
|
5472
|
+
* Deliberately not a RulvarError: the abort is cancellation intent, not
|
|
5473
|
+
* a registry failure class; the suspension entry stays OPEN, so a later
|
|
5474
|
+
* resume parks the decision again and the durable deadline still applies.
|
|
5475
|
+
*/
|
|
5476
|
+
declare class EscalationDecisionAbortedError extends Error {
|
|
5477
|
+
readonly entryRef: number;
|
|
5478
|
+
constructor(message: string, entryRef: number);
|
|
5479
|
+
}
|
|
5387
5480
|
/** The resolution value shape of a tool-approval suspension (M3-T03). */
|
|
5388
5481
|
interface ApprovalDecision {
|
|
5389
5482
|
decision: "allow" | "deny";
|
|
@@ -5484,6 +5577,13 @@ declare class ExternalRegistry {
|
|
|
5484
5577
|
toolName: string;
|
|
5485
5578
|
input: Json;
|
|
5486
5579
|
deadlineAt: string;
|
|
5580
|
+
/**
|
|
5581
|
+
* The branch/run signal: an abort while parked releases the held
|
|
5582
|
+
* activity, removes the waiter, and rejects with
|
|
5583
|
+
* EscalationDecisionAbortedError (v1.35.0 review P1). The suspension
|
|
5584
|
+
* entry stays open for resume.
|
|
5585
|
+
*/
|
|
5586
|
+
signal?: AbortSignal;
|
|
5487
5587
|
onPending?: (entry: JournalEntry, replayed: boolean) => void;
|
|
5488
5588
|
}): Promise<{
|
|
5489
5589
|
value: Json;
|
|
@@ -5548,7 +5648,8 @@ interface AgentProfile {
|
|
|
5548
5648
|
/**
|
|
5549
5649
|
* Per-profile compaction threshold; default 0.8 of the loop model's
|
|
5550
5650
|
* contextWindow (M4-T03). Compaction is ON by
|
|
5551
|
-
* default; history-processor plumbing stays engine-internal.
|
|
5651
|
+
* default; history-processor plumbing stays engine-internal. The
|
|
5652
|
+
* threshold is a fraction in (0, 1], validated at createEngine.
|
|
5552
5653
|
*/
|
|
5553
5654
|
compaction?: {
|
|
5554
5655
|
threshold?: number;
|
|
@@ -5987,8 +6088,12 @@ declare function compileVerifiedLayer(claims: readonly ModelClaim[], ladders: re
|
|
|
5987
6088
|
/**
|
|
5988
6089
|
* The deterministic card render. Pure: same filtered
|
|
5989
6090
|
* claims and ladders give byte-identical text. The render budget is
|
|
5990
|
-
* 4096 chars; over it, the OLDEST-observed notes
|
|
5991
|
-
*
|
|
6091
|
+
* 4096 chars by default; over it, the OLDEST-observed notes withhold
|
|
6092
|
+
* first behind an explicit marker, and the budget is a HARD upper bound
|
|
6093
|
+
* of the returned string: a card whose mandatory sections alone exceed
|
|
6094
|
+
* it is truncated with the shared marker (v1.35.0 review P2-5: a budget
|
|
6095
|
+
* of 32 used to return the full 136-char header form). budgetChars is a
|
|
6096
|
+
* nonnegative integer, validated as a ConfigError.
|
|
5992
6097
|
*/
|
|
5993
6098
|
declare function modelKnowledgeCard(claims: readonly ModelClaim[], ladders: readonly DeclaredLadder[], options?: {
|
|
5994
6099
|
budgetChars?: number;
|
|
@@ -6166,7 +6271,14 @@ interface GitWorktreeProviderOptions {
|
|
|
6166
6271
|
* requests keep on dispose. Default false.
|
|
6167
6272
|
*/
|
|
6168
6273
|
keepOnError?: boolean;
|
|
6169
|
-
/**
|
|
6274
|
+
/**
|
|
6275
|
+
* Pin cap shared by park/unpark and retainWorktree (default 4). A
|
|
6276
|
+
* nonnegative integer (zero retains nothing), validated at
|
|
6277
|
+
* construction: the retention compares `pinned.size < cap`, and every
|
|
6278
|
+
* comparison with NaN is false, so an unvalidated NaN performed the
|
|
6279
|
+
* acquire effects and then dropped every tree as "cap reached"
|
|
6280
|
+
* (v1.35.0 review P2-5).
|
|
6281
|
+
*/
|
|
6170
6282
|
maxPinnedWorktrees?: number;
|
|
6171
6283
|
/** Warning sink (cap overflow); defaults to process.emitWarning. */
|
|
6172
6284
|
onWarn?: (msg: string) => void;
|
|
@@ -6779,4 +6891,4 @@ interface SandboxBridge {
|
|
|
6779
6891
|
declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
|
|
6780
6892
|
declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
|
|
6781
6893
|
//#endregion
|
|
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 };
|
|
6894
|
+
export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, type AdaptiveEvents, AdmissionController, AdmissionDecision, AdmissionRejectedError, AdmissionStatsBefore, AdmitLineage, AdmitRejectReason, AdmitSpec, AdmitVerdict, AgentCallError, AgentError, type AgentEvents, AgentIdentityInput, AgentOpts, AgentProfile, AgentProfilePermissions, AgentResult, AgentResultMeta, AgentStatus, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, BUDGET_ABORT_REASON, BaseAppend, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildIdentityInput, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, CostReport, CreateEngineOptions, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DebitResult, DeclaredLadder, DedupIndex, DedupNote, DerivedKey, DeriverRegistry, DispositionRule, DispositionTable, DonorCandidate, DonorRef, DroppedItem, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EffectiveUsageLimits, Effort, Engine, EngineDefaults, EntryKind, EntryRef, EntryStatus, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishInfo, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, InvocationRole, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, JournalSerializationHook, type JournalStore, type Json, JsonSchema, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, type KbProposal, type KbProposalTrigger, KeyDeriver, KeyRing, KeyedLimiter, KnowledgeCasError, type KnowledgeSnapshot, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LadderSpec, type LeasableStore, type Lease, LeaseHeldError, Ledger, LineageCounters, LineageIndex, LineageRef, LineageRelation, LineageStats, LogicalTaskId, MASKED_SECRET, MAX_DEPTH_CEILING, MatchResult, McpConfig, McpToolSource, MechanicalGateProfile, MechanicalGateVerdict, type MetaLookupStore, type ModelCaps, ModelChoice, type ModelClaim, ModelEpochInputs, type ModelKnowledgeHandle, type ModelKnowledgeStore, ModelListConstraint, ModelRef, ModelRetry, ModelSpec, Msg, NoProgressDetector, NodeId, NodeLinkValue, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OnEscalation, OperationDisposition, OrchestrateOptions, OrchestratorBudgetSpec, OrchestratorCapConfigError, OrchestratorExtension, OrchestratorExtensionIO, OrchestratorRuntime, Out, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, Part, PendingExternal, PendingToolTurn, PermissionConfig, PermissionGate, PermissionHook, PermissionPreset, PermissionRule, PermissionVerdict, PhaseTarget, PipelineCollected, PipelineOpts, PlanInvariantError, PriceTable, PricedUsage, type Pricing, type PricingTier, type ProviderAdapter, QualityFloors, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, RandIdentityInput, RandPayload, RefEntryAppender, RefEntryClassification, RefusalInfo, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunBudget, RunEventSink, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, Semaphore, SerializationHook, Settled, ShellPatternRules, ShellSegment, ShellVerdict, SinglePhaseAppend, SpanMinter, SpanRegistry, SpawnAdmissionValue, SpawnAgentParams, SpawnKey, SpawnLineage, SpawnLineageOpt, SpawnOrigin, SpawnRecord, Spend, Stage, type StandardJSONSchemaV1, type StandardSchemaV1, StepIdentityInput, StructuredOutputTier, SuspendedAppend, SuspensionState, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, TerminalPatch, TerminationAccount, TerminationAccountSnapshot, TerminationDeniedValue, TerminationDeniedWriter, TerminationInitValue, TerminationLimits, TerminationResource, ToolCallRequest, ToolChoice, type ToolContext, ToolContextSeed, ToolContract, type ToolDef, type ToolEvents, type ToolExecutor, ToolInit, type ToolRisk, ToolRuntime, type ToolSource, type ToolSourceSession, ToolsOption, TranscriptSerializationHook, type TranscriptStore, TriggerClass, TtlState, Usage, UsageLimits, UsageSlice, VerifiedRecommendation, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, WakeBudgetBlock, WakeDigest, WakeTrigger, WireError, Workflow, WorkflowCallOpts, type WorkflowEvent, type WorkflowEventBody, WorkflowRegistry, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, atCompactionThreshold, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasMetaLookup, hashRunArgs, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, metaMatchesFilter, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, readRunMeta, readTerminationInit, registryKeyRing, remeasureQueue, replayDisposition, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
|
package/dist/index.js
CHANGED
|
@@ -206,6 +206,25 @@ var BudgetExhaustedError = class extends RulvarError {
|
|
|
206
206
|
}
|
|
207
207
|
};
|
|
208
208
|
/**
|
|
209
|
+
* A declared fail-run policy engaged and closed the run as a failure
|
|
210
|
+
* (v1.35.0 review P2-1): `budget.atCap: 'fail-run'` after the journaled
|
|
211
|
+
* orchestrator cap decision, or `guards.fallback: 'fail-run'` after the
|
|
212
|
+
* journaled guard verdict. The run outcome is 'error' with this code;
|
|
213
|
+
* `data.source` names the policy ('orchestrator_budget_cap' or
|
|
214
|
+
* 'plan_guards') and `data` carries the decision entry reference, so the
|
|
215
|
+
* outcome is a pure roll forward of the journal on resume: no second
|
|
216
|
+
* decision, no model call, no spend.
|
|
217
|
+
*/
|
|
218
|
+
var FailRunError = class extends RulvarError {
|
|
219
|
+
code = "fail_run";
|
|
220
|
+
constructor(message, opts) {
|
|
221
|
+
super(message, {
|
|
222
|
+
retryable: false,
|
|
223
|
+
...opts
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
/**
|
|
209
228
|
* A structural admission rejection (maxDepth, maxChildrenPerNode,
|
|
210
229
|
* maxTotalSpawns) from the AdmissionController (M6-T06). The rejection verdict is embedded in
|
|
211
230
|
* the carrying spawn-admission decision entry and replays identically;
|
|
@@ -2179,6 +2198,51 @@ function modelEpochOf(inputs) {
|
|
|
2179
2198
|
return Object.keys(epoch).length === 0 ? void 0 : epoch;
|
|
2180
2199
|
}
|
|
2181
2200
|
//#endregion
|
|
2201
|
+
//#region src/l0/validate-numbers.ts
|
|
2202
|
+
/**
|
|
2203
|
+
* Shared numeric option validators (v1.34.0 review P2-3). Every public
|
|
2204
|
+
* numeric knob that shapes admission, limits, concurrency, or timers is
|
|
2205
|
+
* validated with these helpers at its intake boundary, so a malformed
|
|
2206
|
+
* value (NaN, Infinity, a negative, a fraction where an integer is
|
|
2207
|
+
* required) fails as a typed ConfigError before any journal entry,
|
|
2208
|
+
* worker, or provider dispatch. NaN needs dedicated handling because
|
|
2209
|
+
* every comparison with it is false: a hand-written range check in the
|
|
2210
|
+
* rejecting polarity (`value < min || value > max`) silently admits it.
|
|
2211
|
+
*/
|
|
2212
|
+
/**
|
|
2213
|
+
* The Node timer ceiling: setTimeout clamps any longer delay to 1 ms, so
|
|
2214
|
+
* a naive far-future timer fires immediately (v1.34.0 review P2-2).
|
|
2215
|
+
* Relative timer options are validated against this bound; absolute
|
|
2216
|
+
* deadlines use the sliced timer in long-timer.ts instead.
|
|
2217
|
+
*/
|
|
2218
|
+
const MAX_TIMER_DELAY_MS = 2147483647;
|
|
2219
|
+
function refuse(site, requirement, value) {
|
|
2220
|
+
throw new ConfigError(`${site} must be ${requirement}; got ${String(value)}`);
|
|
2221
|
+
}
|
|
2222
|
+
/** An integer >= 1 (counts, caps, and depths). */
|
|
2223
|
+
function requirePositiveInteger(value, site) {
|
|
2224
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1) refuse(site, "a positive integer", value);
|
|
2225
|
+
}
|
|
2226
|
+
/** An integer >= 0 (caps where zero means "none allowed"). */
|
|
2227
|
+
function requireNonNegativeInteger(value, site) {
|
|
2228
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) refuse(site, "a nonnegative integer", value);
|
|
2229
|
+
}
|
|
2230
|
+
/** A finite number >= 0 (USD amounts and reserves). */
|
|
2231
|
+
function requireNonNegativeNumber(value, site) {
|
|
2232
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) refuse(site, "a finite nonnegative number", value);
|
|
2233
|
+
}
|
|
2234
|
+
/** A finite fraction in (0, 1]. */
|
|
2235
|
+
function requireFraction(value, site) {
|
|
2236
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > 1) refuse(site, "a fraction in (0, 1]", value);
|
|
2237
|
+
}
|
|
2238
|
+
/**
|
|
2239
|
+
* A relative delay handed to setTimeout as-is: an integer within the
|
|
2240
|
+
* Node timer maximum, mirroring validateRetryPolicy's bound.
|
|
2241
|
+
*/
|
|
2242
|
+
function requireTimerDelayMs(value, site) {
|
|
2243
|
+
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);
|
|
2244
|
+
}
|
|
2245
|
+
//#endregion
|
|
2182
2246
|
//#region src/knowledge/file-store.ts
|
|
2183
2247
|
/**
|
|
2184
2248
|
* FileModelKnowledgeStore (M10-T01): the default ModelKnowledgeStore, a
|
|
@@ -2245,6 +2309,7 @@ var FileModelKnowledgeStore = class {
|
|
|
2245
2309
|
queue = Promise.resolve();
|
|
2246
2310
|
constructor(options) {
|
|
2247
2311
|
this.path = resolve(options?.path ?? "./rulvar.models.json");
|
|
2312
|
+
if (options?.activeClaimsCap !== void 0) requireNonNegativeInteger(options.activeClaimsCap, "FileModelKnowledgeStore activeClaimsCap");
|
|
2248
2313
|
this.activeClaimsCap = options?.activeClaimsCap;
|
|
2249
2314
|
}
|
|
2250
2315
|
read() {
|
|
@@ -2301,6 +2366,19 @@ var FileModelKnowledgeStore = class {
|
|
|
2301
2366
|
return result;
|
|
2302
2367
|
}
|
|
2303
2368
|
};
|
|
2369
|
+
/**
|
|
2370
|
+
* Truncates `raw` to at most `budgetChars` characters. A string within
|
|
2371
|
+
* the budget returns unchanged; a longer one is cut to
|
|
2372
|
+
* `budgetChars - 3` characters plus the marker, and budgets below the
|
|
2373
|
+
* marker length fall back to a bare slice so the bound still holds.
|
|
2374
|
+
* The measure is deterministic characters (UTF-16 units): identical
|
|
2375
|
+
* live and on replay, no tokenizer dependence.
|
|
2376
|
+
*/
|
|
2377
|
+
function truncateToBudget(raw, budgetChars) {
|
|
2378
|
+
if (raw.length <= budgetChars) return raw;
|
|
2379
|
+
if (budgetChars < 3) return raw.slice(0, Math.max(0, budgetChars));
|
|
2380
|
+
return `${raw.slice(0, budgetChars - 3)}...`;
|
|
2381
|
+
}
|
|
2304
2382
|
//#endregion
|
|
2305
2383
|
//#region src/model/floors.ts
|
|
2306
2384
|
/**
|
|
@@ -2442,10 +2520,15 @@ function compileVerifiedLayer(claims, ladders) {
|
|
|
2442
2520
|
/**
|
|
2443
2521
|
* The deterministic card render. Pure: same filtered
|
|
2444
2522
|
* claims and ladders give byte-identical text. The render budget is
|
|
2445
|
-
* 4096 chars; over it, the OLDEST-observed notes
|
|
2446
|
-
*
|
|
2523
|
+
* 4096 chars by default; over it, the OLDEST-observed notes withhold
|
|
2524
|
+
* first behind an explicit marker, and the budget is a HARD upper bound
|
|
2525
|
+
* of the returned string: a card whose mandatory sections alone exceed
|
|
2526
|
+
* it is truncated with the shared marker (v1.35.0 review P2-5: a budget
|
|
2527
|
+
* of 32 used to return the full 136-char header form). budgetChars is a
|
|
2528
|
+
* nonnegative integer, validated as a ConfigError.
|
|
2447
2529
|
*/
|
|
2448
2530
|
function modelKnowledgeCard(claims, ladders, options) {
|
|
2531
|
+
if (options?.budgetChars !== void 0) requireNonNegativeInteger(options.budgetChars, "modelKnowledgeCard budgetChars");
|
|
2449
2532
|
const budget = options?.budgetChars ?? 4096;
|
|
2450
2533
|
const lines = ["Model knowledge card (tier-relative; advisory within declared ladders and hard floors)."];
|
|
2451
2534
|
const verified = compileVerifiedLayer(claims, ladders);
|
|
@@ -2494,7 +2577,7 @@ function modelKnowledgeCard(claims, ladders, options) {
|
|
|
2494
2577
|
shown -= 1;
|
|
2495
2578
|
text = render(shown);
|
|
2496
2579
|
}
|
|
2497
|
-
return text;
|
|
2580
|
+
return truncateToBudget(text, budget);
|
|
2498
2581
|
}
|
|
2499
2582
|
//#endregion
|
|
2500
2583
|
//#region src/tools/presets.ts
|
|
@@ -3047,6 +3130,7 @@ var GitWorktreeProvider = class {
|
|
|
3047
3130
|
constructor(options) {
|
|
3048
3131
|
this.repoRoot = options?.repoRoot ?? process.cwd();
|
|
3049
3132
|
this.keepOnError = options?.keepOnError ?? false;
|
|
3133
|
+
if (options?.maxPinnedWorktrees !== void 0) requireNonNegativeInteger(options.maxPinnedWorktrees, "GitWorktreeProvider maxPinnedWorktrees");
|
|
3050
3134
|
this.maxPinned = options?.maxPinnedWorktrees ?? 4;
|
|
3051
3135
|
this.onWarn = options?.onWarn ?? ((msg) => process.emitWarning(msg, {
|
|
3052
3136
|
code: "RULVAR_WORKTREE",
|
|
@@ -5836,6 +5920,24 @@ var Replayer = class {
|
|
|
5836
5920
|
* Full contract: https://docs.rulvar.com/guide/durability
|
|
5837
5921
|
*/
|
|
5838
5922
|
/**
|
|
5923
|
+
* The rejection carrier of an aborted flavor B decision wait (v1.35.0
|
|
5924
|
+
* review P1): the parked `awaitDecision` observes the branch/run
|
|
5925
|
+
* AbortSignal, releases its held activity, removes its waiter, and
|
|
5926
|
+
* rejects with this class so cancel, host abort, the run deadline, and
|
|
5927
|
+
* failed sibling aborts all settle the run in bounded time.
|
|
5928
|
+
* Deliberately not a RulvarError: the abort is cancellation intent, not
|
|
5929
|
+
* a registry failure class; the suspension entry stays OPEN, so a later
|
|
5930
|
+
* resume parks the decision again and the durable deadline still applies.
|
|
5931
|
+
*/
|
|
5932
|
+
var EscalationDecisionAbortedError = class extends Error {
|
|
5933
|
+
entryRef;
|
|
5934
|
+
constructor(message, entryRef) {
|
|
5935
|
+
super(message);
|
|
5936
|
+
this.name = "EscalationDecisionAbortedError";
|
|
5937
|
+
this.entryRef = entryRef;
|
|
5938
|
+
}
|
|
5939
|
+
};
|
|
5940
|
+
/**
|
|
5839
5941
|
* Normalizes a resolution value into an ApprovalDecision. Anything that
|
|
5840
5942
|
* is not an explicit allow is a deny: an approval never fails open.
|
|
5841
5943
|
*/
|
|
@@ -6112,8 +6214,33 @@ var ExternalRegistry = class ExternalRegistry {
|
|
|
6112
6214
|
},
|
|
6113
6215
|
deadlineAt: options.deadlineAt
|
|
6114
6216
|
});
|
|
6115
|
-
return new Promise((resolve) => {
|
|
6217
|
+
return new Promise((resolve, reject) => {
|
|
6218
|
+
const signal = options.signal;
|
|
6219
|
+
const abortError = () => {
|
|
6220
|
+
const reason = signal?.reason;
|
|
6221
|
+
const detail = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "aborted";
|
|
6222
|
+
return new EscalationDecisionAbortedError(`flavor B escalation decision wait aborted (entry ${String(entry.seq)}): ${detail}`, entry.seq);
|
|
6223
|
+
};
|
|
6224
|
+
if (signal?.aborted === true) {
|
|
6225
|
+
reject(abortError());
|
|
6226
|
+
return;
|
|
6227
|
+
}
|
|
6116
6228
|
const exitActivity = this.enter();
|
|
6229
|
+
let settled = false;
|
|
6230
|
+
let detachAbort;
|
|
6231
|
+
/** Exactly one terminal: activity exits once, the listener detaches once. */
|
|
6232
|
+
const settle = () => {
|
|
6233
|
+
if (settled) return false;
|
|
6234
|
+
settled = true;
|
|
6235
|
+
exitActivity();
|
|
6236
|
+
detachAbort?.();
|
|
6237
|
+
return true;
|
|
6238
|
+
};
|
|
6239
|
+
const onAbort = () => {
|
|
6240
|
+
if (!settle()) return;
|
|
6241
|
+
this.waiters.delete(entry.seq);
|
|
6242
|
+
if (!this.closedFlag) reject(abortError());
|
|
6243
|
+
};
|
|
6117
6244
|
const waiter = {
|
|
6118
6245
|
kind: "decision",
|
|
6119
6246
|
key: ExternalRegistry.approvalKey(entry.seq),
|
|
@@ -6121,7 +6248,7 @@ var ExternalRegistry = class ExternalRegistry {
|
|
|
6121
6248
|
entryRef: entry.seq,
|
|
6122
6249
|
prompt: `decide escalation of '${options.toolName}'`,
|
|
6123
6250
|
resolve: (value) => {
|
|
6124
|
-
|
|
6251
|
+
if (!settle()) return;
|
|
6125
6252
|
resolve({
|
|
6126
6253
|
value,
|
|
6127
6254
|
entryRef: entry.seq
|
|
@@ -6129,6 +6256,12 @@ var ExternalRegistry = class ExternalRegistry {
|
|
|
6129
6256
|
}
|
|
6130
6257
|
};
|
|
6131
6258
|
this.waiters.set(entry.seq, waiter);
|
|
6259
|
+
if (signal !== void 0) {
|
|
6260
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
6261
|
+
detachAbort = () => {
|
|
6262
|
+
signal.removeEventListener("abort", onAbort);
|
|
6263
|
+
};
|
|
6264
|
+
}
|
|
6132
6265
|
options.onPending?.(entry, replayed);
|
|
6133
6266
|
});
|
|
6134
6267
|
}
|
|
@@ -6758,51 +6891,6 @@ function tierWithinCaps(tier, caps) {
|
|
|
6758
6891
|
return TIER_ORDER[tier] <= TIER_ORDER[caps.structuredOutput];
|
|
6759
6892
|
}
|
|
6760
6893
|
//#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
|
|
6806
6894
|
//#region src/engine/scheduler.ts
|
|
6807
6895
|
/**
|
|
6808
6896
|
* Scheduler and concurrency (M1-T08): the per-run semaphore with a FIFO
|
|
@@ -10413,8 +10501,7 @@ const WAKE_SUMMARY_RENDER_BUDGET_CHARS = 400;
|
|
|
10413
10501
|
* spawn ordinal; the LLM distillation upgrade is M7 territory).
|
|
10414
10502
|
*/
|
|
10415
10503
|
function summarizeOutput(result) {
|
|
10416
|
-
|
|
10417
|
-
return raw.length <= 400 ? raw : `${raw.slice(0, 400)}...`;
|
|
10504
|
+
return truncateToBudget(result.status === "ok" ? typeof result.output === "string" ? result.output : JSON.stringify(result.output ?? null) : result.errorMessage ?? `terminal status ${result.status}`, 400);
|
|
10418
10505
|
}
|
|
10419
10506
|
/** Folds one settled child into its digest (spawn-ordinal ordering is the caller's). */
|
|
10420
10507
|
function digestOf(record, result) {
|
|
@@ -11034,6 +11121,7 @@ function createCtx(internals, rootWorkflow) {
|
|
|
11034
11121
|
if (escalation !== void 0) {
|
|
11035
11122
|
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
11123
|
if (escalation.deadlineMs !== void 0) requirePositiveInteger(escalation.deadlineMs, "escalation.deadlineMs");
|
|
11124
|
+
if (escalation.minSpendUsd !== void 0) requireNonNegativeNumber(escalation.minSpendUsd, "escalation.minSpendUsd");
|
|
11037
11125
|
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')");
|
|
11038
11126
|
if (escalation.flavor === "B" && escalation.deadlineMs === void 0) throw new ConfigError("escalation flavor 'B' requires an explicit deadlineMs");
|
|
11039
11127
|
}
|
|
@@ -11589,50 +11677,8 @@ function createCtx(internals, rootWorkflow) {
|
|
|
11589
11677
|
exitActivity?.();
|
|
11590
11678
|
}
|
|
11591
11679
|
internals.budget.releaseReserve(reserve, budgetAccount);
|
|
11592
|
-
|
|
11593
|
-
|
|
11594
|
-
if (internals.external === void 0) throw new ConfigError("flavor B escalation requires the engine run context");
|
|
11595
|
-
const request = result.escalationRequest;
|
|
11596
|
-
const deadlineMs = escalation.deadlineMs;
|
|
11597
|
-
if (deadlineMs === void 0) throw new ConfigError("flavor 'B' escalation requires an explicit deadlineMs");
|
|
11598
|
-
const defaultDecision = escalation.defaultDecision ?? { kind: "accept" };
|
|
11599
|
-
let timer;
|
|
11600
|
-
const decisionOutcome = await internals.external.awaitDecision({
|
|
11601
|
-
scope: agentScope(state.scope, running.seq),
|
|
11602
|
-
spanId: internals.spans.mint(spanId),
|
|
11603
|
-
toolName: "escalate",
|
|
11604
|
-
input: request,
|
|
11605
|
-
deadlineAt: new Date(internals.now() + deadlineMs).toISOString(),
|
|
11606
|
-
onPending: (entry, replayed) => {
|
|
11607
|
-
internals.events.emit({
|
|
11608
|
-
type: "approval:pending",
|
|
11609
|
-
toolName: "escalate",
|
|
11610
|
-
entryRef: entry.seq
|
|
11611
|
-
}, spanId, replayed);
|
|
11612
|
-
const registry = internals.external;
|
|
11613
|
-
timer = setLongTimeout(() => {
|
|
11614
|
-
registry?.submitResolution(entry.seq, {
|
|
11615
|
-
by: "timeout",
|
|
11616
|
-
value: defaultDecision
|
|
11617
|
-
}).catch(() => void 0);
|
|
11618
|
-
}, Date.parse(entry.deadlineAt ?? "") || internals.now(), () => internals.now());
|
|
11619
|
-
if (internals.onEscalation !== void 0) {
|
|
11620
|
-
const preview = buildEscalationReport(request, result, void 0);
|
|
11621
|
-
const previewResult = {
|
|
11622
|
-
...result,
|
|
11623
|
-
escalation: preview
|
|
11624
|
-
};
|
|
11625
|
-
Promise.resolve(internals.onEscalation(previewResult)).then((decision) => registry?.submitResolution(entry.seq, {
|
|
11626
|
-
by: "external",
|
|
11627
|
-
value: decision
|
|
11628
|
-
})).catch(() => void 0);
|
|
11629
|
-
}
|
|
11630
|
-
}
|
|
11631
|
-
});
|
|
11632
|
-
if (timer !== void 0) timer.cancel();
|
|
11633
|
-
flavorBDecision = decisionOutcome.value;
|
|
11634
|
-
}
|
|
11635
|
-
if (acquired !== void 0) {
|
|
11680
|
+
const collectAndDisposeWorktree = async () => {
|
|
11681
|
+
if (acquired === void 0) return;
|
|
11636
11682
|
try {
|
|
11637
11683
|
const { files, patch } = await acquired.collect();
|
|
11638
11684
|
const patchRef = internals.mintTranscriptRef();
|
|
@@ -11652,7 +11698,62 @@ function createCtx(internals, rootWorkflow) {
|
|
|
11652
11698
|
}, spanId);
|
|
11653
11699
|
}
|
|
11654
11700
|
await acquired.dispose(result.status !== "ok" && result.status !== "escalated");
|
|
11701
|
+
};
|
|
11702
|
+
let flavorBDecision;
|
|
11703
|
+
if (result.status === "escalated" && escalation?.flavor === "B" && result.escalationRequest !== void 0) {
|
|
11704
|
+
if (internals.external === void 0) throw new ConfigError("flavor B escalation requires the engine run context");
|
|
11705
|
+
const request = result.escalationRequest;
|
|
11706
|
+
const deadlineMs = escalation.deadlineMs;
|
|
11707
|
+
if (deadlineMs === void 0) throw new ConfigError("flavor 'B' escalation requires an explicit deadlineMs");
|
|
11708
|
+
const defaultDecision = escalation.defaultDecision ?? { kind: "accept" };
|
|
11709
|
+
let timer;
|
|
11710
|
+
let decisionOutcome;
|
|
11711
|
+
try {
|
|
11712
|
+
decisionOutcome = await internals.external.awaitDecision({
|
|
11713
|
+
scope: agentScope(state.scope, running.seq),
|
|
11714
|
+
spanId: internals.spans.mint(spanId),
|
|
11715
|
+
toolName: "escalate",
|
|
11716
|
+
input: request,
|
|
11717
|
+
deadlineAt: new Date(internals.now() + deadlineMs).toISOString(),
|
|
11718
|
+
signal: branchOrRunSignal,
|
|
11719
|
+
onPending: (entry, replayed) => {
|
|
11720
|
+
internals.events.emit({
|
|
11721
|
+
type: "approval:pending",
|
|
11722
|
+
toolName: "escalate",
|
|
11723
|
+
entryRef: entry.seq
|
|
11724
|
+
}, spanId, replayed);
|
|
11725
|
+
const registry = internals.external;
|
|
11726
|
+
timer = setLongTimeout(() => {
|
|
11727
|
+
registry?.submitResolution(entry.seq, {
|
|
11728
|
+
by: "timeout",
|
|
11729
|
+
value: defaultDecision
|
|
11730
|
+
}).catch(() => void 0);
|
|
11731
|
+
}, Date.parse(entry.deadlineAt ?? "") || internals.now(), () => internals.now());
|
|
11732
|
+
if (internals.onEscalation !== void 0) {
|
|
11733
|
+
const preview = buildEscalationReport(request, result, void 0);
|
|
11734
|
+
const previewResult = {
|
|
11735
|
+
...result,
|
|
11736
|
+
escalation: preview
|
|
11737
|
+
};
|
|
11738
|
+
Promise.resolve(internals.onEscalation(previewResult)).then((decision) => registry?.submitResolution(entry.seq, {
|
|
11739
|
+
by: "external",
|
|
11740
|
+
value: decision
|
|
11741
|
+
})).catch(() => void 0);
|
|
11742
|
+
}
|
|
11743
|
+
}
|
|
11744
|
+
});
|
|
11745
|
+
} catch (thrown) {
|
|
11746
|
+
if (thrown instanceof EscalationDecisionAbortedError) {
|
|
11747
|
+
await collectAndDisposeWorktree();
|
|
11748
|
+
throw new AgentCallError(thrown.message, result, state.scope, running.seq);
|
|
11749
|
+
}
|
|
11750
|
+
throw thrown;
|
|
11751
|
+
} finally {
|
|
11752
|
+
if (timer !== void 0) timer.cancel();
|
|
11753
|
+
}
|
|
11754
|
+
flavorBDecision = decisionOutcome.value;
|
|
11655
11755
|
}
|
|
11756
|
+
if (acquired !== void 0) await collectAndDisposeWorktree();
|
|
11656
11757
|
if (result.status === "escalated" && result.escalationRequest !== void 0) {
|
|
11657
11758
|
const patchRef = result.artifacts?.find((artifact) => artifact.kind === "patch")?.ref;
|
|
11658
11759
|
const report = buildEscalationReport(result.escalationRequest, result, patchRef);
|
|
@@ -12290,6 +12391,28 @@ async function executeWorkflow(internals, wf, args) {
|
|
|
12290
12391
|
* written; escalated children simply settle into their digests.
|
|
12291
12392
|
*/
|
|
12292
12393
|
const ORCHESTRATE_WORKFLOW_NAME = "rulvar-orchestrate";
|
|
12394
|
+
/**
|
|
12395
|
+
* The orchestrate intake gate (v1.35.0 review P2-2): every numeric
|
|
12396
|
+
* option and the atCap literal validate SYNCHRONOUSLY at workflow
|
|
12397
|
+
* construction, shared by both surfaces (the top level orchestrate() throws
|
|
12398
|
+
* before a run exists; ctx.orchestrate throws before any journal entry,
|
|
12399
|
+
* provider call, or child dispatch). A NaN here previously disabled the
|
|
12400
|
+
* spawn cap (`spawnOrdinal >= NaN` is false forever) and the digest
|
|
12401
|
+
* render bound, and a negative finalize reserve WIDENED the soft cap
|
|
12402
|
+
* boundary instead of reserving from it.
|
|
12403
|
+
*/
|
|
12404
|
+
function validateOrchestrateOptions(opts) {
|
|
12405
|
+
if (opts === void 0) return;
|
|
12406
|
+
if (opts.maxSpawns !== void 0) requireNonNegativeInteger(opts.maxSpawns, "orchestrate maxSpawns");
|
|
12407
|
+
if (opts.renderBudgetChars !== void 0) requireNonNegativeInteger(opts.renderBudgetChars, "orchestrate renderBudgetChars");
|
|
12408
|
+
const spec = opts.budget;
|
|
12409
|
+
if (spec === void 0) return;
|
|
12410
|
+
if (spec.capUsd !== void 0) requireNonNegativeNumber(spec.capUsd, "orchestrate budget.capUsd");
|
|
12411
|
+
if (spec.capFraction !== void 0) requireFraction(spec.capFraction, "orchestrate budget.capFraction");
|
|
12412
|
+
if (spec.finalizeReserveUsd !== void 0) requireNonNegativeNumber(spec.finalizeReserveUsd, "orchestrate budget.finalizeReserveUsd");
|
|
12413
|
+
if (spec.finalizeTurns !== void 0) requirePositiveInteger(spec.finalizeTurns, "orchestrate budget.finalizeTurns");
|
|
12414
|
+
if (spec.atCap !== void 0 && spec.atCap !== "finish-with-partial" && spec.atCap !== "fail-run") throw new ConfigError(`orchestrate budget.atCap must be 'finish-with-partial' or 'fail-run'; got ${String(spec.atCap)}`);
|
|
12415
|
+
}
|
|
12293
12416
|
function orchestratorPrompt(goal, maxSpawns, extensionLines) {
|
|
12294
12417
|
return [
|
|
12295
12418
|
"You are the orchestrator of a multi-agent run.",
|
|
@@ -12344,6 +12467,7 @@ function filterProfiles(registered, names) {
|
|
|
12344
12467
|
* orchestrator agent with the finish terminal tool.
|
|
12345
12468
|
*/
|
|
12346
12469
|
function makeOrchestratorWorkflow(goal, opts) {
|
|
12470
|
+
validateOrchestrateOptions(opts);
|
|
12347
12471
|
return defineWorkflow({ name: ORCHESTRATE_WORKFLOW_NAME }, async (ctx) => {
|
|
12348
12472
|
const runtime = runtimeOf(ctx);
|
|
12349
12473
|
const { internals } = runtime;
|
|
@@ -12369,7 +12493,6 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
12369
12493
|
const runCeiling = internals.budget.accountView(callingState.budgetScope ?? "run")?.ceilingUsd;
|
|
12370
12494
|
const spec = opts?.budget;
|
|
12371
12495
|
const fraction = spec?.capFraction ?? .2;
|
|
12372
|
-
if (fraction > 1) throw new OrchestratorCapConfigError(`capFraction ${String(fraction)} exceeds 1.0 (opting out of the cap is explicit only, up to 1.0 inclusive)`);
|
|
12373
12496
|
const fromFraction = runCeiling === void 0 ? void 0 : fraction * runCeiling;
|
|
12374
12497
|
const bounds = [spec?.capUsd, fromFraction].filter((bound) => bound !== void 0);
|
|
12375
12498
|
const priorReserveDecision = internals.replayer.snapshot().find((entry) => {
|
|
@@ -12552,6 +12675,15 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
12552
12675
|
byOrdinal.set(spawnOrdinal, record);
|
|
12553
12676
|
return record;
|
|
12554
12677
|
};
|
|
12678
|
+
/**
|
|
12679
|
+
* The declared fail-run terminal (v1.35.0 review P2-1): the first
|
|
12680
|
+
* extension terminate() call stores its failure and aborts the
|
|
12681
|
+
* orchestrator loop; the settle boundary rethrows it deterministically
|
|
12682
|
+
* (boot terminates again from the journaled verdict on resume, so the
|
|
12683
|
+
* same failure rolls forward without a model call).
|
|
12684
|
+
*/
|
|
12685
|
+
let extensionTermination;
|
|
12686
|
+
const forcedFinishController = new AbortController();
|
|
12555
12687
|
const io = {
|
|
12556
12688
|
runId: internals.runId,
|
|
12557
12689
|
baseScope: callingState.scope,
|
|
@@ -12597,7 +12729,12 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
12597
12729
|
},
|
|
12598
12730
|
registerAlias: (donorScope, targetScope) => internals.replayer.registerAlias(donorScope, targetScope),
|
|
12599
12731
|
priceUsd: (servedBy, usage) => servedBy === void 0 ? void 0 : internals.priceUsd(servedBy, usage),
|
|
12600
|
-
emit: (event, options) => internals.events.emit(event, callingState.spanId, options?.replayed)
|
|
12732
|
+
emit: (event, options) => internals.events.emit(event, callingState.spanId, options?.replayed),
|
|
12733
|
+
terminate: (error) => {
|
|
12734
|
+
if (extensionTermination !== void 0) return;
|
|
12735
|
+
extensionTermination = error;
|
|
12736
|
+
forcedFinishController.abort("rulvar:extension-terminate");
|
|
12737
|
+
}
|
|
12601
12738
|
};
|
|
12602
12739
|
const cancelByHandle = async (handle, _reason) => {
|
|
12603
12740
|
const record = records.get(handle);
|
|
@@ -12690,7 +12827,6 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
12690
12827
|
await runExtensionActivity();
|
|
12691
12828
|
};
|
|
12692
12829
|
let capDecisionRef = internals.replayer.snapshot().find((entry) => entry.kind === "decision" && entry.value?.decisionType === "orchestrator_budget_cap")?.seq;
|
|
12693
|
-
const forcedFinishController = new AbortController();
|
|
12694
12830
|
let capInFlight = false;
|
|
12695
12831
|
/**
|
|
12696
12832
|
* The at-cap freeze: EXACTLY one decision entry
|
|
@@ -12772,11 +12908,11 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
12772
12908
|
completedDigests: undelivered.map((record) => {
|
|
12773
12909
|
const row = digestOf(record, record.settled);
|
|
12774
12910
|
const budgetChars = opts?.renderBudgetChars ?? 400;
|
|
12775
|
-
|
|
12911
|
+
const outputSummary = truncateToBudget(row.outputSummary, budgetChars);
|
|
12912
|
+
return outputSummary === row.outputSummary ? row : {
|
|
12776
12913
|
...row,
|
|
12777
|
-
outputSummary
|
|
12914
|
+
outputSummary
|
|
12778
12915
|
};
|
|
12779
|
-
return row;
|
|
12780
12916
|
}),
|
|
12781
12917
|
escalations
|
|
12782
12918
|
};
|
|
@@ -13168,9 +13304,32 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
13168
13304
|
completed: [...records.values()].filter((record) => record.settled !== void 0).sort((a, b) => a.spawnOrdinal - b.spawnOrdinal).map((record) => digestOf(record, record.settled))
|
|
13169
13305
|
};
|
|
13170
13306
|
};
|
|
13171
|
-
|
|
13307
|
+
/**
|
|
13308
|
+
* The settle at the cap: the JOURNALED cap decision drives the policy
|
|
13309
|
+
* branch (its `fallback` field froze budget.atCap when the cap
|
|
13310
|
+
* tripped), so a crash between the decision and its effect rolls the
|
|
13311
|
+
* SAME outcome forward on resume, immune to drift of the live options.
|
|
13312
|
+
* 'finish-with-partial' runs the reserved finalizer;
|
|
13313
|
+
* 'fail-run' skips it and fails the run typed (v1.35.0 review P2-1:
|
|
13314
|
+
* the policy used to be journaled and then ignored).
|
|
13315
|
+
*/
|
|
13316
|
+
const settleCapOutcome = async () => {
|
|
13317
|
+
const capValue = internals.replayer.snapshot().find((entry) => entry.seq === capDecisionRef)?.value;
|
|
13318
|
+
if (capValue?.fallback === "fail-run") throw new FailRunError(`the orchestrator budget cap was reached (decision entry ${String(capDecisionRef ?? -1)}) and budget.atCap is 'fail-run': the reserved finalizer is skipped and the run fails instead of returning a partial result`, { data: {
|
|
13319
|
+
source: "orchestrator_budget_cap",
|
|
13320
|
+
capDecisionRef: capDecisionRef ?? -1,
|
|
13321
|
+
spentUsd: capValue.spentUsd ?? 0,
|
|
13322
|
+
capUsd: capValue.capUsd ?? 0
|
|
13323
|
+
} });
|
|
13324
|
+
return await runForcedFinish();
|
|
13325
|
+
};
|
|
13326
|
+
const bootTermination = extensionTermination;
|
|
13327
|
+
if (bootTermination !== void 0) throw bootTermination;
|
|
13328
|
+
if (capDecisionRef !== void 0) return await settleCapOutcome();
|
|
13172
13329
|
const result = await runtime.runInScope(orchestratorState, () => ctx.agent(orchestratorPrompt(goal, opts?.maxSpawns, extension?.promptLines?.()), agentOpts));
|
|
13173
|
-
|
|
13330
|
+
const liveTermination = extensionTermination;
|
|
13331
|
+
if (liveTermination !== void 0) throw liveTermination;
|
|
13332
|
+
if (capDecisionRef !== void 0) return await settleCapOutcome();
|
|
13174
13333
|
if (orchestratorAccount !== void 0) internals.cost.orchestrator.spentUsd = internals.budget.accountView(orchestratorAccount)?.spentUsd ?? 0;
|
|
13175
13334
|
if (result.status !== "ok") throw new ConfigError(`the orchestrator agent terminated with status '${result.status}'` + (result.errorMessage === void 0 ? "" : `: ${result.errorMessage}`));
|
|
13176
13335
|
return result.output;
|
|
@@ -13565,6 +13724,7 @@ function createEngine(options) {
|
|
|
13565
13724
|
if (profile.limits !== void 0) validateUsageLimits(profile.limits, `createEngine defaults.profiles['${name}'].limits`);
|
|
13566
13725
|
if (profile.estCost !== void 0) requireNonNegativeNumber(profile.estCost, `createEngine defaults.profiles['${name}'].estCost`);
|
|
13567
13726
|
if (profile.escalation?.deadlineMs !== void 0) requirePositiveInteger(profile.escalation.deadlineMs, `createEngine defaults.profiles['${name}'].escalation.deadlineMs`);
|
|
13727
|
+
if (profile.escalation?.minSpendUsd !== void 0) requireNonNegativeNumber(profile.escalation.minSpendUsd, `createEngine defaults.profiles['${name}'].escalation.minSpendUsd`);
|
|
13568
13728
|
if (profile.compaction?.threshold !== void 0) requireFraction(profile.compaction.threshold, `createEngine defaults.profiles['${name}'].compaction.threshold`);
|
|
13569
13729
|
}
|
|
13570
13730
|
const knowledgeStore = options.stores?.modelKnowledge;
|
|
@@ -14319,4 +14479,4 @@ function createSandboxBridge(ctx, options) {
|
|
|
14319
14479
|
};
|
|
14320
14480
|
}
|
|
14321
14481
|
//#endregion
|
|
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 };
|
|
14482
|
+
export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DedupIndex, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GitWorktreeProvider, INBOX_PROPOSAL_TTL_DAYS, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JournalCompatibilityError, JournalMatcher, JournalMissError, JournalOrderViolation, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_DEPTH_CEILING, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, ParallelSiteCounter, PlanInvariantError, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_PROFILES, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, atCompactionThreshold, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileVerifiedLayer, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, foldTermination, formatRePrompt, formatScopePath, hasMetaLookup, hashRunArgs, hashWorkflowBody, hashWorkflowSource, identityJcs, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lexShellCommand, liftRetainedParts, lineageWeightOf, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, mergeUsageLimits, metaMatchesFilter, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, readRunMeta, readTerminationInit, registryKeyRing, remeasureQueue, replayDisposition, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulvar/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.36.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",
|