@tangle-network/agent-runtime 0.337.2 → 0.339.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-DRHM55Oo.d.ts → activation-CJIIl_Ey.d.ts} +90 -22
- package/dist/activation-CVSFxis9.js +876 -0
- package/dist/activation-CVSFxis9.js.map +1 -0
- package/dist/agent.d.ts +4 -4
- package/dist/agent.js +4 -7
- package/dist/agent.js.map +1 -1
- package/dist/{bundle-BPGjESee.js → bundle-DVOhBTic.js} +2 -2
- package/dist/{bundle-BPGjESee.js.map → bundle-DVOhBTic.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +4 -63
- package/dist/candidate-execution/index.js +6 -146
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/content-digest-sBTLujlK.js +9 -0
- package/dist/content-digest-sBTLujlK.js.map +1 -0
- package/dist/{delegate-B-T_ZB50.js → delegate-CCWE_AkU.js} +2 -2
- package/dist/{delegate-B-T_ZB50.js.map → delegate-CCWE_AkU.js.map} +1 -1
- package/dist/{coordination-driver-BHkFVqIq.js → driver-control-acknowledgers-C53ggdJ6.js} +4520 -4442
- package/dist/driver-control-acknowledgers-C53ggdJ6.js.map +1 -0
- package/dist/{durable-file-B_eJr6Mb.js → durable-file-gNI9ILAn.js} +1 -3
- package/dist/durable-file-gNI9ILAn.js.map +1 -0
- package/dist/durable.d.ts +3 -35
- package/dist/durable.js +225 -229
- package/dist/durable.js.map +1 -1
- package/dist/{graph-C4RFlWAJ.js → graph-CI9JXKqO.js} +65 -18
- package/dist/graph-CI9JXKqO.js.map +1 -0
- package/dist/{graph-registry-DAI6KNXB.js → graph-registry-BnO64cn8.js} +18 -17
- package/dist/graph-registry-BnO64cn8.js.map +1 -0
- package/dist/{improvement-cycle-D1I4hQvf.js → improve-BOXTLWJ3.js} +76 -1248
- package/dist/improve-BOXTLWJ3.js.map +1 -0
- package/dist/{improvement-adapter-D5gwwoXQ.d.ts → improvement-adapter-HUt_-cWA.d.ts} +2 -20
- package/dist/index.d.ts +10 -207
- package/dist/index.js +91 -305
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +10 -229
- package/dist/intelligence.js +506 -88
- package/dist/intelligence.js.map +1 -1
- package/dist/{jsonl-file-DBv31uPi.js → jsonl-file-C9Kde_0Z.js} +2 -2
- package/dist/{jsonl-file-DBv31uPi.js.map → jsonl-file-C9Kde_0Z.js.map} +1 -1
- package/dist/kernel.d.ts +4 -3
- package/dist/kernel.js +12 -13
- package/dist/loop-runner-CWzG1bH4.d.ts +32 -0
- package/dist/loop-runner-bin.d.ts +32 -2
- package/dist/loop-runner-bin.js +93 -1
- package/dist/loop-runner-bin.js.map +1 -0
- package/dist/loop-runner-pmPIHFVY.js +59 -0
- package/dist/loop-runner-pmPIHFVY.js.map +1 -0
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +101 -416
- package/dist/mcp/index.js +122 -206
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/memory-bin.js +231 -1
- package/dist/mcp/memory-bin.js.map +1 -1
- package/dist/model-policy-CyCUwHed.js.map +1 -1
- package/dist/placement.d.ts +2 -9
- package/dist/placement.js +1 -1
- package/dist/placement.js.map +1 -1
- package/dist/platform.d.ts +194 -2
- package/dist/platform.js +145 -9
- package/dist/platform.js.map +1 -1
- package/dist/{prepare-CER-ZkPp.js → prepare-bXkvPMJA.js} +1213 -710
- package/dist/prepare-bXkvPMJA.js.map +1 -0
- package/dist/{profile-gNUsHNIJ.js → profile-Dpei_Sq0.js} +89 -3
- package/dist/profile-Dpei_Sq0.js.map +1 -0
- package/dist/{profile-materialization-BnoEf1co.d.ts → profile-materialization-B1wm2SPT.d.ts} +3 -5
- package/dist/profiles.d.ts +2 -2
- package/dist/profiles.js +4 -43
- package/dist/profiles.js.map +1 -1
- package/dist/{protected-model-port-BhpQRTw-.d.ts → protected-model-port-BGgpy2r9.d.ts} +4 -30
- package/dist/protected-redaction-DFCeo4vg.js.map +1 -1
- package/dist/{provision-supervisor-DGegCUH4.js → provision-supervisor-CJ6Zz6dz.js} +13 -10
- package/dist/provision-supervisor-CJ6Zz6dz.js.map +1 -0
- package/dist/record-value-B6bwJxLa.js +12 -0
- package/dist/record-value-B6bwJxLa.js.map +1 -0
- package/dist/{run-layout-Cu8H7aeh.js → run-cancellation-C9oL62sW.js} +175 -100
- package/dist/run-cancellation-C9oL62sW.js.map +1 -0
- package/dist/{runtime-BOGpotnH.js → runtime-B2fjL9Oi.js} +2639 -3187
- package/dist/runtime-B2fjL9Oi.js.map +1 -0
- package/dist/{runtime-hooks-Bj6wJHlH.d.ts → runtime-hooks-nsqxSUFL.d.ts} +2 -6
- package/dist/{sandbox-profile-compat-QTkLe1Z6.js → sandbox-profile-compat-BzVBFqrz.js} +690 -699
- package/dist/sandbox-profile-compat-BzVBFqrz.js.map +1 -0
- package/dist/search-executor-zMumiak_.js +1916 -0
- package/dist/search-executor-zMumiak_.js.map +1 -0
- package/dist/{server-hZWM-G8w.js → server-_4voDNrl.js} +362 -67
- package/dist/server-_4voDNrl.js.map +1 -0
- package/dist/{search-executor-Cm1WZmL-.js → structural-rollout-DpLCXzaL.js} +1680 -3403
- package/dist/structural-rollout-DpLCXzaL.js.map +1 -0
- package/dist/{substrate-B0TYNrXn.js → substrate-CGDFTSRh.js} +2 -9
- package/dist/substrate-CGDFTSRh.js.map +1 -0
- package/dist/{supervise-CvAKVfue.js → supervise-qAwXmPtD.js} +7768 -5360
- package/dist/supervise-qAwXmPtD.js.map +1 -0
- package/dist/{supervisor-Rz8AGpYb.js → supervisor-DHrUJhEZ.js} +26301 -26964
- package/dist/supervisor-DHrUJhEZ.js.map +1 -0
- package/dist/testing.d.ts +227 -2
- package/dist/testing.js +13 -14
- package/dist/testing.js.map +1 -1
- package/dist/tool-loop.d.ts +1 -1
- package/dist/{tool-server-Dqer2M4_.js → tool-server-XV4aJwoQ.js} +2 -2
- package/dist/tool-server-XV4aJwoQ.js.map +1 -0
- package/dist/top-snapshot-CbZE1JsU.js +502 -0
- package/dist/top-snapshot-CbZE1JsU.js.map +1 -0
- package/dist/tui/bin.js +711 -1
- package/dist/tui/bin.js.map +1 -1
- package/dist/tui/index.d.ts +5 -71
- package/dist/tui/index.js +3 -3
- package/dist/{types-Dl5L4r8Z.d.ts → types-CaOXqRTq.d.ts} +16230 -17376
- package/dist/workspace-store/index.d.ts +2 -27
- package/dist/workspace-store/index.js +2 -2
- package/dist/workspace-store/index.js.map +1 -1
- package/dist/{workspace-streams-JLjh5DC6.d.ts → workspace-streams-BiS4ABah.d.ts} +19 -32
- package/package.json +2 -2
- package/skills/agent-graphs/SKILL.md +10 -3
- package/skills/agent-graphs/references/authoring.md +18 -0
- package/skills/profile-authoring/SKILL.md +3 -3
- package/skills/supervise/SKILL.md +2 -2
- package/dist/activation-BDP6Eivv.js +0 -234
- package/dist/activation-BDP6Eivv.js.map +0 -1
- package/dist/coder-yhVWbdWc.js +0 -40
- package/dist/coder-yhVWbdWc.js.map +0 -1
- package/dist/coordination-driver-BHkFVqIq.js.map +0 -1
- package/dist/delegation-status-CF4D0NZ_.js +0 -358
- package/dist/delegation-status-CF4D0NZ_.js.map +0 -1
- package/dist/durable-file-B_eJr6Mb.js.map +0 -1
- package/dist/graph-C4RFlWAJ.js.map +0 -1
- package/dist/graph-registry-DAI6KNXB.js.map +0 -1
- package/dist/improvement-cycle-D1I4hQvf.js.map +0 -1
- package/dist/integrations-DopfCC2a.d.ts +0 -190
- package/dist/integrations-dFi-ALk7.js +0 -132
- package/dist/integrations-dFi-ALk7.js.map +0 -1
- package/dist/kb-gate-C8z2juK8.d.ts +0 -80
- package/dist/kb-gate-DpaSwXVx.js +0 -80
- package/dist/kb-gate-DpaSwXVx.js.map +0 -1
- package/dist/loop-runner-bin-DOuBIJ2O.d.ts +0 -164
- package/dist/loop-runner-bin-Dv5QvYDH.js +0 -246
- package/dist/loop-runner-bin-Dv5QvYDH.js.map +0 -1
- package/dist/memory-server-DXQ8IxGR.js +0 -234
- package/dist/memory-server-DXQ8IxGR.js.map +0 -1
- package/dist/openai-tools-DoQ32vpe.js +0 -44
- package/dist/openai-tools-DoQ32vpe.js.map +0 -1
- package/dist/openai-tools-Oxk4KQrY.d.ts +0 -24
- package/dist/prepare-CER-ZkPp.js.map +0 -1
- package/dist/profile-gNUsHNIJ.js.map +0 -1
- package/dist/protected-model-port-BuRsviSL.js +0 -766
- package/dist/protected-model-port-BuRsviSL.js.map +0 -1
- package/dist/provision-supervisor-DGegCUH4.js.map +0 -1
- package/dist/run-layout-Cu8H7aeh.js.map +0 -1
- package/dist/runtime-BOGpotnH.js.map +0 -1
- package/dist/sandbox-profile-compat-QTkLe1Z6.js.map +0 -1
- package/dist/search-executor-Cm1WZmL-.js.map +0 -1
- package/dist/server-hZWM-G8w.js.map +0 -1
- package/dist/substrate-B0TYNrXn.js.map +0 -1
- package/dist/supervise-CvAKVfue.js.map +0 -1
- package/dist/supervisor-Rz8AGpYb.js.map +0 -1
- package/dist/tool-server-Dqer2M4_.js.map +0 -1
- package/dist/top-app-BaMw1W2z.js +0 -1212
- package/dist/top-app-BaMw1W2z.js.map +0 -1
package/dist/loop-runner-bin.js
CHANGED
|
@@ -1,3 +1,95 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { i as runDelegatedLoop, r as isDelegatedLoopMode, t as DELEGATED_LOOP_MODES } from "./loop-runner-pmPIHFVY.js";
|
|
3
|
+
//#region src/loop-runner-bin.ts
|
|
4
|
+
/**
|
|
5
|
+
*
|
|
6
|
+
* `agent-runtime-loop` — the schedulable entrypoint for the configured
|
|
7
|
+
* delegated loop-runner. A cron job / routine / Makefile target invokes:
|
|
8
|
+
*
|
|
9
|
+
* agent-runtime-loop --mode research --config ./loops.config.js
|
|
10
|
+
*
|
|
11
|
+
* The config module wires the registry (with full access to env / creds —
|
|
12
|
+
* which is why the deps live there, not in this generic bin). It must default-
|
|
13
|
+
* export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.
|
|
14
|
+
* The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and
|
|
15
|
+
* exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.
|
|
16
|
+
*
|
|
17
|
+
* @experimental
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
*
|
|
21
|
+
* Pure CLI core (no process / argv / IO) so it's unit-testable: validate the
|
|
22
|
+
* mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /
|
|
23
|
+
* 2 usage). Exported for embedding in custom runners + tests.
|
|
24
|
+
*
|
|
25
|
+
* @experimental
|
|
26
|
+
*/
|
|
27
|
+
async function runLoopRunnerCli(args) {
|
|
28
|
+
if (!isDelegatedLoopMode(args.mode)) return {
|
|
29
|
+
exitCode: 2,
|
|
30
|
+
error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(", ")})`
|
|
31
|
+
};
|
|
32
|
+
let registry;
|
|
33
|
+
try {
|
|
34
|
+
registry = await args.loadRegistry();
|
|
35
|
+
} catch (err) {
|
|
36
|
+
return {
|
|
37
|
+
exitCode: 2,
|
|
38
|
+
error: `failed to load registry: ${errMsg(err)}`
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
if (!registry[args.mode]) return {
|
|
42
|
+
exitCode: 2,
|
|
43
|
+
error: `config registers no runner for mode '${args.mode}' (registered: ${Object.keys(registry).join(", ") || "none"})`
|
|
44
|
+
};
|
|
45
|
+
const result = await runDelegatedLoop(args.mode, registry, { ...args.now ? { now: args.now } : {} });
|
|
46
|
+
return {
|
|
47
|
+
exitCode: result.ok ? 0 : 1,
|
|
48
|
+
result
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */
|
|
52
|
+
function parseLoopRunnerArgv(argv) {
|
|
53
|
+
const out = {};
|
|
54
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
55
|
+
const a = argv[i];
|
|
56
|
+
if (a === "--mode") out.mode = argv[++i];
|
|
57
|
+
else if (a === "--config") out.config = argv[++i];
|
|
58
|
+
else if (a?.startsWith("--mode=")) out.mode = a.slice(7);
|
|
59
|
+
else if (a?.startsWith("--config=")) out.config = a.slice(9);
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
/** Normalize a config module's default export → a registry. */
|
|
64
|
+
function resolveRegistry(mod) {
|
|
65
|
+
const def = mod?.default ?? mod;
|
|
66
|
+
return typeof def === "function" ? def() : def;
|
|
67
|
+
}
|
|
68
|
+
function errMsg(err) {
|
|
69
|
+
return err instanceof Error ? err.message : String(err);
|
|
70
|
+
}
|
|
71
|
+
/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */
|
|
72
|
+
async function main() {
|
|
73
|
+
const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2));
|
|
74
|
+
if (!mode || !config) {
|
|
75
|
+
process.stderr.write(`usage: agent-runtime-loop --mode <mode> --config <module>
|
|
76
|
+
modes: ${DELEGATED_LOOP_MODES.join(" | ")}\n config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)
|
|
77
|
+
`);
|
|
78
|
+
process.exit(2);
|
|
79
|
+
}
|
|
80
|
+
const { pathToFileURL } = await import("node:url");
|
|
81
|
+
const { resolve } = await import("node:path");
|
|
82
|
+
const cli = await runLoopRunnerCli({
|
|
83
|
+
mode,
|
|
84
|
+
loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href))
|
|
85
|
+
});
|
|
86
|
+
process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\n`);
|
|
87
|
+
if (cli.error) process.stderr.write(`${cli.error}\n`);
|
|
88
|
+
process.exit(cli.exitCode);
|
|
89
|
+
}
|
|
90
|
+
const invokedScript = typeof process !== "undefined" ? process.argv?.[1] : void 0;
|
|
91
|
+
if (invokedScript && /loop-runner-bin\.(js|ts|mjs)$/.test(invokedScript)) main();
|
|
92
|
+
//#endregion
|
|
3
93
|
export { parseLoopRunnerArgv, runLoopRunnerCli };
|
|
94
|
+
|
|
95
|
+
//# sourceMappingURL=loop-runner-bin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loop-runner-bin.js","names":[],"sources":["../src/loop-runner-bin.ts"],"sourcesContent":["#!/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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,eAAsB,iBAAiB,MAAuD;CAC5F,IAAI,CAAC,oBAAoB,KAAK,IAAI,GAChC,OAAO;EACL,UAAU;EACV,OAAO,iBAAiB,KAAK,KAAK,sBAAsB,qBAAqB,KAAK,IAAI,EAAE;CAC1F;CAEF,IAAI;CACJ,IAAI;EACF,WAAW,MAAM,KAAK,aAAa;CACrC,SAAS,KAAK;EACZ,OAAO;GAAE,UAAU;GAAG,OAAO,4BAA4B,OAAO,GAAG;EAAI;CACzE;CACA,IAAI,CAAC,SAAS,KAAK,OACjB,OAAO;EACL,UAAU;EACV,OAAO,wCAAwC,KAAK,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC;CACH;CAIF,MAAM,SAAS,MAAM,iBAAiB,KAAK,MAA2B,UAAU,EAC9E,GAAI,KAAK,MAAM,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC,EACtC,CAAC;CACD,OAAO;EAAE,UAAU,OAAO,KAAK,IAAI;EAAG;CAAO;AAC/C;;AAGA,SAAgB,oBAAoB,MAAoD;CACtF,MAAM,MAA0C,CAAC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K,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { i as ConfigError } from "./errors-DodWX-cb.js";
|
|
2
|
+
import { t as runAnalystLoop } from "./analyst-loop-DZw5QWT9.js";
|
|
3
|
+
import "./runtime-B2fjL9Oi.js";
|
|
4
|
+
//#region src/loop-runner.ts
|
|
5
|
+
/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */
|
|
6
|
+
const DELEGATED_LOOP_MODES = [
|
|
7
|
+
"code",
|
|
8
|
+
"review",
|
|
9
|
+
"research",
|
|
10
|
+
"audit",
|
|
11
|
+
"self-improve"
|
|
12
|
+
];
|
|
13
|
+
/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */
|
|
14
|
+
function isDelegatedLoopMode(value) {
|
|
15
|
+
return typeof value === "string" && DELEGATED_LOOP_MODES.includes(value);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
*
|
|
19
|
+
* Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no
|
|
20
|
+
* runner is registered for the mode — a routine pointed at an unwired mode is a
|
|
21
|
+
* config bug, not a silent no-op. A runner that throws is captured as
|
|
22
|
+
* `{ ok: false }` so unattended runs record the failure rather than crash.
|
|
23
|
+
*
|
|
24
|
+
* @experimental
|
|
25
|
+
*/
|
|
26
|
+
async function runDelegatedLoop(mode, registry, options = {}) {
|
|
27
|
+
const runner = registry[mode];
|
|
28
|
+
if (!runner) throw new ConfigError(`runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${Object.keys(registry).join(", ") || "none"})`);
|
|
29
|
+
const now = options.now ?? Date.now;
|
|
30
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
31
|
+
const start = now();
|
|
32
|
+
try {
|
|
33
|
+
return {
|
|
34
|
+
mode,
|
|
35
|
+
ok: true,
|
|
36
|
+
output: await runner(signal),
|
|
37
|
+
durationMs: now() - start
|
|
38
|
+
};
|
|
39
|
+
} catch (err) {
|
|
40
|
+
return {
|
|
41
|
+
mode,
|
|
42
|
+
ok: false,
|
|
43
|
+
error: err instanceof Error ? err.message : String(err),
|
|
44
|
+
durationMs: now() - start
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* `audit` mode — analyst loop over captured trace/run data.
|
|
50
|
+
*
|
|
51
|
+
* @experimental
|
|
52
|
+
*/
|
|
53
|
+
function auditLoopRunner(options) {
|
|
54
|
+
return async () => runAnalystLoop(options);
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
export { runDelegatedLoop as i, auditLoopRunner as n, isDelegatedLoopMode as r, DELEGATED_LOOP_MODES as t };
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=loop-runner-pmPIHFVY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loop-runner-pmPIHFVY.js","names":[],"sources":["../src/loop-runner.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 `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 */\ninterface 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. */\ninterface 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 */\ninterface 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. */\ninterface 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"],"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;;;;;;AAoKA,SAAgB,gBACd,SAC6D;CAC7D,OAAO,YAAY,eAAiC,OAAO;AAC7D"}
|
package/dist/mcp/bin.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { k as coordinationProfileToolPrefix, nn as readTraceContextFromEnv } from "../supervisor-DHrUJhEZ.js";
|
|
3
3
|
import { i as ConfigError } from "../errors-DodWX-cb.js";
|
|
4
|
-
import { s as supervisorInstructions } from "../delegate-
|
|
5
|
-
import {
|
|
4
|
+
import { s as supervisorInstructions } from "../delegate-CCWE_AkU.js";
|
|
5
|
+
import { i as FileDelegationStore, r as DelegationTaskQueue, t as createMcpServer } from "../server-_4voDNrl.js";
|
|
6
6
|
//#region src/mcp/delegate-supervisor-provisioning.ts
|
|
7
7
|
function trimmed(value) {
|
|
8
8
|
const v = value?.trim();
|
package/dist/mcp/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.js","names":[],"sources":["../../src/mcp/delegate-supervisor-provisioning.ts","../../src/mcp/bin.ts"],"sourcesContent":["/**\n *\n * Resolve the `delegate` supervisor substrate (router brain + worker backend) from env, so the\n * `agent-runtime-mcp` bin can serve the ONE generic `delegate` verb by env, over the SAME stdio\n * invocation a consumer already mounts.\n *\n * `delegate` is wired into `createMcpServer` via `McpServerOptions.delegateSupervisor`, which needs a\n * router (the supervisor brain's transport) and a backend (WHERE the authored workers run). Inside a\n * sandbox child the natural backend is `sandbox`: authored workers run as sub-sandboxes through the\n * SAME `SandboxClient` the bin already loads from its sandbox key. Dedicated MCP variables name\n * the supervisor's router connection and exact model; inherited worker/model aliases are rejected.\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\nimport type { SandboxClient } from '../runtime'\nimport type { RouterTransportConfig } from '../runtime/router-client'\nimport { supervisorInstructions } from '../runtime/supervise/authoring'\nimport { coordinationProfileToolPrefix } from '../runtime/supervise/provider-visible-profile'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { DelegateHandlerOptions } from './tools/delegate'\n\nfunction trimmed(value: string | undefined): string | undefined {\n const v = value?.trim()\n return v ? v : undefined\n}\n\nfunction requiredEnv(env: NodeJS.ProcessEnv, name: string): string {\n const value = trimmed(env[name])\n if (value) return value\n throw new ConfigError(`agent-runtime-mcp: ${name} is required when MCP_ENABLE_DELEGATE=1`)\n}\n\n/** True when the operator opted the generic `delegate` verb in (`MCP_ENABLE_DELEGATE=1`). Default off:\n * the wiring is additive, so consumers that do not enable it are unaffected. */\nexport function delegateEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.MCP_ENABLE_DELEGATE === '1'\n}\n\n/**\n * The Runtime verbs the authoring supervisor is granted. A profile gets no coordination tool it does\n * not declare, so without `spawn_worker` the brain is offered no tools and every delegation settles\n * `no-children-spawned`. The rest let it inspect, steer, stop, and re-read what it already spawned,\n * which its authoring instruction tells it to do.\n */\nconst delegateSupervisorVerbs = [\n 'spawn_worker',\n 'observe_agent',\n 'steer_agent',\n 'cancel_worker',\n 'read_journal',\n] as const\n\n/**\n * The `delegate` caller asked for a worker to do the task, and only a worker's settled result is\n * delivered. A capable brain otherwise answers a small intent itself (gemini-3.7-flash and kimi-k3\n * both replied to \"Reply with exactly DELEGATED-391\" directly), which settles `no-children-spawned`\n * and discards the answer.\n */\nconst delegateContract = [\n '',\n 'This task came through `delegate`: the caller wants a worker to do it. However small the task,',\n 'call spawn_worker at least once before you end your turn. Your own reply is never delivered;',\n \"only a worker's settled result is.\",\n].join('\\n')\n\n/**\n * Resolve the supervisor brain from dedicated MCP configuration. The model is part of the exact\n * profile; the URL and key are transport-only. No generic worker/model/key variable may silently\n * select this paid execution path.\n */\nfunction resolveRouterSupervisor(env: NodeJS.ProcessEnv): {\n router: RouterTransportConfig\n profile: AgentProfile\n} {\n const routerKey = requiredEnv(env, 'MCP_SUPERVISOR_ROUTER_KEY')\n const base = requiredEnv(env, 'MCP_SUPERVISOR_ROUTER_BASE_URL')\n const routerBaseUrl = /\\/v\\d+\\/?$/.test(base)\n ? base.replace(/\\/$/, '')\n : `${base.replace(/\\/$/, '')}/v1`\n const model = requiredEnv(env, 'MCP_SUPERVISOR_MODEL')\n // The consumer's own policy for the workers this supervisor authors, such as the only harness and\n // model its worker boxes can run. Without it the brain picks instruments from memory, and on\n // 2026-10-19 every one it picked (claude-code on Anthropic, nanoclaw, cli-base) died in the box.\n const consumerInstructions = trimmed(env.MCP_SUPERVISOR_INSTRUCTIONS)\n return {\n router: { routerBaseUrl, routerKey },\n profile: {\n name: 'delegate-supervisor',\n harness: 'cli-base',\n model: { provider: 'tangle-router', default: model },\n prompt: {\n systemPrompt: [\n supervisorInstructions(),\n delegateContract,\n ...(consumerInstructions ? ['', consumerInstructions] : []),\n ].join('\\n'),\n },\n tools: Object.fromEntries(\n delegateSupervisorVerbs.map((verb) => [`${coordinationProfileToolPrefix}${verb}`, true]),\n ),\n },\n }\n}\n\n/**\n * Build the `delegateSupervisor` substrate for `createMcpServer` from env + the bin's loaded\n * `SandboxClient`. Returns `undefined` when `delegate` is not opted in, so the caller mounts it only\n * when asked. The worker backend is `sandbox`; every authored worker's exact profile selects its\n * own harness/provider/model.\n */\nexport function resolveDelegateSupervisor(\n sandboxClient: SandboxClient,\n env: NodeJS.ProcessEnv = process.env,\n): DelegateHandlerOptions | undefined {\n if (!delegateEnabled(env)) return undefined\n const supervisor = resolveRouterSupervisor(env)\n const backend: ExecutorConfig = {\n backend: 'sandbox',\n sandboxClient,\n }\n return {\n router: supervisor.router,\n supervisorProfile: supervisor.profile,\n backend,\n }\n}\n","#!/usr/bin/env node\n\n/**\n *\n * `agent-runtime-mcp` — stdio MCP server entry point.\n *\n * Serves the ONE generic `delegate` verb (opt-in via `MCP_ENABLE_DELEGATE=1`): one intent → a\n * supervisor that authors + drives its own worker over `supervise()`, returning the delivered output\n * with its cost. The supervisor brain runs on the router; authored workers run as sub-sandboxes\n * through the `SandboxClient` the bin loads from the sandbox key. The queue-bound tools\n * (`delegate_feedback`, `delegation_status`, `delegation_history`) are always served.\n *\n * A platform key serves one product, so the Sandbox API key and the router key are separate\n * variables: the sandbox key only constructs the Sandbox client, and the router key only reaches\n * the supervisor brain. Neither is forwarded into a worker box; each worker's model access comes\n * from the box its profile provisions.\n *\n * Environment variables:\n * TANGLE_SANDBOX_API_KEY Sandbox API key passed to `new Sandbox({ apiKey })`. Falls back\n * to TANGLE_API_KEY when unset, so one key that serves the Sandbox\n * API keeps working.\n * TANGLE_API_KEY Sandbox API key when TANGLE_SANDBOX_API_KEY is unset\n * SANDBOX_BASE_URL optional — sandbox-SDK base URL override\n * MCP_ENABLE_DELEGATE set to `1` to serve the generic `delegate` verb. Its authoring\n * supervisor runs the brain on the router and spawns authored\n * workers as sub-sandboxes via the same client; needs a sandbox key.\n * MCP_SUPERVISOR_MODEL required exact supervisor brain model id\n * MCP_SUPERVISOR_ROUTER_KEY required router key for the supervisor brain\n * MCP_SUPERVISOR_ROUTER_BASE_URL required router base, normalized to `/v1`\n * MCP_SUPERVISOR_INSTRUCTIONS optional text appended to the supervisor's system prompt: the\n * caller's policy for the workers it authors, such as the harness\n * and model its worker boxes can run\n * AGENT_RUNTIME_DELEGATION_STATE_FILE\n * optional — absolute path of a JSON state\n * file. When set, delegation records persist\n * across MCP restarts (FileDelegationStore):\n * status/history survive and idempotency keys\n * dedupe across processes.\n * AGENT_RUNTIME_DELEGATION_STATE_RECOVER\n * set to `1` to archive a corrupt state file\n * (`<file>.corrupt-<ts>`) and start empty\n * instead of refusing to boot.\n * AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL\n * optional — positive integer cap on retained\n * terminal records. Unset = keep forever.\n *\n * @experimental\n */\n\nimport type { SandboxClient } from '../runtime'\nimport { delegateEnabled, resolveDelegateSupervisor } from './delegate-supervisor-provisioning'\nimport { FileDelegationStore } from './delegation-store'\nimport { createMcpServer } from './server'\nimport { DelegationTaskQueue } from './task-queue'\nimport type { DelegateHandlerOptions } from './tools/delegate'\nimport { readTraceContextFromEnv, type TraceContext } from './trace-propagation'\n\nconst DEFAULT_SANDBOX_BASE_URL = 'https://sandbox.tangle.tools'\n\nasync function main(): Promise<void> {\n const wantDelegate = delegateEnabled(process.env)\n\n // The generic `delegate` verb needs the sandbox client: its authored workers run as sub-sandboxes\n // (the `sandbox` backend). When `delegate` is not opted in, the server runs the queue-only subset\n // (feedback + status + history) with no sandbox.\n let sandboxClient: SandboxClient | undefined\n if (wantDelegate) {\n const apiKey = sandboxApiKey(process.env)\n if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {\n process.stderr.write(\n 'agent-runtime-mcp: a Sandbox API key is required to serve `delegate`: set TANGLE_SANDBOX_API_KEY (or TANGLE_API_KEY when that key serves the Sandbox API). Set AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 to run without it for diagnostics, or unset MCP_ENABLE_DELEGATE to run the queue-only subset.\\n',\n )\n process.exit(2)\n }\n sandboxClient = await loadSandboxClient(apiKey)\n }\n\n // The supervisor's loop topology spans export to the OTLP / Tangle Intelligence sink when\n // OTEL_EXPORTER_OTLP_ENDPOINT is set (+ TRACE_ID / PARENT_SPAN_ID for correlation). The same\n // context is stamped onto every delegation record so journal consumers join records into the\n // caller's trace.\n const traceContext = readTraceContextFromEnv()\n if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {\n process.stderr.write(\n `agent-runtime-mcp: exporting loop topology → ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}\\n`,\n )\n }\n\n // The ONE generic `delegate` verb — opt-in via MCP_ENABLE_DELEGATE=1. Its authoring supervisor\n // runs the brain on the router and spawns authored workers as sub-sandboxes through the SAME\n // client, so it needs the loaded `sandboxClient`. Gated on the client resolving (no key → no\n // delegate, fail-closed).\n let delegateSupervisor: DelegateHandlerOptions | undefined\n if (wantDelegate && sandboxClient) {\n try {\n delegateSupervisor = resolveDelegateSupervisor(sandboxClient)\n } catch (error) {\n // Refuse to serve a verb that cannot work. Advertising `delegate` on an\n // unresolvable substrate spends an agent's turn on a tool whose first\n // inference is guaranteed to reject.\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`)\n process.exit(2)\n }\n }\n if (delegateSupervisor) {\n process.stderr.write(\n `agent-runtime-mcp: delegate enabled — generic authoring supervisor on ${delegateSupervisor.supervisorProfile.model?.default}\\n`,\n )\n }\n\n const durableQueue = await buildDurableQueueFromEnv(traceContext)\n const server = createMcpServer({\n ...(delegateSupervisor ? { delegateSupervisor } : {}),\n traceContext,\n ...(durableQueue ? { queue: durableQueue } : {}),\n })\n\n const shutdown = () => {\n server.stop()\n // Drain journal writes so the state file reflects the final record\n // states before the process exits. A persist failure already routed\n // through onPersistError; swallow the duplicate rejection here.\n if (durableQueue) {\n void durableQueue\n .flush()\n .catch(() => {})\n .finally(() => process.exit(0))\n return\n }\n process.exit(0)\n }\n process.on('SIGINT', shutdown)\n process.on('SIGTERM', shutdown)\n\n await server.serve()\n}\n\nasync function buildDurableQueueFromEnv(\n traceContext: TraceContext,\n): Promise<DelegationTaskQueue | undefined> {\n const stateFile = process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim()\n if (!stateFile) return undefined\n const store = new FileDelegationStore({\n filePath: stateFile,\n recoverCorrupt: process.env.AGENT_RUNTIME_DELEGATION_STATE_RECOVER === '1',\n })\n const maxTerminalRecords = parseRetention(process.env.AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL)\n const queue = await DelegationTaskQueue.restore({\n store,\n traceContext,\n ...(maxTerminalRecords !== undefined ? { maxTerminalRecords } : {}),\n onPersistError: (error) => {\n // Durable mode that can no longer write is a broken contract: crash\n // loud instead of degrading to memory-only behind the caller's back.\n process.stderr.write(`agent-runtime-mcp: ${error.message}\\n`)\n process.exit(1)\n },\n })\n process.stderr.write(`agent-runtime-mcp: durable delegation state → ${stateFile}\\n`)\n return queue\n}\n\nfunction parseRetention(raw: string | undefined): number | undefined {\n if (raw === undefined || raw.trim() === '') return undefined\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1) {\n process.stderr.write(\n `agent-runtime-mcp: AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL must be a positive integer, got \"${raw}\"\\n`,\n )\n process.exit(2)\n }\n return n\n}\n\n/** The Sandbox API key: the dedicated variable when set, else the legacy single key. The router key\n * (`MCP_SUPERVISOR_ROUTER_KEY`) is read only by the supervisor provisioning. */\nfunction sandboxApiKey(env: NodeJS.ProcessEnv): string | undefined {\n return env.TANGLE_SANDBOX_API_KEY?.trim() || env.TANGLE_API_KEY?.trim() || undefined\n}\n\nasync function loadSandboxClient(apiKey: string | undefined): Promise<SandboxClient> {\n // Diagnostic mode: AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 enables tools/list + the\n // queue-bound tools (status / history / feedback) without sandbox creds.\n // `delegate` requires a real client; the stub fails loud at create() so the\n // agent observes the cause instead of silent success.\n if (!apiKey) {\n return {\n async create() {\n throw new Error(\n 'agent-runtime-mcp: no Sandbox API key is set; `delegate` is disabled in diagnostic mode. Set TANGLE_SANDBOX_API_KEY (or TANGLE_API_KEY) or unset MCP_ENABLE_DELEGATE to remove the unsupported tool from the tool list.',\n )\n },\n } satisfies SandboxClient\n }\n // Diagnostic mode does not need a client, so defer SDK initialization until\n // delegation is requested. Runtime declares the SDK as a required peer.\n const mod = await import('@tangle-network/sandbox').catch((err) => {\n process.stderr.write(\n `agent-runtime-mcp: failed to load @tangle-network/sandbox (${err.message}); install the peer dependency\\n`,\n )\n process.exit(2)\n })\n const SandboxCtor = (mod as { Sandbox?: new (config: unknown) => SandboxClient }).Sandbox\n if (!SandboxCtor) {\n process.stderr.write(\n 'agent-runtime-mcp: @tangle-network/sandbox does not export Sandbox; cannot construct client\\n',\n )\n process.exit(2)\n }\n // @tangle-network/sandbox ≥0.6 makes baseUrl required; default it so the MCP server\n // starts without forcing every caller to set SANDBOX_BASE_URL. Treat empty/whitespace as\n // unset (|| not ??) so `SANDBOX_BASE_URL=` still resolves to the default.\n const baseUrl = process.env.SANDBOX_BASE_URL?.trim() || DEFAULT_SANDBOX_BASE_URL\n return new SandboxCtor({ apiKey, baseUrl })\n}\n\nmain().catch((err) => {\n process.stderr.write(`agent-runtime-mcp: ${err instanceof Error ? err.stack : String(err)}\\n`)\n process.exit(1)\n})\n"],"mappings":";;;;;;AAwBA,SAAS,QAAQ,OAA+C;CAC9D,MAAM,IAAI,OAAO,KAAK;CACtB,OAAO,IAAI,IAAI,KAAA;AACjB;AAEA,SAAS,YAAY,KAAwB,MAAsB;CACjE,MAAM,QAAQ,QAAQ,IAAI,KAAK;CAC/B,IAAI,OAAO,OAAO;CAClB,MAAM,IAAI,YAAY,sBAAsB,KAAK,wCAAwC;AAC3F;;;AAIA,SAAgB,gBAAgB,MAAyB,QAAQ,KAAc;CAC7E,OAAO,IAAI,wBAAwB;AACrC;;;;;;;AAQA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;;;AAOX,SAAS,wBAAwB,KAG/B;CACA,MAAM,YAAY,YAAY,KAAK,2BAA2B;CAC9D,MAAM,OAAO,YAAY,KAAK,gCAAgC;CAC9D,MAAM,gBAAgB,aAAa,KAAK,IAAI,IACxC,KAAK,QAAQ,OAAO,EAAE,IACtB,GAAG,KAAK,QAAQ,OAAO,EAAE,EAAE;CAC/B,MAAM,QAAQ,YAAY,KAAK,sBAAsB;CAIrD,MAAM,uBAAuB,QAAQ,IAAI,2BAA2B;CACpE,OAAO;EACL,QAAQ;GAAE;GAAe;EAAU;EACnC,SAAS;GACP,MAAM;GACN,SAAS;GACT,OAAO;IAAE,UAAU;IAAiB,SAAS;GAAM;GACnD,QAAQ,EACN,cAAc;IACZ,uBAAuB;IACvB;IACA,GAAI,uBAAuB,CAAC,IAAI,oBAAoB,IAAI,CAAC;GAC3D,CAAC,CAAC,KAAK,IAAI,EACb;GACA,OAAO,OAAO,YACZ,wBAAwB,KAAK,SAAS,CAAC,GAAG,gCAAgC,QAA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EACF;CAUF,MAAM,eAAe,MANH,OAAO,0BAA0B,CAAC,OAAO,QAAQ;EACjE,QAAQ,OAAO,MACb,8DAA8D,IAAI,QAAQ,iCAC5E;EACA,QAAQ,KAAK,CAAC;CAChB,CAAC,EAAA,CACiF;CAClF,IAAI,CAAC,aAAa;EAChB,QAAQ,OAAO,MACb,+FACF;EACA,QAAQ,KAAK,CAAC;CAChB;CAKA,OAAO,IAAI,YAAY;EAAE;EAAQ,SADjB,QAAQ,IAAI,kBAAkB,KAAK,KAAK;CACf,CAAC;AAC5C;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,OAAO,MAAM,sBAAsB,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG,EAAE,GAAG;CAC7F,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
|
1
|
+
{"version":3,"file":"bin.js","names":[],"sources":["../../src/mcp/delegate-supervisor-provisioning.ts","../../src/mcp/bin.ts"],"sourcesContent":["/**\n *\n * Resolve the `delegate` supervisor substrate (router brain + worker backend) from env, so the\n * `agent-runtime-mcp` bin can serve the ONE generic `delegate` verb by env, over the SAME stdio\n * invocation a consumer already mounts.\n *\n * `delegate` is wired into `createMcpServer` via `McpServerOptions.delegateSupervisor`, which needs a\n * router (the supervisor brain's transport) and a backend (WHERE the authored workers run). Inside a\n * sandbox child the natural backend is `sandbox`: authored workers run as sub-sandboxes through the\n * SAME `SandboxClient` the bin already loads from its sandbox key. Dedicated MCP variables name\n * the supervisor's router connection and exact model; inherited worker/model aliases are rejected.\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../errors'\nimport type { SandboxClient } from '../runtime'\nimport type { RouterTransportConfig } from '../runtime/router-http-transport'\nimport { supervisorInstructions } from '../runtime/supervise/authoring'\nimport { coordinationProfileToolPrefix } from '../runtime/supervise/provider-visible-profile'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { DelegateHandlerOptions } from './tools/delegate'\n\nfunction trimmed(value: string | undefined): string | undefined {\n const v = value?.trim()\n return v ? v : undefined\n}\n\nfunction requiredEnv(env: NodeJS.ProcessEnv, name: string): string {\n const value = trimmed(env[name])\n if (value) return value\n throw new ConfigError(`agent-runtime-mcp: ${name} is required when MCP_ENABLE_DELEGATE=1`)\n}\n\n/** True when the operator opted the generic `delegate` verb in (`MCP_ENABLE_DELEGATE=1`). Default off:\n * the wiring is additive, so consumers that do not enable it are unaffected. */\nexport function delegateEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.MCP_ENABLE_DELEGATE === '1'\n}\n\n/**\n * The Runtime verbs the authoring supervisor is granted. A profile gets no coordination tool it does\n * not declare, so without `spawn_worker` the brain is offered no tools and every delegation settles\n * `no-children-spawned`. The rest let it inspect, steer, stop, and re-read what it already spawned,\n * which its authoring instruction tells it to do.\n */\nconst delegateSupervisorVerbs = [\n 'spawn_worker',\n 'observe_agent',\n 'steer_agent',\n 'cancel_worker',\n 'read_journal',\n] as const\n\n/**\n * The `delegate` caller asked for a worker to do the task, and only a worker's settled result is\n * delivered. A capable brain otherwise answers a small intent itself (gemini-3.7-flash and kimi-k3\n * both replied to \"Reply with exactly DELEGATED-391\" directly), which settles `no-children-spawned`\n * and discards the answer.\n */\nconst delegateContract = [\n '',\n 'This task came through `delegate`: the caller wants a worker to do it. However small the task,',\n 'call spawn_worker at least once before you end your turn. Your own reply is never delivered;',\n \"only a worker's settled result is.\",\n].join('\\n')\n\n/**\n * Resolve the supervisor brain from dedicated MCP configuration. The model is part of the exact\n * profile; the URL and key are transport-only. No generic worker/model/key variable may silently\n * select this paid execution path.\n */\nfunction resolveRouterSupervisor(env: NodeJS.ProcessEnv): {\n router: RouterTransportConfig\n profile: AgentProfile\n} {\n const routerKey = requiredEnv(env, 'MCP_SUPERVISOR_ROUTER_KEY')\n const base = requiredEnv(env, 'MCP_SUPERVISOR_ROUTER_BASE_URL')\n const routerBaseUrl = /\\/v\\d+\\/?$/.test(base)\n ? base.replace(/\\/$/, '')\n : `${base.replace(/\\/$/, '')}/v1`\n const model = requiredEnv(env, 'MCP_SUPERVISOR_MODEL')\n // The consumer's own policy for the workers this supervisor authors, such as the only harness and\n // model its worker boxes can run. Without it the brain picks instruments from memory, and on\n // 2026-10-19 every one it picked (claude-code on Anthropic, nanoclaw, cli-base) died in the box.\n const consumerInstructions = trimmed(env.MCP_SUPERVISOR_INSTRUCTIONS)\n return {\n router: { routerBaseUrl, routerKey },\n profile: {\n name: 'delegate-supervisor',\n harness: 'cli-base',\n model: { provider: 'tangle-router', default: model },\n prompt: {\n systemPrompt: [\n supervisorInstructions(),\n delegateContract,\n ...(consumerInstructions ? ['', consumerInstructions] : []),\n ].join('\\n'),\n },\n tools: Object.fromEntries(\n delegateSupervisorVerbs.map((verb) => [`${coordinationProfileToolPrefix}${verb}`, true]),\n ),\n },\n }\n}\n\n/**\n * Build the `delegateSupervisor` substrate for `createMcpServer` from env + the bin's loaded\n * `SandboxClient`. Returns `undefined` when `delegate` is not opted in, so the caller mounts it only\n * when asked. The worker backend is `sandbox`; every authored worker's exact profile selects its\n * own harness/provider/model.\n */\nexport function resolveDelegateSupervisor(\n sandboxClient: SandboxClient,\n env: NodeJS.ProcessEnv = process.env,\n): DelegateHandlerOptions | undefined {\n if (!delegateEnabled(env)) return undefined\n const supervisor = resolveRouterSupervisor(env)\n const backend: ExecutorConfig = {\n backend: 'sandbox',\n sandboxClient,\n }\n return {\n router: supervisor.router,\n supervisorProfile: supervisor.profile,\n backend,\n }\n}\n","#!/usr/bin/env node\n\n/**\n *\n * `agent-runtime-mcp` — stdio MCP server entry point.\n *\n * Serves the ONE generic `delegate` verb (opt-in via `MCP_ENABLE_DELEGATE=1`): one intent → a\n * supervisor that authors + drives its own worker over `supervise()`, returning the delivered output\n * with its cost. The supervisor brain runs on the router; authored workers run as sub-sandboxes\n * through the `SandboxClient` the bin loads from the sandbox key. The queue-bound tools\n * (`delegate_feedback`, `delegation_status`, `delegation_history`) are always served.\n *\n * A platform key serves one product, so the Sandbox API key and the router key are separate\n * variables: the sandbox key only constructs the Sandbox client, and the router key only reaches\n * the supervisor brain. Neither is forwarded into a worker box; each worker's model access comes\n * from the box its profile provisions.\n *\n * Environment variables:\n * TANGLE_SANDBOX_API_KEY Sandbox API key passed to `new Sandbox({ apiKey })`. Falls back\n * to TANGLE_API_KEY when unset, so one key that serves the Sandbox\n * API keeps working.\n * TANGLE_API_KEY Sandbox API key when TANGLE_SANDBOX_API_KEY is unset\n * SANDBOX_BASE_URL optional — sandbox-SDK base URL override\n * MCP_ENABLE_DELEGATE set to `1` to serve the generic `delegate` verb. Its authoring\n * supervisor runs the brain on the router and spawns authored\n * workers as sub-sandboxes via the same client; needs a sandbox key.\n * MCP_SUPERVISOR_MODEL required exact supervisor brain model id\n * MCP_SUPERVISOR_ROUTER_KEY required router key for the supervisor brain\n * MCP_SUPERVISOR_ROUTER_BASE_URL required router base, normalized to `/v1`\n * MCP_SUPERVISOR_INSTRUCTIONS optional text appended to the supervisor's system prompt: the\n * caller's policy for the workers it authors, such as the harness\n * and model its worker boxes can run\n * AGENT_RUNTIME_DELEGATION_STATE_FILE\n * optional — absolute path of a JSON state\n * file. When set, delegation records persist\n * across MCP restarts (FileDelegationStore):\n * status/history survive and idempotency keys\n * dedupe across processes.\n * AGENT_RUNTIME_DELEGATION_STATE_RECOVER\n * set to `1` to archive a corrupt state file\n * (`<file>.corrupt-<ts>`) and start empty\n * instead of refusing to boot.\n * AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL\n * optional — positive integer cap on retained\n * terminal records. Unset = keep forever.\n *\n * @experimental\n */\n\nimport type { SandboxClient } from '../runtime'\nimport { delegateEnabled, resolveDelegateSupervisor } from './delegate-supervisor-provisioning'\nimport { FileDelegationStore } from './delegation-store'\nimport { createMcpServer } from './server'\nimport { DelegationTaskQueue } from './task-queue'\nimport type { DelegateHandlerOptions } from './tools/delegate'\nimport { readTraceContextFromEnv, type TraceContext } from './trace-propagation'\n\nconst DEFAULT_SANDBOX_BASE_URL = 'https://sandbox.tangle.tools'\n\nasync function main(): Promise<void> {\n const wantDelegate = delegateEnabled(process.env)\n\n // The generic `delegate` verb needs the sandbox client: its authored workers run as sub-sandboxes\n // (the `sandbox` backend). When `delegate` is not opted in, the server runs the queue-only subset\n // (feedback + status + history) with no sandbox.\n let sandboxClient: SandboxClient | undefined\n if (wantDelegate) {\n const apiKey = sandboxApiKey(process.env)\n if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {\n process.stderr.write(\n 'agent-runtime-mcp: a Sandbox API key is required to serve `delegate`: set TANGLE_SANDBOX_API_KEY (or TANGLE_API_KEY when that key serves the Sandbox API). Set AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 to run without it for diagnostics, or unset MCP_ENABLE_DELEGATE to run the queue-only subset.\\n',\n )\n process.exit(2)\n }\n sandboxClient = await loadSandboxClient(apiKey)\n }\n\n // The supervisor's loop topology spans export to the OTLP / Tangle Intelligence sink when\n // OTEL_EXPORTER_OTLP_ENDPOINT is set (+ TRACE_ID / PARENT_SPAN_ID for correlation). The same\n // context is stamped onto every delegation record so journal consumers join records into the\n // caller's trace.\n const traceContext = readTraceContextFromEnv()\n if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {\n process.stderr.write(\n `agent-runtime-mcp: exporting loop topology → ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}\\n`,\n )\n }\n\n // The ONE generic `delegate` verb — opt-in via MCP_ENABLE_DELEGATE=1. Its authoring supervisor\n // runs the brain on the router and spawns authored workers as sub-sandboxes through the SAME\n // client, so it needs the loaded `sandboxClient`. Gated on the client resolving (no key → no\n // delegate, fail-closed).\n let delegateSupervisor: DelegateHandlerOptions | undefined\n if (wantDelegate && sandboxClient) {\n try {\n delegateSupervisor = resolveDelegateSupervisor(sandboxClient)\n } catch (error) {\n // Refuse to serve a verb that cannot work. Advertising `delegate` on an\n // unresolvable substrate spends an agent's turn on a tool whose first\n // inference is guaranteed to reject.\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`)\n process.exit(2)\n }\n }\n if (delegateSupervisor) {\n process.stderr.write(\n `agent-runtime-mcp: delegate enabled — generic authoring supervisor on ${delegateSupervisor.supervisorProfile.model?.default}\\n`,\n )\n }\n\n const durableQueue = await buildDurableQueueFromEnv(traceContext)\n const server = createMcpServer({\n ...(delegateSupervisor ? { delegateSupervisor } : {}),\n traceContext,\n ...(durableQueue ? { queue: durableQueue } : {}),\n })\n\n const shutdown = () => {\n server.stop()\n // Drain journal writes so the state file reflects the final record\n // states before the process exits. A persist failure already routed\n // through onPersistError; swallow the duplicate rejection here.\n if (durableQueue) {\n void durableQueue\n .flush()\n .catch(() => {})\n .finally(() => process.exit(0))\n return\n }\n process.exit(0)\n }\n process.on('SIGINT', shutdown)\n process.on('SIGTERM', shutdown)\n\n await server.serve()\n}\n\nasync function buildDurableQueueFromEnv(\n traceContext: TraceContext,\n): Promise<DelegationTaskQueue | undefined> {\n const stateFile = process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim()\n if (!stateFile) return undefined\n const store = new FileDelegationStore({\n filePath: stateFile,\n recoverCorrupt: process.env.AGENT_RUNTIME_DELEGATION_STATE_RECOVER === '1',\n })\n const maxTerminalRecords = parseRetention(process.env.AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL)\n const queue = await DelegationTaskQueue.restore({\n store,\n traceContext,\n ...(maxTerminalRecords !== undefined ? { maxTerminalRecords } : {}),\n onPersistError: (error) => {\n // Durable mode that can no longer write is a broken contract: crash\n // loud instead of degrading to memory-only behind the caller's back.\n process.stderr.write(`agent-runtime-mcp: ${error.message}\\n`)\n process.exit(1)\n },\n })\n process.stderr.write(`agent-runtime-mcp: durable delegation state → ${stateFile}\\n`)\n return queue\n}\n\nfunction parseRetention(raw: string | undefined): number | undefined {\n if (raw === undefined || raw.trim() === '') return undefined\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1) {\n process.stderr.write(\n `agent-runtime-mcp: AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL must be a positive integer, got \"${raw}\"\\n`,\n )\n process.exit(2)\n }\n return n\n}\n\n/** The Sandbox API key: the dedicated variable when set, else the legacy single key. The router key\n * (`MCP_SUPERVISOR_ROUTER_KEY`) is read only by the supervisor provisioning. */\nfunction sandboxApiKey(env: NodeJS.ProcessEnv): string | undefined {\n return env.TANGLE_SANDBOX_API_KEY?.trim() || env.TANGLE_API_KEY?.trim() || undefined\n}\n\nasync function loadSandboxClient(apiKey: string | undefined): Promise<SandboxClient> {\n // Diagnostic mode: AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 enables tools/list + the\n // queue-bound tools (status / history / feedback) without sandbox creds.\n // `delegate` requires a real client; the stub fails loud at create() so the\n // agent observes the cause instead of silent success.\n if (!apiKey) {\n return {\n async create() {\n throw new Error(\n 'agent-runtime-mcp: no Sandbox API key is set; `delegate` is disabled in diagnostic mode. Set TANGLE_SANDBOX_API_KEY (or TANGLE_API_KEY) or unset MCP_ENABLE_DELEGATE to remove the unsupported tool from the tool list.',\n )\n },\n } satisfies SandboxClient\n }\n // Diagnostic mode does not need a client, so defer SDK initialization until\n // delegation is requested. Runtime declares the SDK as a required peer.\n const mod = await import('@tangle-network/sandbox').catch((err) => {\n process.stderr.write(\n `agent-runtime-mcp: failed to load @tangle-network/sandbox (${err.message}); install the peer dependency\\n`,\n )\n process.exit(2)\n })\n const SandboxCtor = (mod as { Sandbox?: new (config: unknown) => SandboxClient }).Sandbox\n if (!SandboxCtor) {\n process.stderr.write(\n 'agent-runtime-mcp: @tangle-network/sandbox does not export Sandbox; cannot construct client\\n',\n )\n process.exit(2)\n }\n // @tangle-network/sandbox ≥0.6 makes baseUrl required; default it so the MCP server\n // starts without forcing every caller to set SANDBOX_BASE_URL. Treat empty/whitespace as\n // unset (|| not ??) so `SANDBOX_BASE_URL=` still resolves to the default.\n const baseUrl = process.env.SANDBOX_BASE_URL?.trim() || DEFAULT_SANDBOX_BASE_URL\n return new SandboxCtor({ apiKey, baseUrl })\n}\n\nmain().catch((err) => {\n process.stderr.write(`agent-runtime-mcp: ${err instanceof Error ? err.stack : String(err)}\\n`)\n process.exit(1)\n})\n"],"mappings":";;;;;;AAwBA,SAAS,QAAQ,OAA+C;CAC9D,MAAM,IAAI,OAAO,KAAK;CACtB,OAAO,IAAI,IAAI,KAAA;AACjB;AAEA,SAAS,YAAY,KAAwB,MAAsB;CACjE,MAAM,QAAQ,QAAQ,IAAI,KAAK;CAC/B,IAAI,OAAO,OAAO;CAClB,MAAM,IAAI,YAAY,sBAAsB,KAAK,wCAAwC;AAC3F;;;AAIA,SAAgB,gBAAgB,MAAyB,QAAQ,KAAc;CAC7E,OAAO,IAAI,wBAAwB;AACrC;;;;;;;AAQA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;;;AAOX,SAAS,wBAAwB,KAG/B;CACA,MAAM,YAAY,YAAY,KAAK,2BAA2B;CAC9D,MAAM,OAAO,YAAY,KAAK,gCAAgC;CAC9D,MAAM,gBAAgB,aAAa,KAAK,IAAI,IACxC,KAAK,QAAQ,OAAO,EAAE,IACtB,GAAG,KAAK,QAAQ,OAAO,EAAE,EAAE;CAC/B,MAAM,QAAQ,YAAY,KAAK,sBAAsB;CAIrD,MAAM,uBAAuB,QAAQ,IAAI,2BAA2B;CACpE,OAAO;EACL,QAAQ;GAAE;GAAe;EAAU;EACnC,SAAS;GACP,MAAM;GACN,SAAS;GACT,OAAO;IAAE,UAAU;IAAiB,SAAS;GAAM;GACnD,QAAQ,EACN,cAAc;IACZ,uBAAuB;IACvB;IACA,GAAI,uBAAuB,CAAC,IAAI,oBAAoB,IAAI,CAAC;GAC3D,CAAC,CAAC,KAAK,IAAI,EACb;GACA,OAAO,OAAO,YACZ,wBAAwB,KAAK,SAAS,CAAC,GAAG,gCAAgC,QAAQ,IAAI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