@tangle-network/agent-runtime 0.313.2 → 0.313.3

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.
Files changed (37) hide show
  1. package/dist/{activation-B_dUMaW8.js → activation-Cbjng19L.js} +2 -2
  2. package/dist/{activation-B_dUMaW8.js.map → activation-Cbjng19L.js.map} +1 -1
  3. package/dist/agent.js +2 -2
  4. package/dist/{coordination-driver-26qkTbVh.js → coordination-driver-DKoxt1wL.js} +2 -2
  5. package/dist/{coordination-driver-26qkTbVh.js.map → coordination-driver-DKoxt1wL.js.map} +1 -1
  6. package/dist/{delegate-C0ZXShbu.js → delegate-CpWZOxuA.js} +2 -2
  7. package/dist/{delegate-C0ZXShbu.js.map → delegate-CpWZOxuA.js.map} +1 -1
  8. package/dist/durable.js +2 -2
  9. package/dist/{graph-BF6LYqON.js → graph-Cjplvg8L.js} +4 -4
  10. package/dist/{graph-BF6LYqON.js.map → graph-Cjplvg8L.js.map} +1 -1
  11. package/dist/{improvement-cycle-C-F2WKKO.js → improvement-cycle-BcnpQZOP.js} +3 -3
  12. package/dist/{improvement-cycle-C-F2WKKO.js.map → improvement-cycle-BcnpQZOP.js.map} +1 -1
  13. package/dist/index.js +7 -7
  14. package/dist/intelligence.js +3 -3
  15. package/dist/kernel.js +8 -8
  16. package/dist/{loop-runner-bin-CreO-bam.js → loop-runner-bin-bAbpeDOp.js} +3 -3
  17. package/dist/{loop-runner-bin-CreO-bam.js.map → loop-runner-bin-bAbpeDOp.js.map} +1 -1
  18. package/dist/loop-runner-bin.js +1 -1
  19. package/dist/mcp/bin.js +3 -3
  20. package/dist/mcp/index.js +4 -4
  21. package/dist/model-policy-DhvyZ8-O.js.map +1 -1
  22. package/dist/{provision-supervisor-nV0XW_vi.js → provision-supervisor-DyIZEbwJ.js} +3 -3
  23. package/dist/{provision-supervisor-nV0XW_vi.js.map → provision-supervisor-DyIZEbwJ.js.map} +1 -1
  24. package/dist/{runtime-sx7Qtw4g.js → runtime-DqGhWHhs.js} +8 -8
  25. package/dist/{runtime-sx7Qtw4g.js.map → runtime-DqGhWHhs.js.map} +1 -1
  26. package/dist/{search-executor-emDfPe_k.js → search-executor-Q8W7n1Tg.js} +2 -2
  27. package/dist/{search-executor-emDfPe_k.js.map → search-executor-Q8W7n1Tg.js.map} +1 -1
  28. package/dist/{server-DgdTtcch.js → server-Brh9r0MK.js} +3 -3
  29. package/dist/{server-DgdTtcch.js.map → server-Brh9r0MK.js.map} +1 -1
  30. package/dist/{supervise-pxhnrGsA.js → supervise-QObMv9Hy.js} +3 -3
  31. package/dist/{supervise-pxhnrGsA.js.map → supervise-QObMv9Hy.js.map} +1 -1
  32. package/dist/{supervisor-yX008JOQ.js → supervisor-DwfUsy8w.js} +119 -51
  33. package/dist/supervisor-DwfUsy8w.js.map +1 -0
  34. package/dist/testing.js +12 -12
  35. package/dist/tui/index.js +1 -1
  36. package/package.json +1 -1
  37. package/dist/supervisor-yX008JOQ.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
- import { $r as toOtelAttributes, Fr as ROUTER_PRICE_SOURCE, Gr as buildRuntimeEventOtelSpans, Hr as resolveRedactor, Kr as createOpenInferenceFileExporter, Nr as priceTokens, Pr as routerTokenPrice, Qi as executableAgentProfileSnapshot, Qr as padTraceId, Ur as buildLoopOtelSpans, Vr as defaultRedactorIdentityMaterial, Wr as buildLoopSpanNodes, Xr as loopEventToOtelSpan, Yr as generateSpanId, Zr as padSpanId, ei as createRuntimeEventCollector, ii as sanitizeRuntimeStreamEvent, ni as sanitizeAgentRuntimeEvent, qr as createOtelExporter, ri as sanitizeKnowledgeReadinessReport, ti as createRuntimeStreamEventCollector, xa as providerMessageText } from "./supervisor-yX008JOQ.js";
1
+ import { $r as toOtelAttributes, Fr as ROUTER_PRICE_SOURCE, Gr as buildRuntimeEventOtelSpans, Hr as resolveRedactor, Kr as createOpenInferenceFileExporter, Nr as priceTokens, Pr as routerTokenPrice, Qi as executableAgentProfileSnapshot, Qr as padTraceId, Ur as buildLoopOtelSpans, Vr as defaultRedactorIdentityMaterial, Wr as buildLoopSpanNodes, Xr as loopEventToOtelSpan, Yr as generateSpanId, Zr as padSpanId, ei as createRuntimeEventCollector, ii as sanitizeRuntimeStreamEvent, ni as sanitizeAgentRuntimeEvent, qr as createOtelExporter, ri as sanitizeKnowledgeReadinessReport, ti as createRuntimeStreamEventCollector, xa as providerMessageText } from "./supervisor-DwfUsy8w.js";
2
2
  import { a as JudgeError, c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, f as RuntimeRunStateError, i as ConfigError, l as RetainedInteractiveBindingError, m as ValidationError, o as NotFoundError, r as BackendTransportError, s as PlannerError, t as AgentEvalError, u as RetainedRunAdmissionError } from "./errors-DodWX-cb.js";
3
- import { $ as createIterableBackend, Q as streamAgentTurn, X as strategyAuthorMethod, Y as optimizerMethod, at as startOrResumeRuntimeSession, et as createSandboxPromptBackend, i as isSearchEnvironmentFault, it as nowIso, l as sharedBoxLane, nt as InMemoryRuntimeSessionStore, o as routerLane, ot as touchSession, r as dedicatedLane, rt as newRuntimeSession, t as SearchEnvironmentFault, tt as normalizeBackendStreamEvent, u as subscriptionLane, y as decideSearchImprovement } from "./search-executor-emDfPe_k.js";
3
+ import { $ as createIterableBackend, Q as streamAgentTurn, X as strategyAuthorMethod, Y as optimizerMethod, at as startOrResumeRuntimeSession, et as createSandboxPromptBackend, i as isSearchEnvironmentFault, it as nowIso, l as sharedBoxLane, nt as InMemoryRuntimeSessionStore, o as routerLane, ot as touchSession, r as dedicatedLane, rt as newRuntimeSession, t as SearchEnvironmentFault, tt as normalizeBackendStreamEvent, u as subscriptionLane, y as decideSearchImprovement } from "./search-executor-Q8W7n1Tg.js";
4
4
  import { A as canonicalCandidateBytes$1, F as immutableCandidateValue, I as omitTopLevelDigest, P as embeddedCandidateArtifact, d as persistCandidateOutputArtifact, j as canonicalCandidateDigest$1, s as captureAgentCandidateWorkspace } from "./workspace-streams-BEvSX97P.js";
5
5
  import { t as assertExecutableAgentProfile } from "./model-policy-DhvyZ8-O.js";
6
- import { a as createRuntimeUsageTotals, i as addRuntimeUsage, o as isUsageAmount, t as createAgentImprovementActivationResult } from "./activation-B_dUMaW8.js";
7
- import { Ht as McpSpawnFault, Ut as connectStdioMcp } from "./runtime-sx7Qtw4g.js";
6
+ import { a as createRuntimeUsageTotals, i as addRuntimeUsage, o as isUsageAmount, t as createAgentImprovementActivationResult } from "./activation-Cbjng19L.js";
7
+ import { Ht as McpSpawnFault, Ut as connectStdioMcp } from "./runtime-DqGhWHhs.js";
8
8
  import { i as notifyRuntimeHookEvent, n as defineRuntimeHooks, r as notifyRuntimeDecisionPoint, t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
9
- import { $ as commandVerifier, B as assertCandidateValidator, G as rawTraceDistiller, H as parseExecutionRef, J as normalizeRolloutPolicy, K as ROLLOUT_POLICY_EXTENSION, L as improve, Q as agenticGenerator, R as createCommandProfileTrainer, U as privateValuePaths, W as withMethodRuntimeControls, X as serializeRolloutPolicy, Y as parseRolloutPolicy, Z as structuralRolloutPolicyFromProfile, et as defaultBuildPrompt, q as applyRolloutPolicyToProfile, z as searchMethod } from "./improvement-cycle-C-F2WKKO.js";
9
+ import { $ as commandVerifier, B as assertCandidateValidator, G as rawTraceDistiller, H as parseExecutionRef, J as normalizeRolloutPolicy, K as ROLLOUT_POLICY_EXTENSION, L as improve, Q as agenticGenerator, R as createCommandProfileTrainer, U as privateValuePaths, W as withMethodRuntimeControls, X as serializeRolloutPolicy, Y as parseRolloutPolicy, Z as structuralRolloutPolicyFromProfile, et as defaultBuildPrompt, q as applyRolloutPolicyToProfile, z as searchMethod } from "./improvement-cycle-BcnpQZOP.js";
10
10
  import { t as sealAgentCandidateBundle } from "./bundle-BK3XBY6q.js";
11
- import { r as supervise } from "./supervise-pxhnrGsA.js";
12
- import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-CreO-bam.js";
11
+ import { r as supervise } from "./supervise-QObMv9Hy.js";
12
+ import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-bAbpeDOp.js";
13
13
  import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "./openai-tools-DoQ32vpe.js";
14
14
  import { agentCandidateKnowledgeSchema, agentCandidateWorkspaceManifestMaterialSchema, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sha256DigestSchema } from "@tangle-network/agent-interface";
15
15
  import { FAILURE_CLASSES, acquisitionPlansForKnowledgeGaps, blockingKnowledgeEval, canonicalJson, runAgentControlLoop, scoreKnowledgeReadiness, userQuestionsForKnowledgeGaps } from "@tangle-network/agent-eval";
@@ -1,7 +1,7 @@
1
- import { An as resolveAgentEnvironmentProvider, Br as defaultRedactor, Gr as buildRuntimeEventOtelSpans, Hr as resolveRedactor, Jr as flatOtelSpan, Ur as buildLoopOtelSpans, qr as createOtelExporter } from "./supervisor-yX008JOQ.js";
1
+ import { An as resolveAgentEnvironmentProvider, Br as defaultRedactor, Gr as buildRuntimeEventOtelSpans, Hr as resolveRedactor, Jr as flatOtelSpan, Ur as buildLoopOtelSpans, qr as createOtelExporter } from "./supervisor-DwfUsy8w.js";
2
2
  import { F as immutableCandidateValue, j as canonicalCandidateDigest$1 } from "./workspace-streams-BEvSX97P.js";
3
- import { a as createRuntimeUsageTotals, i as addRuntimeUsage, n as executeAgentImprovementActivation, o as isUsageAmount, r as verifyAgentImprovementActivationResult, t as createAgentImprovementActivationResult } from "./activation-B_dUMaW8.js";
4
- import { C as optimizationActivationReceiptFromMetadata, D as agentImprovementProfileSurfaceDigest, E as agentImprovementProfileDiffs, F as isAgentImprovementProfileSurface, I as isAgentProfileMeasuredSurface, N as assertProfileImprovementTargetsShareIdentity, O as agentImprovementProfileSurfaceInput, P as buildAgentImprovementActivationTargets, S as createOptimizationActivationReceipt, T as AGENT_PROFILE_MEASURED_SURFACES, V as assertProfileTrainingIsHeldOut, _ as profilePolicyWithBudget, a as executeAgentCandidateExperimentCell, b as profileTaskScenarioIdentity, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, g as profileImprovementMetadata, h as createProfileImprovementCostLedger, i as createAgentImprovementProposal, j as agentImprovementTargetProfileDiffs, l as reviewAgentImprovementProposal, m as verifyCandidateExecutionEvidence, n as createAgentImprovementActivation, o as proposeAgentImprovement, p as verifyAgentImprovementReview, r as createAgentImprovementMeasuredComparison, s as proposeAgentProfileImprovement, t as AgentCandidateExperimentCellExecutionError, u as runAgentCandidateExperiment, v as profilePreparationAccounting, w as AGENT_IMPROVEMENT_PROFILE_SURFACES, x as sealProfileImprovementBenchmark, y as profileStateDigest$1 } from "./improvement-cycle-C-F2WKKO.js";
3
+ import { a as createRuntimeUsageTotals, i as addRuntimeUsage, n as executeAgentImprovementActivation, o as isUsageAmount, r as verifyAgentImprovementActivationResult, t as createAgentImprovementActivationResult } from "./activation-Cbjng19L.js";
4
+ import { C as optimizationActivationReceiptFromMetadata, D as agentImprovementProfileSurfaceDigest, E as agentImprovementProfileDiffs, F as isAgentImprovementProfileSurface, I as isAgentProfileMeasuredSurface, N as assertProfileImprovementTargetsShareIdentity, O as agentImprovementProfileSurfaceInput, P as buildAgentImprovementActivationTargets, S as createOptimizationActivationReceipt, T as AGENT_PROFILE_MEASURED_SURFACES, V as assertProfileTrainingIsHeldOut, _ as profilePolicyWithBudget, a as executeAgentCandidateExperimentCell, b as profileTaskScenarioIdentity, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, g as profileImprovementMetadata, h as createProfileImprovementCostLedger, i as createAgentImprovementProposal, j as agentImprovementTargetProfileDiffs, l as reviewAgentImprovementProposal, m as verifyCandidateExecutionEvidence, n as createAgentImprovementActivation, o as proposeAgentImprovement, p as verifyAgentImprovementReview, r as createAgentImprovementMeasuredComparison, s as proposeAgentProfileImprovement, t as AgentCandidateExperimentCellExecutionError, u as runAgentCandidateExperiment, v as profilePreparationAccounting, w as AGENT_IMPROVEMENT_PROFILE_SURFACES, x as sealProfileImprovementBenchmark, y as profileStateDigest$1 } from "./improvement-cycle-BcnpQZOP.js";
5
5
  import { a as AGENT_CANDIDATE_EXECUTION_SUPPORT } from "./prepare-8A1CAWG8.js";
6
6
  import { d as omitUndefinedObjectFields, f as parseAgentCandidateProfileActivation, i as applyExactAgentProfileDiff, p as parseExactAgentProfile } from "./profile-BhQShsM1.js";
7
7
  import { n as exactProcessProviderAsCandidateExecutor, t as createProtectedAgentCandidateModelPort } from "./protected-model-port-ug52OmvB.js";
package/dist/kernel.js CHANGED
@@ -1,13 +1,13 @@
1
- import { $n as parseWorkerToolTraceArtifact, $t as PEER_MAIL_WIRE_KEY, An as resolveAgentEnvironmentProvider, Ar as resolveHarnessTranscriptCapture, Bn as InMemoryResultBlobStore, Bt as createInPlaceCliExecutor, Dn as createAgentEnvironmentProviderRegistry, Dr as harnessTranscriptArtifact, Dt as passedItems, Er as captureHarnessTranscript, Et as failedItems, Gn as replaySpawnTree, Gt as workerTraceSeamKey, Ht as readWorkerTraceContext, It as createWorktreeCliExecutor, Jt as createActivityLog, Kr as createOpenInferenceFileExporter, Lt as DEFAULT_SANDBOX_STEERING_MAX_TURNS, Mn as decodeToolPart, Mr as contentAddress, Mt as cliWorktreeExecutor, Nn as sandboxSessionTraceSource, Nt as createExecutor, On as providerAsExecutor, Or as persistHarnessTranscript, Ot as verdictFromJudgeScore, Pt as createExecutorRegistry, Qt as DEFAULT_PEER_MAIL_LIMITS, Rn as FileResultBlobStore, Rt as createSteerableSandboxSession, S as createScope, St as checkVerdictOf, Tt as expandQuestions, Un as loadSpawnForest, Ut as workerTraceEnv, Vn as InMemorySpawnJournal, Wn as materializeTreeView, Wt as workerTraceHeaders, Xn as WORKER_TOOL_TRACE_SCHEMA_VERSION, Xt as createInbox, Yt as readWorkerProgress, Zn as captureWorkerTraceEvidence, Zt as AUTHORITY_MARKERS, _n as runAgentRounds, _t as CONTINUATION_FACTS, a as collectDelivered, ar as createBudgetPool, bn as SandboxEvidenceRetentionError, br as createWorkerSlots, bt as admitFinding, ca as extractLlmCallEvent, cr as spendFromUsageEvents, ct as reconnectRetainedInteractiveRun, d as classifyDriverFailure, da as mapSandboxToolEvent, dn as harnessUsageIsEmpty, dt as freeSlots, en as claimsAuthority, er as workerTraceAnalysisStore, fn as readCodexRolloutSession, ft as queueOf, ga as decodeHarnessUsage, gn as isTerminalDecision, gr as startRetainedRunInEnvironment, ha as sumSandboxUsage, hn as defaultSelectWinner, hr as startRetainedRun, ht as mapExecutorResult, i as bestDelivered, ia as assertSandboxServedModel, in as peerMailVerbNames, j as settledToIteration, jn as createPushTraceSource, jr as retainHarnessTranscript, jt as cliInPlaceExecutor, kn as providerAsSandboxClient, l as DriverAttemptsExhaustedError, ln as addHarnessUsage, lt as recoverRetainedInteractiveRun, m as upstreamUnavailableSignal, ma as sandboxProgressEvents, mr as recoverRetainedRun, mt as gateOnDeliverable, n as createRootHandle, nn as isPeerMailEnvelope, nr as BudgetReconcileFault, o as pickBestDelivered, oa as createSandboxToolPartState, ot as attachWorker, p as summarizeDriverAttempts, pa as sandboxEventServedBackend, pn as TERMINAL_DECISIONS, pr as reconnectRetainedRun, pt as rollingDispatch, qr as createOtelExporter, qt as DEFAULT_STALL_AFTER_MS, r as createSupervisor, rn as peerMailTools, rr as ReservationWaitRefused, s as runFinalizer, sa as createSandboxUsageLedger, st as readWorkerInteractiveBinding, t as DEFAULT_MAX_DEPTH, tn as createPeerMailbox, ua as mapSandboxEvent, un as createCodexRolloutStoreReader, ut as startRetainedInteractiveRun, vn as createSandboxLineage, vt as CheckUnavailableError, wt as distillFindings, xn as captureBeforeDestroy, y as SUBTREE_RESULT_LIMIT, yn as acquireSandbox, yt as admitContinuationPolicy, zn as FileSpawnJournal } from "./supervisor-yX008JOQ.js";
2
- import { A as resolveEntrySymbol, B as runAgentic, C as compareCheckOutcomes, D as filterAuthoredAsserts, E as defaultStructuralRolloutPolicy, F as adaptiveRefine, G as observe, H as sampleThenRefine, I as breadthStrategy, J as profileOptimizerModelCall, K as renderReport, L as defineStrategy, M as selectBestIndex, N as structuralRollout, O as modelAuthoredChecks, P as visibleCheckScore, Q as streamAgentTurn, R as depthStrategy, S as canDisplace, T as defaultExtractCandidate, U as ObservationError, V as sample, W as defaultAnalystInstruction, Z as collectAgentTurn, _ as sharedWorkerClientName, f as DEFAULT_SHARED_BOX_RESOURCES, g as sharedBoxRefusal, h as sharedBoxPlacement, j as sandboxCheckRunner, k as officialChecksFromMeta, m as ROUTER_CLIENT_HEADER, p as DEFAULT_SHARED_BOX_WORKERS, q as profileChatClient, w as composeCheckSources, z as refine } from "./search-executor-emDfPe_k.js";
1
+ import { $n as parseWorkerToolTraceArtifact, $t as PEER_MAIL_WIRE_KEY, An as resolveAgentEnvironmentProvider, Ar as resolveHarnessTranscriptCapture, Bn as InMemoryResultBlobStore, Bt as createInPlaceCliExecutor, Dn as createAgentEnvironmentProviderRegistry, Dr as harnessTranscriptArtifact, Dt as passedItems, Er as captureHarnessTranscript, Et as failedItems, Gn as replaySpawnTree, Gt as workerTraceSeamKey, Ht as readWorkerTraceContext, It as createWorktreeCliExecutor, Jt as createActivityLog, Kr as createOpenInferenceFileExporter, Lt as DEFAULT_SANDBOX_STEERING_MAX_TURNS, Mn as decodeToolPart, Mr as contentAddress, Mt as cliWorktreeExecutor, Nn as sandboxSessionTraceSource, Nt as createExecutor, On as providerAsExecutor, Or as persistHarnessTranscript, Ot as verdictFromJudgeScore, Pt as createExecutorRegistry, Qt as DEFAULT_PEER_MAIL_LIMITS, Rn as FileResultBlobStore, Rt as createSteerableSandboxSession, S as createScope, St as checkVerdictOf, Tt as expandQuestions, Un as loadSpawnForest, Ut as workerTraceEnv, Vn as InMemorySpawnJournal, Wn as materializeTreeView, Wt as workerTraceHeaders, Xn as WORKER_TOOL_TRACE_SCHEMA_VERSION, Xt as createInbox, Yt as readWorkerProgress, Zn as captureWorkerTraceEvidence, Zt as AUTHORITY_MARKERS, _n as runAgentRounds, _t as CONTINUATION_FACTS, a as collectDelivered, ar as createBudgetPool, bn as SandboxEvidenceRetentionError, br as createWorkerSlots, bt as admitFinding, ca as extractLlmCallEvent, cr as spendFromUsageEvents, ct as reconnectRetainedInteractiveRun, d as classifyDriverFailure, da as mapSandboxToolEvent, dn as harnessUsageIsEmpty, dt as freeSlots, en as claimsAuthority, er as workerTraceAnalysisStore, fn as readCodexRolloutSession, ft as queueOf, ga as decodeHarnessUsage, gn as isTerminalDecision, gr as startRetainedRunInEnvironment, ha as sumSandboxUsage, hn as defaultSelectWinner, hr as startRetainedRun, ht as mapExecutorResult, i as bestDelivered, ia as assertSandboxServedModel, in as peerMailVerbNames, j as settledToIteration, jn as createPushTraceSource, jr as retainHarnessTranscript, jt as cliInPlaceExecutor, kn as providerAsSandboxClient, l as DriverAttemptsExhaustedError, ln as addHarnessUsage, lt as recoverRetainedInteractiveRun, m as upstreamUnavailableSignal, ma as sandboxProgressEvents, mr as recoverRetainedRun, mt as gateOnDeliverable, n as createRootHandle, nn as isPeerMailEnvelope, nr as BudgetReconcileFault, o as pickBestDelivered, oa as createSandboxToolPartState, ot as attachWorker, p as summarizeDriverAttempts, pa as sandboxEventServedBackend, pn as TERMINAL_DECISIONS, pr as reconnectRetainedRun, pt as rollingDispatch, qr as createOtelExporter, qt as DEFAULT_STALL_AFTER_MS, r as createSupervisor, rn as peerMailTools, rr as ReservationWaitRefused, s as runFinalizer, sa as createSandboxUsageLedger, st as readWorkerInteractiveBinding, t as DEFAULT_MAX_DEPTH, tn as createPeerMailbox, ua as mapSandboxEvent, un as createCodexRolloutStoreReader, ut as startRetainedInteractiveRun, vn as createSandboxLineage, vt as CheckUnavailableError, wt as distillFindings, xn as captureBeforeDestroy, y as SUBTREE_RESULT_LIMIT, yn as acquireSandbox, yt as admitContinuationPolicy, zn as FileSpawnJournal } from "./supervisor-DwfUsy8w.js";
2
+ import { A as resolveEntrySymbol, B as runAgentic, C as compareCheckOutcomes, D as filterAuthoredAsserts, E as defaultStructuralRolloutPolicy, F as adaptiveRefine, G as observe, H as sampleThenRefine, I as breadthStrategy, J as profileOptimizerModelCall, K as renderReport, L as defineStrategy, M as selectBestIndex, N as structuralRollout, O as modelAuthoredChecks, P as visibleCheckScore, Q as streamAgentTurn, R as depthStrategy, S as canDisplace, T as defaultExtractCandidate, U as ObservationError, V as sample, W as defaultAnalystInstruction, Z as collectAgentTurn, _ as sharedWorkerClientName, f as DEFAULT_SHARED_BOX_RESOURCES, g as sharedBoxRefusal, h as sharedBoxPlacement, j as sandboxCheckRunner, k as officialChecksFromMeta, m as ROUTER_CLIENT_HEADER, p as DEFAULT_SHARED_BOX_WORKERS, q as profileChatClient, w as composeCheckSources, z as refine } from "./search-executor-Q8W7n1Tg.js";
3
3
  import { gt as DEFAULT_CHECK_IN_IDLE_MS, ht as DEADLINE_CHECK_IN_MESSAGE } from "./workspace-streams-BEvSX97P.js";
4
4
  import { runTaskQueue } from "./task-queue.js";
5
5
  import { n as assertModelAllowed, r as assertProfileModelsAllowed } from "./model-policy-DhvyZ8-O.js";
6
- import { $ as renderCorpusToInstructions, A as chatWorkerSeam, At as completionAuthorizes, B as createS3PrivateCasStore, Bt as SqlRunOwnershipError, C as analyzeTrace, Ct as assertDeclaredCheck, D as codeModeSupervisorTools, Dt as declaredCheckJudge, Et as declaredCheckDigest, F as authorStrategy, Ft as pairwiseSignificance, G as trajectoryReport, Gt as createMcpEnvironment, H as runBenchmark, Ht as McpSpawnFault, I as strategyAuthorContract, It as renderLeaderboardHtml, J as builtinShapes, Jt as mcpSecretEnvMetadataKey, K as definePersona, Kt as sanitizeMcpToolSchema, L as strategyAuthorSystemPrompt, Lt as renderLeaderboardMarkdown, M as runStrategyEvolution, Mt as sentinelCompletion, N as strategyTournament, Nt as stopSentinel, O as unsafeInProcessRunner, Ot as readDeclaredCheck, P as assertStrategyContract, Pt as leaderboard, Q as InMemoryCorpus, Qt as createTangleSandboxExactProcessProvider, R as SandboxRunAbortError, Rt as renderLeaderboardSvg, S as withUntrackedArtifacts, St as superviseDispatch, T as patchDelivered, Tt as declaredCheckDeliverable, U as createPrivateCasArtifactPort, Ut as connectStdioMcp, V as printBenchmarkReport, Vt as openSqlRunStore, W as equalKOnCost, Wt as materializeLocalMcp, X as registerShape, Xt as resolveSecretEnv, Y as createShapeRegistry, Yt as resolveMcpServerLaunch, Z as FileCorpus, Zt as secretEnvOfMcpServer, _ as VERIFY_TAIL_CHARS, _t as resolveSandboxClient, a as localShell, at as selectValidWinner, b as settledWorkerOut, bt as loopCampaignDispatch, c as createVerifierEnvironment, ct as assertTraceDerivedFindings, d as harvestSurfaceDiffs, dt as registryScopeAnalyst, et as fanout, f as analystsFromRegistry, ft as observationFromRegistry, g as NOTE_MAX_CHARS, gt as defineLeaderboard, h as EVIDENCE_MAX_CHARS, ht as harvestCorpus, i as jjWorkspace, it as pipeline, j as createChatSessionStore, jt as deterministicCompletion, k as chatTransportExecutor, kt as runIsolatedCheck, l as boxSurfaceReader, lt as buildSteerContext, m as worktreeFanout, mt as HarvestError, n as makeFinding, nt as loopUntil, o as runInWorkspace, ot as verify, p as failuresAnalyst, pt as inProcessSandboxClient, q as runPersonified, qt as envKeyProvider, r as gitWorkspace, rt as panel, s as createWaterfallCollector, st as widen, t as computeFindingId, tt as flatWidenGate, u as fsSurfaceReader, ut as createScopeAnalyst, v as closingWorkerNote, vt as localSandboxClient, w as createFencedSqlRunContext, wt as checkProgramDigest, x as copyUntrackedIntoClone, xt as loopDispatch, y as composeWorkerEvidence, yt as inlineSandboxClient, z as openSandboxRun, zt as renderPairwiseMarkdown } from "./runtime-sx7Qtw4g.js";
7
- import { B as defaultToolDetectors, C as createInMemoryRunContext, I as normalizeAnalyzeOnSettle, S as createFileRunContext, T as FileCoordinationLog, V as watchTrace, _ as anytimeReport, a as DEFAULT_DEADLINE_WARNING_MS, b as plateauLength, d as anyOf, f as createProgressTracker, g as sampleFromSettled, i as finalizeBestDelivered, j as canonicalFindingEvent, l as allOf, m as plateau, p as noProgressFor, u as allWorkersStalled, v as areaUnderCurve, w as withRunContext, x as renderAnytimeTable, y as bestSoFar, z as createEventBus } from "./coordination-driver-26qkTbVh.js";
8
- import { b as createSupervisorSpanRecorder, c as resolveWorkerSpawnRetry, d as assertCoordinationBinding, f as resolveSupervisorProfile, l as retryPreSpawnRefusals, o as workerFromBackend, p as supervisorAgent, r as supervise, s as isPreSpawnExecutorFailure, t as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, u as withWorkerSpawnRetry, v as UNPROVEN_CONTINUITY, x as serveCoordinationMcp, y as composeReentryTask } from "./supervise-pxhnrGsA.js";
6
+ import { $ as renderCorpusToInstructions, A as chatWorkerSeam, At as completionAuthorizes, B as createS3PrivateCasStore, Bt as SqlRunOwnershipError, C as analyzeTrace, Ct as assertDeclaredCheck, D as codeModeSupervisorTools, Dt as declaredCheckJudge, Et as declaredCheckDigest, F as authorStrategy, Ft as pairwiseSignificance, G as trajectoryReport, Gt as createMcpEnvironment, H as runBenchmark, Ht as McpSpawnFault, I as strategyAuthorContract, It as renderLeaderboardHtml, J as builtinShapes, Jt as mcpSecretEnvMetadataKey, K as definePersona, Kt as sanitizeMcpToolSchema, L as strategyAuthorSystemPrompt, Lt as renderLeaderboardMarkdown, M as runStrategyEvolution, Mt as sentinelCompletion, N as strategyTournament, Nt as stopSentinel, O as unsafeInProcessRunner, Ot as readDeclaredCheck, P as assertStrategyContract, Pt as leaderboard, Q as InMemoryCorpus, Qt as createTangleSandboxExactProcessProvider, R as SandboxRunAbortError, Rt as renderLeaderboardSvg, S as withUntrackedArtifacts, St as superviseDispatch, T as patchDelivered, Tt as declaredCheckDeliverable, U as createPrivateCasArtifactPort, Ut as connectStdioMcp, V as printBenchmarkReport, Vt as openSqlRunStore, W as equalKOnCost, Wt as materializeLocalMcp, X as registerShape, Xt as resolveSecretEnv, Y as createShapeRegistry, Yt as resolveMcpServerLaunch, Z as FileCorpus, Zt as secretEnvOfMcpServer, _ as VERIFY_TAIL_CHARS, _t as resolveSandboxClient, a as localShell, at as selectValidWinner, b as settledWorkerOut, bt as loopCampaignDispatch, c as createVerifierEnvironment, ct as assertTraceDerivedFindings, d as harvestSurfaceDiffs, dt as registryScopeAnalyst, et as fanout, f as analystsFromRegistry, ft as observationFromRegistry, g as NOTE_MAX_CHARS, gt as defineLeaderboard, h as EVIDENCE_MAX_CHARS, ht as harvestCorpus, i as jjWorkspace, it as pipeline, j as createChatSessionStore, jt as deterministicCompletion, k as chatTransportExecutor, kt as runIsolatedCheck, l as boxSurfaceReader, lt as buildSteerContext, m as worktreeFanout, mt as HarvestError, n as makeFinding, nt as loopUntil, o as runInWorkspace, ot as verify, p as failuresAnalyst, pt as inProcessSandboxClient, q as runPersonified, qt as envKeyProvider, r as gitWorkspace, rt as panel, s as createWaterfallCollector, st as widen, t as computeFindingId, tt as flatWidenGate, u as fsSurfaceReader, ut as createScopeAnalyst, v as closingWorkerNote, vt as localSandboxClient, w as createFencedSqlRunContext, wt as checkProgramDigest, x as copyUntrackedIntoClone, xt as loopDispatch, y as composeWorkerEvidence, yt as inlineSandboxClient, z as openSandboxRun, zt as renderPairwiseMarkdown } from "./runtime-DqGhWHhs.js";
7
+ import { B as defaultToolDetectors, C as createInMemoryRunContext, I as normalizeAnalyzeOnSettle, S as createFileRunContext, T as FileCoordinationLog, V as watchTrace, _ as anytimeReport, a as DEFAULT_DEADLINE_WARNING_MS, b as plateauLength, d as anyOf, f as createProgressTracker, g as sampleFromSettled, i as finalizeBestDelivered, j as canonicalFindingEvent, l as allOf, m as plateau, p as noProgressFor, u as allWorkersStalled, v as areaUnderCurve, w as withRunContext, x as renderAnytimeTable, y as bestSoFar, z as createEventBus } from "./coordination-driver-DKoxt1wL.js";
8
+ import { b as createSupervisorSpanRecorder, c as resolveWorkerSpawnRetry, d as assertCoordinationBinding, f as resolveSupervisorProfile, l as retryPreSpawnRefusals, o as workerFromBackend, p as supervisorAgent, r as supervise, s as isPreSpawnExecutorFailure, t as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, u as withWorkerSpawnRetry, v as UNPROVEN_CONTINUITY, x as serveCoordinationMcp, y as composeReentryTask } from "./supervise-QObMv9Hy.js";
9
9
  import { C as workerInboxFileFromEventDir, D as workerSteerRequestsDir, E as workerSteerRequestFile, O as workerSteersDir, S as workerInboxFile, T as workerSteerAcknowledgementsDir, _ as supervisorWorkersDir, a as legacySupervisorRunsRoot, b as workerCancellationsDir, c as readWorkerCancelRequests, d as readWorkerSteerRequests, f as runCancelRequestFile, g as supervisorRunsRoot, h as supervisorRunDir, i as legacySupervisorRunDir, j as writeWorkerSteer, l as readWorkerCancellation, m as safeWorkerFile, n as cancelWorker, o as readRunCancelRequest, p as runCancellationFile, s as readRunCancellation, t as cancelRun, u as readWorkerSteerAcknowledgement, v as workerCancelRequestsFile, w as workerSteerAcknowledgementFile, x as workerControlLogFile, y as workerCancellationFile } from "./run-layout-DSCWdbX2.js";
10
- import { n as workerFromInteractiveProvider, r as claimRetainedInteractiveControl, t as provisionSupervisor } from "./provision-supervisor-nV0XW_vi.js";
11
- import { a as defaultProfileRichnessThresholds, i as assessAuthoredProfile, n as delegate, o as profileRichnessFinding, r as asAuthoredProfile, s as supervisorInstructions, t as defaultDelegateBudget } from "./delegate-C0ZXShbu.js";
12
- import { a as analyzesFindingsReportPrompt, c as dumbContinuationFailPrompt, d as kernelPromptRegistry, f as naiveContinuationPrompt, l as dumbContinuationPassPrompt, n as defaultEdgeTraversalCap, o as createPromptRegistry, p as promptHandle, r as runGraph, s as delegatesWorkerBriefPrompt, t as GraphEdgeCapError, u as formatPromptHandle } from "./graph-BF6LYqON.js";
10
+ import { n as workerFromInteractiveProvider, r as claimRetainedInteractiveControl, t as provisionSupervisor } from "./provision-supervisor-DyIZEbwJ.js";
11
+ import { a as defaultProfileRichnessThresholds, i as assessAuthoredProfile, n as delegate, o as profileRichnessFinding, r as asAuthoredProfile, s as supervisorInstructions, t as defaultDelegateBudget } from "./delegate-CpWZOxuA.js";
12
+ import { a as analyzesFindingsReportPrompt, c as dumbContinuationFailPrompt, d as kernelPromptRegistry, f as naiveContinuationPrompt, l as dumbContinuationPassPrompt, n as defaultEdgeTraversalCap, o as createPromptRegistry, p as promptHandle, r as runGraph, s as delegatesWorkerBriefPrompt, t as GraphEdgeCapError, u as formatPromptHandle } from "./graph-Cjplvg8L.js";
13
13
  export { AUTHORITY_MARKERS, BudgetReconcileFault, CONTINUATION_FACTS, CheckUnavailableError, DEADLINE_CHECK_IN_MESSAGE, DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, DEFAULT_CHECK_IN_IDLE_MS, DEFAULT_DEADLINE_WARNING_MS, DEFAULT_MAX_DEPTH, DEFAULT_PEER_MAIL_LIMITS, DEFAULT_SANDBOX_STEERING_MAX_TURNS, DEFAULT_SHARED_BOX_RESOURCES, DEFAULT_SHARED_BOX_WORKERS, DEFAULT_STALL_AFTER_MS, DriverAttemptsExhaustedError, EVIDENCE_MAX_CHARS, FileCoordinationLog, FileCorpus, FileResultBlobStore, FileSpawnJournal, GraphEdgeCapError, HarvestError, InMemoryCorpus, InMemoryResultBlobStore, InMemorySpawnJournal, McpSpawnFault, NOTE_MAX_CHARS, ObservationError, PEER_MAIL_WIRE_KEY, ROUTER_CLIENT_HEADER, ReservationWaitRefused, SUBTREE_RESULT_LIMIT, SandboxEvidenceRetentionError, SandboxRunAbortError, SqlRunOwnershipError, TERMINAL_DECISIONS, UNPROVEN_CONTINUITY, VERIFY_TAIL_CHARS, WORKER_TOOL_TRACE_SCHEMA_VERSION, acquireSandbox, adaptiveRefine, addHarnessUsage, admitContinuationPolicy, admitFinding, allOf, allWorkersStalled, analystsFromRegistry, analyzeTrace, analyzesFindingsReportPrompt, anyOf, anytimeReport, areaUnderCurve, asAuthoredProfile, assertCoordinationBinding, assertDeclaredCheck, assertModelAllowed, assertProfileModelsAllowed, assertSandboxServedModel, assertStrategyContract, assertTraceDerivedFindings, assessAuthoredProfile, attachWorker, authorStrategy, bestDelivered, bestSoFar, boxSurfaceReader, breadthStrategy, buildSteerContext, builtinShapes, canDisplace, cancelRun, cancelWorker, canonicalFindingEvent, captureBeforeDestroy, captureHarnessTranscript, captureWorkerTraceEvidence, chatTransportExecutor, chatWorkerSeam, checkProgramDigest, checkVerdictOf, claimRetainedInteractiveControl, claimsAuthority, classifyDriverFailure, cliInPlaceExecutor, cliWorktreeExecutor, closingWorkerNote, codeModeSupervisorTools, collectAgentTurn, collectDelivered, compareCheckOutcomes, completionAuthorizes, composeCheckSources, composeReentryTask, composeWorkerEvidence, computeFindingId, connectStdioMcp, contentAddress, copyUntrackedIntoClone, createActivityLog, createAgentEnvironmentProviderRegistry, createBudgetPool, createChatSessionStore, createCodexRolloutStoreReader, createEventBus, createExecutor, createExecutorRegistry, createFencedSqlRunContext, createFileRunContext, createInMemoryRunContext, createInPlaceCliExecutor, createInbox, createMcpEnvironment, createOpenInferenceFileExporter, createOtelExporter, createPeerMailbox, createPrivateCasArtifactPort, createProgressTracker, createPromptRegistry, createPushTraceSource, createRootHandle, createS3PrivateCasStore, createSandboxLineage, createSandboxToolPartState, createSandboxUsageLedger, createScope, createScopeAnalyst, createShapeRegistry, createSteerableSandboxSession, createSupervisor, createSupervisorSpanRecorder, createTangleSandboxExactProcessProvider, createVerifierEnvironment, createWaterfallCollector, createWorkerSlots, createWorktreeCliExecutor, declaredCheckDeliverable, declaredCheckDigest, declaredCheckJudge, decodeHarnessUsage, decodeToolPart, defaultAnalystInstruction, defaultDelegateBudget, defaultEdgeTraversalCap, defaultExtractCandidate, defaultProfileRichnessThresholds, defaultSelectWinner, defaultStructuralRolloutPolicy, defaultToolDetectors, defineLeaderboard, definePersona, defineStrategy, delegate, delegatesWorkerBriefPrompt, depthStrategy, deterministicCompletion, distillFindings, dumbContinuationFailPrompt, dumbContinuationPassPrompt, envKeyProvider, equalKOnCost, expandQuestions, extractLlmCallEvent, failedItems, failuresAnalyst, fanout, filterAuthoredAsserts, finalizeBestDelivered, flatWidenGate, formatPromptHandle, freeSlots, fsSurfaceReader, gateOnDeliverable, gitWorkspace, harnessTranscriptArtifact, harnessUsageIsEmpty, harvestCorpus, harvestSurfaceDiffs, inProcessSandboxClient, inlineSandboxClient, isPeerMailEnvelope, isPreSpawnExecutorFailure, isTerminalDecision, jjWorkspace, kernelPromptRegistry, leaderboard, legacySupervisorRunDir, legacySupervisorRunsRoot, loadSpawnForest, localSandboxClient, localShell, loopCampaignDispatch, loopDispatch, loopUntil, makeFinding, mapExecutorResult, mapSandboxEvent, mapSandboxToolEvent, materializeLocalMcp, materializeTreeView, mcpSecretEnvMetadataKey, modelAuthoredChecks, naiveContinuationPrompt, noProgressFor, normalizeAnalyzeOnSettle, observationFromRegistry, observe, officialChecksFromMeta, openSandboxRun, openSqlRunStore, pairwiseSignificance, panel, parseWorkerToolTraceArtifact, passedItems, patchDelivered, peerMailTools, peerMailVerbNames, persistHarnessTranscript, pickBestDelivered, pipeline, plateau, plateauLength, printBenchmarkReport, profileChatClient, profileOptimizerModelCall, profileRichnessFinding, promptHandle, providerAsExecutor, providerAsSandboxClient, provisionSupervisor, queueOf, readCodexRolloutSession, readDeclaredCheck, readRunCancelRequest, readRunCancellation, readWorkerCancelRequests, readWorkerCancellation, readWorkerInteractiveBinding, readWorkerProgress, readWorkerSteerAcknowledgement, readWorkerSteerRequests, readWorkerTraceContext, reconnectRetainedInteractiveRun, reconnectRetainedRun, recoverRetainedInteractiveRun, recoverRetainedRun, refine, registerShape, registryScopeAnalyst, renderAnytimeTable, renderCorpusToInstructions, renderLeaderboardHtml, renderLeaderboardMarkdown, renderLeaderboardSvg, renderPairwiseMarkdown, renderReport, replaySpawnTree, resolveAgentEnvironmentProvider, resolveEntrySymbol, resolveHarnessTranscriptCapture, resolveMcpServerLaunch, resolveSandboxClient, resolveSecretEnv, resolveSupervisorProfile, resolveWorkerSpawnRetry, retainHarnessTranscript, retryPreSpawnRefusals, rollingDispatch, runAgentRounds, runAgentic, runBenchmark, runCancelRequestFile, runCancellationFile, runFinalizer, runGraph, runInWorkspace, runIsolatedCheck, runPersonified, runStrategyEvolution, runTaskQueue, safeWorkerFile, sample, sampleFromSettled, sampleThenRefine, sandboxCheckRunner, sandboxEventServedBackend, sandboxProgressEvents, sandboxSessionTraceSource, sanitizeMcpToolSchema, secretEnvOfMcpServer, selectBestIndex, selectValidWinner, sentinelCompletion, serveCoordinationMcp, settledToIteration, settledWorkerOut, sharedBoxPlacement, sharedBoxRefusal, sharedWorkerClientName, spendFromUsageEvents, startRetainedInteractiveRun, startRetainedRun, startRetainedRunInEnvironment, stopSentinel, strategyAuthorContract, strategyAuthorSystemPrompt, strategyTournament, streamAgentTurn, structuralRollout, sumSandboxUsage, summarizeDriverAttempts, supervise, superviseDispatch, supervisorAgent, supervisorInstructions, supervisorRunDir, supervisorRunsRoot, supervisorWorkersDir, trajectoryReport, unsafeInProcessRunner, upstreamUnavailableSignal, verdictFromJudgeScore, verify, visibleCheckScore, watchTrace, widen, withRunContext, withUntrackedArtifacts, withWorkerSpawnRetry, workerCancelRequestsFile, workerCancellationFile, workerCancellationsDir, workerControlLogFile, workerFromBackend, workerFromInteractiveProvider, workerInboxFile, workerInboxFileFromEventDir, workerSteerAcknowledgementFile, workerSteerAcknowledgementsDir, workerSteerRequestFile, workerSteerRequestsDir, workerSteersDir, workerTraceAnalysisStore, workerTraceEnv, workerTraceHeaders, workerTraceSeamKey, worktreeFanout, writeWorkerSteer };
@@ -1,6 +1,6 @@
1
- import { Pt as createExecutorRegistry } from "./supervisor-yX008JOQ.js";
1
+ import { Pt as createExecutorRegistry } from "./supervisor-DwfUsy8w.js";
2
2
  import { i as ConfigError } from "./errors-DodWX-cb.js";
3
- import { K as definePersona, m as worktreeFanout, q as runPersonified } from "./runtime-sx7Qtw4g.js";
3
+ import { K as definePersona, m as worktreeFanout, q as runPersonified } from "./runtime-DqGhWHhs.js";
4
4
  import { t as runAnalystLoop } from "./analyst-loop-DZw5QWT9.js";
5
5
  import { t as createKbGate } from "./kb-gate-DpaSwXVx.js";
6
6
  //#region src/loop-runner.ts
@@ -243,4 +243,4 @@ if (invokedScript && /loop-runner-bin\.(js|ts|mjs)$/.test(invokedScript)) main()
243
243
  //#endregion
244
244
  export { isDelegatedLoopMode as a, worktreeLoopRunner as c, auditLoopRunner as i, runLoopRunnerCli as n, researchLoopRunner as o, DELEGATED_LOOP_MODES as r, runDelegatedLoop as s, parseLoopRunnerArgv as t };
245
245
 
246
- //# sourceMappingURL=loop-runner-bin-CreO-bam.js.map
246
+ //# sourceMappingURL=loop-runner-bin-bAbpeDOp.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loop-runner-bin-CreO-bam.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MADJ,OAAO,MAAM;GACD,YAAY,IAAI,IAAI;EAAM;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AAK,EAAE;CAEjD;EACA,QAAQ,KAAK,CAAC;CAChB;CACA,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,MAAM,MAAM,MAAM,iBAAiB;EACjC;EACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK;CAC7F,CAAC;CACD,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
1
+ {"version":3,"file":"loop-runner-bin-bAbpeDOp.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;G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AAI,CAAC,QAAQ,CAAC,QAAQ;EACpB,QAAQ,OAAO,MACb;WACc,qBAAqB,KAAK,KAAK,EAAE;CAEjD;EACA,QAAQ,KAAK,CAAC;CAChB;CACA,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,MAAM,MAAM,MAAM,iBAAiB;EACjC;EACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK;CAC7F,CAAC;CACD,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { n as runLoopRunnerCli, t as parseLoopRunnerArgv } from "./loop-runner-bin-CreO-bam.js";
2
+ import { n as runLoopRunnerCli, t as parseLoopRunnerArgv } from "./loop-runner-bin-bAbpeDOp.js";
3
3
  export { parseLoopRunnerArgv, runLoopRunnerCli };
package/dist/mcp/bin.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { Rr as readTraceContextFromEnv } from "../supervisor-yX008JOQ.js";
2
+ import { Rr as readTraceContextFromEnv } from "../supervisor-DwfUsy8w.js";
3
3
  import { i as ConfigError } from "../errors-DodWX-cb.js";
4
- import { s as supervisorInstructions } from "../delegate-C0ZXShbu.js";
5
- import { _ as FileDelegationStore, n as createMcpServer, p as DelegationTaskQueue } from "../server-DgdTtcch.js";
4
+ import { s as supervisorInstructions } from "../delegate-CpWZOxuA.js";
5
+ import { _ as FileDelegationStore, n as createMcpServer, p as DelegationTaskQueue } from "../server-Brh9r0MK.js";
6
6
  //#region src/mcp/delegate-supervisor-provisioning.ts
7
7
  function trimmed(value) {
8
8
  const v = value?.trim();
package/dist/mcp/index.js CHANGED
@@ -1,15 +1,15 @@
1
- import { $ as environmentReader, Ir as createPropagatingTraceEmitter, Lr as mergeTraceEnv, Q as SPAWN_RESOURCE_PATH_MAX_BYTES, Rr as readTraceContextFromEnv, Sn as assertBoxlessPromptOptions, _n as runAgentRounds, ci as createWorktree, di as LOCAL_HARNESSES, et as hostDirectoryReader, gi as CodexExecutionDiagnosticError, hi as parseCodexTokenUsage, li as removeWorktree, mi as localHarnessExecutable, mn as createSandboxForSpec, oi as runWorktreeHarness, pi as harnessSupportsReasoningEffort, si as captureWorktreeDiff, tt as resolveSpawnResourcePaths, ui as DEFAULT_LOCAL_HARNESS, zr as traceContextToEnv } from "../supervisor-yX008JOQ.js";
1
+ import { $ as environmentReader, Ir as createPropagatingTraceEmitter, Lr as mergeTraceEnv, Q as SPAWN_RESOURCE_PATH_MAX_BYTES, Rr as readTraceContextFromEnv, Sn as assertBoxlessPromptOptions, _n as runAgentRounds, ci as createWorktree, di as LOCAL_HARNESSES, et as hostDirectoryReader, gi as CodexExecutionDiagnosticError, hi as parseCodexTokenUsage, li as removeWorktree, mi as localHarnessExecutable, mn as createSandboxForSpec, oi as runWorktreeHarness, pi as harnessSupportsReasoningEffort, si as captureWorktreeDiff, tt as resolveSpawnResourcePaths, ui as DEFAULT_LOCAL_HARNESS, zr as traceContextToEnv } from "../supervisor-DwfUsy8w.js";
2
2
  import { i as ConfigError, m as ValidationError } from "../errors-DodWX-cb.js";
3
3
  import { W as deleteBoxSafe, it as throwIfAborted, rt as throwAbort, tt as sleep } from "../workspace-streams-BEvSX97P.js";
4
4
  import { t as assertExecutableAgentProfile } from "../model-policy-DhvyZ8-O.js";
5
- import { E as runCoderChecks, at as selectValidWinner } from "../runtime-sx7Qtw4g.js";
6
- import { A as analystToolGroupNames, F as downMessageRefusalReasons, L as parseAuthoredAnalystDefinition, N as createCoordinationTools, R as questionEscalationTargets, k as ANALYST_DEFINITION_BOUNDS } from "../coordination-driver-26qkTbVh.js";
5
+ import { E as runCoderChecks, at as selectValidWinner } from "../runtime-DqGhWHhs.js";
6
+ import { A as analystToolGroupNames, F as downMessageRefusalReasons, L as parseAuthoredAnalystDefinition, N as createCoordinationTools, R as questionEscalationTargets, k as ANALYST_DEFINITION_BOUNDS } from "../coordination-driver-DKoxt1wL.js";
7
7
  import { n as SUPPORTED_PROTOCOL_VERSIONS, r as createStdioToolServer } from "../tool-server-Dqer2M4_.js";
8
8
  import { t as createKbGate } from "../kb-gate-DpaSwXVx.js";
9
9
  import { _ as InMemoryFeedbackStore, a as validateDelegationStatusArgs, c as DELEGATION_HISTORY_TOOL_NAME, d as delegationProfiles, f as DELEGATE_FEEDBACK_DESCRIPTION, g as validateDelegateFeedbackArgs, h as createDelegateFeedbackHandler, i as createDelegationStatusHandler, l as createDelegationHistoryHandler, m as DELEGATE_FEEDBACK_TOOL_NAME, n as DELEGATION_STATUS_INPUT_SCHEMA, o as DELEGATION_HISTORY_DESCRIPTION, p as DELEGATE_FEEDBACK_INPUT_SCHEMA, r as DELEGATION_STATUS_TOOL_NAME, s as DELEGATION_HISTORY_INPUT_SCHEMA, t as DELEGATION_STATUS_DESCRIPTION, u as validateDelegationHistoryArgs, v as eventToSnapshot } from "../delegation-status-CF4D0NZ_.js";
10
10
  import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-DoQ32vpe.js";
11
11
  import { t as coderTaskToPrompt } from "../coder-yhVWbdWc.js";
12
- import { C as composeLoopTraceEmitters, S as capDelegationTrace, _ as FileDelegationStore, a as DELEGATE_UI_AUDIT_TOOL_NAME, b as DELEGATION_TRACE_MAX_SPANS, c as DELEGATE_DESCRIPTION, d as createDelegateHandler, f as validateDelegateArgs, g as DelegationStateCorruptError, h as DelegationPersistenceError, i as DELEGATE_UI_AUDIT_INPUT_SCHEMA, l as DELEGATE_INPUT_SCHEMA, m as hashIdempotencyInput, n as createMcpServer, o as createDelegateUiAuditHandler, p as DelegationTaskQueue, r as DELEGATE_UI_AUDIT_DESCRIPTION, s as validateDelegateUiAuditArgs, t as createInProcessTransport, u as DELEGATE_TOOL_NAME, v as InMemoryDelegationStore, w as createDelegationTraceCollector, x as buildDelegationTraceSpans, y as DELEGATION_TRACE_MAX_BYTES } from "../server-DgdTtcch.js";
12
+ import { C as composeLoopTraceEmitters, S as capDelegationTrace, _ as FileDelegationStore, a as DELEGATE_UI_AUDIT_TOOL_NAME, b as DELEGATION_TRACE_MAX_SPANS, c as DELEGATE_DESCRIPTION, d as createDelegateHandler, f as validateDelegateArgs, g as DelegationStateCorruptError, h as DelegationPersistenceError, i as DELEGATE_UI_AUDIT_INPUT_SCHEMA, l as DELEGATE_INPUT_SCHEMA, m as hashIdempotencyInput, n as createMcpServer, o as createDelegateUiAuditHandler, p as DelegationTaskQueue, r as DELEGATE_UI_AUDIT_DESCRIPTION, s as validateDelegateUiAuditArgs, t as createInProcessTransport, u as DELEGATE_TOOL_NAME, v as InMemoryDelegationStore, w as createDelegationTraceCollector, x as buildDelegationTraceSpans, y as DELEGATION_TRACE_MAX_BYTES } from "../server-Brh9r0MK.js";
13
13
  import { a as createMemoryToolServer, c as resolveMemoryFromEnv, i as MEMORY_NAME_ENV, n as MEMORY_ITEMS_ENV, o as parseMemoryItems, r as MEMORY_LOG_ENV, s as readMemoryItemsFile, t as MEMORY_FILE_ENV } from "../memory-server-DXQ8IxGR.js";
14
14
  import { agentProfileSchema } from "@tangle-network/agent-interface";
15
15
  import { randomUUID } from "node:crypto";
@@ -1 +1 @@
1
- {"version":3,"file":"model-policy-DhvyZ8-O.js","names":["positiveInteger"],"sources":["../src/runtime/harness-role.ts","../src/runtime/model-identity.ts","../src/runtime/router-auto-evidence.ts","../src/runtime/router-retry-policy.ts","../src/runtime/supervise/model-policy.ts"],"sourcesContent":["/**\n * Which `HarnessType` values name a real coding-agent runtime, and which name a MODE that has no\n * agent behind it.\n *\n * `cli-base` is the router-backed mode — a plain multi-turn router call with no coding-agent\n * harness (`@tangle-network/agent-interface`'s `HarnessType` doc, and the same table's\n * `harnessReasoningCeiling['cli-base'] = 'none'` commented \"cli-base has no agent\"). The\n * distinction is REAL; what was accidental is that three call sites each spelled the test\n * themselves, so a second no-agent mode would have to be remembered in three places.\n *\n * SHOULD UPSTREAM: this belongs next to `harnessHonorsEffort` in agent-interface's\n * `harness-capabilities.ts`, which already encodes the fact but exports no predicate for it.\n * Until it does, this is the one local copy — extend the set here, never re-test the name.\n */\n\nimport type { HarnessType } from '@tangle-network/agent-interface'\n\n/**\n * Harness ids that select a router/no-agent mode rather than a coding-agent runtime.\n *\n * `nanoclaw` is deliberately ABSENT: the shared capability table clamps its reasoning ceiling the\n * same way it clamps `cli-base`, but nanoclaw does run an agent (a socket-bridge runner to the\n * NanoClaw daemon) and every caller here treats it as a full harness. Add a row only with the\n * behavior change stated, never to make the two clamps look symmetric.\n */\nconst NO_AGENT_HARNESSES: ReadonlySet<string> = new Set<string>(['cli-base' satisfies HarnessType])\n\n/** Whether this profile harness selects a real coding-agent runtime (vs. the router/no-agent mode\n * or no preference at all). Accepts the looser `string` some local profile shapes declare, and\n * preserves the caller's own harness type when it is narrower. */\nexport function harnessRunsAgent<T extends string>(harness: T | null | undefined): harness is T {\n return harness != null && !NO_AGENT_HARNESSES.has(harness)\n}\n\n/** The coding-agent harness this profile selects, or `undefined` when it selects none — the shape\n * callers want when a no-agent mode must fall through to the router arm. */\nexport function agentHarness<T extends string>(harness: T | null | undefined): T | undefined {\n return harnessRunsAgent(harness) ? harness : undefined\n}\n","import { harnessTypeSchema } from '@tangle-network/agent-interface'\n\nconst SNAPSHOT_TOKEN = /^[A-Za-z0-9._-]+$/u\nconst datedIsoSuffix = /^(.*)-(\\d{4})-(\\d{2})-(\\d{2})$/u\nconst datedCompactSuffix = /^(.*)-(\\d{4})(\\d{2})(\\d{2})$/u\nconst datedMonthSuffix = /^(.*)-(\\d{4})-(\\d{2})$/u\n\ntype SnapshotKind = 'date' | 'opaque'\n\ninterface ModelIdentityParts {\n readonly base: string\n readonly snapshot?: string\n readonly snapshotKind?: SnapshotKind\n}\n\nexport interface CanonicalObservedModelParts {\n readonly base: string\n readonly snapshot?: string\n readonly snapshotKind?: SnapshotKind\n readonly canonical: string\n}\n\n/** Match equivalent bare and provider-qualified spellings without discarding observed identity. */\nexport function observedModelMatchesDeclared(observed: string, declared: string): boolean {\n const observedIdentity = modelIdentityParts(observed)\n const declaredIdentity = modelIdentityParts(declared)\n if (!observedIdentity || !declaredIdentity) return false\n if (\n declaredIdentity.snapshot !== undefined &&\n (observedIdentity.snapshot !== declaredIdentity.snapshot ||\n observedIdentity.snapshotKind !== declaredIdentity.snapshotKind)\n ) {\n return false\n }\n return equivalentModelBase(observedIdentity.base, declaredIdentity.base)\n}\n\n/** Merge two observations of one served model while retaining a snapshot-bearing raw identity. */\nexport function mergeObservedModelIdentity(current: string, next: string): string | undefined {\n const currentIdentity = modelIdentityParts(current)\n const nextIdentity = modelIdentityParts(next)\n if (!currentIdentity || !nextIdentity) return undefined\n if (!equivalentModelBase(currentIdentity.base, nextIdentity.base)) return undefined\n if (\n currentIdentity.snapshot !== undefined &&\n nextIdentity.snapshot !== undefined &&\n (currentIdentity.snapshot !== nextIdentity.snapshot ||\n currentIdentity.snapshotKind !== nextIdentity.snapshotKind)\n ) {\n return undefined\n }\n return currentIdentity.snapshot === undefined && nextIdentity.snapshot !== undefined\n ? next\n : current\n}\n\n/** Canonicalize a served model for cross-route identity comparisons. */\nexport function canonicalObservedModel(model: string): string | undefined {\n return canonicalObservedModelParts(model)?.canonical\n}\n\n/** Return the canonical model and its validated snapshot kind for runtime evidence reduction. */\nexport function canonicalObservedModelParts(\n model: string,\n): CanonicalObservedModelParts | undefined {\n const identity = modelIdentityParts(model)\n if (!identity) return undefined\n const base = identity.base.slice(identity.base.lastIndexOf('/') + 1)\n const canonical =\n identity.snapshot === undefined\n ? base\n : identity.snapshotKind === 'date'\n ? `${base}-${identity.snapshot}`\n : `${base}@${identity.snapshot}`\n return {\n base,\n ...(identity.snapshot !== undefined ? { snapshot: identity.snapshot } : {}),\n ...(identity.snapshotKind !== undefined ? { snapshotKind: identity.snapshotKind } : {}),\n canonical,\n }\n}\n\n/** Return whether an observed identity includes a provider snapshot. */\nexport function observedModelHasSnapshot(model: string): boolean {\n return modelIdentityParts(model)?.snapshot !== undefined\n}\n\nfunction modelIdentityParts(model: string): ModelIdentityParts | null {\n if (model.length === 0) return null\n const at = model.lastIndexOf('@')\n if (at < 0) {\n const dated = datedModelIdentity(model)\n if (dated !== undefined) return dated\n return modelLeaf(model).length === 0 ? null : { base: model }\n }\n const base = model.slice(0, at)\n const snapshot = model.slice(at + 1)\n if (base.length === 0 || modelLeaf(base).length === 0 || !SNAPSHOT_TOKEN.test(snapshot)) {\n return null\n }\n return { base, snapshot, snapshotKind: 'opaque' }\n}\n\nfunction equivalentModelBase(observed: string, declared: string): boolean {\n const observedPath = modelBaseParts(observed)\n const declaredPath = modelBaseParts(declared)\n if (!samePath(observedPath.path, declaredPath.path)) return false\n\n // A bare id omits provider routing. It can match an explicitly qualified spelling\n // only when the model path is otherwise identical.\n if (\n observedPath.provider === undefined ||\n declaredPath.provider === undefined ||\n sameProvider(observedPath.provider, declaredPath.provider)\n ) {\n return true\n }\n\n // Tangle Router may report the upstream provider's qualified spelling. Preserve this\n // one documented alias without allowing arbitrary provider-to-provider substitutions.\n if (observedPath.provider === 'tangle-router' || declaredPath.provider === 'tangle-router') {\n const router = observedPath.provider === 'tangle-router' ? observedPath : declaredPath\n const upstream = observedPath.provider === 'tangle-router' ? declaredPath : observedPath\n if (upstream.provider === undefined) return false\n return (\n samePath(router.path, upstream.path) ||\n (router.path[0] === upstream.provider && samePath(router.path.slice(1), upstream.path))\n )\n }\n\n return false\n}\n\n/**\n * Compare provider slugs across catalogs that spell one vendor with or without hyphens,\n * such as `zai` and OpenRouter's `z-ai`. Any other provider difference is a substitution.\n */\nfunction sameProvider(left: string, right: string): boolean {\n return left.replaceAll('-', '') === right.replaceAll('-', '')\n}\n\ninterface ModelBaseParts {\n readonly provider: string | undefined\n readonly path: ReadonlyArray<string>\n}\n\nfunction modelBaseParts(model: string): ModelBaseParts {\n const segments = model.split('/')\n const normalized =\n segments.length > 1 && isHarnessPrefix(segments[0]) ? segments.slice(1) : segments\n if (normalized.length === 1) return { provider: undefined, path: normalized }\n return { provider: normalized[0], path: normalized.slice(1) }\n}\n\nfunction isHarnessPrefix(segment: string | undefined): boolean {\n return segment !== undefined && harnessTypeSchema.safeParse(segment).success\n}\n\nfunction samePath(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {\n return left.length === right.length && left.every((segment, index) => segment === right[index])\n}\n\nfunction modelLeaf(model: string): string {\n return model.slice(model.lastIndexOf('/') + 1)\n}\n\n/**\n * Parse the provider's documented dated snapshot forms.\n *\n * `undefined` means that the model has no dated shape and must be treated as a normal base.\n * `null` means that it has a dated shape but the date is invalid, so identity matching fails.\n */\nfunction datedModelIdentity(model: string): ModelIdentityParts | null | undefined {\n const iso = datedIsoSuffix.exec(model)\n if (iso) {\n const [, base, yearText, monthText, dayText] = iso\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}-${dayText}`,\n isValidCalendarDate(yearText, monthText, dayText),\n )\n }\n\n const compact = datedCompactSuffix.exec(model)\n if (compact) {\n const [, base, yearText, monthText, dayText] = compact\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}-${dayText}`,\n isValidCalendarDate(yearText, monthText, dayText),\n )\n }\n\n const month = datedMonthSuffix.exec(model)\n if (month) {\n const [, base, yearText, monthText] = month\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}`,\n isValidCalendarMonth(yearText, monthText),\n )\n }\n\n return undefined\n}\n\nfunction buildDatedIdentity(\n base: string | undefined,\n snapshot: string,\n valid: boolean,\n): ModelIdentityParts | null | undefined {\n // A date that is the entire model segment is not a snapshot suffix.\n if (base === undefined || base.length === 0 || base.endsWith('/')) return undefined\n return valid ? { base, snapshot, snapshotKind: 'date' } : null\n}\n\nfunction isValidCalendarDate(\n yearText: string | undefined,\n monthText: string | undefined,\n dayText: string | undefined,\n): boolean {\n if (yearText === undefined || monthText === undefined || dayText === undefined) return false\n const year = Number(yearText)\n const month = Number(monthText)\n const day = Number(dayText)\n if (year < 2000 || year > 2099 || month < 1 || month > 12 || day < 1 || day > 31) {\n return false\n }\n const date = new Date(Date.UTC(year, month - 1, day))\n return (\n date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n )\n}\n\nfunction isValidCalendarMonth(\n yearText: string | undefined,\n monthText: string | undefined,\n): boolean {\n if (yearText === undefined || monthText === undefined) return false\n const year = Number(yearText)\n const month = Number(monthText)\n return year >= 2000 && year <= 2099 && month >= 1 && month <= 12\n}\n","import { ValidationError } from '../errors'\nimport { observedModelMatchesDeclared } from './model-identity'\n\nfunction object(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new ValidationError('Router Auto requires an inline policy and routing receipt')\n }\n return value as Record<string, unknown>\n}\n\n/** Router owns policy parsing. Runtime requires visible model authority before dispatch. */\nexport function assertRouterAutoDeclaration(value: unknown, stream: boolean | undefined): void {\n const policy = object(value)\n if (stream === true) throw new ValidationError('Router Auto requires buffered transport')\n if (\n policy.version !== 1 ||\n typeof policy.id !== 'string' ||\n typeof policy.revision !== 'string' ||\n !Array.isArray(policy.strategies) ||\n policy.strategies.length === 0\n ) {\n throw new ValidationError(\n 'Router Auto requires a versioned inline policy with concrete strategies',\n )\n }\n for (const raw of policy.strategies) {\n const strategy = object(raw)\n if (\n typeof strategy.id !== 'string' ||\n typeof strategy.model !== 'string' ||\n strategy.model === 'tangle/auto' ||\n strategy.model.length === 0\n ) {\n throw new ValidationError('Router Auto strategy model authority is missing')\n }\n }\n for (const phase of ['selector', 'review']) {\n if (policy[phase] !== undefined && typeof object(policy[phase]).model !== 'string') {\n throw new ValidationError('Router Auto assessment model authority is missing')\n }\n }\n}\n\n/** An alias does not waive identity checks. Every reported child must match its declared phase. */\nexport function assertRouterAutoResponse(\n policyValue: unknown,\n response: unknown,\n served: string | undefined,\n): void {\n const policy = object(policyValue)\n const receipt = object(object(response).tangle_auto)\n const decision = object(receipt.decision)\n const strategies = policy.strategies as unknown[]\n const selected = strategies.map(object).find((strategy) => strategy.id === decision.strategyId)\n if (\n decision.requestedModel !== 'tangle/auto' ||\n decision.policyId !== policy.id ||\n decision.policyRevision !== policy.revision ||\n typeof decision.policyDigest !== 'string' ||\n !selected ||\n decision.selectedModel !== selected.model ||\n served === undefined ||\n !observedModelMatchesDeclared(served, String(selected.model))\n ) {\n throw new ValidationError(\n 'Router Auto response does not match AgentProfile policy/model authority',\n )\n }\n if (!Array.isArray(receipt.calls) || receipt.calls.length === 0) {\n throw new ValidationError('Router Auto response is missing physical call receipts')\n }\n for (const raw of receipt.calls) {\n const call = object(raw)\n const declared =\n call.phase === 'selector'\n ? object(policy.selector).model\n : call.phase === 'review'\n ? object(policy.review).model\n : call.phase === 'initial' || call.phase === 'escalation'\n ? strategies.map(object).map((strategy) => strategy.model)\n : []\n const allowed = Array.isArray(declared) ? declared : [declared]\n if (\n typeof call.model !== 'string' ||\n !allowed.some(\n (model) =>\n typeof model === 'string' && observedModelMatchesDeclared(call.model as string, model),\n )\n )\n throw new ValidationError('Router Auto physical call exceeds AgentProfile model authority')\n }\n}\n\n/** The concrete authority declared by an inline Auto policy, including paid assessments. */\nexport function routerAutoDeclaredModels(value: unknown): readonly string[] {\n assertRouterAutoDeclaration(value, undefined)\n const policy = object(value)\n const models = (policy.strategies as unknown[]).map((raw) => String(object(raw).model))\n for (const phase of ['selector', 'review']) {\n if (policy[phase] !== undefined) models.push(String(object(policy[phase]).model))\n }\n return [...new Set(models)]\n}\n","import { ValidationError } from '../errors'\n\n/** Exact retry controls accepted at `AgentProfile.model.metadata.retry`. */\nexport interface RouterRetryPolicy {\n /** Total attempts, including the first request. */\n readonly maxAttempts?: number\n /** Delay before the second attempt. Later delays grow exponentially. */\n readonly initialBackoffMs?: number\n /** Maximum delay between attempts. */\n readonly maxBackoffMs?: number\n /** Symmetric random variation around each delay, from 0 through 1. */\n readonly jitter?: number\n /** HTTP statuses that may be retried. */\n readonly retryStatuses?: ReadonlyArray<number>\n /** Deadline for receiving one attempt's response headers. Zero disables it. */\n readonly requestTimeoutMs?: number\n}\n\nexport interface ResolvedRouterRetryPolicy {\n readonly maxAttempts: number\n readonly initialBackoffMs: number\n readonly maxBackoffMs: number\n readonly jitter: number\n readonly retryStatuses: ReadonlyArray<number>\n readonly requestTimeoutMs: number\n}\n\nconst maximumTimerMs = 2_147_483_647\nconst defaultRetryStatuses = Object.freeze([408, 425, 429, 500, 502, 503, 504, 520, 522, 524])\nconst retryPolicyKeys = new Set([\n 'initialBackoffMs',\n 'jitter',\n 'maxAttempts',\n 'maxBackoffMs',\n 'requestTimeoutMs',\n 'retryStatuses',\n])\n\n/** Parse untrusted profile/config data once and return an immutable complete policy. */\nexport function resolveRouterRetryPolicy(\n input: unknown,\n context: string,\n): ResolvedRouterRetryPolicy {\n if (\n input !== undefined &&\n (typeof input !== 'object' || input === null || Array.isArray(input))\n ) {\n throw new ValidationError(`${context} must be an object`)\n }\n const policy = input === undefined ? {} : Object.fromEntries(Object.entries(input))\n const unknown = Object.keys(policy).filter((key) => !retryPolicyKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(`${context} has unsupported fields: ${unknown.join(', ')}`)\n }\n const maxAttempts = positiveInteger(policy.maxAttempts, 5, `${context}.maxAttempts`)\n const initialBackoffMs = timerInteger(\n policy.initialBackoffMs,\n 1_000,\n `${context}.initialBackoffMs`,\n )\n const maxBackoffMs = timerInteger(policy.maxBackoffMs, 30_000, `${context}.maxBackoffMs`)\n const requestTimeoutMs = timerInteger(\n policy.requestTimeoutMs,\n 0,\n `${context}.requestTimeoutMs`,\n Number.MAX_SAFE_INTEGER - Date.now(),\n )\n const jitter = policy.jitter ?? 0.25\n if (typeof jitter !== 'number' || !Number.isFinite(jitter) || jitter < 0 || jitter > 1) {\n throw new ValidationError(`${context}.jitter must be a finite number from 0 through 1`)\n }\n const retryStatuses = parseRetryStatuses(policy.retryStatuses, context)\n return Object.freeze({\n maxAttempts,\n initialBackoffMs,\n maxBackoffMs,\n jitter,\n retryStatuses,\n requestTimeoutMs,\n })\n}\n\nfunction parseRetryStatuses(value: unknown, context: string): ReadonlyArray<number> {\n if (value === undefined) return defaultRetryStatuses\n if (!Array.isArray(value)) {\n throw new ValidationError(`${context}.retryStatuses must be an array of HTTP statuses`)\n }\n const statuses: number[] = []\n const seen = new Set<number>()\n for (const status of value) {\n if (!Number.isSafeInteger(status) || status < 100 || status > 599) {\n throw new ValidationError(\n `${context}.retryStatuses must contain integer HTTP statuses from 100 through 599`,\n )\n }\n if (seen.has(status)) {\n throw new ValidationError(`${context}.retryStatuses must not contain duplicates`)\n }\n seen.add(status)\n statuses.push(status)\n }\n return Object.freeze(statuses)\n}\n\nfunction positiveInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed < 1) {\n throw new ValidationError(`${context} must be a positive safe integer`)\n }\n return parsed\n}\n\nfunction timerInteger(\n value: unknown,\n fallback: number,\n context: string,\n maximum = maximumTimerMs,\n): number {\n const parsed = value ?? fallback\n if (\n typeof parsed !== 'number' ||\n !Number.isSafeInteger(parsed) ||\n parsed < 0 ||\n parsed > maximum\n ) {\n throw new ValidationError(\n `${context} must be a nonnegative safe integer no greater than ${maximum}`,\n )\n }\n return parsed\n}\n","/**\n * `assertModelAllowed` — a fail-loud guard that restricts a run to a chosen subset of\n * models. The two front doors (`supervise()` / `improve()`) call it once per configured\n * model at resolve time, so a run that names a model outside the allowed set throws before\n * any compute is spent — never silently swapped or silently allowed.\n */\nimport { HARNESS_NATIVE_MODEL } from '@tangle-network/agent-eval'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../../errors'\nimport { agentHarness } from '../harness-role'\nimport { routerAutoDeclaredModels } from '../router-auto-evidence'\nimport { type ResolvedRouterRetryPolicy, resolveRouterRetryPolicy } from '../router-retry-policy'\n\n/**\n * Return the model id an executor may send to a provider.\n *\n * Eval stamps {@link HARNESS_NATIVE_MODEL} into a profile when model selection is deliberately\n * delegated to the configured runtime. That marker belongs in experiment identity and cost\n * admission; it is not a provider model id.\n */\nexport function concreteModelId(model: string | undefined): string | undefined {\n if (model === undefined) return undefined\n const id = model.trim()\n return id.length > 0 && !isHarnessNativeModel(id) ? id : undefined\n}\n\n/** Whether a model value delegates selection to the chosen execution system. */\nexport function isHarnessNativeModel(model: string | undefined): boolean {\n return model?.trim() === HARNESS_NATIVE_MODEL\n}\n\n/** Return a profile's explicitly selected provider model, if it has one. */\nexport function concreteProfileModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n return concreteModelId(profile.model?.default)\n}\n\n/**\n * Return the model id for a direct provider request.\n *\n * A portable profile can qualify its model with the selected provider. The direct endpoint already\n * selects that provider, so remove only the exact matching prefix. Preserve every other prefix\n * because it can identify a provider-owned nested route, such as `anthropic/claude-sonnet`.\n */\nexport function profileProviderModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider?.trim()\n if (!model || !provider || !model.startsWith(`${provider}/`)) return model\n return concreteModelId(model.slice(provider.length + 1))\n}\n\n/** The full cli-bridge wire id declared by a profile: harness/provider/model. */\nexport function profileBridgeWireModel(\n profile: Pick<AgentProfile, 'harness' | 'model'>,\n): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider\n const harness = agentHarness(profile.harness)\n const modelWithoutHarness =\n model && harness && model.startsWith(`${harness}/`) ? model.slice(harness.length + 1) : model\n const providerModel = modelWithoutHarness\n ? provider && !modelWithoutHarness.startsWith(`${provider}/`)\n ? `${provider}/${modelWithoutHarness}`\n : modelWithoutHarness\n : undefined\n if (!harness) return providerModel\n if (!providerModel) return harness\n return providerModel.startsWith(`${harness}/`) ? providerModel : `${harness}/${providerModel}`\n}\n\n/**\n * Refuse an incomplete execution identity before any backend may fill it from ambient config.\n * `AgentProfile` is the sole behavioral authority: harness, provider, and concrete model all\n * participate in its digest. Eval's runtime-selected marker is a matrix-planning value, never an\n * executable model.\n */\nexport function assertExecutableAgentProfile(profile: AgentProfile, context: string): void {\n if (profile.harness === undefined) {\n throw new ConfigError(`${context}: AgentProfile.harness must be explicit before execution`)\n }\n const declared = profile.model?.default\n const model = concreteModelId(declared)\n if (!model) {\n const reason = isHarnessNativeModel(declared) ? 'runtime-selected' : 'missing'\n throw new ConfigError(\n `${context}: AgentProfile.model.default is ${reason}; execution requires a concrete model`,\n )\n }\n if (!profile.model?.provider?.trim()) {\n throw new ConfigError(\n `${context}: AgentProfile.model.provider must be explicit before execution`,\n )\n }\n}\n\n/**\n * Separate completion ceilings an exact profile may request.\n *\n * They are distinct because providers do not share one meaning for a single number: measured\n * through the Tangle Router on 2026-08-10, `glm-5.2` accepted `max_tokens: 8` and still billed 135\n * completion tokens — 132 reasoning, 3 visible — while `max_completion_tokens: 256` bounded the\n * total. A path that cannot enforce a requested ceiling refuses the run instead of sending a\n * number that means something else there.\n */\nexport interface ProfileTokenLimits {\n /** Visible answer tokens, from `AgentProfile.model.maxVisibleOutputTokens`. */\n readonly visible?: number\n /** Hidden reasoning tokens, from `AgentProfile.model.maxReasoningTokens`. */\n readonly reasoning?: number\n /** Visible and reasoning tokens together, from `AgentProfile.model.maxTotalOutputTokens`. */\n readonly total?: number\n}\n\n/** The ceilings one execution path actually sends, in the request fields it sends them as. */\nexport interface AppliedTokenLimits {\n /** Sent as `max_tokens`. */\n readonly maxTokens?: number\n /** Sent as `max_completion_tokens`. */\n readonly maxCompletionTokens?: number\n}\n\n/** What a path was asked to enforce and what it sent, for the execution receipt. */\nexport interface TokenLimitDecision {\n readonly requested: ProfileTokenLimits\n readonly applied: AppliedTokenLimits\n}\n\n/** The execution paths that lower a profile into a provider request. */\nexport type ModelExecutionPath = 'router' | 'bridge' | 'sandbox' | 'provider'\n\n/** Generation and loop controls that may affect one model execution. */\nexport interface ProfileModelExecutionSettings {\n readonly temperature?: number\n /** Completion ceilings the profile requested. Empty when it requested none. */\n readonly tokenLimits: ProfileTokenLimits\n readonly retry?: ResolvedRouterRetryPolicy\n readonly seed?: number\n readonly toolChoice?: 'auto' | 'required' | 'none'\n readonly extraBody?: Readonly<Record<string, unknown>>\n /** Zero means no turn-count cap; conserved budgets and deadlines still apply. */\n readonly maxTurns?: number\n readonly stream?: boolean\n}\n\nconst PROFILE_MODEL_METADATA_KEYS = new Set([\n 'extraBody',\n 'maxTurns',\n 'retry',\n 'seed',\n 'stream',\n 'temperature',\n 'toolChoice',\n])\n\n/**\n * Read execution controls from the exact profile and reject unknown controls.\n * Credential intent reaches environment providers unchanged; other paths cannot enforce it.\n * Backends receive endpoint/auth and executable ports only; they cannot silently alter behavior.\n */\nexport function profileModelExecutionSettings(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n path: ModelExecutionPath = 'router',\n): ProfileModelExecutionSettings {\n const metadata = profile.model?.metadata ?? {}\n if (metadata.maxTokens !== undefined) {\n throw new ConfigError(\n `${context}: AgentProfile.model.metadata.maxTokens is ambiguous across providers; declare AgentProfile.model.maxVisibleOutputTokens, maxReasoningTokens, or maxTotalOutputTokens instead`,\n )\n }\n const unknown = Object.keys(metadata).filter(\n (key) =>\n !PROFILE_MODEL_METADATA_KEYS.has(key) && !(path === 'provider' && key === 'credentialSource'),\n )\n if (unknown.length > 0) {\n throw new ConfigError(\n `${context}: unsupported AgentProfile.model.metadata fields: ${unknown.join(', ')}`,\n )\n }\n if (\n metadata.credentialSource !== undefined &&\n metadata.credentialSource !== 'managed' &&\n metadata.credentialSource !== 'subscription'\n ) {\n throw new ConfigError(\n `${context}: AgentProfile.model.metadata.credentialSource must be managed or subscription`,\n )\n }\n const temperature = finiteNumber(metadata.temperature, `${context}: temperature`)\n const tokenLimits = profileTokenLimits(profile, context)\n const retryInput = metadata.retry\n const retry =\n retryInput === undefined\n ? undefined\n : resolveRouterRetryPolicy(retryInput, `${context}: AgentProfile.model.metadata.retry`)\n const seed = safeInteger(metadata.seed, `${context}: seed`)\n const maxTurns = nonnegativeInteger(metadata.maxTurns, `${context}: maxTurns`)\n const stream = optionalBoolean(metadata.stream, `${context}: stream`)\n const toolChoice = metadata.toolChoice\n if (\n toolChoice !== undefined &&\n toolChoice !== 'auto' &&\n toolChoice !== 'required' &&\n toolChoice !== 'none'\n ) {\n throw new ConfigError(`${context}: toolChoice must be auto, required, or none`)\n }\n const extraBody = metadata.extraBody\n if (\n extraBody !== undefined &&\n (typeof extraBody !== 'object' || extraBody === null || Array.isArray(extraBody))\n ) {\n throw new ConfigError(`${context}: extraBody must be an object`)\n }\n return {\n ...(temperature !== undefined ? { temperature } : {}),\n tokenLimits,\n ...(retry !== undefined ? { retry } : {}),\n ...(seed !== undefined ? { seed } : {}),\n ...(toolChoice !== undefined ? { toolChoice } : {}),\n ...(extraBody !== undefined\n ? { extraBody: Object.freeze({ ...(extraBody as Record<string, unknown>) }) }\n : {}),\n ...(maxTurns !== undefined ? { maxTurns } : {}),\n ...(stream !== undefined ? { stream } : {}),\n }\n}\n\n/**\n * Read the completion ceilings an exact profile declares. The Interface schema already refines\n * these fields, but a profile can reach an executor without a parse, so the same rules are\n * enforced here: positive integers, and no single ceiling above the total.\n */\nexport function profileTokenLimits(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n): ProfileTokenLimits {\n const model = profile.model\n const visible = positiveInteger(\n model?.maxVisibleOutputTokens,\n `${context}: maxVisibleOutputTokens`,\n )\n const reasoning = positiveInteger(model?.maxReasoningTokens, `${context}: maxReasoningTokens`)\n const total = positiveInteger(model?.maxTotalOutputTokens, `${context}: maxTotalOutputTokens`)\n if (total !== undefined) {\n for (const [name, value] of [\n ['maxVisibleOutputTokens', visible],\n ['maxReasoningTokens', reasoning],\n ] as const) {\n if (value !== undefined && value > total) {\n throw new ConfigError(\n `${context}: AgentProfile.model.${name} (${value}) exceeds maxTotalOutputTokens (${total})`,\n )\n }\n }\n }\n return {\n ...(visible !== undefined ? { visible } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n ...(total !== undefined ? { total } : {}),\n }\n}\n\n/**\n * Lower the requested ceilings onto one execution path, or refuse the run before any paid\n * transport.\n *\n * - Router and OpenAI-compatible routes send the visible ceiling as `max_tokens` and the total as\n * `max_completion_tokens`.\n * - The CLI Bridge lowers ONE completion cap into the run's model catalog, so it carries the total\n * as `max_tokens` and cannot bound the visible half on its own.\n * - The Sandbox and environment-provider paths expose no completion cap at all.\n * - No route publishes a reasoning-token budget, so a reasoning ceiling is refused everywhere.\n * `AgentProfile.model.reasoningEffort` is an intensity dial, not a token bound.\n */\nexport function enforceTokenLimits(\n limits: ProfileTokenLimits,\n path: ModelExecutionPath,\n context: string,\n): TokenLimitDecision {\n const refuse = (field: string, reason: string): never => {\n throw new ConfigError(\n `${context}: AgentProfile.model.${field} cannot be enforced on the ${path} path (${reason}); remove the ceiling or select a path that enforces it`,\n )\n }\n if (limits.reasoning !== undefined) {\n refuse('maxReasoningTokens', 'no route exposes a reasoning-token budget')\n }\n if (path === 'router') {\n return {\n requested: limits,\n applied: {\n ...(limits.visible !== undefined ? { maxTokens: limits.visible } : {}),\n ...(limits.total !== undefined ? { maxCompletionTokens: limits.total } : {}),\n },\n }\n }\n if (path === 'bridge') {\n if (limits.visible !== undefined) {\n refuse('maxVisibleOutputTokens', 'the bridge lowers one completion cap covering both halves')\n }\n return {\n requested: limits,\n applied: {\n ...(limits.total !== undefined ? { maxTokens: limits.total } : {}),\n },\n }\n }\n if (limits.visible !== undefined) refuse('maxVisibleOutputTokens', 'the backend accepts no cap')\n if (limits.total !== undefined) refuse('maxTotalOutputTokens', 'the backend accepts no cap')\n return { requested: limits, applied: {} }\n}\n\nfunction finiteNumber(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new ConfigError(`${context} must be a finite number`)\n }\n return value\n}\n\nfunction safeInteger(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value)) throw new ConfigError(`${context} must be a safe integer`)\n return value as number\n}\n\nfunction positiveInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 1) {\n throw new ConfigError(`${context} must be positive`)\n }\n return parsed\n}\n\nfunction nonnegativeInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 0) {\n throw new ConfigError(`${context} must be nonnegative`)\n }\n return parsed\n}\n\nfunction optionalBoolean(value: unknown, context: string): boolean | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'boolean') throw new ConfigError(`${context} must be boolean`)\n return value\n}\n\n/**\n * Throw a `ConfigError` when `allowed` is set, `model` is defined, and `model` is not a\n * member of `allowed`. No-op when `allowed` is unset (the unrestricted default) or when\n * `model` is undefined (nothing was configured to check).\n */\nexport function assertModelAllowed(\n model: string | undefined,\n allowed: readonly string[] | undefined,\n): void {\n if (!allowed || model === undefined) return\n if (!allowed.includes(model)) {\n throw new ConfigError(\n `model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`,\n )\n }\n}\n\n/** Check every canonical model-bearing field in a complete profile, including the models a\n * backend may select for cheap work, named subagents, or modes.\n *\n * Every compared value is a bare model id. The composed `harness/provider/model` wire id\n * (`profileBridgeWireModel`) is neither built nor compared here, so this admits any route that\n * declares an allowed id, and a qualified entry in `allowed` matches nothing. Route pinning\n * belongs to `SuperviseOptions.authorizeSpawn`. */\nexport function assertProfileModelsAllowed(\n profile: AgentProfile,\n allowed: readonly string[] | undefined,\n): void {\n assertModelAllowed(profile.model?.default, allowed)\n assertModelAllowed(profile.model?.small, allowed)\n if (profile.model?.default === 'tangle/auto') {\n const extra = profile.model.metadata?.extraBody\n const policy =\n extra !== null && typeof extra === 'object'\n ? (extra as Record<string, unknown>).auto\n : undefined\n for (const model of routerAutoDeclaredModels(policy)) assertModelAllowed(model, allowed)\n }\n for (const subagent of Object.values(profile.subagents ?? {})) {\n assertModelAllowed(subagent.model, allowed)\n }\n for (const mode of Object.values(profile.modes ?? {})) {\n assertModelAllowed(mode.model, allowed)\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,MAAM,qCAA0C,IAAI,IAAY,CAAC,UAAgC,CAAC;;;;AAKlG,SAAgB,iBAAmC,SAA6C;CAC9F,OAAO,WAAW,QAAQ,CAAC,mBAAmB,IAAI,OAAO;AAC3D;;;AAIA,SAAgB,aAA+B,SAA8C;CAC3F,OAAO,iBAAiB,OAAO,IAAI,UAAU,KAAA;AAC/C;;;ACpCA,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;;AAkBzB,SAAgB,6BAA6B,UAAkB,UAA2B;CACxF,MAAM,mBAAmB,mBAAmB,QAAQ;CACpD,MAAM,mBAAmB,mBAAmB,QAAQ;CACpD,IAAI,CAAC,oBAAoB,CAAC,kBAAkB,OAAO;CACnD,IACE,iBAAiB,aAAa,KAAA,MAC7B,iBAAiB,aAAa,iBAAiB,YAC9C,iBAAiB,iBAAiB,iBAAiB,eAErD,OAAO;CAET,OAAO,oBAAoB,iBAAiB,MAAM,iBAAiB,IAAI;AACzE;;AAGA,SAAgB,2BAA2B,SAAiB,MAAkC;CAC5F,MAAM,kBAAkB,mBAAmB,OAAO;CAClD,MAAM,eAAe,mBAAmB,IAAI;CAC5C,IAAI,CAAC,mBAAmB,CAAC,cAAc,OAAO,KAAA;CAC9C,IAAI,CAAC,oBAAoB,gBAAgB,MAAM,aAAa,IAAI,GAAG,OAAO,KAAA;CAC1E,IACE,gBAAgB,aAAa,KAAA,KAC7B,aAAa,aAAa,KAAA,MACzB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identity.ts","../src/runtime/router-auto-evidence.ts","../src/runtime/router-retry-policy.ts","../src/runtime/supervise/model-policy.ts"],"sourcesContent":["/**\n * Which `HarnessType` values name a real coding-agent runtime, and which name a MODE that has no\n * agent behind it.\n *\n * `cli-base` is the router-backed mode — a plain multi-turn router call with no coding-agent\n * harness (`@tangle-network/agent-interface`'s `HarnessType` doc, and the same table's\n * `harnessReasoningCeiling['cli-base'] = 'none'` commented \"cli-base has no agent\"). The\n * distinction is REAL; what was accidental is that three call sites each spelled the test\n * themselves, so a second no-agent mode would have to be remembered in three places.\n *\n * SHOULD UPSTREAM: this belongs next to `harnessHonorsEffort` in agent-interface's\n * `harness-capabilities.ts`, which already encodes the fact but exports no predicate for it.\n * Until it does, this is the one local copy — extend the set here, never re-test the name.\n */\n\nimport type { HarnessType } from '@tangle-network/agent-interface'\n\n/**\n * Harness ids that select a router/no-agent mode rather than a coding-agent runtime.\n *\n * `nanoclaw` is deliberately ABSENT: the shared capability table clamps its reasoning ceiling the\n * same way it clamps `cli-base`, but nanoclaw does run an agent (a socket-bridge runner to the\n * NanoClaw daemon) and every caller here treats it as a full harness. Add a row only with the\n * behavior change stated, never to make the two clamps look symmetric.\n */\nconst NO_AGENT_HARNESSES: ReadonlySet<string> = new Set<string>(['cli-base' satisfies HarnessType])\n\n/** Whether this profile harness selects a real coding-agent runtime (vs. the router/no-agent mode\n * or no preference at all). Accepts the looser `string` some local profile shapes declare, and\n * preserves the caller's own harness type when it is narrower. */\nexport function harnessRunsAgent<T extends string>(harness: T | null | undefined): harness is T {\n return harness != null && !NO_AGENT_HARNESSES.has(harness)\n}\n\n/** The coding-agent harness this profile selects, or `undefined` when it selects none — the shape\n * callers want when a no-agent mode must fall through to the router arm. */\nexport function agentHarness<T extends string>(harness: T | null | undefined): T | undefined {\n return harnessRunsAgent(harness) ? harness : undefined\n}\n","import { harnessTypeSchema } from '@tangle-network/agent-interface'\n\nconst SNAPSHOT_TOKEN = /^[A-Za-z0-9._-]+$/u\nconst datedIsoSuffix = /^(.*)-(\\d{4})-(\\d{2})-(\\d{2})$/u\nconst datedCompactSuffix = /^(.*)-(\\d{4})(\\d{2})(\\d{2})$/u\nconst datedMonthSuffix = /^(.*)-(\\d{4})-(\\d{2})$/u\n\ntype SnapshotKind = 'date' | 'opaque'\n\ninterface ModelIdentityParts {\n readonly base: string\n readonly snapshot?: string\n readonly snapshotKind?: SnapshotKind\n}\n\nexport interface CanonicalObservedModelParts {\n readonly base: string\n readonly snapshot?: string\n readonly snapshotKind?: SnapshotKind\n readonly canonical: string\n}\n\n/** Match equivalent bare and provider-qualified spellings without discarding observed identity. */\nexport function observedModelMatchesDeclared(observed: string, declared: string): boolean {\n const observedIdentity = modelIdentityParts(observed)\n const declaredIdentity = modelIdentityParts(declared)\n if (!observedIdentity || !declaredIdentity) return false\n if (\n declaredIdentity.snapshot !== undefined &&\n (observedIdentity.snapshot !== declaredIdentity.snapshot ||\n observedIdentity.snapshotKind !== declaredIdentity.snapshotKind)\n ) {\n return false\n }\n return equivalentModelBase(observedIdentity.base, declaredIdentity.base)\n}\n\n/** Merge two observations of one served model while retaining a snapshot-bearing raw identity. */\nexport function mergeObservedModelIdentity(current: string, next: string): string | undefined {\n const currentIdentity = modelIdentityParts(current)\n const nextIdentity = modelIdentityParts(next)\n if (!currentIdentity || !nextIdentity) return undefined\n if (!equivalentModelBase(currentIdentity.base, nextIdentity.base)) return undefined\n if (\n currentIdentity.snapshot !== undefined &&\n nextIdentity.snapshot !== undefined &&\n (currentIdentity.snapshot !== nextIdentity.snapshot ||\n currentIdentity.snapshotKind !== nextIdentity.snapshotKind)\n ) {\n return undefined\n }\n return currentIdentity.snapshot === undefined && nextIdentity.snapshot !== undefined\n ? next\n : current\n}\n\n/** Canonicalize a served model for cross-route identity comparisons. */\nexport function canonicalObservedModel(model: string): string | undefined {\n return canonicalObservedModelParts(model)?.canonical\n}\n\n/** Return the canonical model and its validated snapshot kind for runtime evidence reduction. */\nexport function canonicalObservedModelParts(\n model: string,\n): CanonicalObservedModelParts | undefined {\n const identity = modelIdentityParts(model)\n if (!identity) return undefined\n const base = identity.base.slice(identity.base.lastIndexOf('/') + 1)\n const canonical =\n identity.snapshot === undefined\n ? base\n : identity.snapshotKind === 'date'\n ? `${base}-${identity.snapshot}`\n : `${base}@${identity.snapshot}`\n return {\n base,\n ...(identity.snapshot !== undefined ? { snapshot: identity.snapshot } : {}),\n ...(identity.snapshotKind !== undefined ? { snapshotKind: identity.snapshotKind } : {}),\n canonical,\n }\n}\n\n/** Return whether an observed identity includes a provider snapshot. */\nexport function observedModelHasSnapshot(model: string): boolean {\n return modelIdentityParts(model)?.snapshot !== undefined\n}\n\nfunction modelIdentityParts(model: string): ModelIdentityParts | null {\n if (model.length === 0) return null\n const at = model.lastIndexOf('@')\n if (at < 0) {\n const dated = datedModelIdentity(model)\n if (dated !== undefined) return dated\n return modelLeaf(model).length === 0 ? null : { base: model }\n }\n const base = model.slice(0, at)\n const snapshot = model.slice(at + 1)\n if (base.length === 0 || modelLeaf(base).length === 0 || !SNAPSHOT_TOKEN.test(snapshot)) {\n return null\n }\n return { base, snapshot, snapshotKind: 'opaque' }\n}\n\nfunction equivalentModelBase(observed: string, declared: string): boolean {\n const observedPath = modelBaseParts(observed)\n const declaredPath = modelBaseParts(declared)\n if (!samePath(observedPath.path, declaredPath.path)) return false\n\n // A bare id omits provider routing. It can match an explicitly qualified spelling\n // only when the model path is otherwise identical.\n if (\n observedPath.provider === undefined ||\n declaredPath.provider === undefined ||\n sameProvider(observedPath.provider, declaredPath.provider)\n ) {\n return true\n }\n\n // Tangle Router may report the upstream provider's qualified spelling. Preserve this\n // one documented alias without allowing arbitrary provider-to-provider substitutions.\n if (observedPath.provider === 'tangle-router' || declaredPath.provider === 'tangle-router') {\n const router = observedPath.provider === 'tangle-router' ? observedPath : declaredPath\n const upstream = observedPath.provider === 'tangle-router' ? declaredPath : observedPath\n if (upstream.provider === undefined) return false\n return (\n samePath(router.path, upstream.path) ||\n (router.path[0] === upstream.provider && samePath(router.path.slice(1), upstream.path))\n )\n }\n\n return false\n}\n\n/**\n * Compare provider slugs across catalogs that spell one vendor with or without hyphens,\n * such as `zai` and OpenRouter's `z-ai`. Any other provider difference is a substitution.\n */\nfunction sameProvider(left: string, right: string): boolean {\n return left.replaceAll('-', '') === right.replaceAll('-', '')\n}\n\ninterface ModelBaseParts {\n readonly provider: string | undefined\n readonly path: ReadonlyArray<string>\n}\n\nfunction modelBaseParts(model: string): ModelBaseParts {\n const segments = model.split('/')\n const normalized =\n segments.length > 1 && isHarnessPrefix(segments[0]) ? segments.slice(1) : segments\n if (normalized.length === 1) return { provider: undefined, path: normalized }\n return { provider: normalized[0], path: normalized.slice(1) }\n}\n\nfunction isHarnessPrefix(segment: string | undefined): boolean {\n return segment !== undefined && harnessTypeSchema.safeParse(segment).success\n}\n\nfunction samePath(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {\n return left.length === right.length && left.every((segment, index) => segment === right[index])\n}\n\nfunction modelLeaf(model: string): string {\n return model.slice(model.lastIndexOf('/') + 1)\n}\n\n/**\n * Parse the provider's documented dated snapshot forms.\n *\n * `undefined` means that the model has no dated shape and must be treated as a normal base.\n * `null` means that it has a dated shape but the date is invalid, so identity matching fails.\n */\nfunction datedModelIdentity(model: string): ModelIdentityParts | null | undefined {\n const iso = datedIsoSuffix.exec(model)\n if (iso) {\n const [, base, yearText, monthText, dayText] = iso\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}-${dayText}`,\n isValidCalendarDate(yearText, monthText, dayText),\n )\n }\n\n const compact = datedCompactSuffix.exec(model)\n if (compact) {\n const [, base, yearText, monthText, dayText] = compact\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}-${dayText}`,\n isValidCalendarDate(yearText, monthText, dayText),\n )\n }\n\n const month = datedMonthSuffix.exec(model)\n if (month) {\n const [, base, yearText, monthText] = month\n return buildDatedIdentity(\n base,\n `${yearText}-${monthText}`,\n isValidCalendarMonth(yearText, monthText),\n )\n }\n\n return undefined\n}\n\nfunction buildDatedIdentity(\n base: string | undefined,\n snapshot: string,\n valid: boolean,\n): ModelIdentityParts | null | undefined {\n // A date that is the entire model segment is not a snapshot suffix.\n if (base === undefined || base.length === 0 || base.endsWith('/')) return undefined\n return valid ? { base, snapshot, snapshotKind: 'date' } : null\n}\n\nfunction isValidCalendarDate(\n yearText: string | undefined,\n monthText: string | undefined,\n dayText: string | undefined,\n): boolean {\n if (yearText === undefined || monthText === undefined || dayText === undefined) return false\n const year = Number(yearText)\n const month = Number(monthText)\n const day = Number(dayText)\n if (year < 2000 || year > 2099 || month < 1 || month > 12 || day < 1 || day > 31) {\n return false\n }\n const date = new Date(Date.UTC(year, month - 1, day))\n return (\n date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n )\n}\n\nfunction isValidCalendarMonth(\n yearText: string | undefined,\n monthText: string | undefined,\n): boolean {\n if (yearText === undefined || monthText === undefined) return false\n const year = Number(yearText)\n const month = Number(monthText)\n return year >= 2000 && year <= 2099 && month >= 1 && month <= 12\n}\n","import { ValidationError } from '../errors'\nimport { observedModelMatchesDeclared } from './model-identity'\n\nfunction object(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new ValidationError('Router Auto requires an inline policy and routing receipt')\n }\n return value as Record<string, unknown>\n}\n\n/** Router owns policy parsing. Runtime requires visible model authority before dispatch. */\nexport function assertRouterAutoDeclaration(value: unknown, stream: boolean | undefined): void {\n const policy = object(value)\n if (stream === true) throw new ValidationError('Router Auto requires buffered transport')\n if (\n policy.version !== 1 ||\n typeof policy.id !== 'string' ||\n typeof policy.revision !== 'string' ||\n !Array.isArray(policy.strategies) ||\n policy.strategies.length === 0\n ) {\n throw new ValidationError(\n 'Router Auto requires a versioned inline policy with concrete strategies',\n )\n }\n for (const raw of policy.strategies) {\n const strategy = object(raw)\n if (\n typeof strategy.id !== 'string' ||\n typeof strategy.model !== 'string' ||\n strategy.model === 'tangle/auto' ||\n strategy.model.length === 0\n ) {\n throw new ValidationError('Router Auto strategy model authority is missing')\n }\n }\n for (const phase of ['selector', 'review']) {\n if (policy[phase] !== undefined && typeof object(policy[phase]).model !== 'string') {\n throw new ValidationError('Router Auto assessment model authority is missing')\n }\n }\n}\n\n/** An alias does not waive identity checks. Every reported child must match its declared phase. */\nexport function assertRouterAutoResponse(\n policyValue: unknown,\n response: unknown,\n served: string | undefined,\n): void {\n const policy = object(policyValue)\n const receipt = object(object(response).tangle_auto)\n const decision = object(receipt.decision)\n const strategies = policy.strategies as unknown[]\n const selected = strategies.map(object).find((strategy) => strategy.id === decision.strategyId)\n if (\n decision.requestedModel !== 'tangle/auto' ||\n decision.policyId !== policy.id ||\n decision.policyRevision !== policy.revision ||\n typeof decision.policyDigest !== 'string' ||\n !selected ||\n decision.selectedModel !== selected.model ||\n served === undefined ||\n !observedModelMatchesDeclared(served, String(selected.model))\n ) {\n throw new ValidationError(\n 'Router Auto response does not match AgentProfile policy/model authority',\n )\n }\n if (!Array.isArray(receipt.calls) || receipt.calls.length === 0) {\n throw new ValidationError('Router Auto response is missing physical call receipts')\n }\n for (const raw of receipt.calls) {\n const call = object(raw)\n const declared =\n call.phase === 'selector'\n ? object(policy.selector).model\n : call.phase === 'review'\n ? object(policy.review).model\n : call.phase === 'initial' || call.phase === 'escalation'\n ? strategies.map(object).map((strategy) => strategy.model)\n : []\n const allowed = Array.isArray(declared) ? declared : [declared]\n if (\n typeof call.model !== 'string' ||\n !allowed.some(\n (model) =>\n typeof model === 'string' && observedModelMatchesDeclared(call.model as string, model),\n )\n )\n throw new ValidationError('Router Auto physical call exceeds AgentProfile model authority')\n }\n}\n\n/** The concrete authority declared by an inline Auto policy, including paid assessments. */\nexport function routerAutoDeclaredModels(value: unknown): readonly string[] {\n assertRouterAutoDeclaration(value, undefined)\n const policy = object(value)\n const models = (policy.strategies as unknown[]).map((raw) => String(object(raw).model))\n for (const phase of ['selector', 'review']) {\n if (policy[phase] !== undefined) models.push(String(object(policy[phase]).model))\n }\n return [...new Set(models)]\n}\n","import { ValidationError } from '../errors'\n\n/** Exact retry controls accepted at `AgentProfile.model.metadata.retry`. */\nexport interface RouterRetryPolicy {\n /** Total attempts, including the first request. */\n readonly maxAttempts?: number\n /** Delay before the second attempt. Later delays grow exponentially. */\n readonly initialBackoffMs?: number\n /** Maximum delay between attempts. */\n readonly maxBackoffMs?: number\n /** Symmetric random variation around each delay, from 0 through 1. */\n readonly jitter?: number\n /** HTTP statuses that may be retried. */\n readonly retryStatuses?: ReadonlyArray<number>\n /** Deadline for receiving one attempt's response headers. Zero disables it. */\n readonly requestTimeoutMs?: number\n}\n\nexport interface ResolvedRouterRetryPolicy {\n readonly maxAttempts: number\n readonly initialBackoffMs: number\n readonly maxBackoffMs: number\n readonly jitter: number\n readonly retryStatuses: ReadonlyArray<number>\n readonly requestTimeoutMs: number\n}\n\nconst maximumTimerMs = 2_147_483_647\nconst defaultRetryStatuses = Object.freeze([408, 425, 429, 500, 502, 503, 504, 520, 522, 524])\nconst retryPolicyKeys = new Set([\n 'initialBackoffMs',\n 'jitter',\n 'maxAttempts',\n 'maxBackoffMs',\n 'requestTimeoutMs',\n 'retryStatuses',\n])\n\n/** Parse untrusted profile/config data once and return an immutable complete policy. */\nexport function resolveRouterRetryPolicy(\n input: unknown,\n context: string,\n): ResolvedRouterRetryPolicy {\n if (\n input !== undefined &&\n (typeof input !== 'object' || input === null || Array.isArray(input))\n ) {\n throw new ValidationError(`${context} must be an object`)\n }\n const policy = input === undefined ? {} : Object.fromEntries(Object.entries(input))\n const unknown = Object.keys(policy).filter((key) => !retryPolicyKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(`${context} has unsupported fields: ${unknown.join(', ')}`)\n }\n const maxAttempts = positiveInteger(policy.maxAttempts, 5, `${context}.maxAttempts`)\n const initialBackoffMs = timerInteger(\n policy.initialBackoffMs,\n 1_000,\n `${context}.initialBackoffMs`,\n )\n const maxBackoffMs = timerInteger(policy.maxBackoffMs, 30_000, `${context}.maxBackoffMs`)\n const requestTimeoutMs = timerInteger(\n policy.requestTimeoutMs,\n 0,\n `${context}.requestTimeoutMs`,\n Number.MAX_SAFE_INTEGER - Date.now(),\n )\n const jitter = policy.jitter ?? 0.25\n if (typeof jitter !== 'number' || !Number.isFinite(jitter) || jitter < 0 || jitter > 1) {\n throw new ValidationError(`${context}.jitter must be a finite number from 0 through 1`)\n }\n const retryStatuses = parseRetryStatuses(policy.retryStatuses, context)\n return Object.freeze({\n maxAttempts,\n initialBackoffMs,\n maxBackoffMs,\n jitter,\n retryStatuses,\n requestTimeoutMs,\n })\n}\n\nfunction parseRetryStatuses(value: unknown, context: string): ReadonlyArray<number> {\n if (value === undefined) return defaultRetryStatuses\n if (!Array.isArray(value)) {\n throw new ValidationError(`${context}.retryStatuses must be an array of HTTP statuses`)\n }\n const statuses: number[] = []\n const seen = new Set<number>()\n for (const status of value) {\n if (!Number.isSafeInteger(status) || status < 100 || status > 599) {\n throw new ValidationError(\n `${context}.retryStatuses must contain integer HTTP statuses from 100 through 599`,\n )\n }\n if (seen.has(status)) {\n throw new ValidationError(`${context}.retryStatuses must not contain duplicates`)\n }\n seen.add(status)\n statuses.push(status)\n }\n return Object.freeze(statuses)\n}\n\nfunction positiveInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed < 1) {\n throw new ValidationError(`${context} must be a positive safe integer`)\n }\n return parsed\n}\n\nfunction timerInteger(\n value: unknown,\n fallback: number,\n context: string,\n maximum = maximumTimerMs,\n): number {\n const parsed = value ?? fallback\n if (\n typeof parsed !== 'number' ||\n !Number.isSafeInteger(parsed) ||\n parsed < 0 ||\n parsed > maximum\n ) {\n throw new ValidationError(\n `${context} must be a nonnegative safe integer no greater than ${maximum}`,\n )\n }\n return parsed\n}\n","/**\n * `assertModelAllowed` — a fail-loud guard that restricts a run to a chosen subset of\n * models. The two front doors (`supervise()` / `improve()`) call it once per configured\n * model at resolve time, so a run that names a model outside the allowed set throws before\n * any compute is spent — never silently swapped or silently allowed.\n */\nimport { HARNESS_NATIVE_MODEL } from '@tangle-network/agent-eval'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../../errors'\nimport { agentHarness } from '../harness-role'\nimport { routerAutoDeclaredModels } from '../router-auto-evidence'\nimport { type ResolvedRouterRetryPolicy, resolveRouterRetryPolicy } from '../router-retry-policy'\n\n/**\n * Return the model id an executor may send to a provider.\n *\n * Eval stamps {@link HARNESS_NATIVE_MODEL} into a profile when model selection is deliberately\n * delegated to the configured runtime. That marker belongs in experiment identity and cost\n * admission; it is not a provider model id.\n */\nexport function concreteModelId(model: string | undefined): string | undefined {\n if (model === undefined) return undefined\n const id = model.trim()\n return id.length > 0 && !isHarnessNativeModel(id) ? id : undefined\n}\n\n/** Whether a model value delegates selection to the chosen execution system. */\nexport function isHarnessNativeModel(model: string | undefined): boolean {\n return model?.trim() === HARNESS_NATIVE_MODEL\n}\n\n/** Return a profile's explicitly selected provider model, if it has one. */\nexport function concreteProfileModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n return concreteModelId(profile.model?.default)\n}\n\n/**\n * Return the model id for a direct provider request.\n *\n * A portable profile can qualify its model with the selected provider. The direct endpoint already\n * selects that provider, so remove only the exact matching prefix. Preserve every other prefix\n * because it can identify a provider-owned nested route, such as `anthropic/claude-sonnet`.\n */\nexport function profileProviderModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider?.trim()\n if (!model || !provider || !model.startsWith(`${provider}/`)) return model\n return concreteModelId(model.slice(provider.length + 1))\n}\n\n/** The full cli-bridge wire id declared by a profile: harness/provider/model. */\nexport function profileBridgeWireModel(\n profile: Pick<AgentProfile, 'harness' | 'model'>,\n): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider\n const harness = agentHarness(profile.harness)\n const modelWithoutHarness =\n model && harness && model.startsWith(`${harness}/`) ? model.slice(harness.length + 1) : model\n const providerModel = modelWithoutHarness\n ? provider && !modelWithoutHarness.startsWith(`${provider}/`)\n ? `${provider}/${modelWithoutHarness}`\n : modelWithoutHarness\n : undefined\n if (!harness) return providerModel\n if (!providerModel) return harness\n return providerModel.startsWith(`${harness}/`) ? providerModel : `${harness}/${providerModel}`\n}\n\n/**\n * Refuse an incomplete execution identity before any backend may fill it from ambient config.\n * `AgentProfile` is the sole behavioral authority: harness, provider, and concrete model all\n * participate in its digest. Eval's runtime-selected marker is a matrix-planning value, never an\n * executable model.\n */\nexport function assertExecutableAgentProfile(profile: AgentProfile, context: string): void {\n if (profile.harness === undefined) {\n throw new ConfigError(`${context}: AgentProfile.harness must be explicit before execution`)\n }\n const declared = profile.model?.default\n const model = concreteModelId(declared)\n if (!model) {\n const reason = isHarnessNativeModel(declared) ? 'runtime-selected' : 'missing'\n throw new ConfigError(\n `${context}: AgentProfile.model.default is ${reason}; execution requires a concrete model`,\n )\n }\n if (!profile.model?.provider?.trim()) {\n throw new ConfigError(\n `${context}: AgentProfile.model.provider must be explicit before execution`,\n )\n }\n}\n\n/**\n * Separate completion ceilings an exact profile may request.\n *\n * They are distinct because providers do not share one meaning for a single number: measured\n * through the Tangle Router on 2026-08-10, `glm-5.2` accepted `max_tokens: 8` and still billed 135\n * completion tokens — 132 reasoning, 3 visible — while `max_completion_tokens: 256` bounded the\n * total. A path that cannot enforce a requested ceiling refuses the run instead of sending a\n * number that means something else there.\n */\nexport interface ProfileTokenLimits {\n /** Visible answer tokens, from `AgentProfile.model.maxVisibleOutputTokens`. */\n readonly visible?: number\n /** Hidden reasoning tokens, from `AgentProfile.model.maxReasoningTokens`. */\n readonly reasoning?: number\n /** Visible and reasoning tokens together, from `AgentProfile.model.maxTotalOutputTokens`. */\n readonly total?: number\n}\n\n/** The ceilings one execution path actually sends, in the request fields it sends them as. */\nexport interface AppliedTokenLimits {\n /** Sent as `max_tokens`. */\n readonly maxTokens?: number\n /** Sent as `max_completion_tokens`. */\n readonly maxCompletionTokens?: number\n}\n\n/** What a path was asked to enforce and what it sent, for the execution receipt. */\nexport interface TokenLimitDecision {\n readonly requested: ProfileTokenLimits\n readonly applied: AppliedTokenLimits\n}\n\n/** The execution paths that lower a profile into a provider request. */\nexport type ModelExecutionPath = 'router' | 'bridge' | 'sandbox' | 'provider'\n\n/** Generation and loop controls that may affect one model execution. */\nexport interface ProfileModelExecutionSettings {\n readonly temperature?: number\n /** Completion ceilings the profile requested. Empty when it requested none. */\n readonly tokenLimits: ProfileTokenLimits\n readonly retry?: ResolvedRouterRetryPolicy\n readonly seed?: number\n readonly toolChoice?: 'auto' | 'required' | 'none'\n readonly extraBody?: Readonly<Record<string, unknown>>\n /** Zero means no turn-count cap; conserved budgets and deadlines still apply. */\n readonly maxTurns?: number\n /**\n * Take each Router completion over SSE, with or without tools. The Router's request deadline ends\n * when response headers are committed, so a long thinking-model answer needs a stream to finish.\n * Requires the HTTP transport; an injected buffered `complete` transport is refused.\n */\n readonly stream?: boolean\n}\n\nconst PROFILE_MODEL_METADATA_KEYS = new Set([\n 'extraBody',\n 'maxTurns',\n 'retry',\n 'seed',\n 'stream',\n 'temperature',\n 'toolChoice',\n])\n\n/**\n * Read execution controls from the exact profile and reject unknown controls.\n * Credential intent reaches environment providers unchanged; other paths cannot enforce it.\n * Backends receive endpoint/auth and executable ports only; they cannot silently alter behavior.\n */\nexport function profileModelExecutionSettings(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n path: ModelExecutionPath = 'router',\n): ProfileModelExecutionSettings {\n const metadata = profile.model?.metadata ?? {}\n if (metadata.maxTokens !== undefined) {\n throw new ConfigError(\n `${context}: AgentProfile.model.metadata.maxTokens is ambiguous across providers; declare AgentProfile.model.maxVisibleOutputTokens, maxReasoningTokens, or maxTotalOutputTokens instead`,\n )\n }\n const unknown = Object.keys(metadata).filter(\n (key) =>\n !PROFILE_MODEL_METADATA_KEYS.has(key) && !(path === 'provider' && key === 'credentialSource'),\n )\n if (unknown.length > 0) {\n throw new ConfigError(\n `${context}: unsupported AgentProfile.model.metadata fields: ${unknown.join(', ')}`,\n )\n }\n if (\n metadata.credentialSource !== undefined &&\n metadata.credentialSource !== 'managed' &&\n metadata.credentialSource !== 'subscription'\n ) {\n throw new ConfigError(\n `${context}: AgentProfile.model.metadata.credentialSource must be managed or subscription`,\n )\n }\n const temperature = finiteNumber(metadata.temperature, `${context}: temperature`)\n const tokenLimits = profileTokenLimits(profile, context)\n const retryInput = metadata.retry\n const retry =\n retryInput === undefined\n ? undefined\n : resolveRouterRetryPolicy(retryInput, `${context}: AgentProfile.model.metadata.retry`)\n const seed = safeInteger(metadata.seed, `${context}: seed`)\n const maxTurns = nonnegativeInteger(metadata.maxTurns, `${context}: maxTurns`)\n const stream = optionalBoolean(metadata.stream, `${context}: stream`)\n const toolChoice = metadata.toolChoice\n if (\n toolChoice !== undefined &&\n toolChoice !== 'auto' &&\n toolChoice !== 'required' &&\n toolChoice !== 'none'\n ) {\n throw new ConfigError(`${context}: toolChoice must be auto, required, or none`)\n }\n const extraBody = metadata.extraBody\n if (\n extraBody !== undefined &&\n (typeof extraBody !== 'object' || extraBody === null || Array.isArray(extraBody))\n ) {\n throw new ConfigError(`${context}: extraBody must be an object`)\n }\n return {\n ...(temperature !== undefined ? { temperature } : {}),\n tokenLimits,\n ...(retry !== undefined ? { retry } : {}),\n ...(seed !== undefined ? { seed } : {}),\n ...(toolChoice !== undefined ? { toolChoice } : {}),\n ...(extraBody !== undefined\n ? { extraBody: Object.freeze({ ...(extraBody as Record<string, unknown>) }) }\n : {}),\n ...(maxTurns !== undefined ? { maxTurns } : {}),\n ...(stream !== undefined ? { stream } : {}),\n }\n}\n\n/**\n * Read the completion ceilings an exact profile declares. The Interface schema already refines\n * these fields, but a profile can reach an executor without a parse, so the same rules are\n * enforced here: positive integers, and no single ceiling above the total.\n */\nexport function profileTokenLimits(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n): ProfileTokenLimits {\n const model = profile.model\n const visible = positiveInteger(\n model?.maxVisibleOutputTokens,\n `${context}: maxVisibleOutputTokens`,\n )\n const reasoning = positiveInteger(model?.maxReasoningTokens, `${context}: maxReasoningTokens`)\n const total = positiveInteger(model?.maxTotalOutputTokens, `${context}: maxTotalOutputTokens`)\n if (total !== undefined) {\n for (const [name, value] of [\n ['maxVisibleOutputTokens', visible],\n ['maxReasoningTokens', reasoning],\n ] as const) {\n if (value !== undefined && value > total) {\n throw new ConfigError(\n `${context}: AgentProfile.model.${name} (${value}) exceeds maxTotalOutputTokens (${total})`,\n )\n }\n }\n }\n return {\n ...(visible !== undefined ? { visible } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n ...(total !== undefined ? { total } : {}),\n }\n}\n\n/**\n * Lower the requested ceilings onto one execution path, or refuse the run before any paid\n * transport.\n *\n * - Router and OpenAI-compatible routes send the visible ceiling as `max_tokens` and the total as\n * `max_completion_tokens`.\n * - The CLI Bridge lowers ONE completion cap into the run's model catalog, so it carries the total\n * as `max_tokens` and cannot bound the visible half on its own.\n * - The Sandbox and environment-provider paths expose no completion cap at all.\n * - No route publishes a reasoning-token budget, so a reasoning ceiling is refused everywhere.\n * `AgentProfile.model.reasoningEffort` is an intensity dial, not a token bound.\n */\nexport function enforceTokenLimits(\n limits: ProfileTokenLimits,\n path: ModelExecutionPath,\n context: string,\n): TokenLimitDecision {\n const refuse = (field: string, reason: string): never => {\n throw new ConfigError(\n `${context}: AgentProfile.model.${field} cannot be enforced on the ${path} path (${reason}); remove the ceiling or select a path that enforces it`,\n )\n }\n if (limits.reasoning !== undefined) {\n refuse('maxReasoningTokens', 'no route exposes a reasoning-token budget')\n }\n if (path === 'router') {\n return {\n requested: limits,\n applied: {\n ...(limits.visible !== undefined ? { maxTokens: limits.visible } : {}),\n ...(limits.total !== undefined ? { maxCompletionTokens: limits.total } : {}),\n },\n }\n }\n if (path === 'bridge') {\n if (limits.visible !== undefined) {\n refuse('maxVisibleOutputTokens', 'the bridge lowers one completion cap covering both halves')\n }\n return {\n requested: limits,\n applied: {\n ...(limits.total !== undefined ? { maxTokens: limits.total } : {}),\n },\n }\n }\n if (limits.visible !== undefined) refuse('maxVisibleOutputTokens', 'the backend accepts no cap')\n if (limits.total !== undefined) refuse('maxTotalOutputTokens', 'the backend accepts no cap')\n return { requested: limits, applied: {} }\n}\n\nfunction finiteNumber(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new ConfigError(`${context} must be a finite number`)\n }\n return value\n}\n\nfunction safeInteger(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value)) throw new ConfigError(`${context} must be a safe integer`)\n return value as number\n}\n\nfunction positiveInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 1) {\n throw new ConfigError(`${context} must be positive`)\n }\n return parsed\n}\n\nfunction nonnegativeInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 0) {\n throw new ConfigError(`${context} must be nonnegative`)\n }\n return parsed\n}\n\nfunction optionalBoolean(value: unknown, context: string): boolean | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'boolean') throw new ConfigError(`${context} must be boolean`)\n return value\n}\n\n/**\n * Throw a `ConfigError` when `allowed` is set, `model` is defined, and `model` is not a\n * member of `allowed`. No-op when `allowed` is unset (the unrestricted default) or when\n * `model` is undefined (nothing was configured to check).\n */\nexport function assertModelAllowed(\n model: string | undefined,\n allowed: readonly string[] | undefined,\n): void {\n if (!allowed || model === undefined) return\n if (!allowed.includes(model)) {\n throw new ConfigError(\n `model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`,\n )\n }\n}\n\n/** Check every canonical model-bearing field in a complete profile, including the models a\n * backend may select for cheap work, named subagents, or modes.\n *\n * Every compared value is a bare model id. The composed `harness/provider/model` wire id\n * (`profileBridgeWireModel`) is neither built nor compared here, so this admits any route that\n * declares an allowed id, and a qualified entry in `allowed` matches nothing. Route pinning\n * belongs to `SuperviseOptions.authorizeSpawn`. */\nexport function assertProfileModelsAllowed(\n profile: AgentProfile,\n allowed: readonly string[] | undefined,\n): void {\n assertModelAllowed(profile.model?.default, allowed)\n assertModelAllowed(profile.model?.small, allowed)\n if (profile.model?.default === 'tangle/auto') {\n const extra = profile.model.metadata?.extraBody\n const policy =\n extra !== null && typeof extra === 'object'\n ? (extra as Record<string, unknown>).auto\n : undefined\n for (const model of routerAutoDeclaredModels(policy)) assertModelAllowed(model, allowed)\n }\n for (const subagent of Object.values(profile.subagents ?? {})) {\n assertModelAllowed(subagent.model, allowed)\n }\n for (const mode of Object.values(profile.modes ?? {})) {\n assertModelAllowed(mode.model, allowed)\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,MAAM,qCAA0C,IAAI,IAAY,CAAC,UAAgC,CAAC;;;;AAKlG,SAAgB,iBAAmC,SAA6C;CAC9F,OAAO,WAAW,QAAQ,CAAC,mBAAmB,IAAI,OAAO;AAC3D;;;AAIA,SAAgB,aAA+B,SAA8C;CAC3F,OAAO,iBAAiB,OAAO,IAAI,UAAU,KAAA;AAC/C;;;ACpCA,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;;AAkBzB,SAAgB,6BAA6B,UAAkB,UAA2B;CACxF,MAAM,mBAAmB,mBAAmB,QAAQ;CACpD,MAAM,mBAAmB,mBAAmB,QAAQ;CACpD,IAAI,CAAC,oBAAoB,CAAC,kBAAkB,OAAO;CACnD,IACE,iBAAiB,aAAa,KAAA,MAC7B,iBAAiB,aAAa,iBAAiB,YAC9C,iBAAiB,iBAAiB,iBAAiB,eAErD,OAAO;CAET,OAAO,oBAAoB,iBAAiB,MAAM,iBAAiB,IAAI;AACzE;;AAGA,SAAgB,2BAA2B,SAAiB,MAAkC;CAC5F,MAAM,kBAAkB,mBAAmB,OAAO;CAClD,MAAM,eAAe,mBAAmB,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;CAE5C,KAAK,MAAM,QAAQ,OAAO,OAAO,QAAQ,SAAS,CAAC,CAAC,GAClD,mBAAmB,KAAK,OAAO,OAAO;AAE1C"}
@@ -1,8 +1,8 @@
1
- import { Cr as abortError$1, Kt as taskToPrompt, Li as finalizeRuntimeOwnedPendingExecutor, Mr as contentAddress, Pi as attestRuntimeOwnedPendingExecutor, Qi as executableAgentProfileSnapshot, Vi as newExecutionAttemptId, Xt as createInbox, _a as abortError, _r as retainedCreateMaterial, at as interactiveAdmissionSeamKey, n as createRootHandle, r as createSupervisor, st as readWorkerInteractiveBinding, ta as detachedSnapshot, ut as startRetainedInteractiveRun, vr as destroyInteractiveEnvironment, wr as linkAbort, yr as environmentGone } from "./supervisor-yX008JOQ.js";
1
+ import { Cr as abortError$1, Kt as taskToPrompt, Li as finalizeRuntimeOwnedPendingExecutor, Mr as contentAddress, Pi as attestRuntimeOwnedPendingExecutor, Qi as executableAgentProfileSnapshot, Vi as newExecutionAttemptId, Xt as createInbox, _a as abortError, _r as retainedCreateMaterial, at as interactiveAdmissionSeamKey, n as createRootHandle, r as createSupervisor, st as readWorkerInteractiveBinding, ta as detachedSnapshot, ut as startRetainedInteractiveRun, vr as destroyInteractiveEnvironment, wr as linkAbort, yr as environmentGone } from "./supervisor-DwfUsy8w.js";
2
2
  import { tt as sleep, yt as armDeadlineTimer } from "./workspace-streams-BEvSX97P.js";
3
3
  import { a as concreteProfileModel } from "./model-policy-DhvyZ8-O.js";
4
4
  import { a as writeAtomicDurableFile } from "./durable-file-DWQA4ooo.js";
5
- import { N as createCoordinationTools, S as createFileRunContext, n as createSteerAcknowledger, t as createCancelAcknowledger } from "./coordination-driver-26qkTbVh.js";
5
+ import { N as createCoordinationTools, S as createFileRunContext, n as createSteerAcknowledger, t as createCancelAcknowledger } from "./coordination-driver-DKoxt1wL.js";
6
6
  import { h as supervisorRunDir } from "./run-layout-DSCWdbX2.js";
7
7
  import { agentInteractiveSessionControlClaimRequestDigest, agentInteractiveSessionPromptRequestDigest, agentInteractiveSessionStopRequestDigest, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest } from "@tangle-network/agent-interface";
8
8
  import { randomUUID } from "node:crypto";
@@ -999,4 +999,4 @@ function writeState(path, state) {
999
999
  //#endregion
1000
1000
  export { workerFromInteractiveProvider as n, claimRetainedInteractiveControl as r, provisionSupervisor as t };
1001
1001
 
1002
- //# sourceMappingURL=provision-supervisor-nV0XW_vi.js.map
1002
+ //# sourceMappingURL=provision-supervisor-DyIZEbwJ.js.map