@tangle-network/agent-runtime 0.105.0 → 0.106.1

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 (218) hide show
  1. package/README.md +2 -2
  2. package/dist/activation-CRjVfOiy.js +203 -0
  3. package/dist/activation-CRjVfOiy.js.map +1 -0
  4. package/dist/activation-DyWB0K6E.d.ts +98 -0
  5. package/dist/agent.d.ts +216 -234
  6. package/dist/agent.js +615 -547
  7. package/dist/agent.js.map +1 -1
  8. package/dist/analyst-loop-DGdtVENg.js +517 -0
  9. package/dist/analyst-loop-DGdtVENg.js.map +1 -0
  10. package/dist/analyst-loop.d.ts +10 -43
  11. package/dist/analyst-loop.js +2 -11
  12. package/dist/backends-CiOCyRHb.js +743 -0
  13. package/dist/backends-CiOCyRHb.js.map +1 -0
  14. package/dist/candidate-execution/index.d.ts +4 -192
  15. package/dist/candidate-execution/index.js +5 -66
  16. package/dist/candidate-execution-DqMbv1rU.js +488 -0
  17. package/dist/candidate-execution-DqMbv1rU.js.map +1 -0
  18. package/dist/coder-yhVWbdWc.js +40 -0
  19. package/dist/coder-yhVWbdWc.js.map +1 -0
  20. package/dist/conversation-BpLQZGPH.js +1265 -0
  21. package/dist/conversation-BpLQZGPH.js.map +1 -0
  22. package/dist/conversation.d.ts +2 -804
  23. package/dist/conversation.js +2 -55
  24. package/dist/environment-provider-CfLUmKmf.js +1168 -0
  25. package/dist/environment-provider-CfLUmKmf.js.map +1 -0
  26. package/dist/environment-provider-IUGU3epE.d.ts +964 -0
  27. package/dist/environment-provider.d.ts +2 -78
  28. package/dist/environment-provider.js +2 -18
  29. package/dist/errors-DEAvWQPy.js +111 -0
  30. package/dist/errors-DEAvWQPy.js.map +1 -0
  31. package/dist/improvement-adapter-Cr5TBSji.d.ts +166 -0
  32. package/dist/improvement-cycle-C095kS_g.js +2624 -0
  33. package/dist/improvement-cycle-C095kS_g.js.map +1 -0
  34. package/dist/index-BGdxAwfO.d.ts +838 -0
  35. package/dist/index-C-FYUuFG.d.ts +193 -0
  36. package/dist/index-CbNM40xG.d.ts +140 -0
  37. package/dist/index-DruSKs3Z.d.ts +7224 -0
  38. package/dist/index-Efjb3nrQ.d.ts +671 -0
  39. package/dist/index.d.ts +14 -1058
  40. package/dist/index.js +2106 -2082
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +768 -889
  43. package/dist/intelligence.js +1466 -1367
  44. package/dist/intelligence.js.map +1 -1
  45. package/dist/{kb-gate-CwHO0vz6.d.ts → kb-gate-C8z2juK8.d.ts} +33 -31
  46. package/dist/kb-gate-DpaSwXVx.js +80 -0
  47. package/dist/kb-gate-DpaSwXVx.js.map +1 -0
  48. package/dist/knowledge-Ku-mPP4f.js +433 -0
  49. package/dist/knowledge-Ku-mPP4f.js.map +1 -0
  50. package/dist/knowledge.d.ts +2 -150
  51. package/dist/knowledge.js +2 -40
  52. package/dist/local-harness-Dh8PJ0ot.d.ts +455 -0
  53. package/dist/loop-runner-bin-BXsFEUcf.d.ts +162 -0
  54. package/dist/loop-runner-bin-CRagyuNb.js +268 -0
  55. package/dist/loop-runner-bin-CRagyuNb.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -15
  57. package/dist/loop-runner-bin.js +2 -24
  58. package/dist/loops.d.ts +5 -4164
  59. package/dist/loops.js +8 -419
  60. package/dist/mcp/bin.d.ts +1 -1
  61. package/dist/mcp/bin.js +116 -146
  62. package/dist/mcp/bin.js.map +1 -1
  63. package/dist/mcp/index.d.ts +295 -436
  64. package/dist/mcp/index.js +1242 -1177
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/mcp/memory-bin.d.ts +1 -1
  67. package/dist/mcp/memory-bin.js +37 -16
  68. package/dist/mcp/memory-bin.js.map +1 -1
  69. package/dist/memory-server-DL6cE2Ag.js +234 -0
  70. package/dist/memory-server-DL6cE2Ag.js.map +1 -0
  71. package/dist/model-resolution-Btd9iIKV.js +98 -0
  72. package/dist/model-resolution-Btd9iIKV.js.map +1 -0
  73. package/dist/openai-tools-B68JaOCx.d.ts +24 -0
  74. package/dist/openai-tools-CKLy1C7M.js +44 -0
  75. package/dist/openai-tools-CKLy1C7M.js.map +1 -0
  76. package/dist/otel-export-D34IQW1C.js +843 -0
  77. package/dist/otel-export-D34IQW1C.js.map +1 -0
  78. package/dist/platform.d.ts +188 -185
  79. package/dist/platform.js +185 -218
  80. package/dist/platform.js.map +1 -1
  81. package/dist/prepare-B53sPV7M.js +4292 -0
  82. package/dist/prepare-B53sPV7M.js.map +1 -0
  83. package/dist/primeintellect/index.d.ts +149 -145
  84. package/dist/primeintellect/index.js +626 -1003
  85. package/dist/primeintellect/index.js.map +1 -1
  86. package/dist/profiles.d.ts +296 -490
  87. package/dist/profiles.js +722 -749
  88. package/dist/profiles.js.map +1 -1
  89. package/dist/protected-model-port-BLPH5VVv.js +722 -0
  90. package/dist/protected-model-port-BLPH5VVv.js.map +1 -0
  91. package/dist/protected-model-port-BP6Z4eau.d.ts +283 -0
  92. package/dist/protected-redaction--F3v1oo8.js +200 -0
  93. package/dist/protected-redaction--F3v1oo8.js.map +1 -0
  94. package/dist/redact-D-u-rrcn.js +82 -0
  95. package/dist/redact-D-u-rrcn.js.map +1 -0
  96. package/dist/redact-kbIOjfjM.d.ts +452 -0
  97. package/dist/researcher-CoVqNhfI.js +433 -0
  98. package/dist/researcher-CoVqNhfI.js.map +1 -0
  99. package/dist/runtime-5zM5XxLr.js +5408 -0
  100. package/dist/runtime-5zM5XxLr.js.map +1 -0
  101. package/dist/sandbox-events-DeI5xX8P.js +316 -0
  102. package/dist/sandbox-events-DeI5xX8P.js.map +1 -0
  103. package/dist/spawn-journal-CwPvKUTa.js +456 -0
  104. package/dist/spawn-journal-CwPvKUTa.js.map +1 -0
  105. package/dist/structural-rollout-IXUEplky.js +1445 -0
  106. package/dist/structural-rollout-IXUEplky.js.map +1 -0
  107. package/dist/substrate-B0TYNrXn.js +27 -0
  108. package/dist/substrate-B0TYNrXn.js.map +1 -0
  109. package/dist/{substrate-Dyiqmd3o.d.ts → substrate-BcnuSHXm.d.ts} +57 -54
  110. package/dist/supervise-BiRutHS9.js +7321 -0
  111. package/dist/supervise-BiRutHS9.js.map +1 -0
  112. package/dist/supervisor-DTKhF-RV.js +3826 -0
  113. package/dist/supervisor-DTKhF-RV.js.map +1 -0
  114. package/dist/testing.d.ts +4 -3
  115. package/dist/testing.js +2478 -2637
  116. package/dist/testing.js.map +1 -1
  117. package/dist/tool-server-RcWgLIsL.js +141 -0
  118. package/dist/tool-server-RcWgLIsL.js.map +1 -0
  119. package/dist/trace-propagation-CJJC7SVB.js +57 -0
  120. package/dist/trace-propagation-CJJC7SVB.js.map +1 -0
  121. package/dist/types-BaIpb0XT.d.ts +492 -0
  122. package/dist/types-BevOjfTY.d.ts +765 -0
  123. package/dist/types-C9j4qg6l.d.ts +500 -0
  124. package/dist/types-Cja5OTGh.d.ts +190 -0
  125. package/dist/util-MVgdwuIS.js +145 -0
  126. package/dist/util-MVgdwuIS.js.map +1 -0
  127. package/dist/workspace-archive-BosQiotA.js +575 -0
  128. package/dist/workspace-archive-BosQiotA.js.map +1 -0
  129. package/package.json +44 -56
  130. package/skills/build-with-agent-runtime/SKILL.md +1 -0
  131. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  132. package/dist/analyst-loop.js.map +0 -1
  133. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  134. package/dist/candidate-execution/index.js.map +0 -1
  135. package/dist/chunk-2KGAN2HM.js +0 -1256
  136. package/dist/chunk-2KGAN2HM.js.map +0 -1
  137. package/dist/chunk-2VZYRB55.js +0 -834
  138. package/dist/chunk-2VZYRB55.js.map +0 -1
  139. package/dist/chunk-3MDZX7YU.js +0 -125
  140. package/dist/chunk-3MDZX7YU.js.map +0 -1
  141. package/dist/chunk-5IBQAPVB.js +0 -29
  142. package/dist/chunk-5IBQAPVB.js.map +0 -1
  143. package/dist/chunk-5QOB7H74.js +0 -387
  144. package/dist/chunk-5QOB7H74.js.map +0 -1
  145. package/dist/chunk-C5RTIBNZ.js +0 -48
  146. package/dist/chunk-C5RTIBNZ.js.map +0 -1
  147. package/dist/chunk-CTRA64LY.js +0 -680
  148. package/dist/chunk-CTRA64LY.js.map +0 -1
  149. package/dist/chunk-DPEUKJRO.js +0 -27
  150. package/dist/chunk-DPEUKJRO.js.map +0 -1
  151. package/dist/chunk-FD2MBMOH.js +0 -494
  152. package/dist/chunk-FD2MBMOH.js.map +0 -1
  153. package/dist/chunk-H5QPIZNX.js +0 -907
  154. package/dist/chunk-H5QPIZNX.js.map +0 -1
  155. package/dist/chunk-HLKC4UYB.js +0 -3514
  156. package/dist/chunk-HLKC4UYB.js.map +0 -1
  157. package/dist/chunk-HNP72PNU.js +0 -192
  158. package/dist/chunk-HNP72PNU.js.map +0 -1
  159. package/dist/chunk-ISPWRSEC.js +0 -408
  160. package/dist/chunk-ISPWRSEC.js.map +0 -1
  161. package/dist/chunk-KRBFHMV6.js +0 -1228
  162. package/dist/chunk-KRBFHMV6.js.map +0 -1
  163. package/dist/chunk-M22PL4GH.js +0 -171
  164. package/dist/chunk-M22PL4GH.js.map +0 -1
  165. package/dist/chunk-NURIQBJQ.js +0 -72
  166. package/dist/chunk-NURIQBJQ.js.map +0 -1
  167. package/dist/chunk-OPVWXJ2H.js +0 -75
  168. package/dist/chunk-OPVWXJ2H.js.map +0 -1
  169. package/dist/chunk-PZZKQVQV.js +0 -52
  170. package/dist/chunk-PZZKQVQV.js.map +0 -1
  171. package/dist/chunk-Q2JSAVQ3.js +0 -671
  172. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  173. package/dist/chunk-RDOAVVHY.js +0 -699
  174. package/dist/chunk-RDOAVVHY.js.map +0 -1
  175. package/dist/chunk-SGKPNBXE.js +0 -60
  176. package/dist/chunk-SGKPNBXE.js.map +0 -1
  177. package/dist/chunk-SMQXZGLZ.js +0 -351
  178. package/dist/chunk-SMQXZGLZ.js.map +0 -1
  179. package/dist/chunk-UHEZW5BU.js +0 -2918
  180. package/dist/chunk-UHEZW5BU.js.map +0 -1
  181. package/dist/chunk-UPWGXKXB.js +0 -254
  182. package/dist/chunk-UPWGXKXB.js.map +0 -1
  183. package/dist/chunk-VISA6CI3.js +0 -200
  184. package/dist/chunk-VISA6CI3.js.map +0 -1
  185. package/dist/chunk-WMTCUOQL.js +0 -474
  186. package/dist/chunk-WMTCUOQL.js.map +0 -1
  187. package/dist/chunk-WRTOVNN4.js +0 -4728
  188. package/dist/chunk-WRTOVNN4.js.map +0 -1
  189. package/dist/chunk-WSTRQZYQ.js +0 -5576
  190. package/dist/chunk-WSTRQZYQ.js.map +0 -1
  191. package/dist/chunk-XBG2W2VW.js +0 -6434
  192. package/dist/chunk-XBG2W2VW.js.map +0 -1
  193. package/dist/chunk-YEJR7IXO.js +0 -68
  194. package/dist/chunk-YEJR7IXO.js.map +0 -1
  195. package/dist/chunk-YJZA2BIK.js +0 -1338
  196. package/dist/chunk-YJZA2BIK.js.map +0 -1
  197. package/dist/completion-gate-BMy5LGoP.d.ts +0 -256
  198. package/dist/conversation.js.map +0 -1
  199. package/dist/coordination-BZZSVYpZ.d.ts +0 -2570
  200. package/dist/environment-provider.js.map +0 -1
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-BDNcl6jI.d.ts +0 -175
  204. package/dist/loop-runner-bin-68aoM9-7.d.ts +0 -199
  205. package/dist/loop-runner-bin.js.map +0 -1
  206. package/dist/loops.js.map +0 -1
  207. package/dist/openai-tools-fnj6SRVg.d.ts +0 -46
  208. package/dist/protected-model-port-B4t-OQjL.d.ts +0 -271
  209. package/dist/redact-BuFjxBUJ.d.ts +0 -481
  210. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  211. package/dist/structural-rollout-DEh6CEsa.d.ts +0 -446
  212. package/dist/supervise-4_48wwvy.d.ts +0 -379
  213. package/dist/types-BCoemcXU.d.ts +0 -802
  214. package/dist/types-BwoZWq-i.d.ts +0 -510
  215. package/dist/types-Cbp72qyu.d.ts +0 -491
  216. package/dist/types-CmYCMbFT.d.ts +0 -203
  217. package/dist/types-CvNwMzQt.d.ts +0 -957
  218. package/dist/worktree-fanout-DxhAWr5Z.d.ts +0 -999
package/dist/mcp/bin.js CHANGED
@@ -1,166 +1,136 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- readTraceContextFromEnv
4
- } from "../chunk-PZZKQVQV.js";
5
- import {
6
- resolveRouterBaseUrl
7
- } from "../chunk-NURIQBJQ.js";
8
- import {
9
- DelegationTaskQueue,
10
- FileDelegationStore,
11
- createMcpServer
12
- } from "../chunk-XBG2W2VW.js";
13
- import "../chunk-DPEUKJRO.js";
14
- import "../chunk-2VZYRB55.js";
15
- import "../chunk-HLKC4UYB.js";
16
- import "../chunk-ISPWRSEC.js";
17
- import "../chunk-KRBFHMV6.js";
18
- import "../chunk-3MDZX7YU.js";
19
- import "../chunk-M22PL4GH.js";
20
- import "../chunk-YEJR7IXO.js";
21
-
22
- // src/mcp/delegate-supervisor-provisioning.ts
23
- var DEFAULT_SUPERVISOR_MODEL = "moonshotai/kimi-k2.6";
24
- var DEFAULT_WORKER_HARNESS = "opencode";
2
+ import { B as DelegationTaskQueue, X as FileDelegationStore, o as createMcpServer } from "../supervise-BiRutHS9.js";
3
+ import { a as resolveRouterBaseUrl } from "../model-resolution-Btd9iIKV.js";
4
+ import { n as readTraceContextFromEnv } from "../trace-propagation-CJJC7SVB.js";
5
+ //#region src/mcp/delegate-supervisor-provisioning.ts
6
+ const DEFAULT_SUPERVISOR_MODEL = "moonshotai/kimi-k2.6";
7
+ const DEFAULT_WORKER_HARNESS = "opencode";
25
8
  function trimmed(value) {
26
- const v = value?.trim();
27
- return v ? v : void 0;
9
+ const v = value?.trim();
10
+ return v ? v : void 0;
28
11
  }
12
+ /** True when the operator opted the generic `delegate` verb in (`MCP_ENABLE_DELEGATE=1`). Default off:
13
+ * the wiring is additive, so consumers that do not enable it are unaffected. */
29
14
  function delegateEnabled(env = process.env) {
30
- return env.MCP_ENABLE_DELEGATE === "1";
15
+ return env.MCP_ENABLE_DELEGATE === "1";
31
16
  }
17
+ /** Resolve the supervisor brain's router substrate from env. The key falls back through the platform
18
+ * key the bin already requires; the base reuses `resolveRouterBaseUrl`, normalised to `/v1`. */
32
19
  function resolveRouter(env) {
33
- const routerKey = trimmed(env.MCP_SUPERVISOR_ROUTER_KEY) ?? trimmed(env.TANGLE_API_KEY) ?? "";
34
- const base = trimmed(env.MCP_SUPERVISOR_ROUTER_BASE_URL) ?? resolveRouterBaseUrl(env);
35
- const routerBaseUrl = /\/v\d+\/?$/.test(base) ? base.replace(/\/$/, "") : `${base.replace(/\/$/, "")}/v1`;
36
- const model = trimmed(env.MCP_SUPERVISOR_MODEL) ?? trimmed(env.MCP_WORKER_MODEL) ?? trimmed(env.WORKER_MODEL) ?? DEFAULT_SUPERVISOR_MODEL;
37
- return { routerBaseUrl, routerKey, model };
20
+ const routerKey = trimmed(env.MCP_SUPERVISOR_ROUTER_KEY) ?? trimmed(env.TANGLE_API_KEY) ?? "";
21
+ const base = trimmed(env.MCP_SUPERVISOR_ROUTER_BASE_URL) ?? resolveRouterBaseUrl(env);
22
+ return {
23
+ routerBaseUrl: /\/v\d+\/?$/.test(base) ? base.replace(/\/$/, "") : `${base.replace(/\/$/, "")}/v1`,
24
+ routerKey,
25
+ model: trimmed(env.MCP_SUPERVISOR_MODEL) ?? trimmed(env.MCP_WORKER_MODEL) ?? trimmed(env.WORKER_MODEL) ?? DEFAULT_SUPERVISOR_MODEL
26
+ };
38
27
  }
28
+ /**
29
+ * Build the `delegateSupervisor` substrate for `createMcpServer` from env + the bin's loaded
30
+ * `SandboxClient`. Returns `undefined` when `delegate` is not opted in, so the caller mounts it only
31
+ * when asked. The worker backend is `sandbox` (authored workers run as sub-sandboxes via the same
32
+ * client) on the harness named by `MCP_DELEGATE_WORKER_HARNESS` (default `opencode`).
33
+ */
39
34
  function resolveDelegateSupervisor(sandboxClient, env = process.env) {
40
- if (!delegateEnabled(env)) return void 0;
41
- const router = resolveRouter(env);
42
- const harness = trimmed(env.MCP_DELEGATE_WORKER_HARNESS) ?? DEFAULT_WORKER_HARNESS;
43
- const backend = {
44
- backend: "sandbox",
45
- harness,
46
- sandboxClient
47
- };
48
- return {
49
- router,
50
- backend,
51
- model: router.model
52
- };
35
+ if (!delegateEnabled(env)) return void 0;
36
+ const router = resolveRouter(env);
37
+ return {
38
+ router,
39
+ backend: {
40
+ backend: "sandbox",
41
+ harness: trimmed(env.MCP_DELEGATE_WORKER_HARNESS) ?? DEFAULT_WORKER_HARNESS,
42
+ sandboxClient
43
+ },
44
+ model: router.model
45
+ };
53
46
  }
54
-
55
- // src/mcp/bin.ts
56
- var DEFAULT_SANDBOX_BASE_URL = "https://sandbox.tangle.tools";
47
+ //#endregion
48
+ //#region src/mcp/bin.ts
49
+ const DEFAULT_SANDBOX_BASE_URL = "https://sandbox.tangle.tools";
57
50
  async function main() {
58
- const wantDelegate = delegateEnabled(process.env);
59
- let sandboxClient;
60
- if (wantDelegate) {
61
- const apiKey = process.env.TANGLE_API_KEY;
62
- if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {
63
- process.stderr.write(
64
- "agent-runtime-mcp: TANGLE_API_KEY is required to serve `delegate`. 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"
65
- );
66
- process.exit(2);
67
- }
68
- sandboxClient = await loadSandboxClient(apiKey);
69
- }
70
- const traceContext = readTraceContextFromEnv();
71
- if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {
72
- process.stderr.write(
73
- `agent-runtime-mcp: exporting loop topology \u2192 ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}
74
- `
75
- );
76
- }
77
- const delegateSupervisor = wantDelegate && sandboxClient ? resolveDelegateSupervisor(sandboxClient) : void 0;
78
- if (wantDelegate && delegateSupervisor) {
79
- process.stderr.write("agent-runtime-mcp: delegate enabled \u2014 generic authoring supervisor\n");
80
- }
81
- const durableQueue = await buildDurableQueueFromEnv(traceContext);
82
- const server = createMcpServer({
83
- ...delegateSupervisor ? { delegateSupervisor } : {},
84
- traceContext,
85
- ...durableQueue ? { queue: durableQueue } : {}
86
- });
87
- const shutdown = () => {
88
- server.stop();
89
- if (durableQueue) {
90
- void durableQueue.flush().catch(() => {
91
- }).finally(() => process.exit(0));
92
- return;
93
- }
94
- process.exit(0);
95
- };
96
- process.on("SIGINT", shutdown);
97
- process.on("SIGTERM", shutdown);
98
- await server.serve();
51
+ const wantDelegate = delegateEnabled(process.env);
52
+ let sandboxClient;
53
+ if (wantDelegate) {
54
+ const apiKey = process.env.TANGLE_API_KEY;
55
+ if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {
56
+ process.stderr.write("agent-runtime-mcp: TANGLE_API_KEY is required to serve `delegate`. 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");
57
+ process.exit(2);
58
+ }
59
+ sandboxClient = await loadSandboxClient(apiKey);
60
+ }
61
+ const traceContext = readTraceContextFromEnv();
62
+ if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) process.stderr.write(`agent-runtime-mcp: exporting loop topology → ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}\n`);
63
+ const delegateSupervisor = wantDelegate && sandboxClient ? resolveDelegateSupervisor(sandboxClient) : void 0;
64
+ if (wantDelegate && delegateSupervisor) process.stderr.write("agent-runtime-mcp: delegate enabled — generic authoring supervisor\n");
65
+ const durableQueue = await buildDurableQueueFromEnv(traceContext);
66
+ const server = createMcpServer({
67
+ ...delegateSupervisor ? { delegateSupervisor } : {},
68
+ traceContext,
69
+ ...durableQueue ? { queue: durableQueue } : {}
70
+ });
71
+ const shutdown = () => {
72
+ server.stop();
73
+ if (durableQueue) {
74
+ durableQueue.flush().catch(() => {}).finally(() => process.exit(0));
75
+ return;
76
+ }
77
+ process.exit(0);
78
+ };
79
+ process.on("SIGINT", shutdown);
80
+ process.on("SIGTERM", shutdown);
81
+ await server.serve();
99
82
  }
100
83
  async function buildDurableQueueFromEnv(traceContext) {
101
- const stateFile = process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim();
102
- if (!stateFile) return void 0;
103
- const store = new FileDelegationStore({
104
- filePath: stateFile,
105
- recoverCorrupt: process.env.AGENT_RUNTIME_DELEGATION_STATE_RECOVER === "1"
106
- });
107
- const maxTerminalRecords = parseRetention(process.env.AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL);
108
- const queue = await DelegationTaskQueue.restore({
109
- store,
110
- traceContext,
111
- ...maxTerminalRecords !== void 0 ? { maxTerminalRecords } : {},
112
- onPersistError: (error) => {
113
- process.stderr.write(`agent-runtime-mcp: ${error.message}
114
- `);
115
- process.exit(1);
116
- }
117
- });
118
- process.stderr.write(`agent-runtime-mcp: durable delegation state \u2192 ${stateFile}
119
- `);
120
- return queue;
84
+ const stateFile = process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim();
85
+ if (!stateFile) return void 0;
86
+ const store = new FileDelegationStore({
87
+ filePath: stateFile,
88
+ recoverCorrupt: process.env.AGENT_RUNTIME_DELEGATION_STATE_RECOVER === "1"
89
+ });
90
+ const maxTerminalRecords = parseRetention(process.env.AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL);
91
+ const queue = await DelegationTaskQueue.restore({
92
+ store,
93
+ traceContext,
94
+ ...maxTerminalRecords !== void 0 ? { maxTerminalRecords } : {},
95
+ onPersistError: (error) => {
96
+ process.stderr.write(`agent-runtime-mcp: ${error.message}\n`);
97
+ process.exit(1);
98
+ }
99
+ });
100
+ process.stderr.write(`agent-runtime-mcp: durable delegation state → ${stateFile}\n`);
101
+ return queue;
121
102
  }
122
103
  function parseRetention(raw) {
123
- if (raw === void 0 || raw.trim() === "") return void 0;
124
- const n = Number(raw);
125
- if (!Number.isInteger(n) || n < 1) {
126
- process.stderr.write(
127
- `agent-runtime-mcp: AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL must be a positive integer, got "${raw}"
128
- `
129
- );
130
- process.exit(2);
131
- }
132
- return n;
104
+ if (raw === void 0 || raw.trim() === "") return void 0;
105
+ const n = Number(raw);
106
+ if (!Number.isInteger(n) || n < 1) {
107
+ process.stderr.write(`agent-runtime-mcp: AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL must be a positive integer, got "${raw}"\n`);
108
+ process.exit(2);
109
+ }
110
+ return n;
133
111
  }
134
112
  async function loadSandboxClient(apiKey) {
135
- if (!apiKey) {
136
- return {
137
- async create() {
138
- throw new Error(
139
- "agent-runtime-mcp: TANGLE_API_KEY is unset; `delegate` is disabled in diagnostic mode. Set TANGLE_API_KEY or unset MCP_ENABLE_DELEGATE to remove the unsupported tool from the tool list."
140
- );
141
- }
142
- };
143
- }
144
- const mod = await import("@tangle-network/sandbox").catch((err) => {
145
- process.stderr.write(
146
- `agent-runtime-mcp: failed to load @tangle-network/sandbox (${err.message}); install the peer dependency
147
- `
148
- );
149
- process.exit(2);
150
- });
151
- const SandboxCtor = mod.Sandbox;
152
- if (!SandboxCtor) {
153
- process.stderr.write(
154
- "agent-runtime-mcp: @tangle-network/sandbox does not export Sandbox; cannot construct client\n"
155
- );
156
- process.exit(2);
157
- }
158
- const baseUrl = process.env.SANDBOX_BASE_URL?.trim() || DEFAULT_SANDBOX_BASE_URL;
159
- return new SandboxCtor({ apiKey, baseUrl });
113
+ if (!apiKey) return { async create() {
114
+ throw new Error("agent-runtime-mcp: TANGLE_API_KEY is unset; `delegate` is disabled in diagnostic mode. Set TANGLE_API_KEY or unset MCP_ENABLE_DELEGATE to remove the unsupported tool from the tool list.");
115
+ } };
116
+ const SandboxCtor = (await import("@tangle-network/sandbox").catch((err) => {
117
+ process.stderr.write(`agent-runtime-mcp: failed to load @tangle-network/sandbox (${err.message}); install the peer dependency\n`);
118
+ process.exit(2);
119
+ })).Sandbox;
120
+ if (!SandboxCtor) {
121
+ process.stderr.write("agent-runtime-mcp: @tangle-network/sandbox does not export Sandbox; cannot construct client\n");
122
+ process.exit(2);
123
+ }
124
+ return new SandboxCtor({
125
+ apiKey,
126
+ baseUrl: process.env.SANDBOX_BASE_URL?.trim() || DEFAULT_SANDBOX_BASE_URL
127
+ });
160
128
  }
161
129
  main().catch((err) => {
162
- process.stderr.write(`agent-runtime-mcp: ${err instanceof Error ? err.stack : String(err)}
163
- `);
164
- process.exit(1);
130
+ process.stderr.write(`agent-runtime-mcp: ${err instanceof Error ? err.stack : String(err)}\n`);
131
+ process.exit(1);
165
132
  });
133
+ //#endregion
134
+ export {};
135
+
166
136
  //# sourceMappingURL=bin.js.map
@@ -1 +1 @@
1
- {"version":3,"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 substrate) 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 `TANGLE_API_KEY`. The brain's router reuses the\n * repo's `resolveRouterBaseUrl` convention\n * (`TANGLE_ROUTER_URL` / `TANGLE_ROUTER_BASE_URL`), normalised to an OpenAI-compatible `/v1` endpoint,\n * keyed by `TANGLE_API_KEY`.\n *\n * @experimental\n */\n\nimport type { BackendType } from '@tangle-network/sandbox'\nimport { type RouterEnv, resolveRouterBaseUrl } from '../model-resolution.js'\nimport type { SandboxClient } from '../runtime'\nimport type { RouterConfig } from '../runtime/router-client'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { DelegateHandlerOptions } from './tools/delegate'\n\nconst DEFAULT_SUPERVISOR_MODEL = 'moonshotai/kimi-k2.6'\nconst DEFAULT_WORKER_HARNESS = 'opencode'\n\nfunction trimmed(value: string | undefined): string | undefined {\n const v = value?.trim()\n return v ? v : undefined\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/** Resolve the supervisor brain's router substrate from env. The key falls back through the platform\n * key the bin already requires; the base reuses `resolveRouterBaseUrl`, normalised to `/v1`. */\nfunction resolveRouter(env: NodeJS.ProcessEnv): RouterConfig {\n const routerKey = trimmed(env.MCP_SUPERVISOR_ROUTER_KEY) ?? trimmed(env.TANGLE_API_KEY) ?? ''\n const base = trimmed(env.MCP_SUPERVISOR_ROUTER_BASE_URL) ?? resolveRouterBaseUrl(env as RouterEnv)\n const routerBaseUrl = /\\/v\\d+\\/?$/.test(base)\n ? base.replace(/\\/$/, '')\n : `${base.replace(/\\/$/, '')}/v1`\n const model =\n trimmed(env.MCP_SUPERVISOR_MODEL) ??\n trimmed(env.MCP_WORKER_MODEL) ??\n trimmed(env.WORKER_MODEL) ??\n DEFAULT_SUPERVISOR_MODEL\n return { routerBaseUrl, routerKey, model }\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` (authored workers run as sub-sandboxes via the same\n * client) on the harness named by `MCP_DELEGATE_WORKER_HARNESS` (default `opencode`).\n */\nexport function resolveDelegateSupervisor(\n sandboxClient: SandboxClient,\n env: NodeJS.ProcessEnv = process.env,\n): DelegateHandlerOptions | undefined {\n if (!delegateEnabled(env)) return undefined\n const router = resolveRouter(env)\n const harness = (trimmed(env.MCP_DELEGATE_WORKER_HARNESS) ??\n DEFAULT_WORKER_HARNESS) as BackendType\n const backend: ExecutorConfig = {\n backend: 'sandbox',\n harness,\n sandboxClient,\n }\n return {\n router,\n backend,\n model: router.model,\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 same `SandboxClient` the bin loads from `TANGLE_API_KEY`. The queue-bound tools\n * (`delegate_feedback`, `delegation_status`, `delegation_history`) are always served.\n *\n * Environment variables:\n * TANGLE_API_KEY required — passed to `new Sandbox({ apiKey })`\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 TANGLE_API_KEY.\n * MCP_SUPERVISOR_MODEL supervisor brain model id (falls back to MCP_WORKER_MODEL, then\n * WORKER_MODEL, then a default). Must be a tool-calling model.\n * MCP_SUPERVISOR_ROUTER_KEY router key for the supervisor brain (defaults to TANGLE_API_KEY)\n * MCP_SUPERVISOR_ROUTER_BASE_URL router base for the supervisor brain (defaults to the repo's\n * resolveRouterBaseUrl, normalized to `/v1`)\n * MCP_DELEGATE_WORKER_HARNESS harness the authored workers run on (default `opencode`)\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 { 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 = process.env.TANGLE_API_KEY\n if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {\n process.stderr.write(\n 'agent-runtime-mcp: TANGLE_API_KEY is required to serve `delegate`. 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 const delegateSupervisor =\n wantDelegate && sandboxClient ? resolveDelegateSupervisor(sandboxClient) : undefined\n if (wantDelegate && delegateSupervisor) {\n process.stderr.write('agent-runtime-mcp: delegate enabled — generic authoring supervisor\\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\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: TANGLE_API_KEY is unset; `delegate` is disabled in diagnostic mode. Set TANGLE_API_KEY or unset MCP_ENABLE_DELEGATE to remove the unsupported tool from the tool list.',\n )\n },\n } satisfies SandboxClient\n }\n // Dynamic import keeps the bin importable in environments that haven't\n // installed `@tangle-network/sandbox` yet (the runtime package lists it\n // as a peer dep, not a hard dep).\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,IAAM,2BAA2B;AACjC,IAAM,yBAAyB;AAE/B,SAAS,QAAQ,OAA+C;AAC9D,QAAM,IAAI,OAAO,KAAK;AACtB,SAAO,IAAI,IA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AQ,OAAO,MAAM,sDAAiD,SAAS;AAAA,CAAI;AACnF,SAAO;AACT;AAEA,SAAS,eAAe,KAA6C;AACnE,MAAI,QAAQ,UAAa,IAAI,KAAK,MAAM,GAAI,QAAO;AACnD,QAAM,IAAI,OAAO,GAAG;AACpB,MAAI,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,GAAG;AACjC,YAAQ,OAAO;AAAA,MACb,gGAAgG,GAAG;AAAA;AAAA,IACrG;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,SAAO;AACT;AAEA,eAAe,kBAAkB,QAAoD;AAKnF,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,MACL,MAAM,SAAS;AACb,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAIA,QAAM,MAAM,MAAM,OAAO,yBAAyB,EAAE,MAAM,CAAC,QAAQ;AACjE,YAAQ,OAAO;AAAA,MACb,8DAA8D,IAAI,OAAO;AAAA;AAAA,IAC3E;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACD,QAAM,cAAe,IAA6D;AAClF,MAAI,CAAC,aAAa;AAChB,YAAQ,OAAO;AAAA,MACb;AAAA,IACF;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AAIA,QAAM,UAAU,QAAQ,IAAI,kBAAkB,KAAK,KAAK;AACxD,SAAO,IAAI,YAAY,EAAE,QAAQ,QAAQ,CAAC;AAC5C;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,OAAO,MAAM,sBAAsB,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG,CAAC;AAAA,CAAI;AAC7F,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":[]}
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 substrate) 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 `TANGLE_API_KEY`. The brain's router reuses the\n * repo's `resolveRouterBaseUrl` convention\n * (`TANGLE_ROUTER_URL` / `TANGLE_ROUTER_BASE_URL`), normalised to an OpenAI-compatible `/v1` endpoint,\n * keyed by `TANGLE_API_KEY`.\n *\n * @experimental\n */\n\nimport type { BackendType } from '@tangle-network/sandbox'\nimport { type RouterEnv, resolveRouterBaseUrl } from '../model-resolution.js'\nimport type { SandboxClient } from '../runtime'\nimport type { RouterConfig } from '../runtime/router-client'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { DelegateHandlerOptions } from './tools/delegate'\n\nconst DEFAULT_SUPERVISOR_MODEL = 'moonshotai/kimi-k2.6'\nconst DEFAULT_WORKER_HARNESS = 'opencode'\n\nfunction trimmed(value: string | undefined): string | undefined {\n const v = value?.trim()\n return v ? v : undefined\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/** Resolve the supervisor brain's router substrate from env. The key falls back through the platform\n * key the bin already requires; the base reuses `resolveRouterBaseUrl`, normalised to `/v1`. */\nfunction resolveRouter(env: NodeJS.ProcessEnv): RouterConfig {\n const routerKey = trimmed(env.MCP_SUPERVISOR_ROUTER_KEY) ?? trimmed(env.TANGLE_API_KEY) ?? ''\n const base = trimmed(env.MCP_SUPERVISOR_ROUTER_BASE_URL) ?? resolveRouterBaseUrl(env as RouterEnv)\n const routerBaseUrl = /\\/v\\d+\\/?$/.test(base)\n ? base.replace(/\\/$/, '')\n : `${base.replace(/\\/$/, '')}/v1`\n const model =\n trimmed(env.MCP_SUPERVISOR_MODEL) ??\n trimmed(env.MCP_WORKER_MODEL) ??\n trimmed(env.WORKER_MODEL) ??\n DEFAULT_SUPERVISOR_MODEL\n return { routerBaseUrl, routerKey, model }\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` (authored workers run as sub-sandboxes via the same\n * client) on the harness named by `MCP_DELEGATE_WORKER_HARNESS` (default `opencode`).\n */\nexport function resolveDelegateSupervisor(\n sandboxClient: SandboxClient,\n env: NodeJS.ProcessEnv = process.env,\n): DelegateHandlerOptions | undefined {\n if (!delegateEnabled(env)) return undefined\n const router = resolveRouter(env)\n const harness = (trimmed(env.MCP_DELEGATE_WORKER_HARNESS) ??\n DEFAULT_WORKER_HARNESS) as BackendType\n const backend: ExecutorConfig = {\n backend: 'sandbox',\n harness,\n sandboxClient,\n }\n return {\n router,\n backend,\n model: router.model,\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 same `SandboxClient` the bin loads from `TANGLE_API_KEY`. The queue-bound tools\n * (`delegate_feedback`, `delegation_status`, `delegation_history`) are always served.\n *\n * Environment variables:\n * TANGLE_API_KEY required — passed to `new Sandbox({ apiKey })`\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 TANGLE_API_KEY.\n * MCP_SUPERVISOR_MODEL supervisor brain model id (falls back to MCP_WORKER_MODEL, then\n * WORKER_MODEL, then a default). Must be a tool-calling model.\n * MCP_SUPERVISOR_ROUTER_KEY router key for the supervisor brain (defaults to TANGLE_API_KEY)\n * MCP_SUPERVISOR_ROUTER_BASE_URL router base for the supervisor brain (defaults to the repo's\n * resolveRouterBaseUrl, normalized to `/v1`)\n * MCP_DELEGATE_WORKER_HARNESS harness the authored workers run on (default `opencode`)\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 { 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 = process.env.TANGLE_API_KEY\n if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {\n process.stderr.write(\n 'agent-runtime-mcp: TANGLE_API_KEY is required to serve `delegate`. 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 const delegateSupervisor =\n wantDelegate && sandboxClient ? resolveDelegateSupervisor(sandboxClient) : undefined\n if (wantDelegate && delegateSupervisor) {\n process.stderr.write('agent-runtime-mcp: delegate enabled — generic authoring supervisor\\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\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: TANGLE_API_KEY is unset; `delegate` is disabled in diagnostic mode. Set TANGLE_API_KEY or unset MCP_ENABLE_DELEGATE to remove the unsupported tool from the tool list.',\n )\n },\n } satisfies SandboxClient\n }\n // Dynamic import keeps the bin importable in environments that haven't\n // installed `@tangle-network/sandbox` yet (the runtime package lists it\n // as a peer dep, not a hard dep).\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,MAAM,2BAA2B;AACjC,MAAM,yBAAyB;AAE/B,SAAS,QAAQ,OAA+C;CAC9D,MAAM,IAAI,OAAO,KAAK;CACtB,OAAO,IAAI,IAAI,KAAA;AACjB;;;AAIA,SAAgB,gBAAgB,MAAyB,QAAQ,KAAc;CAC7E,OAAO,IAAI,wBAAwB;AACrC;;;AAIA,SAAS,cAAc,KAAsC;CAC3D,MAAM,YAAY,QAAQ,IAAI,yBAAyB,KAAK,QAAQ,IAAI,cAAc,KAAK;CAC3F,MAAM,OAAO,QAAQ,IAAI,8BAA8B,KAAK,qBAAqB,GAAgB;CASjG,OAAO;EAAE,eARa,aAAa,KAAK,IAAI,IACxC,KAAK,QAAQ,OAAO,EAAE,IACtB,GAAG,KAAK,QAAQ,OAAO,EAAE,EAAE;EAMP;EAAW,OAJjC,QAAQ,IAAI,oBAAoB,KAChC,QAAQ,IAAI,gBAAgB,KAC5B,QAAQ,IAAI,YAAY,KACxB;CACuC;AAC3C;;;;;;;AAQA,SAAgB,0BACd,eACA,MAAyB,QAAQ,KACG;CACpC,IAAI,CAAC,gBAAgB,GAAG,GAAG,OAAO,KAAA;CAClC,MAAM,SAAS,cAAc,GAAG;CAQhC,OAAO;EACL;EACA,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