@tangle-network/agent-runtime 0.325.5 → 0.325.6
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/agent.js +1 -1
- package/dist/index.js +2 -2
- package/dist/kernel.js +1 -1
- package/dist/{loop-runner-bin-CdDJs_hF.js → loop-runner-bin-CrGUj3K9.js} +2 -2
- package/dist/{loop-runner-bin-CdDJs_hF.js.map → loop-runner-bin-CrGUj3K9.js.map} +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/index.js +1 -1
- package/dist/{runtime-B1dDO_VV.js → runtime-urcakzYm.js} +75 -47
- package/dist/runtime-urcakzYm.js.map +1 -0
- package/dist/testing.js +8 -8
- package/package.json +1 -1
- package/dist/runtime-B1dDO_VV.js.map +0 -1
package/dist/agent.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Gr as defineProfileMaterializationContract, Hr as assertProfileMaterialization, Jr as promptControlProfileMaterialization, Kr as fullProfileMaterialization, Qr as renderProfileMaterializationIssues, Ur as assertProfileMaterializes, Vr as AGENT_PROFILE_MATERIALIZATION_AXES, Wi as mapSandboxEvent, Wr as controlProfileMaterialization, Xr as promptOnlyProfileMaterialization, Yr as promptModelProfileMaterialization, Zr as promptResourceProfileMaterialization, ei as sandboxActProfileMaterialization, hn as createSandboxForSpec, ii as worktreeCliProfileMaterialization, qr as profileMaterializationAxes, ri as validateProfileMaterialization } from "./supervisor-Crul0LFI.js";
|
|
2
|
-
import "./runtime-
|
|
2
|
+
import "./runtime-urcakzYm.js";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
5
5
|
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
package/dist/index.js
CHANGED
|
@@ -4,12 +4,12 @@ import { $ as createIterableBackend, Q as streamAgentTurn, X as strategyAuthorMe
|
|
|
4
4
|
import { B as omitTopLevelDigest, F as canonicalCandidateDigest$1, P as canonicalCandidateBytes$1, R as embeddedCandidateArtifact, l as captureAgentCandidateWorkspace, m as persistCandidateOutputArtifact, z as immutableCandidateValue } from "./sandbox-profile-compat-Dq7ujONv.js";
|
|
5
5
|
import { t as assertExecutableAgentProfile } from "./model-policy-CyCUwHed.js";
|
|
6
6
|
import { a as createRuntimeUsageTotals, i as addRuntimeUsage, o as isUsageAmount, t as createAgentImprovementActivationResult } from "./activation-CHJAawWa.js";
|
|
7
|
-
import { $t as McpSpawnFault, en as connectStdioMcp } from "./runtime-
|
|
7
|
+
import { $t as McpSpawnFault, en as connectStdioMcp } from "./runtime-urcakzYm.js";
|
|
8
8
|
import { i as notifyRuntimeHookEvent, n as defineRuntimeHooks, r as notifyRuntimeDecisionPoint, t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
|
|
9
9
|
import { $ as commandVerifier, B as assertCandidateValidator, G as rawTraceDistiller, H as parseExecutionRef, J as normalizeRolloutPolicy, K as ROLLOUT_POLICY_EXTENSION, L as improve, Q as agenticGenerator, R as createCommandProfileTrainer, U as privateValuePaths, W as withMethodRuntimeControls, X as serializeRolloutPolicy, Y as parseRolloutPolicy, Z as structuralRolloutPolicyFromProfile, et as defaultBuildPrompt, q as applyRolloutPolicyToProfile, z as searchMethod } from "./improvement-cycle-VPes2yY3.js";
|
|
10
10
|
import { t as sealAgentCandidateBundle } from "./bundle-KZGUQqRM.js";
|
|
11
11
|
import { r as supervise } from "./supervise-ttbcgYgS.js";
|
|
12
|
-
import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-
|
|
12
|
+
import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-CrGUj3K9.js";
|
|
13
13
|
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "./openai-tools-DoQ32vpe.js";
|
|
14
14
|
import { agentCandidateKnowledgeSchema, agentCandidateWorkspaceManifestMaterialSchema, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sha256DigestSchema } from "@tangle-network/agent-interface";
|
|
15
15
|
import { FAILURE_CLASSES, acquisitionPlansForKnowledgeGaps, blockingKnowledgeEval, canonicalJson, runAgentControlLoop, scoreKnowledgeReadiness, userQuestionsForKnowledgeGaps } from "@tangle-network/agent-eval";
|
package/dist/kernel.js
CHANGED
|
@@ -3,7 +3,7 @@ import { A as resolveEntrySymbol, B as runAgentic, C as compareCheckOutcomes, D
|
|
|
3
3
|
import { bt as DEFAULT_CHECK_IN_IDLE_MS, yt as DEADLINE_CHECK_IN_MESSAGE } from "./sandbox-profile-compat-Dq7ujONv.js";
|
|
4
4
|
import { runTaskQueue } from "./task-queue.js";
|
|
5
5
|
import { n as assertModelAllowed, r as assertProfileModelsAllowed } from "./model-policy-CyCUwHed.js";
|
|
6
|
-
import { $ as runBenchmark, $t as McpSpawnFault, A as connectRemoteSupervisor, At as inlineSandboxClient, B as chatTransportExecutor, Bt as runIsolatedCheck, C as analyzeTrace, Ct as observationFromRegistry, D as compileSearchSpec, Dt as defineLeaderboard, E as assertSearchSpec, Et as harvestCorpus, F as profileRunsForName, Ft as checkProgramDigest, G as assertStrategyContract, Gt as leaderboard, H as createChatSessionStore, Ht as deterministicCompletion, I as recordProfileRun, It as declaredCheckDeliverable, J as strategyAuthorSystemPrompt, Jt as renderLeaderboardMarkdown, K as authorStrategy, Kt as pairwiseSignificance, L as patchDelivered, Lt as declaredCheckDigest, M as loadProfile, Mt as loopDispatch, N as pickBestProfile, Nt as superviseDispatch, O as searchPresets, Ot as resolveSandboxClient, P as profileRegistry, Pt as assertDeclaredCheck, Q as printBenchmarkReport, Qt as openSqlRunStore, Rt as declaredCheckJudge, S as withUntrackedArtifacts, St as registryScopeAnalyst, T as SEARCH_SPEC_CORRELATION_KEY, Tt as HarvestError, U as runStrategyEvolution, Ut as sentinelCompletion, V as chatWorkerSeam, Vt as completionAuthorizes, W as strategyTournament, Wt as stopSentinel, X as openSandboxRun, Xt as renderPairwiseMarkdown, Y as SandboxRunAbortError, Yt as renderLeaderboardSvg, Z as createS3PrivateCasStore, Zt as SqlRunOwnershipError, _ as VERIFY_TAIL_CHARS, _t as verify, a as localShell, an as mcpSecretEnvMetadataKey, at as builtinShapes, b as settledWorkerOut, bt as buildSteerContext, c as createVerifierEnvironment, cn as secretEnvOfMcpServer, ct as FileCorpus, d as harvestSurfaceDiffs, dt as fanout, en as connectStdioMcp, et as createPrivateCasArtifactPort, f as analystsFromRegistry, ft as flatWidenGate, g as NOTE_MAX_CHARS, gt as selectValidWinner, h as EVIDENCE_MAX_CHARS, ht as pipeline, i as jjWorkspace, in as envKeyProvider, it as runPersonified, j as bestProfileFor, jt as loopCampaignDispatch, k as searchSpecDigest, kt as localSandboxClient, l as boxSurfaceReader, ln as createTangleSandboxExactProcessProvider, lt as InMemoryCorpus, m as worktreeFanout, mt as panel, n as makeFinding, nn as createMcpEnvironment, nt as trajectoryReport, o as runInWorkspace, on as resolveMcpServerLaunch, ot as createShapeRegistry, p as failuresAnalyst, pt as loopUntil, q as strategyAuthorContract, qt as renderLeaderboardHtml, r as gitWorkspace, rn as sanitizeMcpToolSchema, rt as definePersona, s as createWaterfallCollector, sn as resolveSecretEnv, st as registerShape, t as computeFindingId, tn as materializeLocalMcp, tt as equalKOnCost, u as fsSurfaceReader, ut as renderCorpusToInstructions, v as closingWorkerNote, vt as widen, w as createFencedSqlRunContext, wt as inProcessSandboxClient, x as copyUntrackedIntoClone, xt as createScopeAnalyst, y as composeWorkerEvidence, yt as assertTraceDerivedFindings, z as graphDesignerExtraTools, zt as readDeclaredCheck } from "./runtime-
|
|
6
|
+
import { $ as runBenchmark, $t as McpSpawnFault, A as connectRemoteSupervisor, At as inlineSandboxClient, B as chatTransportExecutor, Bt as runIsolatedCheck, C as analyzeTrace, Ct as observationFromRegistry, D as compileSearchSpec, Dt as defineLeaderboard, E as assertSearchSpec, Et as harvestCorpus, F as profileRunsForName, Ft as checkProgramDigest, G as assertStrategyContract, Gt as leaderboard, H as createChatSessionStore, Ht as deterministicCompletion, I as recordProfileRun, It as declaredCheckDeliverable, J as strategyAuthorSystemPrompt, Jt as renderLeaderboardMarkdown, K as authorStrategy, Kt as pairwiseSignificance, L as patchDelivered, Lt as declaredCheckDigest, M as loadProfile, Mt as loopDispatch, N as pickBestProfile, Nt as superviseDispatch, O as searchPresets, Ot as resolveSandboxClient, P as profileRegistry, Pt as assertDeclaredCheck, Q as printBenchmarkReport, Qt as openSqlRunStore, Rt as declaredCheckJudge, S as withUntrackedArtifacts, St as registryScopeAnalyst, T as SEARCH_SPEC_CORRELATION_KEY, Tt as HarvestError, U as runStrategyEvolution, Ut as sentinelCompletion, V as chatWorkerSeam, Vt as completionAuthorizes, W as strategyTournament, Wt as stopSentinel, X as openSandboxRun, Xt as renderPairwiseMarkdown, Y as SandboxRunAbortError, Yt as renderLeaderboardSvg, Z as createS3PrivateCasStore, Zt as SqlRunOwnershipError, _ as VERIFY_TAIL_CHARS, _t as verify, a as localShell, an as mcpSecretEnvMetadataKey, at as builtinShapes, b as settledWorkerOut, bt as buildSteerContext, c as createVerifierEnvironment, cn as secretEnvOfMcpServer, ct as FileCorpus, d as harvestSurfaceDiffs, dt as fanout, en as connectStdioMcp, et as createPrivateCasArtifactPort, f as analystsFromRegistry, ft as flatWidenGate, g as NOTE_MAX_CHARS, gt as selectValidWinner, h as EVIDENCE_MAX_CHARS, ht as pipeline, i as jjWorkspace, in as envKeyProvider, it as runPersonified, j as bestProfileFor, jt as loopCampaignDispatch, k as searchSpecDigest, kt as localSandboxClient, l as boxSurfaceReader, ln as createTangleSandboxExactProcessProvider, lt as InMemoryCorpus, m as worktreeFanout, mt as panel, n as makeFinding, nn as createMcpEnvironment, nt as trajectoryReport, o as runInWorkspace, on as resolveMcpServerLaunch, ot as createShapeRegistry, p as failuresAnalyst, pt as loopUntil, q as strategyAuthorContract, qt as renderLeaderboardHtml, r as gitWorkspace, rn as sanitizeMcpToolSchema, rt as definePersona, s as createWaterfallCollector, sn as resolveSecretEnv, st as registerShape, t as computeFindingId, tn as materializeLocalMcp, tt as equalKOnCost, u as fsSurfaceReader, ut as renderCorpusToInstructions, v as closingWorkerNote, vt as widen, w as createFencedSqlRunContext, wt as inProcessSandboxClient, x as copyUntrackedIntoClone, xt as createScopeAnalyst, y as composeWorkerEvidence, yt as assertTraceDerivedFindings, z as graphDesignerExtraTools, zt as readDeclaredCheck } from "./runtime-urcakzYm.js";
|
|
7
7
|
import { B as createEventBus, C as createFileRunContext, E as FileCoordinationLog, H as watchTrace, L as normalizeAnalyzeOnSettle, M as canonicalFindingEvent, S as renderAnytimeTable, T as withRunContext, V as defaultToolDetectors, _ as sampleFromSettled, a as DEFAULT_DEADLINE_WARNING_MS, b as bestSoFar, d as allWorkersStalled, f as anyOf, h as plateau, i as finalizeBestDelivered, m as noProgressFor, p as createProgressTracker, u as allOf, v as anytimeReport, w as createInMemoryRunContext, x as plateauLength, y as areaUnderCurve } from "./coordination-driver-B2XzW5aV.js";
|
|
8
8
|
import { A as dumbContinuationPassPrompt, C as defaultEdgeTraversalCap, D as createPromptRegistry, E as analyzesFindingsReportPrompt, F as serveCoordinationMcp, M as kernelPromptRegistry, N as naiveContinuationPrompt, O as delegatesWorkerBriefPrompt, P as promptHandle, b as composeReentryTask, c as isPreSpawnExecutorFailure, d as withWorkerSpawnRetry, f as assertCoordinationBinding, i as superviseFleetCapabilities, j as formatPromptHandle, k as dumbContinuationFailPrompt, l as resolveWorkerSpawnRetry, m as supervisorAgent, p as resolveSupervisorProfile, r as supervise, s as workerFromBackend, t as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, u as retryPreSpawnRefusals, x as createSupervisorSpanRecorder, y as UNPROVEN_CONTINUITY } from "./supervise-ttbcgYgS.js";
|
|
9
9
|
import { a as graphRunsFor, c as loadGraph, d as recordGraphRun, f as storedGraphDigests, i as graphRegistry, l as lookupGraph, n as graphDigest, p as taskShapeDigest, r as graphFromStored, s as listGraphRuns, t as digestOfGraph, u as pickBestGraph } from "./graph-registry-DAI6KNXB.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Ft as createExecutorRegistry } from "./supervisor-Crul0LFI.js";
|
|
2
2
|
import { i as ConfigError } from "./errors-DodWX-cb.js";
|
|
3
|
-
import { it as runPersonified, m as worktreeFanout, rt as definePersona } from "./runtime-
|
|
3
|
+
import { it as runPersonified, m as worktreeFanout, rt as definePersona } from "./runtime-urcakzYm.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-CrGUj3K9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop-runner-bin-CdDJs_hF.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,qBAA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AI,GAAG,WAAW,WAAW,GAAG,IAAI,SAAS,EAAE,MAAM,CAAkB;CAC9E;CACA,OAAO;AACT;;AAGA,SAAS,gBAAgB,KAAqC;CAC5D,MAAM,MAAO,KAA+B,WAAW;CAEvD,OADc,OAAO,QAAQ,aAAc,IAAsB,IAAI;AAEvE;AAEA,SAAS,OAAO,KAAsB;CACpC,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;;AAGA,eAAe,OAAsB;CACnC,MAAM,EAAE,MAAM,WAAW,oBAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC;CAClE,IAAI,CAAC,QAAQ,CAAC,QAAQ;EACpB,QAAQ,OAAO,MACb;WACc,qBAAqB,KAAK,KAAK,EAAE;CAEjD;EACA,QAAQ,KAAK,CAAC;CAChB;CACA,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,MAAM,MAAM,MAAM,iBAAiB;EACjC;EACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK;CAC7F,CAAC;CACD,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
|
|
1
|
+
{"version":3,"file":"loop-runner-bin-CrGUj3K9.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;CA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ertBoxlessP
|
|
|
2
2
|
import { i as ConfigError, m as ValidationError } from "../errors-DodWX-cb.js";
|
|
3
3
|
import { J as deleteBoxSafe, at as sleep, ct as throwIfAborted, st as throwAbort } from "../sandbox-profile-compat-Dq7ujONv.js";
|
|
4
4
|
import { t as assertExecutableAgentProfile } from "../model-policy-CyCUwHed.js";
|
|
5
|
-
import { R as runCoderChecks, gt as selectValidWinner } from "../runtime-
|
|
5
|
+
import { R as runCoderChecks, gt as selectValidWinner } from "../runtime-urcakzYm.js";
|
|
6
6
|
import { A as ANALYST_DEFINITION_BOUNDS, I as downMessageRefusalReasons, P as createCoordinationTools, R as parseAuthoredAnalystDefinition, j as analystToolGroupNames, z as questionEscalationTargets } from "../coordination-driver-B2XzW5aV.js";
|
|
7
7
|
import { n as SUPPORTED_PROTOCOL_VERSIONS, r as createStdioToolServer } from "../tool-server-Dqer2M4_.js";
|
|
8
8
|
import { t as createKbGate } from "../kb-gate-DpaSwXVx.js";
|
|
@@ -5061,7 +5061,59 @@ function createPrivateCasArtifactPort(root, namespace, options = {}) {
|
|
|
5061
5061
|
}
|
|
5062
5062
|
return objects;
|
|
5063
5063
|
};
|
|
5064
|
+
const streamDurably = async (digest, path, byteLength, signal) => {
|
|
5065
|
+
const ref = {
|
|
5066
|
+
locator: {
|
|
5067
|
+
kind: "private-cas",
|
|
5068
|
+
namespace,
|
|
5069
|
+
digest
|
|
5070
|
+
},
|
|
5071
|
+
sha256: digest,
|
|
5072
|
+
byteLength
|
|
5073
|
+
};
|
|
5074
|
+
let failure;
|
|
5075
|
+
for (let attempt = 1; attempt <= DURABLE_ATTEMPTS; attempt++) {
|
|
5076
|
+
signal?.throwIfAborted();
|
|
5077
|
+
const chunks = readObject(path, ref, signal);
|
|
5078
|
+
try {
|
|
5079
|
+
await durable.putStream({
|
|
5080
|
+
namespace,
|
|
5081
|
+
digest,
|
|
5082
|
+
byteLength,
|
|
5083
|
+
chunks,
|
|
5084
|
+
signal
|
|
5085
|
+
});
|
|
5086
|
+
await writeReceipt(digest, byteLength);
|
|
5087
|
+
return;
|
|
5088
|
+
} catch (error) {
|
|
5089
|
+
failure = error;
|
|
5090
|
+
if (signal?.aborted) throw error;
|
|
5091
|
+
if (attempt < DURABLE_ATTEMPTS) await new Promise((settle) => setTimeout(settle, 1e3 * 4 ** (attempt - 1)));
|
|
5092
|
+
} finally {
|
|
5093
|
+
await chunks.return(void 0);
|
|
5094
|
+
}
|
|
5095
|
+
}
|
|
5096
|
+
throw failure;
|
|
5097
|
+
};
|
|
5098
|
+
let lastPass;
|
|
5099
|
+
const settlePut = async (sha, byteLength, linked, upload, signal) => {
|
|
5100
|
+
if (upload !== void 0 && !await hasReceipt(sha)) await upload().catch(() => void 0);
|
|
5101
|
+
const durableNow = await hasReceipt(sha);
|
|
5102
|
+
const added = linked ? byteLength : 0;
|
|
5103
|
+
const known = lastPass;
|
|
5104
|
+
if (durableNow && known !== void 0 && known.pending === 0 && (localBudgetBytes === void 0 || known.localBytes + added <= localBudgetBytes)) {
|
|
5105
|
+
known.localBytes += added;
|
|
5106
|
+
return;
|
|
5107
|
+
}
|
|
5108
|
+
await offload(signal);
|
|
5109
|
+
};
|
|
5064
5110
|
const uploading = /* @__PURE__ */ new Map();
|
|
5111
|
+
const startUpload = (sha) => uploading.set(sha, (uploading.get(sha) ?? 0) + 1);
|
|
5112
|
+
const endUpload = (sha) => {
|
|
5113
|
+
const count = (uploading.get(sha) ?? 1) - 1;
|
|
5114
|
+
if (count === 0) uploading.delete(sha);
|
|
5115
|
+
else uploading.set(sha, count);
|
|
5116
|
+
};
|
|
5065
5117
|
const sweep = async (signal) => {
|
|
5066
5118
|
const objects = await localObjects();
|
|
5067
5119
|
const pending = [];
|
|
@@ -5090,41 +5142,8 @@ function createPrivateCasArtifactPort(root, namespace, options = {}) {
|
|
|
5090
5142
|
continue;
|
|
5091
5143
|
}
|
|
5092
5144
|
try {
|
|
5093
|
-
if (durable.putStream && durable.getStream)
|
|
5094
|
-
|
|
5095
|
-
locator: {
|
|
5096
|
-
kind: "private-cas",
|
|
5097
|
-
namespace,
|
|
5098
|
-
digest
|
|
5099
|
-
},
|
|
5100
|
-
sha256: digest,
|
|
5101
|
-
byteLength: object.size
|
|
5102
|
-
};
|
|
5103
|
-
let failure;
|
|
5104
|
-
for (let attempt = 1; attempt <= DURABLE_ATTEMPTS; attempt++) {
|
|
5105
|
-
signal?.throwIfAborted();
|
|
5106
|
-
const chunks = readObject(object.path, ref, signal);
|
|
5107
|
-
try {
|
|
5108
|
-
await durable.putStream({
|
|
5109
|
-
namespace,
|
|
5110
|
-
digest,
|
|
5111
|
-
byteLength: object.size,
|
|
5112
|
-
chunks,
|
|
5113
|
-
signal
|
|
5114
|
-
});
|
|
5115
|
-
await writeReceipt(digest, object.size);
|
|
5116
|
-
failure = void 0;
|
|
5117
|
-
break;
|
|
5118
|
-
} catch (error) {
|
|
5119
|
-
failure = error;
|
|
5120
|
-
if (signal?.aborted) throw error;
|
|
5121
|
-
if (attempt < DURABLE_ATTEMPTS) await new Promise((settle) => setTimeout(settle, 1e3 * 4 ** (attempt - 1)));
|
|
5122
|
-
} finally {
|
|
5123
|
-
await chunks.return(void 0);
|
|
5124
|
-
}
|
|
5125
|
-
}
|
|
5126
|
-
if (failure !== void 0) throw failure;
|
|
5127
|
-
} else {
|
|
5145
|
+
if (durable.putStream && durable.getStream) await streamDurably(digest, object.path, object.size, signal);
|
|
5146
|
+
else {
|
|
5128
5147
|
const bytes = await readLocal(object.path);
|
|
5129
5148
|
if (bytes === void 0) continue;
|
|
5130
5149
|
if (sha256(bytes) !== digest) {
|
|
@@ -5160,6 +5179,10 @@ function createPrivateCasArtifactPort(root, namespace, options = {}) {
|
|
|
5160
5179
|
localBytes -= object.size;
|
|
5161
5180
|
evicted++;
|
|
5162
5181
|
}
|
|
5182
|
+
lastPass = {
|
|
5183
|
+
localBytes,
|
|
5184
|
+
pending: pending.length
|
|
5185
|
+
};
|
|
5163
5186
|
let receiptCount = 0;
|
|
5164
5187
|
try {
|
|
5165
5188
|
receiptCount = (await readdir(receipts)).filter((name) => HEX.test(name)).length;
|
|
@@ -5273,10 +5296,12 @@ function createPrivateCasArtifactPort(root, namespace, options = {}) {
|
|
|
5273
5296
|
const directory = join(store, sha.slice(0, 2));
|
|
5274
5297
|
await checkDirectories(directory, true);
|
|
5275
5298
|
signal?.throwIfAborted();
|
|
5299
|
+
let linked = true;
|
|
5276
5300
|
try {
|
|
5277
5301
|
await link(temporary, path);
|
|
5278
5302
|
} catch (error) {
|
|
5279
5303
|
if (error.code !== "EEXIST") throw error;
|
|
5304
|
+
linked = false;
|
|
5280
5305
|
for await (const _chunk of readStream(ref, { signal }));
|
|
5281
5306
|
}
|
|
5282
5307
|
const dir = await open(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
@@ -5285,7 +5310,15 @@ function createPrivateCasArtifactPort(root, namespace, options = {}) {
|
|
|
5285
5310
|
} finally {
|
|
5286
5311
|
await dir.close();
|
|
5287
5312
|
}
|
|
5288
|
-
if (durable !== void 0) await
|
|
5313
|
+
if (durable !== void 0) await settlePut(sha, byteLength, linked, async () => {
|
|
5314
|
+
if (uploading.has(sha)) return;
|
|
5315
|
+
startUpload(sha);
|
|
5316
|
+
try {
|
|
5317
|
+
await streamDurably(digest, path, byteLength, signal);
|
|
5318
|
+
} finally {
|
|
5319
|
+
endUpload(sha);
|
|
5320
|
+
}
|
|
5321
|
+
}, signal);
|
|
5289
5322
|
return ref;
|
|
5290
5323
|
} finally {
|
|
5291
5324
|
await unlink(temporary).catch((error) => {
|
|
@@ -5302,15 +5335,11 @@ function createPrivateCasArtifactPort(root, namespace, options = {}) {
|
|
|
5302
5335
|
signal?.throwIfAborted();
|
|
5303
5336
|
const digest = sha256(bytes);
|
|
5304
5337
|
const sha = hexOf(digest);
|
|
5305
|
-
if (durable !== void 0)
|
|
5338
|
+
if (durable !== void 0) startUpload(sha);
|
|
5306
5339
|
try {
|
|
5307
5340
|
return await putBuffered(bytes, digest, sha, signal);
|
|
5308
5341
|
} finally {
|
|
5309
|
-
if (durable !== void 0)
|
|
5310
|
-
const count = (uploading.get(sha) ?? 1) - 1;
|
|
5311
|
-
if (count === 0) uploading.delete(sha);
|
|
5312
|
-
else uploading.set(sha, count);
|
|
5313
|
-
}
|
|
5342
|
+
if (durable !== void 0) endUpload(sha);
|
|
5314
5343
|
}
|
|
5315
5344
|
},
|
|
5316
5345
|
async read(ref) {
|
|
@@ -5355,12 +5384,14 @@ function createPrivateCasArtifactPort(root, namespace, options = {}) {
|
|
|
5355
5384
|
} finally {
|
|
5356
5385
|
await file.close();
|
|
5357
5386
|
}
|
|
5387
|
+
let linked = true;
|
|
5358
5388
|
try {
|
|
5359
5389
|
signal?.throwIfAborted();
|
|
5360
5390
|
try {
|
|
5361
5391
|
await link(temporary, path);
|
|
5362
5392
|
} catch (error) {
|
|
5363
5393
|
if (error.code !== "EEXIST") throw error;
|
|
5394
|
+
linked = false;
|
|
5364
5395
|
}
|
|
5365
5396
|
await syncDirectory(directory);
|
|
5366
5397
|
} finally {
|
|
@@ -5376,10 +5407,7 @@ function createPrivateCasArtifactPort(root, namespace, options = {}) {
|
|
|
5376
5407
|
byteLength: bytes.byteLength
|
|
5377
5408
|
};
|
|
5378
5409
|
await readRef(ref);
|
|
5379
|
-
if (durable !== void 0)
|
|
5380
|
-
if (!await hasReceipt(sha)) await storeDurably(digest, bytes, signal).catch(() => void 0);
|
|
5381
|
-
await offload(signal);
|
|
5382
|
-
}
|
|
5410
|
+
if (durable !== void 0) await settlePut(sha, bytes.byteLength, linked, () => storeDurably(digest, bytes, signal), signal);
|
|
5383
5411
|
return ref;
|
|
5384
5412
|
}
|
|
5385
5413
|
async function readRef(ref) {
|
|
@@ -9283,4 +9311,4 @@ function tail(s) {
|
|
|
9283
9311
|
//#endregion
|
|
9284
9312
|
export { runBenchmark as $, McpSpawnFault as $t, connectRemoteSupervisor as A, inlineSandboxClient as At, chatTransportExecutor as B, runIsolatedCheck as Bt, analyzeTrace as C, observationFromRegistry as Ct, compileSearchSpec as D, defineLeaderboard as Dt, assertSearchSpec as E, harvestCorpus as Et, profileRunsForName as F, checkProgramDigest as Ft, assertStrategyContract as G, leaderboard as Gt, createChatSessionStore as H, deterministicCompletion as Ht, recordProfileRun as I, declaredCheckDeliverable as It, strategyAuthorSystemPrompt as J, renderLeaderboardMarkdown as Jt, authorStrategy as K, pairwiseSignificance as Kt, patchDelivered as L, declaredCheckDigest as Lt, loadProfile as M, loopDispatch as Mt, pickBestProfile as N, superviseDispatch as Nt, searchPresets as O, resolveSandboxClient as Ot, profileRegistry as P, assertDeclaredCheck as Pt, printBenchmarkReport as Q, openSqlRunStore as Qt, runCoderChecks as R, declaredCheckJudge as Rt, withUntrackedArtifacts as S, registryScopeAnalyst as St, SEARCH_SPEC_CORRELATION_KEY as T, HarvestError as Tt, runStrategyEvolution as U, sentinelCompletion as Ut, chatWorkerSeam as V, completionAuthorizes as Vt, strategyTournament as W, stopSentinel as Wt, openSandboxRun as X, renderPairwiseMarkdown as Xt, SandboxRunAbortError as Y, renderLeaderboardSvg as Yt, createS3PrivateCasStore as Z, SqlRunOwnershipError as Zt, VERIFY_TAIL_CHARS as _, verify as _t, localShell as a, mcpSecretEnvMetadataKey as an, builtinShapes as at, settledWorkerOut as b, buildSteerContext as bt, createVerifierEnvironment as c, secretEnvOfMcpServer as cn, FileCorpus as ct, harvestSurfaceDiffs as d, fanout as dt, connectStdioMcp as en, createPrivateCasArtifactPort as et, analystsFromRegistry as f, flatWidenGate as ft, NOTE_MAX_CHARS as g, selectValidWinner as gt, EVIDENCE_MAX_CHARS as h, pipeline as ht, jjWorkspace as i, envKeyProvider as in, runPersonified as it, bestProfileFor as j, loopCampaignDispatch as jt, searchSpecDigest as k, localSandboxClient as kt, boxSurfaceReader as l, createTangleSandboxExactProcessProvider as ln, InMemoryCorpus as lt, worktreeFanout as m, panel as mt, makeFinding$1 as n, createMcpEnvironment as nn, trajectoryReport as nt, runInWorkspace as o, resolveMcpServerLaunch as on, createShapeRegistry as ot, failuresAnalyst as p, loopUntil as pt, strategyAuthorContract as q, renderLeaderboardHtml as qt, gitWorkspace as r, sanitizeMcpToolSchema as rn, definePersona as rt, createWaterfallCollector as s, resolveSecretEnv as sn, registerShape as st, computeFindingId$1 as t, materializeLocalMcp as tn, equalKOnCost as tt, fsSurfaceReader as u, renderCorpusToInstructions as ut, closingWorkerNote as v, widen as vt, createFencedSqlRunContext as w, inProcessSandboxClient as wt, copyUntrackedIntoClone as x, createScopeAnalyst as xt, composeWorkerEvidence as y, assertTraceDerivedFindings as yt, graphDesignerExtraTools as z, readDeclaredCheck as zt };
|
|
9285
9313
|
|
|
9286
|
-
//# sourceMappingURL=runtime-
|
|
9314
|
+
//# sourceMappingURL=runtime-urcakzYm.js.map
|