@tangle-network/agent-runtime 0.128.0 → 0.131.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +70 -20
  2. package/dist/{activation-DhWJ3p8N.js → activation-BCzMOTaV.js} +3 -3
  3. package/dist/{activation-DhWJ3p8N.js.map → activation-BCzMOTaV.js.map} +1 -1
  4. package/dist/agent.d.ts +2 -3
  5. package/dist/agent.js +4 -5
  6. package/dist/agent.js.map +1 -1
  7. package/dist/{analyst-loop-DvSciOfB.js → analyst-loop-BE8cDs5Q.js} +2 -2
  8. package/dist/{analyst-loop-DvSciOfB.js.map → analyst-loop-BE8cDs5Q.js.map} +1 -1
  9. package/dist/analyst-loop.d.ts +1 -1
  10. package/dist/analyst-loop.js +1 -1
  11. package/dist/authoring-CvHwo1oW.js +163 -0
  12. package/dist/authoring-CvHwo1oW.js.map +1 -0
  13. package/dist/candidate-execution/index.js +4 -4
  14. package/dist/{candidate-execution-BFpq-Xi6.js → candidate-execution-BNxKr-Bu.js} +5 -5
  15. package/dist/{candidate-execution-BFpq-Xi6.js.map → candidate-execution-BNxKr-Bu.js.map} +1 -1
  16. package/dist/{conversation-BpLQZGPH.js → conversation-DNtxaJ1Z.js} +113 -31
  17. package/dist/conversation-DNtxaJ1Z.js.map +1 -0
  18. package/dist/conversation.d.ts +2 -2
  19. package/dist/conversation.js +2 -2
  20. package/dist/environment-provider-CxvSd1W6.d.ts +86 -0
  21. package/dist/{environment-provider-DqFS6FSZ.js → environment-provider-Dyg8DtLK.js} +8 -4
  22. package/dist/environment-provider-Dyg8DtLK.js.map +1 -0
  23. package/dist/environment-provider.d.ts +1 -1
  24. package/dist/environment-provider.js +1 -1
  25. package/dist/graph-BJTxGOFB.js +471 -0
  26. package/dist/graph-BJTxGOFB.js.map +1 -0
  27. package/dist/{improvement-cycle-IJgCbKWQ.js → improvement-cycle-Csp38cWg.js} +133 -224
  28. package/dist/improvement-cycle-Csp38cWg.js.map +1 -0
  29. package/dist/{index-BhZhQw77.d.ts → index-CoO7atyo.d.ts} +556 -1278
  30. package/dist/{index-BhuzfG2r.d.ts → index-DwGtu9nc.d.ts} +7 -9
  31. package/dist/{index-Efjb3nrQ.d.ts → index-qYHpsmG2.d.ts} +36 -18
  32. package/dist/index.d.ts +353 -11
  33. package/dist/index.js +111 -354
  34. package/dist/index.js.map +1 -1
  35. package/dist/intelligence.d.ts +6 -6
  36. package/dist/intelligence.js +9 -8
  37. package/dist/intelligence.js.map +1 -1
  38. package/dist/kernel.d.ts +7 -5
  39. package/dist/kernel.js +13 -9
  40. package/dist/{knowledge-DF63xPr4.js → knowledge-ce0_uKCl.js} +19 -17
  41. package/dist/knowledge-ce0_uKCl.js.map +1 -0
  42. package/dist/knowledge.d.ts +1 -1
  43. package/dist/knowledge.js +1 -1
  44. package/dist/{loop-runner-bin-Ckp_9tmD.d.ts → loop-runner-bin-BwgZ8m_7.d.ts} +6 -3
  45. package/dist/{loop-runner-bin-CWqOpCEw.js → loop-runner-bin-DSbuDDqM.js} +5 -27
  46. package/dist/loop-runner-bin-DSbuDDqM.js.map +1 -0
  47. package/dist/loop-runner-bin.d.ts +1 -1
  48. package/dist/loop-runner-bin.js +1 -1
  49. package/dist/materialization-COJ1UYQ-.js +272 -0
  50. package/dist/materialization-COJ1UYQ-.js.map +1 -0
  51. package/dist/mcp/bin.js +39 -47
  52. package/dist/mcp/bin.js.map +1 -1
  53. package/dist/mcp/index.d.ts +24 -26
  54. package/dist/mcp/index.js +66 -83
  55. package/dist/mcp/index.js.map +1 -1
  56. package/dist/mcp/memory-bin.js +1 -1
  57. package/dist/{memory-server-DL6cE2Ag.js → memory-server-5HEJH672.js} +2 -2
  58. package/dist/{memory-server-DL6cE2Ag.js.map → memory-server-5HEJH672.js.map} +1 -1
  59. package/dist/model-policy-CqziaqS1.js +232 -0
  60. package/dist/model-policy-CqziaqS1.js.map +1 -0
  61. package/dist/{openai-tools-B68JaOCx.d.ts → openai-tools-D3oMyVGl.d.ts} +2 -2
  62. package/dist/{openai-tools-D3XfrrQ6.js → openai-tools-ru75mLjq.js} +2 -2
  63. package/dist/openai-tools-ru75mLjq.js.map +1 -0
  64. package/dist/{prepare--8EvLqCr.js → prepare-DYWjVcPx.js} +169 -153
  65. package/dist/prepare-DYWjVcPx.js.map +1 -0
  66. package/dist/primeintellect/index.d.ts +7 -6
  67. package/dist/primeintellect/index.js +9 -11
  68. package/dist/primeintellect/index.js.map +1 -1
  69. package/dist/profiles.d.ts +21 -174
  70. package/dist/profiles.js +67 -276
  71. package/dist/profiles.js.map +1 -1
  72. package/dist/{protected-model-port-CXVfOUu_.js → protected-model-port-48ALLGxT.js} +2 -2
  73. package/dist/{protected-model-port-CXVfOUu_.js.map → protected-model-port-48ALLGxT.js.map} +1 -1
  74. package/dist/{redact-PQzmE1Jn.d.ts → redact-9_Gf-8m3.d.ts} +58 -69
  75. package/dist/{researcher-CoVqNhfI.js → researcher-Skz5-Uc8.js} +50 -26
  76. package/dist/researcher-Skz5-Uc8.js.map +1 -0
  77. package/dist/{run-layout-C2FGmZ3v.js → run-layout-CeJsEAom.js} +2 -2
  78. package/dist/{run-layout-C2FGmZ3v.js.map → run-layout-CeJsEAom.js.map} +1 -1
  79. package/dist/runtime-D-QfLbSd.d.ts +893 -0
  80. package/dist/{runtime-5uDVVfER.js → runtime-hiAABiTk.js} +315 -1191
  81. package/dist/runtime-hiAABiTk.js.map +1 -0
  82. package/dist/{sandbox-events-Yhd1GYWl.js → sandbox-events-CRDwc5WN.js} +42 -5
  83. package/dist/sandbox-events-CRDwc5WN.js.map +1 -0
  84. package/dist/snapshot-CXiiuHhL.js +21 -0
  85. package/dist/snapshot-CXiiuHhL.js.map +1 -0
  86. package/dist/{spawn-journal-DsZKDqeh.js → spawn-journal-saHQzqYi.js} +15 -21
  87. package/dist/spawn-journal-saHQzqYi.js.map +1 -0
  88. package/dist/stream-agent-turn-C852AgMT.d.ts +128 -0
  89. package/dist/stream-agent-turn-rYgaOLO0.js +910 -0
  90. package/dist/stream-agent-turn-rYgaOLO0.js.map +1 -0
  91. package/dist/{structural-rollout-zY0oqQzO.js → structural-rollout-3uxVGcg2.js} +459 -235
  92. package/dist/structural-rollout-3uxVGcg2.js.map +1 -0
  93. package/dist/{supervise-CsTKbH9R.js → supervise-iPN27pO0.js} +864 -4785
  94. package/dist/supervise-iPN27pO0.js.map +1 -0
  95. package/dist/{supervisor-DpjO0Gmy.js → supervisor-CV6Jh28D.js} +7439 -2897
  96. package/dist/supervisor-CV6Jh28D.js.map +1 -0
  97. package/dist/testing.d.ts +3 -1
  98. package/dist/testing.js +271 -221
  99. package/dist/testing.js.map +1 -1
  100. package/dist/{top-app-5unxqovu.js → top-app-G4M18b6i.js} +3 -3
  101. package/dist/{top-app-5unxqovu.js.map → top-app-G4M18b6i.js.map} +1 -1
  102. package/dist/tui/bin.js +1 -1
  103. package/dist/tui/index.js +1 -1
  104. package/dist/{environment-provider-CUFsyymu.d.ts → types-C6Q-J0Dt.d.ts} +51 -114
  105. package/dist/{types-DnNGJ5Gz.d.ts → types-ebIY0dMG.d.ts} +556 -30
  106. package/dist/{util-MVgdwuIS.js → util-Bw6srryQ.js} +3 -2
  107. package/dist/{util-MVgdwuIS.js.map → util-Bw6srryQ.js.map} +1 -1
  108. package/dist/{workspace-archive-BQxvkypI.js → workspace-archive-aOfJ47ms.js} +3 -3
  109. package/dist/{workspace-archive-BQxvkypI.js.map → workspace-archive-aOfJ47ms.js.map} +1 -1
  110. package/package.json +12 -15
  111. package/skills/agent-graphs/IMPROVE.md +3 -3
  112. package/skills/agent-graphs/SKILL.md +4 -5
  113. package/skills/agent-graphs/cases/review-pipeline.json +1 -2
  114. package/skills/agent-graphs/cases/unmeasured-harness.json +2 -4
  115. package/dist/backends-CiOCyRHb.js +0 -743
  116. package/dist/backends-CiOCyRHb.js.map +0 -1
  117. package/dist/conversation-BpLQZGPH.js.map +0 -1
  118. package/dist/environment-provider-DqFS6FSZ.js.map +0 -1
  119. package/dist/improvement-cycle-IJgCbKWQ.js.map +0 -1
  120. package/dist/index-DLM0W1h1.d.ts +0 -545
  121. package/dist/knowledge-DF63xPr4.js.map +0 -1
  122. package/dist/local-harness-BIajef4A.d.ts +0 -465
  123. package/dist/loop-runner-bin-CWqOpCEw.js.map +0 -1
  124. package/dist/model-resolution-Btd9iIKV.js +0 -98
  125. package/dist/model-resolution-Btd9iIKV.js.map +0 -1
  126. package/dist/openai-tools-D3XfrrQ6.js.map +0 -1
  127. package/dist/prepare--8EvLqCr.js.map +0 -1
  128. package/dist/researcher-CoVqNhfI.js.map +0 -1
  129. package/dist/runtime-5uDVVfER.js.map +0 -1
  130. package/dist/sandbox-events-Yhd1GYWl.js.map +0 -1
  131. package/dist/spawn-journal-DsZKDqeh.js.map +0 -1
  132. package/dist/structural-rollout-zY0oqQzO.js.map +0 -1
  133. package/dist/supervise-CsTKbH9R.js.map +0 -1
  134. package/dist/supervisor-DpjO0Gmy.js.map +0 -1
  135. package/dist/types-C9j4qg6l.d.ts +0 -500
  136. package/skills/agent-graphs/cases/floor-trap-pi.json +0 -11
@@ -0,0 +1,272 @@
1
+ import { u as ValidationError } from "./errors-DEAvWQPy.js";
2
+ import { t as detachedSnapshot } from "./snapshot-CXiiuHhL.js";
3
+ import { t as assertExecutableAgentProfile } from "./model-policy-CqziaqS1.js";
4
+ import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest } from "@tangle-network/agent-interface";
5
+ import { randomUUID } from "node:crypto";
6
+ //#region src/runtime/supervise/executable-spec.ts
7
+ /**
8
+ * Parse one untrusted profile into the exact immutable value execution may consume.
9
+ *
10
+ * Snapshotting before schema parsing reads caller-owned fields once. Snapshotting the parsed
11
+ * result prevents downstream custom code from changing any identity or authority field.
12
+ */
13
+ function executableAgentProfileSnapshot(raw, context) {
14
+ const input = detachedSnapshot(raw, `${context}: AgentProfile input`);
15
+ const profile = agentProfileSchema.parse(input);
16
+ assertExecutableAgentProfile(profile, context);
17
+ return detachedSnapshot(profile, `${context}: parsed AgentProfile`);
18
+ }
19
+ /** Snapshot an executable spec while retaining trusted callbacks by reference. */
20
+ function executableAgentSpecSnapshot(raw, context) {
21
+ const { profile: rawProfile, harness, execution: rawExecution, ...runtimeExtensions } = raw;
22
+ const profile = executableAgentProfileSnapshot(rawProfile, context);
23
+ const execution = rawExecution === void 0 ? void 0 : detachedSnapshot(rawExecution, `${context}: execution attribution`);
24
+ return Object.freeze({
25
+ ...runtimeExtensions,
26
+ profile,
27
+ harness,
28
+ ...execution === void 0 ? {} : { execution }
29
+ });
30
+ }
31
+ //#endregion
32
+ //#region src/runtime/supervise/materialization.ts
33
+ const runtimeOwnedExecutorMaterializations = /* @__PURE__ */ new WeakMap();
34
+ const runtimeOwnedScopeOwners = /* @__PURE__ */ new WeakMap();
35
+ const declarationKeys = /* @__PURE__ */ new Set([
36
+ "effectiveProfile",
37
+ "backend",
38
+ "model",
39
+ "execution",
40
+ "materializer",
41
+ "plan",
42
+ "platformAttachments"
43
+ ]);
44
+ /**
45
+ * Bind a declaration to a runtime-owned executor without putting an attestable method on the
46
+ * public Executor interface. This module is not a package export: arbitrary caller executors stay
47
+ * unknown even if they add a lookalike `materialization()` property.
48
+ */
49
+ function attestRuntimeOwnedExecutor(executor, declaration, binding) {
50
+ runtimeOwnedExecutorMaterializations.set(executor, { current: Object.freeze({
51
+ kind: "known",
52
+ declaration: detachedSnapshot(declaration, "runtime-owned executor materialization"),
53
+ ...binding === void 0 ? {} : { binding: detachedSnapshot(binding, "runtime-owned executor execution binding") }
54
+ }) });
55
+ return executor;
56
+ }
57
+ /** Brand an external Runtime executor whose exact remote materialization is provable only after
58
+ * its terminal protocol acknowledgement. The declaration is a planned authority check, never a
59
+ * known receipt; callers must finalize this same object after validating the acknowledgement. */
60
+ function attestRuntimeOwnedPendingExecutor(executor, runtime, declaration, binding) {
61
+ runtimeOwnedExecutorMaterializations.set(executor, { current: Object.freeze({
62
+ kind: "pending",
63
+ runtime,
64
+ declaration: detachedSnapshot(declaration, "pending executor materialization"),
65
+ binding: detachedSnapshot(binding, "pending executor execution binding")
66
+ }) });
67
+ return executor;
68
+ }
69
+ /** Replace a private pending brand with terminally acknowledged evidence. A caller-owned executor
70
+ * cannot enter this path because only this module can create the pending WeakMap entry. */
71
+ function finalizeRuntimeOwnedPendingExecutor(executor, declaration, binding) {
72
+ const ref = runtimeOwnedExecutorMaterializations.get(executor);
73
+ if (ref?.current.kind !== "pending" || ref.current.runtime !== executor.runtime) throw new ValidationError("executor materialization: terminal acknowledgement has no matching Runtime-owned pending executor");
74
+ ref.current = Object.freeze({
75
+ kind: "known",
76
+ declaration: detachedSnapshot(declaration, "runtime-owned executor materialization"),
77
+ binding: detachedSnapshot(binding, "runtime-owned executor execution binding")
78
+ });
79
+ return executor;
80
+ }
81
+ /** Mark a runtime-owned orchestration executor whose exact leaf declaration is published through
82
+ * its private nested Scope before the first backend inference. Arbitrary executors cannot opt in. */
83
+ function attestRuntimeOwnedDeferredExecutor(executor, runtime) {
84
+ runtimeOwnedExecutorMaterializations.set(executor, { current: Object.freeze({
85
+ kind: "deferred",
86
+ runtime
87
+ }) });
88
+ return executor;
89
+ }
90
+ /** Preserve the runtime-owned attestation when a trusted wrapper changes result semantics only. */
91
+ function inheritRuntimeOwnedExecutorAttestation(source, wrapper) {
92
+ const ref = runtimeOwnedExecutorMaterializations.get(source);
93
+ if (ref !== void 0) runtimeOwnedExecutorMaterializations.set(wrapper, ref);
94
+ return wrapper;
95
+ }
96
+ /** Read a declaration only when Runtime itself branded this exact executor object. */
97
+ function runtimeOwnedExecutorMaterialization(executor) {
98
+ const attestation = runtimeOwnedExecutorMaterializations.get(executor)?.current;
99
+ return attestation?.kind === "known" ? attestation.declaration : void 0;
100
+ }
101
+ /** Read one attempt binding only from the private brand on this exact executor object. */
102
+ function runtimeOwnedExecutorExecutionBinding(executor) {
103
+ const attestation = runtimeOwnedExecutorMaterializations.get(executor)?.current;
104
+ return attestation?.kind === "known" ? attestation.binding : void 0;
105
+ }
106
+ /** Read a planned external declaration only for Runtime's private pending brand. This is useful for
107
+ * pre-execution authority checks, but must never be turned into a known durable receipt. */
108
+ function runtimeOwnedPendingExecutorMaterialization(executor) {
109
+ const attestation = runtimeOwnedExecutorMaterializations.get(executor)?.current;
110
+ return attestation?.kind === "pending" ? {
111
+ runtime: attestation.runtime,
112
+ declaration: attestation.declaration,
113
+ binding: attestation.binding
114
+ } : void 0;
115
+ }
116
+ /** Read the expected leaf runtime only for a privately branded deferred orchestration executor. */
117
+ function runtimeOwnedDeferredExecutorRuntime(executor) {
118
+ const attestation = runtimeOwnedExecutorMaterializations.get(executor)?.current;
119
+ return attestation?.kind === "deferred" ? attestation.runtime : void 0;
120
+ }
121
+ /** Propagate trust from a built-in driver adapter to the Agent and recursive executor it owns. */
122
+ function attestRuntimeOwnedScopeOwner(owner, runtime) {
123
+ runtimeOwnedScopeOwners.set(owner, runtime);
124
+ return owner;
125
+ }
126
+ /** Return a built-in scope owner's expected concrete leaf runtime; caller-owned functions/Agents
127
+ * deliberately have no entry even if they add lookalike fields. */
128
+ function runtimeOwnedScopeOwnerRuntime(owner) {
129
+ return runtimeOwnedScopeOwners.get(owner);
130
+ }
131
+ /** Build one kernel-owned known receipt from a data-only executor declaration. */
132
+ function knownMaterializationReceipt(input) {
133
+ const declaration = detachedSnapshot(input.declaration, "executor materialization");
134
+ assertExactDeclaration(declaration);
135
+ const effectiveProfile = agentProfileSchema.safeParse(declaration.effectiveProfile);
136
+ if (!effectiveProfile.success) throw new ValidationError("executor materialization: effectiveProfile must be an AgentProfile");
137
+ assertNonEmpty(declaration.backend, "backend");
138
+ assertNonEmpty(declaration.materializer, "materializer");
139
+ assertNonEmpty(declaration.execution?.kind, "execution.kind");
140
+ assertNonEmpty(declaration.execution?.id, "execution.id");
141
+ assertModel(declaration.model);
142
+ let effectiveProfileDigest;
143
+ let materializationPlanDigest;
144
+ let platformAttachmentsDigest;
145
+ try {
146
+ effectiveProfileDigest = canonicalAgentProfileDigest(effectiveProfile.data);
147
+ materializationPlanDigest = canonicalCandidateDigest(jsonWireSnapshot(declaration.plan));
148
+ platformAttachmentsDigest = declaration.platformAttachments === void 0 ? void 0 : canonicalCandidateDigest(jsonWireSnapshot(declaration.platformAttachments));
149
+ } catch (error) {
150
+ throw new ValidationError("executor materialization: profile, plan, and attachments must be finite RFC 8785 JSON", { cause: error });
151
+ }
152
+ return Object.freeze({
153
+ status: "known",
154
+ authoredProfileDigest: input.authoredProfileDigest,
155
+ effectiveProfileDigest,
156
+ materializationPlanDigest,
157
+ ...platformAttachmentsDigest === void 0 ? {} : { platformAttachmentsDigest },
158
+ runtime: input.runtime,
159
+ backend: declaration.backend,
160
+ model: declaration.model,
161
+ execution: declaration.execution,
162
+ materializer: declaration.materializer
163
+ });
164
+ }
165
+ /** Build an explicit unknown receipt without fabricating any executor-owned identity. */
166
+ function unknownMaterializationReceipt(input) {
167
+ return Object.freeze({
168
+ status: "unknown",
169
+ ...input.authoredProfileDigest === void 0 ? {} : { authoredProfileDigest: input.authoredProfileDigest },
170
+ runtime: input.runtime,
171
+ reason: input.reason
172
+ });
173
+ }
174
+ /** Mint a process-unique attempt id before executor construction. */
175
+ function newExecutionAttemptId(nodeId) {
176
+ return `${nodeId}:attempt:${randomUUID()}`;
177
+ }
178
+ /** Build the immutable safe receipt for a full, transient execution binding. */
179
+ function knownExecutionBindingReceipt(materialization, bindingInput) {
180
+ const binding = detachedSnapshot(bindingInput, "executor execution binding");
181
+ assertNonEmpty(binding.attemptId, "binding.attemptId");
182
+ assertSafeDescriptor(binding.descriptor);
183
+ let materializationReceiptDigest;
184
+ let bindingDigest;
185
+ try {
186
+ materializationReceiptDigest = canonicalCandidateDigest(materialization);
187
+ bindingDigest = canonicalCandidateDigest(jsonWireSnapshot(binding.binding));
188
+ } catch (error) {
189
+ throw new ValidationError("executor binding must be finite RFC 8785 JSON", { cause: error });
190
+ }
191
+ return Object.freeze({
192
+ status: "known",
193
+ attemptId: binding.attemptId,
194
+ materializationReceiptDigest,
195
+ bindingDigest,
196
+ descriptor: binding.descriptor
197
+ });
198
+ }
199
+ /** Preserve an attempt boundary even when its caller-owned transport cannot be attested. */
200
+ function unknownExecutionBindingReceipt(materialization, attemptId, reason) {
201
+ assertNonEmpty(attemptId, "binding.attemptId");
202
+ return Object.freeze({
203
+ status: "unknown",
204
+ attemptId,
205
+ materializationReceiptDigest: canonicalCandidateDigest(materialization),
206
+ reason
207
+ });
208
+ }
209
+ /** Derive an authored-profile digest without turning non-canonical input into a fake identity. */
210
+ function authoredProfileDigest(profile) {
211
+ try {
212
+ return canonicalAgentProfileDigest(agentProfileSchema.parse(profile));
213
+ } catch {
214
+ return;
215
+ }
216
+ }
217
+ function assertExactDeclaration(value) {
218
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ValidationError("executor materialization: declaration must be an object");
219
+ const unknown = Object.keys(value).filter((key) => !declarationKeys.has(key));
220
+ if (unknown.length > 0) throw new ValidationError(`executor materialization: unknown declaration fields: ${unknown.sort().join(", ")}`);
221
+ if (!Object.hasOwn(value, "plan")) throw new ValidationError("executor materialization: plan is required");
222
+ }
223
+ function assertModel(model) {
224
+ if (typeof model !== "object" || model === null || Array.isArray(model)) throw new ValidationError("executor materialization: model must be a known/unknown identity");
225
+ const keys = Object.keys(model).sort();
226
+ if (model.status === "known") {
227
+ if (keys.join(",") !== "id,status") throw new ValidationError("executor materialization: known model accepts only status and id");
228
+ assertNonEmpty(model.id, "model.id");
229
+ return;
230
+ }
231
+ if (model.status === "unknown") {
232
+ if (keys.join(",") !== "reason,status") throw new ValidationError("executor materialization: unknown model accepts only status and reason");
233
+ assertNonEmpty(model.reason, "model.reason");
234
+ return;
235
+ }
236
+ throw new ValidationError("executor materialization: model.status must be known or unknown");
237
+ }
238
+ function assertNonEmpty(value, field) {
239
+ if (typeof value !== "string" || value.trim().length === 0) throw new ValidationError(`executor materialization: ${field} must be a non-empty string`);
240
+ }
241
+ function assertSafeDescriptor(descriptor) {
242
+ if (typeof descriptor !== "object" || descriptor === null || Array.isArray(descriptor)) throw new ValidationError("executor binding: descriptor must be an object");
243
+ for (const [key, value] of Object.entries(descriptor)) {
244
+ if (/(url|uri|token|key|secret|bearer|credential|authorization)/i.test(key)) throw new ValidationError(`executor binding: unsafe descriptor key ${JSON.stringify(key)}`);
245
+ if (value !== null && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw new ValidationError(`executor binding: descriptor ${JSON.stringify(key)} must be scalar`);
246
+ if (typeof value === "string" && (value.includes("://") || value.includes("@"))) throw new ValidationError(`executor binding: descriptor ${JSON.stringify(key)} contains transport or credential text`);
247
+ }
248
+ }
249
+ function jsonWireSnapshot(value, path = "$") {
250
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
251
+ if (typeof value === "number") {
252
+ if (!Number.isFinite(value)) throw new ValidationError(`executor binding: ${path} must be finite`);
253
+ return value;
254
+ }
255
+ if (Array.isArray(value)) return value.map((item, index) => {
256
+ if (item === void 0) throw new ValidationError(`executor binding: ${path}[${index}] cannot be undefined`);
257
+ return jsonWireSnapshot(item, `${path}[${index}]`);
258
+ });
259
+ if (typeof value !== "object" || value === null) throw new ValidationError(`executor binding: ${path} must be JSON data`);
260
+ const prototype = Object.getPrototypeOf(value);
261
+ if (prototype !== Object.prototype && prototype !== null) throw new ValidationError(`executor binding: ${path} must be a plain object`);
262
+ const out = {};
263
+ for (const [key, item] of Object.entries(value)) {
264
+ if (item === void 0) continue;
265
+ out[key] = jsonWireSnapshot(item, `${path}.${key}`);
266
+ }
267
+ return out;
268
+ }
269
+ //#endregion
270
+ export { unknownMaterializationReceipt as _, authoredProfileDigest as a, knownExecutionBindingReceipt as c, runtimeOwnedDeferredExecutorRuntime as d, runtimeOwnedExecutorExecutionBinding as f, unknownExecutionBindingReceipt as g, runtimeOwnedScopeOwnerRuntime as h, attestRuntimeOwnedScopeOwner as i, knownMaterializationReceipt as l, runtimeOwnedPendingExecutorMaterialization as m, attestRuntimeOwnedExecutor as n, finalizeRuntimeOwnedPendingExecutor as o, runtimeOwnedExecutorMaterialization as p, attestRuntimeOwnedPendingExecutor as r, inheritRuntimeOwnedExecutorAttestation as s, attestRuntimeOwnedDeferredExecutor as t, newExecutionAttemptId as u, executableAgentProfileSnapshot as v, executableAgentSpecSnapshot as y };
271
+
272
+ //# sourceMappingURL=materialization-COJ1UYQ-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"materialization-COJ1UYQ-.js","names":[],"sources":["../src/runtime/supervise/executable-spec.ts","../src/runtime/supervise/materialization.ts"],"sourcesContent":["import { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport { assertExecutableAgentProfile } from './model-policy'\nimport { detachedSnapshot } from './snapshot'\nimport type { AgentSpec } from './types'\n\n/**\n * Parse one untrusted profile into the exact immutable value execution may consume.\n *\n * Snapshotting before schema parsing reads caller-owned fields once. Snapshotting the parsed\n * result prevents downstream custom code from changing any identity or authority field.\n */\nexport function executableAgentProfileSnapshot(raw: unknown, context: string): AgentProfile {\n const input = detachedSnapshot(raw, `${context}: AgentProfile input`)\n const profile = agentProfileSchema.parse(input)\n assertExecutableAgentProfile(profile, context)\n return detachedSnapshot(profile, `${context}: parsed AgentProfile`)\n}\n\n/** Snapshot an executable spec while retaining trusted callbacks by reference. */\nexport function executableAgentSpecSnapshot(raw: AgentSpec, context: string): AgentSpec {\n const {\n profile: rawProfile,\n harness,\n execution: rawExecution,\n ...runtimeExtensions\n } = raw as AgentSpec & Readonly<Record<string, unknown>>\n const profile = executableAgentProfileSnapshot(rawProfile, context)\n const execution =\n rawExecution === undefined\n ? undefined\n : detachedSnapshot(rawExecution, `${context}: execution attribution`)\n return Object.freeze({\n ...runtimeExtensions,\n profile,\n harness,\n ...(execution === undefined ? {} : { execution }),\n }) as AgentSpec\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport { detachedSnapshot } from './snapshot'\nimport type {\n ExecutionBindingReceipt,\n Executor,\n ExecutorExecutionBinding,\n ExecutorMaterialization,\n ProfileMaterializationReceipt,\n Runtime,\n UnknownMaterializationReason,\n} from './types'\n\ntype RuntimeOwnedExecutorMaterialization =\n | {\n readonly kind: 'known'\n readonly declaration: ExecutorMaterialization\n readonly binding?: ExecutorExecutionBinding\n }\n | {\n /** A Runtime-owned external executor whose exact launch is known, but whose remote\n * materializer has not yet returned its terminal acknowledgement. This private state lets\n * Runtime validate the planned authority before execution without presenting it as proof\n * that the remote process actually used that plan. */\n readonly kind: 'pending'\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | { readonly kind: 'deferred'; readonly runtime: Runtime }\n\ninterface RuntimeOwnedExecutorMaterializationRef {\n current: RuntimeOwnedExecutorMaterialization\n}\n\nconst runtimeOwnedExecutorMaterializations = new WeakMap<\n object,\n RuntimeOwnedExecutorMaterializationRef\n>()\nconst runtimeOwnedScopeOwners = new WeakMap<object, Runtime>()\n\ninterface KnownReceiptInput {\n readonly authoredProfileDigest: Sha256Digest\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n}\n\ninterface UnknownReceiptInput {\n readonly authoredProfileDigest?: Sha256Digest\n readonly runtime: Runtime\n readonly reason: UnknownMaterializationReason\n}\n\nconst declarationKeys = new Set([\n 'effectiveProfile',\n 'backend',\n 'model',\n 'execution',\n 'materializer',\n 'plan',\n 'platformAttachments',\n])\n\n/**\n * Bind a declaration to a runtime-owned executor without putting an attestable method on the\n * public Executor interface. This module is not a package export: arbitrary caller executors stay\n * unknown even if they add a lookalike `materialization()` property.\n */\nexport function attestRuntimeOwnedExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding?: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n ...(binding === undefined\n ? {}\n : {\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n }),\n }),\n })\n return executor\n}\n\n/** Brand an external Runtime executor whose exact remote materialization is provable only after\n * its terminal protocol acknowledgement. The declaration is a planned authority check, never a\n * known receipt; callers must finalize this same object after validating the acknowledgement. */\nexport function attestRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'pending',\n runtime,\n declaration: detachedSnapshot(declaration, 'pending executor materialization'),\n binding: detachedSnapshot(binding, 'pending executor execution binding'),\n }),\n })\n return executor\n}\n\n/** Replace a private pending brand with terminally acknowledged evidence. A caller-owned executor\n * cannot enter this path because only this module can create the pending WeakMap entry. */\nexport function finalizeRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(executor as object)\n if (ref?.current.kind !== 'pending' || ref.current.runtime !== executor.runtime) {\n throw new ValidationError(\n 'executor materialization: terminal acknowledgement has no matching Runtime-owned pending executor',\n )\n }\n ref.current = Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n })\n return executor\n}\n\n/** Mark a runtime-owned orchestration executor whose exact leaf declaration is published through\n * its private nested Scope before the first backend inference. Arbitrary executors cannot opt in. */\nexport function attestRuntimeOwnedDeferredExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({ kind: 'deferred', runtime }),\n })\n return executor\n}\n\n/** Preserve the runtime-owned attestation when a trusted wrapper changes result semantics only. */\nexport function inheritRuntimeOwnedExecutorAttestation<In, Out>(\n source: Executor<In>,\n wrapper: Executor<Out>,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(source as object)\n if (ref !== undefined) {\n runtimeOwnedExecutorMaterializations.set(wrapper as object, ref)\n }\n return wrapper\n}\n\n/** Read a declaration only when Runtime itself branded this exact executor object. */\nexport function runtimeOwnedExecutorMaterialization<Out>(\n executor: Executor<Out>,\n): ExecutorMaterialization | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.declaration : undefined\n}\n\n/** Read one attempt binding only from the private brand on this exact executor object. */\nexport function runtimeOwnedExecutorExecutionBinding<Out>(\n executor: Executor<Out>,\n): ExecutorExecutionBinding | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.binding : undefined\n}\n\n/** Read a planned external declaration only for Runtime's private pending brand. This is useful for\n * pre-execution authority checks, but must never be turned into a known durable receipt. */\nexport function runtimeOwnedPendingExecutorMaterialization<Out>(executor: Executor<Out>):\n | {\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'pending'\n ? {\n runtime: attestation.runtime,\n declaration: attestation.declaration,\n binding: attestation.binding,\n }\n : undefined\n}\n\n/** Read the expected leaf runtime only for a privately branded deferred orchestration executor. */\nexport function runtimeOwnedDeferredExecutorRuntime<Out>(\n executor: Executor<Out>,\n): Runtime | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'deferred' ? attestation.runtime : undefined\n}\n\n/** Propagate trust from a built-in driver adapter to the Agent and recursive executor it owns. */\nexport function attestRuntimeOwnedScopeOwner<T extends object>(owner: T, runtime: Runtime): T {\n runtimeOwnedScopeOwners.set(owner, runtime)\n return owner\n}\n\n/** Return a built-in scope owner's expected concrete leaf runtime; caller-owned functions/Agents\n * deliberately have no entry even if they add lookalike fields. */\nexport function runtimeOwnedScopeOwnerRuntime(owner: object): Runtime | undefined {\n return runtimeOwnedScopeOwners.get(owner)\n}\n\n/** Build one kernel-owned known receipt from a data-only executor declaration. */\nexport function knownMaterializationReceipt(\n input: KnownReceiptInput,\n): ProfileMaterializationReceipt {\n const declaration = detachedSnapshot(input.declaration, 'executor materialization')\n assertExactDeclaration(declaration)\n const effectiveProfile = agentProfileSchema.safeParse(declaration.effectiveProfile)\n if (!effectiveProfile.success) {\n throw new ValidationError('executor materialization: effectiveProfile must be an AgentProfile')\n }\n assertNonEmpty(declaration.backend, 'backend')\n assertNonEmpty(declaration.materializer, 'materializer')\n assertNonEmpty(declaration.execution?.kind, 'execution.kind')\n assertNonEmpty(declaration.execution?.id, 'execution.id')\n assertModel(declaration.model)\n\n let effectiveProfileDigest: Sha256Digest\n let materializationPlanDigest: Sha256Digest\n let platformAttachmentsDigest: Sha256Digest | undefined\n try {\n effectiveProfileDigest = canonicalAgentProfileDigest(effectiveProfile.data)\n materializationPlanDigest = canonicalCandidateDigest(jsonWireSnapshot(declaration.plan))\n platformAttachmentsDigest =\n declaration.platformAttachments === undefined\n ? undefined\n : canonicalCandidateDigest(jsonWireSnapshot(declaration.platformAttachments))\n } catch (error) {\n throw new ValidationError(\n 'executor materialization: profile, plan, and attachments must be finite RFC 8785 JSON',\n { cause: error },\n )\n }\n\n return Object.freeze({\n status: 'known' as const,\n authoredProfileDigest: input.authoredProfileDigest,\n effectiveProfileDigest,\n materializationPlanDigest,\n ...(platformAttachmentsDigest === undefined ? {} : { platformAttachmentsDigest }),\n runtime: input.runtime,\n backend: declaration.backend,\n model: declaration.model,\n execution: declaration.execution,\n materializer: declaration.materializer,\n })\n}\n\n/** Build an explicit unknown receipt without fabricating any executor-owned identity. */\nexport function unknownMaterializationReceipt(\n input: UnknownReceiptInput,\n): ProfileMaterializationReceipt {\n return Object.freeze({\n status: 'unknown' as const,\n ...(input.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: input.authoredProfileDigest }),\n runtime: input.runtime,\n reason: input.reason,\n })\n}\n\n/** Mint a process-unique attempt id before executor construction. */\nexport function newExecutionAttemptId(nodeId: string): string {\n return `${nodeId}:attempt:${randomUUID()}`\n}\n\n/** Build the immutable safe receipt for a full, transient execution binding. */\nexport function knownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n bindingInput: ExecutorExecutionBinding,\n): ExecutionBindingReceipt {\n const binding = detachedSnapshot(bindingInput, 'executor execution binding')\n assertNonEmpty(binding.attemptId, 'binding.attemptId')\n assertSafeDescriptor(binding.descriptor)\n let materializationReceiptDigest: Sha256Digest\n let bindingDigest: Sha256Digest\n try {\n materializationReceiptDigest = canonicalCandidateDigest(materialization)\n // Bind the exact JSON document a backend receives. Optional AgentProfile fields are represented\n // as `undefined` in memory but omitted by JSON transport; normalize that one distinction while\n // rejecting every non-finite/non-data value instead of silently coercing it.\n bindingDigest = canonicalCandidateDigest(jsonWireSnapshot(binding.binding))\n } catch (error) {\n throw new ValidationError('executor binding must be finite RFC 8785 JSON', { cause: error })\n }\n return Object.freeze({\n status: 'known' as const,\n attemptId: binding.attemptId,\n materializationReceiptDigest,\n bindingDigest,\n descriptor: binding.descriptor,\n })\n}\n\n/** Preserve an attempt boundary even when its caller-owned transport cannot be attested. */\nexport function unknownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n attemptId: string,\n reason: UnknownMaterializationReason,\n): ExecutionBindingReceipt {\n assertNonEmpty(attemptId, 'binding.attemptId')\n return Object.freeze({\n status: 'unknown' as const,\n attemptId,\n materializationReceiptDigest: canonicalCandidateDigest(materialization),\n reason,\n })\n}\n\n/** Derive an authored-profile digest without turning non-canonical input into a fake identity. */\nexport function authoredProfileDigest(profile: unknown): Sha256Digest | undefined {\n try {\n return canonicalAgentProfileDigest(agentProfileSchema.parse(profile))\n } catch {\n return undefined\n }\n}\n\nfunction assertExactDeclaration(value: ExecutorMaterialization): void {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError('executor materialization: declaration must be an object')\n }\n const unknown = Object.keys(value).filter((key) => !declarationKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(\n `executor materialization: unknown declaration fields: ${unknown.sort().join(', ')}`,\n )\n }\n if (!Object.hasOwn(value, 'plan')) {\n throw new ValidationError('executor materialization: plan is required')\n }\n}\n\nfunction assertModel(model: ExecutorMaterialization['model']): void {\n if (typeof model !== 'object' || model === null || Array.isArray(model)) {\n throw new ValidationError('executor materialization: model must be a known/unknown identity')\n }\n const keys = Object.keys(model).sort()\n if (model.status === 'known') {\n if (keys.join(',') !== 'id,status') {\n throw new ValidationError('executor materialization: known model accepts only status and id')\n }\n assertNonEmpty(model.id, 'model.id')\n return\n }\n if (model.status === 'unknown') {\n if (keys.join(',') !== 'reason,status') {\n throw new ValidationError(\n 'executor materialization: unknown model accepts only status and reason',\n )\n }\n assertNonEmpty(model.reason, 'model.reason')\n return\n }\n throw new ValidationError('executor materialization: model.status must be known or unknown')\n}\n\nfunction assertNonEmpty(value: unknown, field: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`executor materialization: ${field} must be a non-empty string`)\n }\n}\n\nfunction assertSafeDescriptor(descriptor: ExecutorExecutionBinding['descriptor']): void {\n if (typeof descriptor !== 'object' || descriptor === null || Array.isArray(descriptor)) {\n throw new ValidationError('executor binding: descriptor must be an object')\n }\n for (const [key, value] of Object.entries(descriptor)) {\n if (/(url|uri|token|key|secret|bearer|credential|authorization)/i.test(key)) {\n throw new ValidationError(`executor binding: unsafe descriptor key ${JSON.stringify(key)}`)\n }\n if (\n value !== null &&\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} must be scalar`,\n )\n }\n if (typeof value === 'string' && (value.includes('://') || value.includes('@'))) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} contains transport or credential text`,\n )\n }\n }\n}\n\nfunction jsonWireSnapshot(value: unknown, path = '$'): unknown {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new ValidationError(`executor binding: ${path} must be finite`)\n }\n return value\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => {\n if (item === undefined) {\n throw new ValidationError(`executor binding: ${path}[${index}] cannot be undefined`)\n }\n return jsonWireSnapshot(item, `${path}[${index}]`)\n })\n }\n if (typeof value !== 'object' || value === null) {\n throw new ValidationError(`executor binding: ${path} must be JSON data`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new ValidationError(`executor binding: ${path} must be a plain object`)\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (item === undefined) continue\n out[key] = jsonWireSnapshot(item, `${path}.${key}`)\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,+BAA+B,KAAc,SAA+B;CAC1F,MAAM,QAAQ,iBAAiB,KAAK,GAAG,QAAQ,qBAAqB;CACpE,MAAM,UAAU,mBAAmB,MAAM,KAAK;CAC9C,6BAA6B,SAAS,OAAO;CAC7C,OAAO,iBAAiB,SAAS,GAAG,QAAQ,sBAAsB;AACpE;;AAGA,SAAgB,4BAA4B,KAAgB,SAA4B;CACtF,MAAM,EACJ,SAAS,YACT,SACA,WAAW,cACX,GAAG,sBACD;CACJ,MAAM,UAAU,+BAA+B,YAAY,OAAO;CAClE,MAAM,YACJ,iBAAiB,KAAA,IACb,KAAA,IACA,iBAAiB,cAAc,GAAG,QAAQ,wBAAwB;CACxE,OAAO,OAAO,OAAO;EACnB,GAAG;EACH;EACA;EACA,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;CACjD,CAAC;AACH;;;ACIA,MAAM,uDAAuC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AM,CAAC,KAAK,SAAS,OAAO,QAAQ,KAAgC,GAAG;EAC1E,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI,OAAO,iBAAiB,MAAM,GAAG,KAAK,GAAG,KAAK;CACpD;CACA,OAAO;AACT"}
package/dist/mcp/bin.js CHANGED
@@ -1,74 +1,66 @@
1
1
  #!/usr/bin/env node
2
2
  import { i as ConfigError } from "../errors-DEAvWQPy.js";
3
- import { x as readTraceContextFromEnv } from "../supervisor-DpjO0Gmy.js";
4
- import { L as DelegationTaskQueue, l as createMcpServer, q as FileDelegationStore } from "../supervise-CsTKbH9R.js";
5
- import { a as resolveRouterBaseUrl } from "../model-resolution-Btd9iIKV.js";
3
+ import { ot as readTraceContextFromEnv } from "../supervisor-CV6Jh28D.js";
4
+ import { C as createMcpServer, Z as DelegationTaskQueue, st as FileDelegationStore } from "../supervise-iPN27pO0.js";
5
+ import { a as supervisorInstructions } from "../authoring-CvHwo1oW.js";
6
6
  //#region src/mcp/delegate-supervisor-provisioning.ts
7
- const DEFAULT_WORKER_HARNESS = "opencode";
8
7
  function trimmed(value) {
9
8
  const v = value?.trim();
10
9
  return v ? v : void 0;
11
10
  }
11
+ function requiredEnv(env, name) {
12
+ const value = trimmed(env[name]);
13
+ if (value) return value;
14
+ throw new ConfigError(`agent-runtime-mcp: ${name} is required when MCP_ENABLE_DELEGATE=1`);
15
+ }
12
16
  /** True when the operator opted the generic `delegate` verb in (`MCP_ENABLE_DELEGATE=1`). Default off:
13
17
  * the wiring is additive, so consumers that do not enable it are unaffected. */
14
18
  function delegateEnabled(env = process.env) {
15
19
  return env.MCP_ENABLE_DELEGATE === "1";
16
20
  }
17
21
  /**
18
- * Resolve the supervisor brain's router substrate from env. The base reuses `resolveRouterBaseUrl`,
19
- * normalised to `/v1`.
20
- *
21
- * The KEY is the one for INFERENCE, which inside a sandbox is not the one for the sandbox. A box
22
- * carries both: an inference credential for the OpenAI-compatible endpoint the brain calls, and
23
- * `TANGLE_API_KEY`, which authenticates the sandbox CONTROL API — create a box, run a process —
24
- * and which the router answers `403`. The brain therefore prefers the inference credential and
25
- * keeps the platform key as the last rung, for a host that runs one key for both.
26
- *
27
- * `TANGLE_INFERENCE_KEY` leads because it is Tangle's own name for that credential. `OPENAI_API_KEY`
28
- * holds the identical value and stays on the ladder for boxes provisioned before the Tangle-native
29
- * name existed, and for a BYO OpenAI key — but it is a vendor spelling of a Tangle credential, and
30
- * naming it first made this ladder read as "prefer OpenAI over Tangle" to the people who own the
31
- * product (agent-dev-container#4614). A name that needs a paragraph to disclaim is the wrong name.
32
- *
33
- * The order is not a preference between vendors. It is: what the caller explicitly set, then the
34
- * inference credential, then the control-plane key as a single-key-host fallback.
35
- *
36
- * The MODEL is NAMED, never guessed. Which ids a given router serves is deployment state this
37
- * package cannot know, and a wrong guess is invisible until the supervisor's first completion
38
- * rejects — after the tool has been advertised to an agent, from inside a child process whose
39
- * stderr nobody reads. `TANGLE_ROUTER_MODEL` is on the ladder because the sandbox platform sets it
40
- * on every box: a delegate child running there inherits the model its own host declared. When
41
- * nothing names one, fail at startup with the ladder in the message.
22
+ * Resolve the supervisor brain from dedicated MCP configuration. The model is part of the exact
23
+ * profile; the URL and key are transport-only. No generic worker/model/key variable may silently
24
+ * select this paid execution path.
42
25
  */
43
- function resolveRouter(env) {
44
- const routerKey = trimmed(env.MCP_SUPERVISOR_ROUTER_KEY) ?? trimmed(env.TANGLE_INFERENCE_KEY) ?? trimmed(env.OPENAI_API_KEY) ?? trimmed(env.TANGLE_API_KEY) ?? "";
45
- const base = trimmed(env.MCP_SUPERVISOR_ROUTER_BASE_URL) ?? resolveRouterBaseUrl(env);
26
+ function resolveRouterSupervisor(env) {
27
+ const routerKey = requiredEnv(env, "MCP_SUPERVISOR_ROUTER_KEY");
28
+ const base = requiredEnv(env, "MCP_SUPERVISOR_ROUTER_BASE_URL");
46
29
  const routerBaseUrl = /\/v\d+\/?$/.test(base) ? base.replace(/\/$/, "") : `${base.replace(/\/$/, "")}/v1`;
47
- const model = trimmed(env.MCP_SUPERVISOR_MODEL) ?? trimmed(env.MCP_WORKER_MODEL) ?? trimmed(env.WORKER_MODEL) ?? trimmed(env.TANGLE_ROUTER_MODEL);
48
- if (!model) throw new ConfigError("agent-runtime-mcp: no supervisor brain model — set MCP_SUPERVISOR_MODEL (or MCP_WORKER_MODEL / WORKER_MODEL / TANGLE_ROUTER_MODEL) to a tool-calling model the router serves.");
30
+ const model = requiredEnv(env, "MCP_SUPERVISOR_MODEL");
49
31
  return {
50
- routerBaseUrl,
51
- routerKey,
52
- model
32
+ router: {
33
+ routerBaseUrl,
34
+ routerKey
35
+ },
36
+ profile: {
37
+ name: "delegate-supervisor",
38
+ harness: "cli-base",
39
+ model: {
40
+ provider: "tangle-router",
41
+ default: model
42
+ },
43
+ prompt: { systemPrompt: supervisorInstructions() }
44
+ }
53
45
  };
54
46
  }
55
47
  /**
56
48
  * Build the `delegateSupervisor` substrate for `createMcpServer` from env + the bin's loaded
57
49
  * `SandboxClient`. Returns `undefined` when `delegate` is not opted in, so the caller mounts it only
58
- * when asked. The worker backend is `sandbox` (authored workers run as sub-sandboxes via the same
59
- * client) on the harness named by `MCP_DELEGATE_WORKER_HARNESS` (default `opencode`).
50
+ * when asked. The worker backend is `sandbox`; every authored worker's exact profile selects its
51
+ * own harness/provider/model.
60
52
  */
61
53
  function resolveDelegateSupervisor(sandboxClient, env = process.env) {
62
54
  if (!delegateEnabled(env)) return void 0;
63
- const router = resolveRouter(env);
55
+ const supervisor = resolveRouterSupervisor(env);
56
+ const backend = {
57
+ backend: "sandbox",
58
+ sandboxClient
59
+ };
64
60
  return {
65
- router,
66
- backend: {
67
- backend: "sandbox",
68
- harness: trimmed(env.MCP_DELEGATE_WORKER_HARNESS) ?? DEFAULT_WORKER_HARNESS,
69
- sandboxClient
70
- },
71
- model: router.model
61
+ router: supervisor.router,
62
+ supervisorProfile: supervisor.profile,
63
+ backend
72
64
  };
73
65
  }
74
66
  //#endregion
@@ -94,7 +86,7 @@ async function main() {
94
86
  process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
95
87
  process.exit(2);
96
88
  }
97
- if (delegateSupervisor) process.stderr.write(`agent-runtime-mcp: delegate enabled — generic authoring supervisor on ${delegateSupervisor.router.model}\n`);
89
+ if (delegateSupervisor) process.stderr.write(`agent-runtime-mcp: delegate enabled — generic authoring supervisor on ${delegateSupervisor.supervisorProfile.model?.default}\n`);
98
90
  const durableQueue = await buildDurableQueueFromEnv(traceContext);
99
91
  const server = createMcpServer({
100
92
  ...delegateSupervisor ? { delegateSupervisor } : {},
@@ -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 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 { ConfigError } from '../errors'\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\n// Composition-root default: a worker must run on SOME harness, and the router-backed one is the\n// least vendor-locked choice. Not a capability claim — nothing here branches on the name.\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/**\n * Resolve the supervisor brain's router substrate from env. The base reuses `resolveRouterBaseUrl`,\n * normalised to `/v1`.\n *\n * The KEY is the one for INFERENCE, which inside a sandbox is not the one for the sandbox. A box\n * carries both: an inference credential for the OpenAI-compatible endpoint the brain calls, and\n * `TANGLE_API_KEY`, which authenticates the sandbox CONTROL API — create a box, run a process —\n * and which the router answers `403`. The brain therefore prefers the inference credential and\n * keeps the platform key as the last rung, for a host that runs one key for both.\n *\n * `TANGLE_INFERENCE_KEY` leads because it is Tangle's own name for that credential. `OPENAI_API_KEY`\n * holds the identical value and stays on the ladder for boxes provisioned before the Tangle-native\n * name existed, and for a BYO OpenAI key — but it is a vendor spelling of a Tangle credential, and\n * naming it first made this ladder read as \"prefer OpenAI over Tangle\" to the people who own the\n * product (agent-dev-container#4614). A name that needs a paragraph to disclaim is the wrong name.\n *\n * The order is not a preference between vendors. It is: what the caller explicitly set, then the\n * inference credential, then the control-plane key as a single-key-host fallback.\n *\n * The MODEL is NAMED, never guessed. Which ids a given router serves is deployment state this\n * package cannot know, and a wrong guess is invisible until the supervisor's first completion\n * rejects — after the tool has been advertised to an agent, from inside a child process whose\n * stderr nobody reads. `TANGLE_ROUTER_MODEL` is on the ladder because the sandbox platform sets it\n * on every box: a delegate child running there inherits the model its own host declared. When\n * nothing names one, fail at startup with the ladder in the message.\n */\nfunction resolveRouter(env: NodeJS.ProcessEnv): RouterConfig {\n const routerKey =\n trimmed(env.MCP_SUPERVISOR_ROUTER_KEY) ??\n trimmed(env.TANGLE_INFERENCE_KEY) ??\n trimmed(env.OPENAI_API_KEY) ??\n trimmed(env.TANGLE_API_KEY) ??\n ''\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 trimmed(env.TANGLE_ROUTER_MODEL)\n if (!model) {\n throw new ConfigError(\n 'agent-runtime-mcp: no supervisor brain model — set MCP_SUPERVISOR_MODEL (or MCP_WORKER_MODEL / ' +\n 'WORKER_MODEL / TANGLE_ROUTER_MODEL) to a tool-calling model the router serves.',\n )\n }\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 TANGLE_ROUTER_MODEL). Must be a tool-calling\n * model the router serves; with none named the bin exits 2.\n * MCP_SUPERVISOR_ROUTER_KEY router key for the supervisor brain (falls back to the box's\n * inference credential TANGLE_INFERENCE_KEY, then its vendor\n * spelling OPENAI_API_KEY, then TANGLE_API_KEY — which\n * authenticates the sandbox API, not the router)\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 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 = 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 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.router.model}\\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\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":";;;;;;AA2BA,MAAM,yBAAyB;AAE/B,SAAS,QAAQ,OAA+C;CAC9D,MAAM,IAAI,OAAO,KAAK;CACtB,OAAO,IAAI,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AAO,MAAM,sBAAsB,MAAM,QAAQ,GAAG;GAC5D,QAAQ,KAAK,CAAC;EAChB;CACF,CAAC;CACD,QAAQ,OAAO,MAAM,iDAAiD,UAAU,GAAG;CACnF,OAAO;AACT;AAEA,SAAS,eAAe,KAA6C;CACnE,IAAI,QAAQ,KAAA,KAAa,IAAI,KAAK,MAAM,IAAI,OAAO,KAAA;CACnD,MAAM,IAAI,OAAO,GAAG;CACpB,IAAI,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,GAAG;EACjC,QAAQ,OAAO,MACb,gGAAgG,IAAI,IACtG;EACA,QAAQ,KAAK,CAAC;CAChB;CACA,OAAO;AACT;AAEA,eAAe,kBAAkB,QAAoD;CAKnF,IAAI,CAAC,QACH,OAAO,EACL,MAAM,SAAS;EACb,MAAM,IAAI,MACR,2LACF;CACF,EACF;CAWF,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 `TANGLE_API_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 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 * 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 return {\n router: { routerBaseUrl, routerKey },\n profile: {\n name: 'delegate-supervisor',\n harness: 'cli-base',\n model: { provider: 'tangle-router', default: model },\n prompt: { systemPrompt: supervisorInstructions() },\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 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 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 * 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 = 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 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\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":";;;;;;AAuBA,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;;;;;;AAOA,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;CACrD,OAAO;EACL,QAAQ;GAAE;GAAe;EAAU;EACnC,SAAS;GACP,MAAM;GACN,SAAS;GACT,OAAO;IAAE,UAAU;IAAiB,SAAS;GAAM;GACnD,QAAQ,EAAE,cAAc,uBAAuB,EAAE;EACnD;CACF;AACF;;;;;;;AAQA,SAAgB,0BACd,eACA,MAAyB,QAAQ,KACG;CACpC,IAAI,CAAC,gBAA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