@tangle-network/agent-runtime 0.289.2 → 0.291.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-ClgRxMQ9.js → activation-BPZL1WCG.js} +2 -2
- package/dist/{activation-ClgRxMQ9.js.map → activation-BPZL1WCG.js.map} +1 -1
- package/dist/{activation-BH2oPn09.d.ts → activation-D8DOMMZc.d.ts} +3 -3
- package/dist/agent.d.ts +2 -2
- package/dist/agent.js +2 -2
- package/dist/{coordination-driver-CrsMoYmK.js → coordination-driver-CUnF7gfN.js} +3 -2
- package/dist/coordination-driver-CUnF7gfN.js.map +1 -0
- package/dist/{delegate-BtA5G0Zi.js → delegate-B0j4915d.js} +2 -2
- package/dist/{delegate-BtA5G0Zi.js.map → delegate-B0j4915d.js.map} +1 -1
- package/dist/durable.d.ts +2 -2
- package/dist/durable.js +2 -2
- package/dist/{graph-9xDBu--o.js → graph-ByPZb_xc.js} +5 -5
- package/dist/{graph-9xDBu--o.js.map → graph-ByPZb_xc.js.map} +1 -1
- package/dist/{improvement-cycle-Rq1wYTxJ.js → improvement-cycle-DipoyAM3.js} +4 -4
- package/dist/{improvement-cycle-Rq1wYTxJ.js.map → improvement-cycle-DipoyAM3.js.map} +1 -1
- package/dist/{index-w7xjlAcL.d.ts → index-D-5e8mss.d.ts} +16 -18
- package/dist/index.d.ts +7 -7
- package/dist/index.js +9 -9
- package/dist/intelligence.d.ts +3 -3
- package/dist/intelligence.js +4 -4
- package/dist/kernel.d.ts +4 -4
- package/dist/kernel.js +10 -10
- package/dist/{loop-runner-bin-DxZdgqD5.d.ts → loop-runner-bin-Bkw-_LkG.d.ts} +3 -3
- package/dist/{loop-runner-bin-D6vu3zKo.js → loop-runner-bin-DhPBdCux.js} +3 -3
- package/dist/{loop-runner-bin-D6vu3zKo.js.map → loop-runner-bin-DhPBdCux.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +5 -5
- package/dist/mcp/index.js +5 -5
- package/dist/{model-policy-CA5d1YUP.js → model-policy-DydyWTQg.js} +186 -2
- package/dist/model-policy-DydyWTQg.js.map +1 -0
- package/dist/{openai-tools-CWp4nc4r.d.ts → openai-tools-De6m7S4Y.d.ts} +2 -2
- package/dist/profiles.d.ts +2 -2
- package/dist/profiles.js +1 -1
- package/dist/{provision-supervisor-43_bsO7n.js → provision-supervisor-DvEpuocs.js} +9 -26
- package/dist/provision-supervisor-DvEpuocs.js.map +1 -0
- package/dist/{runtime-Coi8gH_G.js → runtime-Ba7oK4M1.js} +9 -9
- package/dist/{runtime-Coi8gH_G.js.map → runtime-Ba7oK4M1.js.map} +1 -1
- package/dist/{search-method-Dooo6JxE.js → search-method-Cs6SLt8I.js} +87 -49
- package/dist/search-method-Cs6SLt8I.js.map +1 -0
- package/dist/{server-xIUtcV4x.js → server-CVRFM3ZF.js} +3 -3
- package/dist/{server-xIUtcV4x.js.map → server-CVRFM3ZF.js.map} +1 -1
- package/dist/{stream-agent-turn-DJqcRoxP.d.ts → stream-agent-turn-n3kOukD_.d.ts} +22 -48
- package/dist/{substrate-C9cGwDJ5.d.ts → substrate-DFWtsdNI.d.ts} +2 -2
- package/dist/{supervise-B_GnmIw0.js → supervise-dYioyGT-.js} +27 -7
- package/dist/supervise-dYioyGT-.js.map +1 -0
- package/dist/{supervisor-CDsr_sZD.js → supervisor-DpUCJtKC.js} +162 -696
- package/dist/supervisor-DpUCJtKC.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +12 -12
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/{types-BPO06pPv.d.ts → types-BFcLI8Ge.d.ts} +5 -1
- package/package.json +5 -5
- package/dist/coordination-driver-CrsMoYmK.js.map +0 -1
- package/dist/model-policy-CA5d1YUP.js.map +0 -1
- package/dist/provision-supervisor-43_bsO7n.js.map +0 -1
- package/dist/search-method-Dooo6JxE.js.map +0 -1
- package/dist/supervise-B_GnmIw0.js.map +0 -1
- package/dist/supervisor-CDsr_sZD.js.map +0 -1
package/dist/kernel.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { $ as waitUntil, $n as
|
|
2
|
-
import { $ as sampleThenRefine, B as officialChecksFromMeta, F as composeCheckSources, G as visibleCheckScore, H as sandboxCheckRunner, I as defaultExtractCandidate, J as defineStrategy, K as adaptiveRefine, L as defaultStructuralRolloutPolicy, N as canDisplace, P as compareCheckOutcomes, Q as sample, R as filterAuthoredAsserts, U as selectBestIndex, V as resolveEntrySymbol, W as structuralRollout, X as refine, Y as depthStrategy, Z as runAgentic, _ as sharedBoxRefusal, at as profileOptimizerModelCall, et as ObservationError, g as sharedBoxPlacement, h as ROUTER_CLIENT_HEADER, it as profileChatClient, lt as collectAgentTurn, m as DEFAULT_SHARED_BOX_WORKERS, nt as observe, p as DEFAULT_SHARED_BOX_RESOURCES, q as breadthStrategy, rt as renderReport, tt as defaultAnalystInstruction, ut as streamAgentTurn, v as sharedWorkerClientName, z as modelAuthoredChecks } from "./search-method-
|
|
3
|
-
import { n as assertModelAllowed, r as assertProfileModelsAllowed } from "./model-policy-
|
|
4
|
-
import { $ as InMemoryCorpus, $t as mcpSecretEnvMetadataKey, A as unsafeInProcessRunner, At as runIsolatedCheck, B as SandboxRunAbortError, Bt as renderPairwiseMarkdown, C as withUntrackedArtifacts, Ct as superviseDispatch, D as patchDelivered, Dt as declaredCheckDigest, E as createSqlRunContext, Et as declaredCheckDeliverable, F as strategyTournament, Ft as leaderboard, G as equalKOnCost, Gt as SqlResultBlobStore, H as printBenchmarkReport, Ht as defaultAuditorInstruction, I as assertStrategyContract, It as pairwiseSignificance, J as runPersonified, Jt as connectStdioMcp, K as trajectoryReport, Kt as SqlSpawnJournal, L as authorStrategy, Lt as renderLeaderboardHtml, M as chatWorkerSeam, Mt as deterministicCompletion, N as createChatSessionStore, Nt as sentinelCompletion, Ot as declaredCheckJudge, P as runStrategyEvolution, Pt as stopSentinel, Q as FileCorpus, Qt as envKeyProvider, R as strategyAuthorContract, Rt as renderLeaderboardMarkdown, S as copyUntrackedIntoClone, St as loopDispatch, T as createFencedSqlRunContext, Tt as checkProgramDigest, U as runBenchmark, Ut as SqlRunOwnershipError, V as openSandboxRun, Vt as auditIntent, W as createPrivateCasArtifactPort, Wt as openSqlRunStore, X as createShapeRegistry, Xt as createMcpEnvironment, Y as builtinShapes, Yt as materializeLocalMcp, Z as registerShape, Zt as sanitizeMcpToolSchema, _ as NOTE_MAX_CHARS, _t as defineLeaderboard, a as localShell, at as pipeline, b as composeWorkerEvidence, bt as inlineSandboxClient, c as createVerifierEnvironment, ct as widen, d as harvestSurfaceDiffs, dt as createScopeAnalyst, en as resolveMcpServerLaunch, et as renderCorpusToInstructions, f as analystsFromRegistry, ft as registryScopeAnalyst, g as EVIDENCE_MAX_CHARS, gt as harvestCorpus, h as worktreeFanout, ht as HarvestError, i as jjWorkspace, it as panel, j as chatTransportExecutor, jt as completionAuthorizes, k as codeModeSupervisorTools, kt as readDeclaredCheck, l as boxSurfaceReader, lt as assertTraceDerivedFindings, m as superviseSurface, mt as inProcessSandboxClient, n as makeFinding, nn as secretEnvOfMcpServer, nt as flatWidenGate, o as runInWorkspace, ot as selectValidWinner, p as failuresAnalyst, pt as observationFromRegistry, q as definePersona, qt as McpSpawnFault, r as gitWorkspace, rn as createTangleSandboxExactProcessProvider, rt as loopUntil, s as createWaterfallCollector, st as verify, t as computeFindingId, tn as resolveSecretEnv, tt as fanout, u as fsSurfaceReader, ut as buildSteerContext, v as VERIFY_TAIL_CHARS, vt as resolveSandboxClient, w as analyzeTrace, wt as assertDeclaredCheck, x as settledWorkerOut, xt as loopCampaignDispatch, y as closingWorkerNote, yt as localSandboxClient, z as strategyAuthorSystemPrompt, zt as renderLeaderboardSvg } from "./runtime-
|
|
5
|
-
import { E as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, I as createEventBus, L as defaultToolDetectors, N as normalizeAnalyzeOnSettle, O as canonicalFindingEvent, R as watchTrace, _ as renderAnytimeTable, a as allOf, b as withRunContext, c as createProgressTracker, f as sampleFromSettled, g as plateauLength, h as bestSoFar, i as finalizeBestDelivered, l as noProgressFor, m as areaUnderCurve, o as allWorkersStalled, p as anytimeReport, s as anyOf, u as plateau, v as createFileRunContext, x as FileCoordinationLog, y as createInMemoryRunContext } from "./coordination-driver-
|
|
6
|
-
import { C as gateOnDeliverable, S as serveCoordinationMcp, b as composeReentryTask, c as resolveWorkerSpawnRetry, d as assertCoordinationBinding, l as retryPreSpawnRefusals, m as supervisorAgent, o as workerFromBackend, p as resolveSupervisorProfile, r as supervise, s as isPreSpawnExecutorFailure, t as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, u as withWorkerSpawnRetry, w as mapExecutorResult, x as createSupervisorSpanRecorder, y as UNPROVEN_CONTINUITY } from "./supervise-
|
|
1
|
+
import { $ as waitUntil, $n as captureWorkerTraceEvidence, $t as claimsAuthority, An as providerAsExecutor, At as cliInPlaceExecutor, Bn as FileResultBlobStore, Br as createOtelExporter, Cn as captureBeforeDestroy, Ct as recoverRetainedInteractiveRun, D as passedItems, Dt as rollingDispatch, E as failedItems, Er as persistHarnessTranscript, Et as queueOf, Fn as createPushTraceSource, Ft as createWorktreeCliExecutor, G as settledToIteration, Hn as InMemoryResultBlobStore, Ht as workerTraceEnv, I as createScope, In as decodeToolPart, It as DEFAULT_SANDBOX_STEERING_MAX_TURNS, J as createWaitProbes, Jn as loadSpawnForest, Jt as readWorkerProgress, K as createWorkerSlots, Kt as DEFAULT_STALL_AFTER_MS, Ln as sandboxSessionTraceSource, Lt as createSteerableSandboxSession, Mn as resolveAgentEnvironmentProvider, Mt as createExecutor, N as SUBTREE_RESULT_LIMIT, Nt as createExecutorRegistry, O as verdictFromJudgeScore, Or as contentAddress, Q as validateWaitSpec, Qn as WORKER_TOOL_TRACE_SCHEMA_VERSION, Qt as PEER_MAIL_WIRE_KEY, S as composeContinuationNote, Sn as SandboxEvidenceRetentionError, St as reconnectRetainedInteractiveRun, T as expandQuestions, Tr as harnessTranscriptArtifact, Tt as freeSlots, Un as InMemorySpawnJournal, Ut as workerTraceHeaders, Vn as FileSpawnJournal, Vt as readWorkerTraceContext, Wt as workerTraceSeamKey, X as pollFor, Xn as pendingWaits, Xt as AUTHORITY_MARKERS, Y as isWaitOutcome, Yn as materializeTreeView, Yt as createInbox, Z as timerAt, Zn as replaySpawnTree, Zt as DEFAULT_PEER_MAIL_LIMITS, _ as CheckUnavailableError, _n as isTerminalDecision, _t as workerInteractiveAdmissionFile, a as collectDelivered, aa as extractLlmCallEvent, ar as ReservationWaitRefused, bn as probeSandboxCapabilities, bt as workerInteractiveBindingFile, ca as mapSandboxToolEvent, cn as addHarnessUsage, d as classifyDriverFailure, da as sandboxProgressEvents, dn as readCodexRolloutSession, en as createPeerMailbox, fa as sumSandboxUsage, g as CONTINUATION_FACTS, gn as defaultSelectWinner, gr as startRetainedRunInEnvironment, gt as readWorkerInteractiveAdmissions, h as CONTINUATIONS_DIR, hr as startRetainedRun, i as bestDelivered, ia as createSandboxUsageLedger, ir as BudgetReconcileFault, ja as decodeHarnessUsage, jn as providerAsSandboxClient, jt as cliWorktreeExecutor, kn as createAgentEnvironmentProviderRegistry, l as DriverAttemptsExhaustedError, ln as createCodexRolloutStoreReader, m as upstreamUnavailableSignal, mn as TERMINAL_DECISIONS, mr as recoverRetainedRun, n as createRootHandle, nn as peerMailTools, nr as workerTraceAnalysisStore, o as pickBestDelivered, p as summarizeDriverAttempts, pr as reconnectRetainedRun, qt as createActivityLog, r as createSupervisor, ra as createSandboxToolPartState, rn as peerMailVerbNames, s as runFinalizer, sa as mapSandboxEvent, sr as createBudgetPool, t as DEFAULT_MAX_DEPTH, ta as assertSandboxServedModel, tn as isPeerMailEnvelope, tr as parseWorkerToolTraceArtifact, ua as sandboxEventServedBackend, un as harnessUsageIsEmpty, ur as spendFromUsageEvents, v as admitContinuationPolicy, vn as runAgentRounds, vt as attachWorker, w as distillFindings, wr as captureHarnessTranscript, wt as startRetainedInteractiveRun, x as checkVerdictOf, xn as acquireSandbox, xt as workerInteractiveBindingsDir, y as admitFinding, yn as createSandboxLineage, yt as readWorkerInteractiveBinding, zr as createOpenInferenceFileExporter, zt as createInPlaceCliExecutor } from "./supervisor-DpUCJtKC.js";
|
|
2
|
+
import { $ as sampleThenRefine, B as officialChecksFromMeta, F as composeCheckSources, G as visibleCheckScore, H as sandboxCheckRunner, I as defaultExtractCandidate, J as defineStrategy, K as adaptiveRefine, L as defaultStructuralRolloutPolicy, N as canDisplace, P as compareCheckOutcomes, Q as sample, R as filterAuthoredAsserts, U as selectBestIndex, V as resolveEntrySymbol, W as structuralRollout, X as refine, Y as depthStrategy, Z as runAgentic, _ as sharedBoxRefusal, at as profileOptimizerModelCall, et as ObservationError, g as sharedBoxPlacement, h as ROUTER_CLIENT_HEADER, it as profileChatClient, lt as collectAgentTurn, m as DEFAULT_SHARED_BOX_WORKERS, nt as observe, p as DEFAULT_SHARED_BOX_RESOURCES, q as breadthStrategy, rt as renderReport, tt as defaultAnalystInstruction, ut as streamAgentTurn, v as sharedWorkerClientName, z as modelAuthoredChecks } from "./search-method-Cs6SLt8I.js";
|
|
3
|
+
import { n as assertModelAllowed, r as assertProfileModelsAllowed } from "./model-policy-DydyWTQg.js";
|
|
4
|
+
import { $ as InMemoryCorpus, $t as mcpSecretEnvMetadataKey, A as unsafeInProcessRunner, At as runIsolatedCheck, B as SandboxRunAbortError, Bt as renderPairwiseMarkdown, C as withUntrackedArtifacts, Ct as superviseDispatch, D as patchDelivered, Dt as declaredCheckDigest, E as createSqlRunContext, Et as declaredCheckDeliverable, F as strategyTournament, Ft as leaderboard, G as equalKOnCost, Gt as SqlResultBlobStore, H as printBenchmarkReport, Ht as defaultAuditorInstruction, I as assertStrategyContract, It as pairwiseSignificance, J as runPersonified, Jt as connectStdioMcp, K as trajectoryReport, Kt as SqlSpawnJournal, L as authorStrategy, Lt as renderLeaderboardHtml, M as chatWorkerSeam, Mt as deterministicCompletion, N as createChatSessionStore, Nt as sentinelCompletion, Ot as declaredCheckJudge, P as runStrategyEvolution, Pt as stopSentinel, Q as FileCorpus, Qt as envKeyProvider, R as strategyAuthorContract, Rt as renderLeaderboardMarkdown, S as copyUntrackedIntoClone, St as loopDispatch, T as createFencedSqlRunContext, Tt as checkProgramDigest, U as runBenchmark, Ut as SqlRunOwnershipError, V as openSandboxRun, Vt as auditIntent, W as createPrivateCasArtifactPort, Wt as openSqlRunStore, X as createShapeRegistry, Xt as createMcpEnvironment, Y as builtinShapes, Yt as materializeLocalMcp, Z as registerShape, Zt as sanitizeMcpToolSchema, _ as NOTE_MAX_CHARS, _t as defineLeaderboard, a as localShell, at as pipeline, b as composeWorkerEvidence, bt as inlineSandboxClient, c as createVerifierEnvironment, ct as widen, d as harvestSurfaceDiffs, dt as createScopeAnalyst, en as resolveMcpServerLaunch, et as renderCorpusToInstructions, f as analystsFromRegistry, ft as registryScopeAnalyst, g as EVIDENCE_MAX_CHARS, gt as harvestCorpus, h as worktreeFanout, ht as HarvestError, i as jjWorkspace, it as panel, j as chatTransportExecutor, jt as completionAuthorizes, k as codeModeSupervisorTools, kt as readDeclaredCheck, l as boxSurfaceReader, lt as assertTraceDerivedFindings, m as superviseSurface, mt as inProcessSandboxClient, n as makeFinding, nn as secretEnvOfMcpServer, nt as flatWidenGate, o as runInWorkspace, ot as selectValidWinner, p as failuresAnalyst, pt as observationFromRegistry, q as definePersona, qt as McpSpawnFault, r as gitWorkspace, rn as createTangleSandboxExactProcessProvider, rt as loopUntil, s as createWaterfallCollector, st as verify, t as computeFindingId, tn as resolveSecretEnv, tt as fanout, u as fsSurfaceReader, ut as buildSteerContext, v as VERIFY_TAIL_CHARS, vt as resolveSandboxClient, w as analyzeTrace, wt as assertDeclaredCheck, x as settledWorkerOut, xt as loopCampaignDispatch, y as closingWorkerNote, yt as localSandboxClient, z as strategyAuthorSystemPrompt, zt as renderLeaderboardSvg } from "./runtime-Ba7oK4M1.js";
|
|
5
|
+
import { E as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, I as createEventBus, L as defaultToolDetectors, N as normalizeAnalyzeOnSettle, O as canonicalFindingEvent, R as watchTrace, _ as renderAnytimeTable, a as allOf, b as withRunContext, c as createProgressTracker, f as sampleFromSettled, g as plateauLength, h as bestSoFar, i as finalizeBestDelivered, l as noProgressFor, m as areaUnderCurve, o as allWorkersStalled, p as anytimeReport, s as anyOf, u as plateau, v as createFileRunContext, x as FileCoordinationLog, y as createInMemoryRunContext } from "./coordination-driver-CUnF7gfN.js";
|
|
6
|
+
import { C as gateOnDeliverable, S as serveCoordinationMcp, b as composeReentryTask, c as resolveWorkerSpawnRetry, d as assertCoordinationBinding, l as retryPreSpawnRefusals, m as supervisorAgent, o as workerFromBackend, p as resolveSupervisorProfile, r as supervise, s as isPreSpawnExecutorFailure, t as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, u as withWorkerSpawnRetry, w as mapExecutorResult, x as createSupervisorSpanRecorder, y as UNPROVEN_CONTINUITY } from "./supervise-dYioyGT-.js";
|
|
7
7
|
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";
|
|
8
|
-
import { n as workerFromInteractiveProvider, r as claimRetainedInteractiveControl, t as provisionSupervisor } from "./provision-supervisor-
|
|
9
|
-
import { a as defaultProfileRichnessThresholds, i as assessAuthoredProfile, n as delegate, o as profileRichnessFinding, r as asAuthoredProfile, s as supervisorInstructions, t as defaultDelegateBudget } from "./delegate-
|
|
10
|
-
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-
|
|
11
|
-
export { AUTHORITY_MARKERS, BudgetReconcileFault, CONTINUATIONS_DIR, CONTINUATION_FACTS, CheckUnavailableError, DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, DEFAULT_AWAIT_EVENT_TIMEOUT_MS, DEFAULT_MAX_DEPTH, DEFAULT_PEER_MAIL_LIMITS,
|
|
8
|
+
import { n as workerFromInteractiveProvider, r as claimRetainedInteractiveControl, t as provisionSupervisor } from "./provision-supervisor-DvEpuocs.js";
|
|
9
|
+
import { a as defaultProfileRichnessThresholds, i as assessAuthoredProfile, n as delegate, o as profileRichnessFinding, r as asAuthoredProfile, s as supervisorInstructions, t as defaultDelegateBudget } from "./delegate-B0j4915d.js";
|
|
10
|
+
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-ByPZb_xc.js";
|
|
11
|
+
export { AUTHORITY_MARKERS, BudgetReconcileFault, CONTINUATIONS_DIR, CONTINUATION_FACTS, CheckUnavailableError, DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, DEFAULT_AWAIT_EVENT_TIMEOUT_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, SqlResultBlobStore, SqlRunOwnershipError, SqlSpawnJournal, 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, auditIntent, 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, composeContinuationNote, 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, createSandboxLineage, createSandboxToolPartState, createSandboxUsageLedger, createScope, createScopeAnalyst, createShapeRegistry, createSqlRunContext, createSteerableSandboxSession, createSupervisor, createSupervisorSpanRecorder, createTangleSandboxExactProcessProvider, createVerifierEnvironment, createWaitProbes, createWaterfallCollector, createWorkerSlots, createWorktreeCliExecutor, declaredCheckDeliverable, declaredCheckDigest, declaredCheckJudge, decodeHarnessUsage, decodeToolPart, defaultAnalystInstruction, defaultAuditorInstruction, 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, isWaitOutcome, 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, pendingWaits, persistHarnessTranscript, pickBestDelivered, pipeline, plateau, plateauLength, pollFor, printBenchmarkReport, probeSandboxCapabilities, profileChatClient, profileOptimizerModelCall, profileRichnessFinding, promptHandle, providerAsExecutor, providerAsSandboxClient, provisionSupervisor, queueOf, readCodexRolloutSession, readDeclaredCheck, readRunCancelRequest, readRunCancellation, readWorkerCancelRequests, readWorkerCancellation, readWorkerInteractiveAdmissions, readWorkerInteractiveBinding, readWorkerProgress, readWorkerSteerAcknowledgement, readWorkerSteerRequests, readWorkerTraceContext, reconnectRetainedInteractiveRun, reconnectRetainedRun, recoverRetainedInteractiveRun, recoverRetainedRun, refine, registerShape, registryScopeAnalyst, renderAnytimeTable, renderCorpusToInstructions, renderLeaderboardHtml, renderLeaderboardMarkdown, renderLeaderboardSvg, renderPairwiseMarkdown, renderReport, replaySpawnTree, resolveAgentEnvironmentProvider, resolveEntrySymbol, resolveMcpServerLaunch, resolveSandboxClient, resolveSecretEnv, resolveSupervisorProfile, resolveWorkerSpawnRetry, retryPreSpawnRefusals, rollingDispatch, runAgentRounds, runAgentic, runBenchmark, runCancelRequestFile, runCancellationFile, runFinalizer, runGraph, runInWorkspace, runIsolatedCheck, runPersonified, runStrategyEvolution, 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, superviseSurface, supervisorAgent, supervisorInstructions, supervisorRunDir, supervisorRunsRoot, supervisorWorkersDir, timerAt, trajectoryReport, unsafeInProcessRunner, upstreamUnavailableSignal, validateWaitSpec, verdictFromJudgeScore, verify, visibleCheckScore, waitUntil, watchTrace, widen, withRunContext, withUntrackedArtifacts, withWorkerSpawnRetry, workerCancelRequestsFile, workerCancellationFile, workerCancellationsDir, workerControlLogFile, workerFromBackend, workerFromInteractiveProvider, workerInboxFile, workerInboxFileFromEventDir, workerInteractiveAdmissionFile, workerInteractiveBindingFile, workerInteractiveBindingsDir, workerSteerAcknowledgementFile, workerSteerAcknowledgementsDir, workerSteerRequestFile, workerSteerRequestsDir, workerSteersDir, workerTraceAnalysisStore, workerTraceEnv, workerTraceHeaders, workerTraceSeamKey, worktreeFanout, writeWorkerSteer };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { i as Budget } from "./types-
|
|
1
|
+
import { i as Budget } from "./types-BFcLI8Ge.js";
|
|
2
2
|
import { d as RunAnalystLoopOpts, f as RunAnalystLoopResult } from "./types-zWfqDjeL.js";
|
|
3
|
-
import { O as AuthoredHarness, jt as WorktreePatchArtifact, k as WorktreeFanoutOptions, ts as WinnerStrategy } from "./index-
|
|
3
|
+
import { O as AuthoredHarness, jt as WorktreePatchArtifact, k as WorktreeFanoutOptions, ts as WinnerStrategy } from "./index-D-5e8mss.js";
|
|
4
4
|
import { n as FactCandidate, t as CreateKbGateOptions } from "./kb-gate-C8z2juK8.js";
|
|
5
5
|
import { AgentProfile } from "@tangle-network/agent-interface";
|
|
6
6
|
//#region src/loop-runner.d.ts
|
|
@@ -162,4 +162,4 @@ declare function parseLoopRunnerArgv(argv: string[]): {
|
|
|
162
162
|
};
|
|
163
163
|
//#endregion
|
|
164
164
|
export { researchLoopRunner as _, DELEGATED_LOOP_MODES as a, DelegatedLoopResult as c, ResearchLoopRunnerOptions as d, RunDelegatedLoopOptions as f, isDelegatedLoopMode as g, auditLoopRunner as h, runLoopRunnerCli as i, DelegatedLoopRunner as l, WorktreeLoopRunnerOptions as m, LoopRunnerCliResult as n, DelegatedLoopMode as o, VetoedFact as p, parseLoopRunnerArgv as r, DelegatedLoopRegistry as s, LoopRunnerCliArgs as t, ResearchLoopResult as u, runDelegatedLoop as v, worktreeLoopRunner as y };
|
|
165
|
-
//# sourceMappingURL=loop-runner-bin-
|
|
165
|
+
//# sourceMappingURL=loop-runner-bin-Bkw-_LkG.d.ts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Nt as createExecutorRegistry } from "./supervisor-
|
|
1
|
+
import { Nt as createExecutorRegistry } from "./supervisor-DpUCJtKC.js";
|
|
2
2
|
import { i as ConfigError } from "./errors-DodWX-cb.js";
|
|
3
|
-
import { J as runPersonified, h as worktreeFanout, q as definePersona } from "./runtime-
|
|
3
|
+
import { J as runPersonified, h as worktreeFanout, q as definePersona } from "./runtime-Ba7oK4M1.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-
|
|
246
|
+
//# sourceMappingURL=loop-runner-bin-DhPBdCux.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop-runner-bin-D6vu3zKo.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-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
|
1
|
+
{"version":3,"file":"loop-runner-bin-DhPBdCux.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;CAC7D,SAAS,KAAK;EACZ,OAAO;GACL;GACA,IAAI;GACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GACtD,YAAY,IAAI,IAAI;EACtB;CACF;AACF;;;;;;;;;;;;;;;AA8CA,SAAgB,mBACd,SAC4C;CAC5C,MAAM,QAAQ,eAAuB;EACnC,UAAU,QAAQ;EAClB,YAAY,QAAQ;EACpB,WAAW,QAAQ;EACnB,GAAI,QAAQ,YAAY,KAAA,IAAY,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;EACpE,GAAI,QAAQ,iBAAiB,KAAA,IAAY,EAAE,cAAc,QAAQ,aAAa,IAAI,CAAC;EACnF,GAAI,QAAQ,YAAY,KAAA,IAAY,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;EACpE,GAAI,QA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AAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-
|
|
1
|
+
import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-Bkw-_LkG.js";
|
|
2
2
|
export { LoopRunnerCliArgs, LoopRunnerCliResult, parseLoopRunnerArgv, runLoopRunnerCli };
|
package/dist/loop-runner-bin.js
CHANGED
package/dist/mcp/bin.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { jr as readTraceContextFromEnv } from "../supervisor-DpUCJtKC.js";
|
|
3
3
|
import { i as ConfigError } from "../errors-DodWX-cb.js";
|
|
4
|
-
import { s as supervisorInstructions } from "../delegate-
|
|
5
|
-
import { _ as FileDelegationStore, n as createMcpServer, p as DelegationTaskQueue } from "../server-
|
|
4
|
+
import { s as supervisorInstructions } from "../delegate-B0j4915d.js";
|
|
5
|
+
import { _ as FileDelegationStore, n as createMcpServer, p as DelegationTaskQueue } from "../server-CVRFM3ZF.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.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { At as TraceContext, Mt as mergeTraceEnv, Nt as readTraceContextFromEnv, Pt as traceContextToEnv, ba as SandboxClient, jt as createPropagatingTraceEmitter, la as LoopSandboxPlacement } from "../types-
|
|
2
|
-
import { $d as EventAcknowledgement, $f as eventToSnapshot, $p as DelegationHistoryArgs, Ad as AnalystFindingEvent, Af as SPAWN_RESOURCE_PATH_MAX_BYTES, Am as CoderOutput, Ap as DelegationResumeContext, Bd as ContinuationInstruction, Bf as createMcpServer, Bp as DelegateCodeConfig, Cf as createCoordinationTools, Cm as createDelegationTraceCollector, Cp as createDetachedTurnResumeDriver, Df as questionEscalationTargets, Dm as FileDelegationStore, Dp as runDetachedTurn, Ef as parseAuthoredAnalystDefinition, Em as DelegationStore, Ep as parseDetachedSessionRef, Ff as hostDirectoryReader, Fp as DelegationTaskQueueOptions, Gd as CoordinationToolsOptions, Gf as DelegateError, Gp as DelegateResearchConfig, Hd as CoordinationEvent, Hf as DELEGATE_INPUT_SCHEMA, Hp as DelegateFeedbackArgs, Id as AuthoredAnalystDefinition, If as resolveSpawnResourcePaths, Ip as SubmitInput, Jd as DownMessageAuthorizationInput, Jf as createDelegateHandler, Jp as DelegateUiAuditConfig, Kd as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Kf as DelegateHandlerOptions, Kp as DelegateResearchResult, Ld as AuthoredAnalystLimits, Lf as McpServer, Lp as SubmitOutput, Mf as SpawnResourceRead, Mp as DelegationResumeTick, Nd as AnalystRegistry, Nf as SpawnResourceReader, Np as DelegationRunContext, Od as ANALYST_DEFINITION_BOUNDS, Of as ResolveSpawnResourcePathsResult, Om as FileDelegationStoreOptions, Op as DelegationArgs, Pd as AnalystToolGroupName, Pf as environmentReader, Pp as DelegationTaskQueue, Qd as EscalateQuestion, Qf as InMemoryFeedbackStore, Qp as DelegationFeedbackSnapshot, Rd as AuthorizeDownMessage, Rf as McpServerOptions, Rp as hashIdempotencyInput, Sm as composeLoopTraceEmitters, Sp as RunDetachedTurnOptions, Tm as DelegationStateCorruptError, Tp as formatDetachedSessionRef, Uf as DELEGATE_TOOL_NAME, Up as DelegateFeedbackResult, Vf as DELEGATE_DESCRIPTION, Vp as DelegateCodeResult, Wd as CoordinationTools, Wf as DelegateArgs, Wp as DelegateResearchArgs, Xd as DownMessageDeliveryOutcome, Xf as FeedbackEvent, Xp as DelegateUiAuditRoute, Yd as DownMessageDeliveryAttempt, Yf as validateDelegateArgs, Yp as DelegateUiAuditResult, Zd as DownMessageEvent, Zf as FeedbackStore, Zp as DelegationError, _m as DelegationTraceCaps, _p as DetachedSessionRefParts, af as QuestionEscalationRecord, am as DelegationStatus, ap as DetachedWinnerSelection, bf as WorkerWatchOptions, bm as buildDelegationTraceSpans, bp as DriveTurnCapableBox, cf as QuestionOption, cm as FeedbackRating, cp as coderTaskFromArgs, df as QuestionUrgency, dm as UiAuditLensFilter, dp as DelegationExecutor, ef as MakeWorkerAgent, em as DelegationHistoryEntry, ep as CoderDelegate, ff as SettledWorker, fm as UiAuditorDelegationOutput, fp as FleetHandle, gm as DELEGATION_TRACE_MAX_SPANS, gp as createSiblingSandboxExecutor, hm as DELEGATION_TRACE_MAX_BYTES, hp as createFleetWorkspaceExecutor, if as QuestionEscalationOutcome, im as DelegationResultPayload, ip as DetachedSessionDelegateOptions, jd as AnalystKind, jf as SpawnResourceBytes, jp as DelegationResumeDriver, kd as AnalystDefinitionIssue, kf as ResolvedSpawnResourcePath, km as InMemoryDelegationStore, kp as DelegationRecord, lf as QuestionPolicy, lm as FeedbackRefersTo, lp as detachedSessionDelegate, mm as CappedDelegationTrace, mp as SiblingSandboxExecutorOptions, nf as Question, nm as DelegationProfile, np as CoderReviewer, of as QuestionEscalationTarget, om as DelegationStatusArgs, op as SettleDetachedCoderTurnOptions, pm as delegationProfiles, pp as FleetWorkspaceExecutorOptions, qd as DefinedAnalystRecord, qf as DelegateResult, qp as DelegateUiAuditArgs, rf as QuestionDecision, rm as DelegationProgress, rp as DelegateRunCtx, sf as QuestionLevel, sm as DelegationStatusResult, sp as UiAuditorDelegate, tf as ManagerReentryState, tm as DelegationHistoryResult, tp as CoderReview, uf as QuestionRecord, um as ResearchOutputShape, up as settleDetachedCoderTurn, vm as DelegationTraceCollector, vp as DetachedTurn, wf as downMessageRefusalReasons, wm as DelegationPersistenceError, wp as detachedTurnEvents, xf as analystToolGroupNames, xm as capDelegationTrace, xp as DriveTurnTick, yf as WorkerSpawnContext, ym as DelegationTraceSpan, yp as DetachedTurnResumeDriverOptions, zd as AuthorizedDownMessage, zf as createInProcessTransport, zp as DelegateCodeArgs } from "../index-
|
|
3
|
-
import { An as
|
|
4
|
-
import { d as ResearchSource, o as UiLens } from "../substrate-
|
|
1
|
+
import { At as TraceContext, Mt as mergeTraceEnv, Nt as readTraceContextFromEnv, Pt as traceContextToEnv, ba as SandboxClient, jt as createPropagatingTraceEmitter, la as LoopSandboxPlacement } from "../types-BFcLI8Ge.js";
|
|
2
|
+
import { $d as EventAcknowledgement, $f as eventToSnapshot, $p as DelegationHistoryArgs, Ad as AnalystFindingEvent, Af as SPAWN_RESOURCE_PATH_MAX_BYTES, Am as CoderOutput, Ap as DelegationResumeContext, Bd as ContinuationInstruction, Bf as createMcpServer, Bp as DelegateCodeConfig, Cf as createCoordinationTools, Cm as createDelegationTraceCollector, Cp as createDetachedTurnResumeDriver, Df as questionEscalationTargets, Dm as FileDelegationStore, Dp as runDetachedTurn, Ef as parseAuthoredAnalystDefinition, Em as DelegationStore, Ep as parseDetachedSessionRef, Ff as hostDirectoryReader, Fp as DelegationTaskQueueOptions, Gd as CoordinationToolsOptions, Gf as DelegateError, Gp as DelegateResearchConfig, Hd as CoordinationEvent, Hf as DELEGATE_INPUT_SCHEMA, Hp as DelegateFeedbackArgs, Id as AuthoredAnalystDefinition, If as resolveSpawnResourcePaths, Ip as SubmitInput, Jd as DownMessageAuthorizationInput, Jf as createDelegateHandler, Jp as DelegateUiAuditConfig, Kd as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Kf as DelegateHandlerOptions, Kp as DelegateResearchResult, Ld as AuthoredAnalystLimits, Lf as McpServer, Lp as SubmitOutput, Mf as SpawnResourceRead, Mp as DelegationResumeTick, Nd as AnalystRegistry, Nf as SpawnResourceReader, Np as DelegationRunContext, Od as ANALYST_DEFINITION_BOUNDS, Of as ResolveSpawnResourcePathsResult, Om as FileDelegationStoreOptions, Op as DelegationArgs, Pd as AnalystToolGroupName, Pf as environmentReader, Pp as DelegationTaskQueue, Qd as EscalateQuestion, Qf as InMemoryFeedbackStore, Qp as DelegationFeedbackSnapshot, Rd as AuthorizeDownMessage, Rf as McpServerOptions, Rp as hashIdempotencyInput, Sm as composeLoopTraceEmitters, Sp as RunDetachedTurnOptions, Tm as DelegationStateCorruptError, Tp as formatDetachedSessionRef, Uf as DELEGATE_TOOL_NAME, Up as DelegateFeedbackResult, Vf as DELEGATE_DESCRIPTION, Vp as DelegateCodeResult, Wd as CoordinationTools, Wf as DelegateArgs, Wp as DelegateResearchArgs, Xd as DownMessageDeliveryOutcome, Xf as FeedbackEvent, Xp as DelegateUiAuditRoute, Yd as DownMessageDeliveryAttempt, Yf as validateDelegateArgs, Yp as DelegateUiAuditResult, Zd as DownMessageEvent, Zf as FeedbackStore, Zp as DelegationError, _m as DelegationTraceCaps, _p as DetachedSessionRefParts, af as QuestionEscalationRecord, am as DelegationStatus, ap as DetachedWinnerSelection, bf as WorkerWatchOptions, bm as buildDelegationTraceSpans, bp as DriveTurnCapableBox, cf as QuestionOption, cm as FeedbackRating, cp as coderTaskFromArgs, df as QuestionUrgency, dm as UiAuditLensFilter, dp as DelegationExecutor, ef as MakeWorkerAgent, em as DelegationHistoryEntry, ep as CoderDelegate, ff as SettledWorker, fm as UiAuditorDelegationOutput, fp as FleetHandle, gm as DELEGATION_TRACE_MAX_SPANS, gp as createSiblingSandboxExecutor, hm as DELEGATION_TRACE_MAX_BYTES, hp as createFleetWorkspaceExecutor, if as QuestionEscalationOutcome, im as DelegationResultPayload, ip as DetachedSessionDelegateOptions, jd as AnalystKind, jf as SpawnResourceBytes, jp as DelegationResumeDriver, kd as AnalystDefinitionIssue, kf as ResolvedSpawnResourcePath, km as InMemoryDelegationStore, kp as DelegationRecord, lf as QuestionPolicy, lm as FeedbackRefersTo, lp as detachedSessionDelegate, mm as CappedDelegationTrace, mp as SiblingSandboxExecutorOptions, nf as Question, nm as DelegationProfile, np as CoderReviewer, of as QuestionEscalationTarget, om as DelegationStatusArgs, op as SettleDetachedCoderTurnOptions, pm as delegationProfiles, pp as FleetWorkspaceExecutorOptions, qd as DefinedAnalystRecord, qf as DelegateResult, qp as DelegateUiAuditArgs, rf as QuestionDecision, rm as DelegationProgress, rp as DelegateRunCtx, sf as QuestionLevel, sm as DelegationStatusResult, sp as UiAuditorDelegate, tf as ManagerReentryState, tm as DelegationHistoryResult, tp as CoderReview, uf as QuestionRecord, um as ResearchOutputShape, up as settleDetachedCoderTurn, vm as DelegationTraceCollector, vp as DetachedTurn, wf as downMessageRefusalReasons, wm as DelegationPersistenceError, wp as detachedTurnEvents, xf as analystToolGroupNames, xm as capDelegationTrace, xp as DriveTurnTick, yf as WorkerSpawnContext, ym as DelegationTraceSpan, yp as DetachedTurnResumeDriverOptions, zd as AuthorizedDownMessage, zf as createInProcessTransport, zp as DelegateCodeArgs } from "../index-D-5e8mss.js";
|
|
3
|
+
import { An as CodexExecutionPolicy, Bn as runLocalHarness, Cn as GitRunner, Dn as createWorktree, En as captureWorktreeDiff, Fn as LocalHarnessResult, In as RunLocalHarnessOptions, Ln as harnessSupportsReasoningEffort, Mn as DEFAULT_LOCAL_HARNESS, Nn as LOCAL_HARNESSES, On as removeWorktree, Pn as LocalHarness, Rn as localHarnessExecutable, Sn as DiffResult, Tn as WorktreeHandle, _r as McpToolDescriptor, bn as CreateWorktreeOptions, gr as McpToolAnnotations, hr as JsonRpcResponse, jn as CodexTokenUsage, kn as CodexExecutionEvidence, mr as JsonRpcMessage, vr as McpTransport, wn as RemoveWorktreeOptions, xn as DiffOptions, zn as parseCodexTokenUsage } from "../stream-agent-turn-n3kOukD_.js";
|
|
4
|
+
import { d as ResearchSource, o as UiLens } from "../substrate-DFWtsdNI.js";
|
|
5
5
|
import { a as KbGateResult, i as FactJudgeVerdict, n as FactCandidate, o as createKbGate, r as FactJudge, t as CreateKbGateOptions } from "../kb-gate-C8z2juK8.js";
|
|
6
|
-
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-
|
|
6
|
+
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-De6m7S4Y.js";
|
|
7
7
|
import { AgentProfileMcpServer, HarnessType } from "@tangle-network/agent-interface";
|
|
8
8
|
//#region src/mcp/codex-diagnostics.d.ts
|
|
9
9
|
/** Bounded, credential-redacted process context attached when reproducible Codex output fails
|
package/dist/mcp/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $r as runWorktreeHarness, Ar as mergeTraceEnv, Ca as throwAbort, Mr as traceContextToEnv, ci as parseCodexTokenUsage, dt as SPAWN_RESOURCE_PATH_MAX_BYTES, ei as captureWorktreeDiff, ft as environmentReader, ga as deleteBoxSafe, hn as createSandboxForSpec, ii as LOCAL_HARNESSES, jr as readTraceContextFromEnv, kr as createPropagatingTraceEmitter, li as CodexExecutionDiagnosticError, mt as resolveSpawnResourcePaths, ni as removeWorktree, oi as harnessSupportsReasoningEffort, pt as hostDirectoryReader, ri as DEFAULT_LOCAL_HARNESS, si as localHarnessExecutable, ti as createWorktree, vn as runAgentRounds, wa as throwIfAborted, wn as assertBoxlessPromptOptions, xa as sleep } from "../supervisor-DpUCJtKC.js";
|
|
2
2
|
import { i as ConfigError, m as ValidationError } from "../errors-DodWX-cb.js";
|
|
3
|
-
import { t as assertExecutableAgentProfile } from "../model-policy-
|
|
4
|
-
import { O as runCoderChecks, ot as selectValidWinner } from "../runtime-
|
|
5
|
-
import { A as createCoordinationTools, D as analystToolGroupNames, E as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, F as questionEscalationTargets, M as downMessageRefusalReasons, P as parseAuthoredAnalystDefinition, T as ANALYST_DEFINITION_BOUNDS } from "../coordination-driver-
|
|
3
|
+
import { t as assertExecutableAgentProfile } from "../model-policy-DydyWTQg.js";
|
|
4
|
+
import { O as runCoderChecks, ot as selectValidWinner } from "../runtime-Ba7oK4M1.js";
|
|
5
|
+
import { A as createCoordinationTools, D as analystToolGroupNames, E as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, F as questionEscalationTargets, M as downMessageRefusalReasons, P as parseAuthoredAnalystDefinition, T as ANALYST_DEFINITION_BOUNDS } from "../coordination-driver-CUnF7gfN.js";
|
|
6
6
|
import { n as SUPPORTED_PROTOCOL_VERSIONS, r as createStdioToolServer } from "../tool-server-Dqer2M4_.js";
|
|
7
7
|
import { t as createKbGate } from "../kb-gate-DpaSwXVx.js";
|
|
8
8
|
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";
|
|
9
9
|
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-DoQ32vpe.js";
|
|
10
10
|
import { t as coderTaskToPrompt } from "../coder-yhVWbdWc.js";
|
|
11
|
-
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-
|
|
11
|
+
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-CVRFM3ZF.js";
|
|
12
12
|
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";
|
|
13
13
|
import { agentProfileSchema } from "@tangle-network/agent-interface";
|
|
14
14
|
import { randomUUID } from "node:crypto";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { i as ConfigError, m as ValidationError } from "./errors-DodWX-cb.js";
|
|
2
|
+
import { harnessTypeSchema } from "@tangle-network/agent-interface";
|
|
2
3
|
import { HARNESS_NATIVE_MODEL } from "@tangle-network/agent-eval";
|
|
3
4
|
//#region src/runtime/harness-role.ts
|
|
4
5
|
/**
|
|
@@ -22,6 +23,184 @@ function agentHarness(harness) {
|
|
|
22
23
|
return harnessRunsAgent(harness) ? harness : void 0;
|
|
23
24
|
}
|
|
24
25
|
//#endregion
|
|
26
|
+
//#region src/runtime/model-identity.ts
|
|
27
|
+
const SNAPSHOT_TOKEN = /^[A-Za-z0-9._-]+$/u;
|
|
28
|
+
const datedIsoSuffix = /^(.*)-(\d{4})-(\d{2})-(\d{2})$/u;
|
|
29
|
+
const datedCompactSuffix = /^(.*)-(\d{4})(\d{2})(\d{2})$/u;
|
|
30
|
+
const datedMonthSuffix = /^(.*)-(\d{4})-(\d{2})$/u;
|
|
31
|
+
/** Match equivalent bare and provider-qualified spellings without discarding observed identity. */
|
|
32
|
+
function observedModelMatchesDeclared(observed, declared) {
|
|
33
|
+
const observedIdentity = modelIdentityParts(observed);
|
|
34
|
+
const declaredIdentity = modelIdentityParts(declared);
|
|
35
|
+
if (!observedIdentity || !declaredIdentity) return false;
|
|
36
|
+
if (declaredIdentity.snapshot !== void 0 && (observedIdentity.snapshot !== declaredIdentity.snapshot || observedIdentity.snapshotKind !== declaredIdentity.snapshotKind)) return false;
|
|
37
|
+
return equivalentModelBase(observedIdentity.base, declaredIdentity.base);
|
|
38
|
+
}
|
|
39
|
+
/** Merge two observations of one served model while retaining a snapshot-bearing raw identity. */
|
|
40
|
+
function mergeObservedModelIdentity(current, next) {
|
|
41
|
+
const currentIdentity = modelIdentityParts(current);
|
|
42
|
+
const nextIdentity = modelIdentityParts(next);
|
|
43
|
+
if (!currentIdentity || !nextIdentity) return void 0;
|
|
44
|
+
if (!equivalentModelBase(currentIdentity.base, nextIdentity.base)) return void 0;
|
|
45
|
+
if (currentIdentity.snapshot !== void 0 && nextIdentity.snapshot !== void 0 && (currentIdentity.snapshot !== nextIdentity.snapshot || currentIdentity.snapshotKind !== nextIdentity.snapshotKind)) return;
|
|
46
|
+
return currentIdentity.snapshot === void 0 && nextIdentity.snapshot !== void 0 ? next : current;
|
|
47
|
+
}
|
|
48
|
+
/** Return the canonical model and its validated snapshot kind for runtime evidence reduction. */
|
|
49
|
+
function canonicalObservedModelParts(model) {
|
|
50
|
+
const identity = modelIdentityParts(model);
|
|
51
|
+
if (!identity) return void 0;
|
|
52
|
+
const base = identity.base.slice(identity.base.lastIndexOf("/") + 1);
|
|
53
|
+
const canonical = identity.snapshot === void 0 ? base : identity.snapshotKind === "date" ? `${base}-${identity.snapshot}` : `${base}@${identity.snapshot}`;
|
|
54
|
+
return {
|
|
55
|
+
base,
|
|
56
|
+
...identity.snapshot !== void 0 ? { snapshot: identity.snapshot } : {},
|
|
57
|
+
...identity.snapshotKind !== void 0 ? { snapshotKind: identity.snapshotKind } : {},
|
|
58
|
+
canonical
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** Return whether an observed identity includes a provider snapshot. */
|
|
62
|
+
function observedModelHasSnapshot(model) {
|
|
63
|
+
return modelIdentityParts(model)?.snapshot !== void 0;
|
|
64
|
+
}
|
|
65
|
+
function modelIdentityParts(model) {
|
|
66
|
+
if (model.length === 0) return null;
|
|
67
|
+
const at = model.lastIndexOf("@");
|
|
68
|
+
if (at < 0) {
|
|
69
|
+
const dated = datedModelIdentity(model);
|
|
70
|
+
if (dated !== void 0) return dated;
|
|
71
|
+
return modelLeaf(model).length === 0 ? null : { base: model };
|
|
72
|
+
}
|
|
73
|
+
const base = model.slice(0, at);
|
|
74
|
+
const snapshot = model.slice(at + 1);
|
|
75
|
+
if (base.length === 0 || modelLeaf(base).length === 0 || !SNAPSHOT_TOKEN.test(snapshot)) return null;
|
|
76
|
+
return {
|
|
77
|
+
base,
|
|
78
|
+
snapshot,
|
|
79
|
+
snapshotKind: "opaque"
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function equivalentModelBase(observed, declared) {
|
|
83
|
+
const observedPath = modelBaseParts(observed);
|
|
84
|
+
const declaredPath = modelBaseParts(declared);
|
|
85
|
+
if (!samePath(observedPath.path, declaredPath.path)) return false;
|
|
86
|
+
if (observedPath.provider === void 0 || declaredPath.provider === void 0 || observedPath.provider === declaredPath.provider) return true;
|
|
87
|
+
if (observedPath.provider === "tangle-router" || declaredPath.provider === "tangle-router") {
|
|
88
|
+
const router = observedPath.provider === "tangle-router" ? observedPath : declaredPath;
|
|
89
|
+
const upstream = observedPath.provider === "tangle-router" ? declaredPath : observedPath;
|
|
90
|
+
if (upstream.provider === void 0) return false;
|
|
91
|
+
return samePath(router.path, upstream.path) || router.path[0] === upstream.provider && samePath(router.path.slice(1), upstream.path);
|
|
92
|
+
}
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
function modelBaseParts(model) {
|
|
96
|
+
const segments = model.split("/");
|
|
97
|
+
const normalized = segments.length > 1 && isHarnessPrefix(segments[0]) ? segments.slice(1) : segments;
|
|
98
|
+
if (normalized.length === 1) return {
|
|
99
|
+
provider: void 0,
|
|
100
|
+
path: normalized
|
|
101
|
+
};
|
|
102
|
+
return {
|
|
103
|
+
provider: normalized[0],
|
|
104
|
+
path: normalized.slice(1)
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function isHarnessPrefix(segment) {
|
|
108
|
+
return segment !== void 0 && harnessTypeSchema.safeParse(segment).success;
|
|
109
|
+
}
|
|
110
|
+
function samePath(left, right) {
|
|
111
|
+
return left.length === right.length && left.every((segment, index) => segment === right[index]);
|
|
112
|
+
}
|
|
113
|
+
function modelLeaf(model) {
|
|
114
|
+
return model.slice(model.lastIndexOf("/") + 1);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Parse the provider's documented dated snapshot forms.
|
|
118
|
+
*
|
|
119
|
+
* `undefined` means that the model has no dated shape and must be treated as a normal base.
|
|
120
|
+
* `null` means that it has a dated shape but the date is invalid, so identity matching fails.
|
|
121
|
+
*/
|
|
122
|
+
function datedModelIdentity(model) {
|
|
123
|
+
const iso = datedIsoSuffix.exec(model);
|
|
124
|
+
if (iso) {
|
|
125
|
+
const [, base, yearText, monthText, dayText] = iso;
|
|
126
|
+
return buildDatedIdentity(base, `${yearText}-${monthText}-${dayText}`, isValidCalendarDate(yearText, monthText, dayText));
|
|
127
|
+
}
|
|
128
|
+
const compact = datedCompactSuffix.exec(model);
|
|
129
|
+
if (compact) {
|
|
130
|
+
const [, base, yearText, monthText, dayText] = compact;
|
|
131
|
+
return buildDatedIdentity(base, `${yearText}-${monthText}-${dayText}`, isValidCalendarDate(yearText, monthText, dayText));
|
|
132
|
+
}
|
|
133
|
+
const month = datedMonthSuffix.exec(model);
|
|
134
|
+
if (month) {
|
|
135
|
+
const [, base, yearText, monthText] = month;
|
|
136
|
+
return buildDatedIdentity(base, `${yearText}-${monthText}`, isValidCalendarMonth(yearText, monthText));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function buildDatedIdentity(base, snapshot, valid) {
|
|
140
|
+
if (base === void 0 || base.length === 0 || base.endsWith("/")) return void 0;
|
|
141
|
+
return valid ? {
|
|
142
|
+
base,
|
|
143
|
+
snapshot,
|
|
144
|
+
snapshotKind: "date"
|
|
145
|
+
} : null;
|
|
146
|
+
}
|
|
147
|
+
function isValidCalendarDate(yearText, monthText, dayText) {
|
|
148
|
+
if (yearText === void 0 || monthText === void 0 || dayText === void 0) return false;
|
|
149
|
+
const year = Number(yearText);
|
|
150
|
+
const month = Number(monthText);
|
|
151
|
+
const day = Number(dayText);
|
|
152
|
+
if (year < 2e3 || year > 2099 || month < 1 || month > 12 || day < 1 || day > 31) return false;
|
|
153
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
154
|
+
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
|
|
155
|
+
}
|
|
156
|
+
function isValidCalendarMonth(yearText, monthText) {
|
|
157
|
+
if (yearText === void 0 || monthText === void 0) return false;
|
|
158
|
+
const year = Number(yearText);
|
|
159
|
+
const month = Number(monthText);
|
|
160
|
+
return year >= 2e3 && year <= 2099 && month >= 1 && month <= 12;
|
|
161
|
+
}
|
|
162
|
+
//#endregion
|
|
163
|
+
//#region src/runtime/router-auto-evidence.ts
|
|
164
|
+
function object(value) {
|
|
165
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new ValidationError("Router Auto requires an inline policy and routing receipt");
|
|
166
|
+
return value;
|
|
167
|
+
}
|
|
168
|
+
/** Router owns policy parsing. Runtime requires visible model authority before dispatch. */
|
|
169
|
+
function assertRouterAutoDeclaration(value, stream) {
|
|
170
|
+
const policy = object(value);
|
|
171
|
+
if (stream === true) throw new ValidationError("Router Auto requires buffered transport");
|
|
172
|
+
if (policy.version !== 1 || typeof policy.id !== "string" || typeof policy.revision !== "string" || !Array.isArray(policy.strategies) || policy.strategies.length === 0) throw new ValidationError("Router Auto requires a versioned inline policy with concrete strategies");
|
|
173
|
+
for (const raw of policy.strategies) {
|
|
174
|
+
const strategy = object(raw);
|
|
175
|
+
if (typeof strategy.id !== "string" || typeof strategy.model !== "string" || strategy.model === "tangle/auto" || strategy.model.length === 0) throw new ValidationError("Router Auto strategy model authority is missing");
|
|
176
|
+
}
|
|
177
|
+
for (const phase of ["selector", "review"]) if (policy[phase] !== void 0 && typeof object(policy[phase]).model !== "string") throw new ValidationError("Router Auto assessment model authority is missing");
|
|
178
|
+
}
|
|
179
|
+
/** An alias does not waive identity checks. Every reported child must match its declared phase. */
|
|
180
|
+
function assertRouterAutoResponse(policyValue, response, served) {
|
|
181
|
+
const policy = object(policyValue);
|
|
182
|
+
const receipt = object(object(response).tangle_auto);
|
|
183
|
+
const decision = object(receipt.decision);
|
|
184
|
+
const strategies = policy.strategies;
|
|
185
|
+
const selected = strategies.map(object).find((strategy) => strategy.id === decision.strategyId);
|
|
186
|
+
if (decision.requestedModel !== "tangle/auto" || decision.policyId !== policy.id || decision.policyRevision !== policy.revision || typeof decision.policyDigest !== "string" || !selected || decision.selectedModel !== selected.model || served === void 0 || !observedModelMatchesDeclared(served, String(selected.model))) throw new ValidationError("Router Auto response does not match AgentProfile policy/model authority");
|
|
187
|
+
if (!Array.isArray(receipt.calls) || receipt.calls.length === 0) throw new ValidationError("Router Auto response is missing physical call receipts");
|
|
188
|
+
for (const raw of receipt.calls) {
|
|
189
|
+
const call = object(raw);
|
|
190
|
+
const declared = call.phase === "selector" ? object(policy.selector).model : call.phase === "review" ? object(policy.review).model : call.phase === "initial" || call.phase === "escalation" ? strategies.map(object).map((strategy) => strategy.model) : [];
|
|
191
|
+
const allowed = Array.isArray(declared) ? declared : [declared];
|
|
192
|
+
if (typeof call.model !== "string" || !allowed.some((model) => typeof model === "string" && observedModelMatchesDeclared(call.model, model))) throw new ValidationError("Router Auto physical call exceeds AgentProfile model authority");
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** The concrete authority declared by an inline Auto policy, including paid assessments. */
|
|
196
|
+
function routerAutoDeclaredModels(value) {
|
|
197
|
+
assertRouterAutoDeclaration(value, void 0);
|
|
198
|
+
const policy = object(value);
|
|
199
|
+
const models = policy.strategies.map((raw) => String(object(raw).model));
|
|
200
|
+
for (const phase of ["selector", "review"]) if (policy[phase] !== void 0) models.push(String(object(policy[phase]).model));
|
|
201
|
+
return [...new Set(models)];
|
|
202
|
+
}
|
|
203
|
+
//#endregion
|
|
25
204
|
//#region src/runtime/router-retry-policy.ts
|
|
26
205
|
const maximumTimerMs = 2147483647;
|
|
27
206
|
const defaultRetryStatuses = Object.freeze([
|
|
@@ -296,10 +475,15 @@ function assertModelAllowed(model, allowed) {
|
|
|
296
475
|
function assertProfileModelsAllowed(profile, allowed) {
|
|
297
476
|
assertModelAllowed(profile.model?.default, allowed);
|
|
298
477
|
assertModelAllowed(profile.model?.small, allowed);
|
|
478
|
+
if (profile.model?.default === "tangle/auto") {
|
|
479
|
+
const extra = profile.model.metadata?.extraBody;
|
|
480
|
+
const policy = extra !== null && typeof extra === "object" ? extra.auto : void 0;
|
|
481
|
+
for (const model of routerAutoDeclaredModels(policy)) assertModelAllowed(model, allowed);
|
|
482
|
+
}
|
|
299
483
|
for (const subagent of Object.values(profile.subagents ?? {})) assertModelAllowed(subagent.model, allowed);
|
|
300
484
|
for (const mode of Object.values(profile.modes ?? {})) assertModelAllowed(mode.model, allowed);
|
|
301
485
|
}
|
|
302
486
|
//#endregion
|
|
303
|
-
export { concreteProfileModel as a, profileModelExecutionSettings as c,
|
|
487
|
+
export { agentHarness as _, concreteProfileModel as a, profileModelExecutionSettings as c, assertRouterAutoDeclaration as d, assertRouterAutoResponse as f, observedModelMatchesDeclared as g, observedModelHasSnapshot as h, concreteModelId as i, profileProviderModel as l, mergeObservedModelIdentity as m, assertModelAllowed as n, enforceTokenLimits as o, canonicalObservedModelParts as p, assertProfileModelsAllowed as r, profileBridgeWireModel as s, assertExecutableAgentProfile as t, resolveRouterRetryPolicy as u, harnessRunsAgent as v };
|
|
304
488
|
|
|
305
|
-
//# sourceMappingURL=model-policy-
|
|
489
|
+
//# sourceMappingURL=model-policy-DydyWTQg.js.map
|