@tangle-network/agent-runtime 0.70.0 → 0.71.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.
Files changed (53) hide show
  1. package/dist/agent.d.ts +4 -4
  2. package/dist/agent.js +5 -3
  3. package/dist/agent.js.map +1 -1
  4. package/dist/analyst-loop.d.ts +51 -0
  5. package/dist/analyst-loop.js +11 -0
  6. package/dist/analyst-loop.js.map +1 -0
  7. package/dist/{chunk-EDCVUZZC.js → chunk-4KGQHS7U.js} +2 -2
  8. package/dist/{chunk-QXWGSDAQ.js → chunk-5ISW5JUF.js} +287 -286
  9. package/dist/chunk-5ISW5JUF.js.map +1 -0
  10. package/dist/{chunk-ZNQVMMR5.js → chunk-74UAWZXE.js} +4 -4
  11. package/dist/{chunk-L5ZFBVT6.js → chunk-INXDNX2W.js} +2 -2
  12. package/dist/chunk-K3RM4MPM.js +214 -0
  13. package/dist/chunk-K3RM4MPM.js.map +1 -0
  14. package/dist/chunk-P5OKDSLB.js +580 -0
  15. package/dist/chunk-P5OKDSLB.js.map +1 -0
  16. package/dist/chunk-VLF5RHEQ.js +143 -0
  17. package/dist/chunk-VLF5RHEQ.js.map +1 -0
  18. package/dist/{chunk-G3RGMA7C.js → chunk-VMNEQHJR.js} +6 -1
  19. package/dist/chunk-VMNEQHJR.js.map +1 -0
  20. package/dist/{coordination-C7WxwHXq.d.ts → coordination-BPQmuwv8.d.ts} +280 -2
  21. package/dist/{delegates-DqAgo32T.d.ts → delegates-CsXJPZDH.d.ts} +48 -2
  22. package/dist/{improvement-adapter-BVuMragr.d.ts → improvement-adapter-CioiEE2z.d.ts} +1 -1
  23. package/dist/index.d.ts +9 -9
  24. package/dist/index.js +20 -17
  25. package/dist/index.js.map +1 -1
  26. package/dist/intelligence.d.ts +1 -1
  27. package/dist/intelligence.js +1 -1
  28. package/dist/{loop-runner-bin-B0NeLTRd.d.ts → loop-runner-bin-DLM_bVQO.d.ts} +4 -4
  29. package/dist/loop-runner-bin.d.ts +5 -5
  30. package/dist/loop-runner-bin.js +6 -4
  31. package/dist/loops.d.ts +121 -242
  32. package/dist/loops.js +10 -4
  33. package/dist/mcp/bin.js +8 -7
  34. package/dist/mcp/bin.js.map +1 -1
  35. package/dist/mcp/index.d.ts +7 -6
  36. package/dist/mcp/index.js +23 -12
  37. package/dist/mcp/index.js.map +1 -1
  38. package/dist/{openai-tools-DPx9Gzvn.d.ts → openai-tools-kdCS-T12.d.ts} +1 -1
  39. package/dist/platform.d.ts +255 -0
  40. package/dist/platform.js +229 -0
  41. package/dist/platform.js.map +1 -0
  42. package/dist/profiles.d.ts +1 -1
  43. package/dist/{types-DJu6TBGp.d.ts → types-BC3bZpH0.d.ts} +15 -1
  44. package/dist/{types-BYa2ZOAx.d.ts → types-CdnEAE3U.d.ts} +1 -1
  45. package/dist/{worktree-fanout-gNfl0Byj.d.ts → worktree-fanout-CK2ypmEm.d.ts} +3 -45
  46. package/package.json +11 -1
  47. package/dist/chunk-BYZCXQHF.js +0 -474
  48. package/dist/chunk-BYZCXQHF.js.map +0 -1
  49. package/dist/chunk-G3RGMA7C.js.map +0 -1
  50. package/dist/chunk-QXWGSDAQ.js.map +0 -1
  51. /package/dist/{chunk-EDCVUZZC.js.map → chunk-4KGQHS7U.js.map} +0 -0
  52. /package/dist/{chunk-ZNQVMMR5.js.map → chunk-74UAWZXE.js.map} +0 -0
  53. /package/dist/{chunk-L5ZFBVT6.js.map → chunk-INXDNX2W.js.map} +0 -0
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  createFleetWorkspaceExecutor,
3
3
  createSiblingSandboxExecutor
4
- } from "./chunk-L5ZFBVT6.js";
4
+ } from "./chunk-INXDNX2W.js";
5
5
  import {
6
6
  runWorktreeHarness
7
- } from "./chunk-QXWGSDAQ.js";
7
+ } from "./chunk-5ISW5JUF.js";
8
8
  import {
9
9
  buildLoopOtelSpans,
10
10
  createOtelExporter
11
- } from "./chunk-G3RGMA7C.js";
11
+ } from "./chunk-VMNEQHJR.js";
12
12
 
13
13
  // src/mcp/in-process-executor.ts
14
14
  import { randomUUID } from "crypto";
@@ -275,4 +275,4 @@ export {
275
275
  createPropagatingTraceEmitter,
276
276
  traceContextToEnv
277
277
  };
278
- //# sourceMappingURL=chunk-ZNQVMMR5.js.map
278
+ //# sourceMappingURL=chunk-74UAWZXE.js.map
@@ -7,7 +7,7 @@ import {
7
7
  runDetachedTurn,
8
8
  runLoop,
9
9
  selectValidWinner
10
- } from "./chunk-QXWGSDAQ.js";
10
+ } from "./chunk-5ISW5JUF.js";
11
11
  import {
12
12
  coderProfile,
13
13
  coderTaskToPrompt
@@ -472,4 +472,4 @@ export {
472
472
  coderTaskFromArgs,
473
473
  settleDetachedCoderTurn
474
474
  };
475
- //# sourceMappingURL=chunk-L5ZFBVT6.js.map
475
+ //# sourceMappingURL=chunk-INXDNX2W.js.map
@@ -0,0 +1,214 @@
1
+ import {
2
+ runAnalystLoop
3
+ } from "./chunk-P5OKDSLB.js";
4
+ import {
5
+ createKbGate
6
+ } from "./chunk-FNMGYYSS.js";
7
+ import {
8
+ detachedSessionDelegate
9
+ } from "./chunk-INXDNX2W.js";
10
+ import {
11
+ createExecutorRegistry,
12
+ definePersona,
13
+ runPersonified,
14
+ worktreeFanout
15
+ } from "./chunk-5ISW5JUF.js";
16
+ import {
17
+ ConfigError
18
+ } from "./chunk-VLF5RHEQ.js";
19
+
20
+ // src/loop-runner.ts
21
+ import {
22
+ selfImprove
23
+ } from "@tangle-network/agent-eval/contract";
24
+ var DELEGATED_LOOP_MODES = ["code", "review", "research", "audit", "self-improve"];
25
+ function isDelegatedLoopMode(value) {
26
+ return typeof value === "string" && DELEGATED_LOOP_MODES.includes(value);
27
+ }
28
+ async function runDelegatedLoop(mode, registry, options = {}) {
29
+ const runner = registry[mode];
30
+ if (!runner) {
31
+ throw new ConfigError(
32
+ `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${Object.keys(registry).join(", ") || "none"})`
33
+ );
34
+ }
35
+ const now = options.now ?? Date.now;
36
+ const signal = options.signal ?? new AbortController().signal;
37
+ const start = now();
38
+ try {
39
+ const output = await runner(signal);
40
+ return { mode, ok: true, output, durationMs: now() - start };
41
+ } catch (err) {
42
+ return {
43
+ mode,
44
+ ok: false,
45
+ error: err instanceof Error ? err.message : String(err),
46
+ durationMs: now() - start
47
+ };
48
+ }
49
+ }
50
+ function coderLoopRunner(options) {
51
+ const delegate = detachedSessionDelegate({
52
+ sandboxClient: options.sandboxClient,
53
+ ...options.reviewer ? { reviewer: options.reviewer } : {},
54
+ ...options.winnerSelection ? { winnerSelection: options.winnerSelection } : {},
55
+ ...options.fanoutHarnesses ? { fanoutHarnesses: options.fanoutHarnesses } : {}
56
+ });
57
+ return async (signal) => {
58
+ const ctx = { signal, report: () => {
59
+ } };
60
+ return delegate(options.args, ctx);
61
+ };
62
+ }
63
+ function worktreeLoopRunner(options) {
64
+ const shape = worktreeFanout({
65
+ repoRoot: options.repoRoot,
66
+ taskPrompt: options.taskPrompt,
67
+ harnesses: options.harnesses,
68
+ ...options.testCmd !== void 0 ? { testCmd: options.testCmd } : {},
69
+ ...options.typecheckCmd !== void 0 ? { typecheckCmd: options.typecheckCmd } : {},
70
+ ...options.require !== void 0 ? { require: options.require } : {},
71
+ ...options.maxDiffLines !== void 0 ? { maxDiffLines: options.maxDiffLines } : {},
72
+ ...options.forbiddenPaths !== void 0 ? { forbiddenPaths: options.forbiddenPaths } : {},
73
+ ...options.winnerStrategy !== void 0 ? { winnerStrategy: options.winnerStrategy } : {},
74
+ ...options.runGit ? { runGit: options.runGit } : {},
75
+ ...options.runHarness ? { runHarness: options.runHarness } : {},
76
+ ...options.runCommand ? { runCommand: options.runCommand } : {}
77
+ });
78
+ const persona = definePersona({
79
+ name: "worktree-coder",
80
+ root: { profile: { name: "worktree-coder" }, harness: null },
81
+ directive: "deliver a minimal validated patch on a fresh worktree",
82
+ context: { role: "coder" },
83
+ executors: { registry: createExecutorRegistry() }
84
+ });
85
+ return async (signal) => {
86
+ const result = await runPersonified({
87
+ persona,
88
+ shape,
89
+ task: options.taskPrompt,
90
+ budget: options.budget,
91
+ signal
92
+ });
93
+ if (result.kind !== "winner" || result.out.kind !== "done") {
94
+ const blockers = result.kind === "winner" && result.out.kind === "blocked" ? result.out.blockers.join("; ") : `supervisor settled ${result.kind}`;
95
+ throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`);
96
+ }
97
+ return result.out.deliverable;
98
+ };
99
+ }
100
+ function researchLoopRunner(o) {
101
+ const gate = createKbGate(o.gate);
102
+ const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1));
103
+ return async (signal) => {
104
+ const accepted = [];
105
+ let vetoed = [];
106
+ let rounds = 0;
107
+ for (let round = 0; round < maxRounds; round += 1) {
108
+ if (signal.aborted) break;
109
+ rounds += 1;
110
+ const candidates = await o.research(round, vetoed);
111
+ if (candidates.length === 0) break;
112
+ vetoed = [];
113
+ for (const c of candidates) {
114
+ const v = await gate(c);
115
+ if (v.accepted) accepted.push(c);
116
+ else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason });
117
+ }
118
+ if (vetoed.length === 0) break;
119
+ }
120
+ return { accepted, vetoed, rounds };
121
+ };
122
+ }
123
+ function selfImproveLoopRunner(options) {
124
+ return async () => selfImprove(options);
125
+ }
126
+ function auditLoopRunner(options) {
127
+ return async () => runAnalystLoop(options);
128
+ }
129
+
130
+ // src/loop-runner-bin.ts
131
+ async function runLoopRunnerCli(args) {
132
+ if (!isDelegatedLoopMode(args.mode)) {
133
+ return {
134
+ exitCode: 2,
135
+ error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(", ")})`
136
+ };
137
+ }
138
+ let registry;
139
+ try {
140
+ registry = await args.loadRegistry();
141
+ } catch (err) {
142
+ return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` };
143
+ }
144
+ if (!registry[args.mode]) {
145
+ return {
146
+ exitCode: 2,
147
+ error: `config registers no runner for mode '${args.mode}' (registered: ${Object.keys(registry).join(", ") || "none"})`
148
+ };
149
+ }
150
+ const result = await runDelegatedLoop(args.mode, registry, {
151
+ ...args.now ? { now: args.now } : {}
152
+ });
153
+ return { exitCode: result.ok ? 0 : 1, result };
154
+ }
155
+ function parseLoopRunnerArgv(argv) {
156
+ const out = {};
157
+ for (let i = 0; i < argv.length; i += 1) {
158
+ const a = argv[i];
159
+ if (a === "--mode") out.mode = argv[++i];
160
+ else if (a === "--config") out.config = argv[++i];
161
+ else if (a?.startsWith("--mode=")) out.mode = a.slice("--mode=".length);
162
+ else if (a?.startsWith("--config=")) out.config = a.slice("--config=".length);
163
+ }
164
+ return out;
165
+ }
166
+ function resolveRegistry(mod) {
167
+ const def = mod?.default ?? mod;
168
+ const value = typeof def === "function" ? def() : def;
169
+ return value;
170
+ }
171
+ function errMsg(err) {
172
+ return err instanceof Error ? err.message : String(err);
173
+ }
174
+ async function main() {
175
+ const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2));
176
+ if (!mode || !config) {
177
+ process.stderr.write(
178
+ `usage: agent-runtime-loop --mode <mode> --config <module>
179
+ modes: ${DELEGATED_LOOP_MODES.join(" | ")}
180
+ config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)
181
+ `
182
+ );
183
+ process.exit(2);
184
+ }
185
+ const { pathToFileURL } = await import("url");
186
+ const { resolve } = await import("path");
187
+ const cli = await runLoopRunnerCli({
188
+ mode,
189
+ loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href))
190
+ });
191
+ process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}
192
+ `);
193
+ if (cli.error) process.stderr.write(`${cli.error}
194
+ `);
195
+ process.exit(cli.exitCode);
196
+ }
197
+ var invokedScript = typeof process !== "undefined" ? process.argv?.[1] : void 0;
198
+ if (invokedScript && /loop-runner-bin\.(js|ts|mjs)$/.test(invokedScript)) {
199
+ void main();
200
+ }
201
+
202
+ export {
203
+ DELEGATED_LOOP_MODES,
204
+ isDelegatedLoopMode,
205
+ runDelegatedLoop,
206
+ coderLoopRunner,
207
+ worktreeLoopRunner,
208
+ researchLoopRunner,
209
+ selfImproveLoopRunner,
210
+ auditLoopRunner,
211
+ runLoopRunnerCli,
212
+ parseLoopRunnerArgv
213
+ };
214
+ //# sourceMappingURL=chunk-K3RM4MPM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n * @experimental\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 via the coder delegate (no-op + secret floor,\n * optional reviewer gate, winner-selection)\n * review → code mode with a REQUIRED reviewer (the gate is the point)\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 → closed-loop text/config optimization (selfImprove, held-out gated)\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\nimport type { Scenario } from '@tangle-network/agent-eval/campaign'\nimport {\n type SelfImproveOptions,\n type SelfImproveResult,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport {\n type CoderReviewer,\n type DelegateRunCtx,\n type DetachedWinnerSelection,\n detachedSessionDelegate,\n} from './mcp/delegates'\nimport type { CoderOutput } from './mcp/detached-coder'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport type { DelegateCodeArgs } from './mcp/types'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type SandboxClient,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** @experimental Every delegated-loop mode, for validation + CLI surfaces. */\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/** @experimental Type guard for an untrusted mode string (CLI / config input). */\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 * @experimental\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 */\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 default `code`/`review` runner. */\nexport interface CoderLoopRunnerOptions {\n sandboxClient: SandboxClient\n /** What to build — the delegate args (goal, repoRoot, variants, config, …). */\n args: DelegateCodeArgs\n /** Adversarial reviewer. Pass one to run `review` mode (an approval gate over the candidate). */\n reviewer?: CoderReviewer\n /** Winner-selection strategy. Default `highest-score`. */\n winnerSelection?: DetachedWinnerSelection\n /** Harnesses for `variants > 1` fanout. */\n fanoutHarnesses?: string[]\n}\n\n/**\n * @experimental Build a `code`/`review`-mode runner over the sandbox-session coder delegate. Pass a\n * `reviewer` to run `review` mode — an approval gate over the validated candidate.\n */\nexport function coderLoopRunner(options: CoderLoopRunnerOptions): DelegatedLoopRunner<CoderOutput> {\n const delegate = detachedSessionDelegate({\n sandboxClient: options.sandboxClient,\n ...(options.reviewer ? { reviewer: options.reviewer } : {}),\n ...(options.winnerSelection ? { winnerSelection: options.winnerSelection } : {}),\n ...(options.fanoutHarnesses ? { fanoutHarnesses: options.fanoutHarnesses } : {}),\n })\n return async (signal) => {\n const ctx: DelegateRunCtx = { signal, report: () => {} }\n return delegate(options.args, ctx)\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\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 * @experimental\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. This is the local-repo counterpart to\n * {@link coderLoopRunner} (which drives the in-box harness over a `SandboxClient`): no `runLoop`\n * driver, no role-coupled delegate — the harness list is the fanout, the gate is `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 */\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: { name: 'worktree-coder' }, 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 * @experimental `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 */\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/** @experimental `self-improve` mode — agent-eval's one-call closed loop (held-out gated). */\nexport function selfImproveLoopRunner<TScenario extends Scenario, TArtifact>(\n options: SelfImproveOptions<TScenario, TArtifact>,\n): DelegatedLoopRunner<SelfImproveResult<TScenario, TArtifact>> {\n return async () => selfImprove<TScenario, TArtifact>(options)\n}\n\n/** @experimental `audit` mode — analyst loop over captured trace/run data. */\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 * @experimental\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\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 * @experimental\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 */\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 !== 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