@tangle-network/agent-runtime 0.337.2 → 0.339.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/dist/{activation-DRHM55Oo.d.ts → activation-CJIIl_Ey.d.ts} +90 -22
  2. package/dist/activation-CVSFxis9.js +876 -0
  3. package/dist/activation-CVSFxis9.js.map +1 -0
  4. package/dist/agent.d.ts +4 -4
  5. package/dist/agent.js +4 -7
  6. package/dist/agent.js.map +1 -1
  7. package/dist/{bundle-BPGjESee.js → bundle-DVOhBTic.js} +2 -2
  8. package/dist/{bundle-BPGjESee.js.map → bundle-DVOhBTic.js.map} +1 -1
  9. package/dist/candidate-execution/index.d.ts +4 -63
  10. package/dist/candidate-execution/index.js +6 -146
  11. package/dist/candidate-execution/index.js.map +1 -1
  12. package/dist/content-digest-sBTLujlK.js +9 -0
  13. package/dist/content-digest-sBTLujlK.js.map +1 -0
  14. package/dist/{delegate-B-T_ZB50.js → delegate-CCWE_AkU.js} +2 -2
  15. package/dist/{delegate-B-T_ZB50.js.map → delegate-CCWE_AkU.js.map} +1 -1
  16. package/dist/{coordination-driver-BHkFVqIq.js → driver-control-acknowledgers-C53ggdJ6.js} +4520 -4442
  17. package/dist/driver-control-acknowledgers-C53ggdJ6.js.map +1 -0
  18. package/dist/{durable-file-B_eJr6Mb.js → durable-file-gNI9ILAn.js} +1 -3
  19. package/dist/durable-file-gNI9ILAn.js.map +1 -0
  20. package/dist/durable.d.ts +3 -35
  21. package/dist/durable.js +225 -229
  22. package/dist/durable.js.map +1 -1
  23. package/dist/{graph-C4RFlWAJ.js → graph-CI9JXKqO.js} +65 -18
  24. package/dist/graph-CI9JXKqO.js.map +1 -0
  25. package/dist/{graph-registry-DAI6KNXB.js → graph-registry-BnO64cn8.js} +18 -17
  26. package/dist/graph-registry-BnO64cn8.js.map +1 -0
  27. package/dist/{improvement-cycle-D1I4hQvf.js → improve-BOXTLWJ3.js} +76 -1248
  28. package/dist/improve-BOXTLWJ3.js.map +1 -0
  29. package/dist/{improvement-adapter-D5gwwoXQ.d.ts → improvement-adapter-HUt_-cWA.d.ts} +2 -20
  30. package/dist/index.d.ts +10 -207
  31. package/dist/index.js +91 -305
  32. package/dist/index.js.map +1 -1
  33. package/dist/intelligence.d.ts +10 -229
  34. package/dist/intelligence.js +506 -88
  35. package/dist/intelligence.js.map +1 -1
  36. package/dist/{jsonl-file-DBv31uPi.js → jsonl-file-C9Kde_0Z.js} +2 -2
  37. package/dist/{jsonl-file-DBv31uPi.js.map → jsonl-file-C9Kde_0Z.js.map} +1 -1
  38. package/dist/kernel.d.ts +4 -3
  39. package/dist/kernel.js +12 -13
  40. package/dist/loop-runner-CWzG1bH4.d.ts +32 -0
  41. package/dist/loop-runner-bin.d.ts +32 -2
  42. package/dist/loop-runner-bin.js +93 -1
  43. package/dist/loop-runner-bin.js.map +1 -0
  44. package/dist/loop-runner-pmPIHFVY.js +59 -0
  45. package/dist/loop-runner-pmPIHFVY.js.map +1 -0
  46. package/dist/mcp/bin.js +3 -3
  47. package/dist/mcp/bin.js.map +1 -1
  48. package/dist/mcp/index.d.ts +101 -416
  49. package/dist/mcp/index.js +122 -206
  50. package/dist/mcp/index.js.map +1 -1
  51. package/dist/mcp/memory-bin.js +231 -1
  52. package/dist/mcp/memory-bin.js.map +1 -1
  53. package/dist/model-policy-CyCUwHed.js.map +1 -1
  54. package/dist/placement.d.ts +2 -9
  55. package/dist/placement.js +1 -1
  56. package/dist/placement.js.map +1 -1
  57. package/dist/platform.d.ts +194 -2
  58. package/dist/platform.js +145 -9
  59. package/dist/platform.js.map +1 -1
  60. package/dist/{prepare-CER-ZkPp.js → prepare-bXkvPMJA.js} +1213 -710
  61. package/dist/prepare-bXkvPMJA.js.map +1 -0
  62. package/dist/{profile-gNUsHNIJ.js → profile-Dpei_Sq0.js} +89 -3
  63. package/dist/profile-Dpei_Sq0.js.map +1 -0
  64. package/dist/{profile-materialization-BnoEf1co.d.ts → profile-materialization-B1wm2SPT.d.ts} +3 -5
  65. package/dist/profiles.d.ts +2 -2
  66. package/dist/profiles.js +4 -43
  67. package/dist/profiles.js.map +1 -1
  68. package/dist/{protected-model-port-BhpQRTw-.d.ts → protected-model-port-BGgpy2r9.d.ts} +4 -30
  69. package/dist/protected-redaction-DFCeo4vg.js.map +1 -1
  70. package/dist/{provision-supervisor-DGegCUH4.js → provision-supervisor-CJ6Zz6dz.js} +13 -10
  71. package/dist/provision-supervisor-CJ6Zz6dz.js.map +1 -0
  72. package/dist/record-value-B6bwJxLa.js +12 -0
  73. package/dist/record-value-B6bwJxLa.js.map +1 -0
  74. package/dist/{run-layout-Cu8H7aeh.js → run-cancellation-C9oL62sW.js} +175 -100
  75. package/dist/run-cancellation-C9oL62sW.js.map +1 -0
  76. package/dist/{runtime-BOGpotnH.js → runtime-B2fjL9Oi.js} +2639 -3187
  77. package/dist/runtime-B2fjL9Oi.js.map +1 -0
  78. package/dist/{runtime-hooks-Bj6wJHlH.d.ts → runtime-hooks-nsqxSUFL.d.ts} +2 -6
  79. package/dist/{sandbox-profile-compat-QTkLe1Z6.js → sandbox-profile-compat-BzVBFqrz.js} +690 -699
  80. package/dist/sandbox-profile-compat-BzVBFqrz.js.map +1 -0
  81. package/dist/search-executor-zMumiak_.js +1916 -0
  82. package/dist/search-executor-zMumiak_.js.map +1 -0
  83. package/dist/{server-hZWM-G8w.js → server-_4voDNrl.js} +362 -67
  84. package/dist/server-_4voDNrl.js.map +1 -0
  85. package/dist/{search-executor-Cm1WZmL-.js → structural-rollout-DpLCXzaL.js} +1680 -3403
  86. package/dist/structural-rollout-DpLCXzaL.js.map +1 -0
  87. package/dist/{substrate-B0TYNrXn.js → substrate-CGDFTSRh.js} +2 -9
  88. package/dist/substrate-CGDFTSRh.js.map +1 -0
  89. package/dist/{supervise-CvAKVfue.js → supervise-qAwXmPtD.js} +7768 -5360
  90. package/dist/supervise-qAwXmPtD.js.map +1 -0
  91. package/dist/{supervisor-Rz8AGpYb.js → supervisor-DHrUJhEZ.js} +26301 -26964
  92. package/dist/supervisor-DHrUJhEZ.js.map +1 -0
  93. package/dist/testing.d.ts +227 -2
  94. package/dist/testing.js +13 -14
  95. package/dist/testing.js.map +1 -1
  96. package/dist/tool-loop.d.ts +1 -1
  97. package/dist/{tool-server-Dqer2M4_.js → tool-server-XV4aJwoQ.js} +2 -2
  98. package/dist/tool-server-XV4aJwoQ.js.map +1 -0
  99. package/dist/top-snapshot-CbZE1JsU.js +502 -0
  100. package/dist/top-snapshot-CbZE1JsU.js.map +1 -0
  101. package/dist/tui/bin.js +711 -1
  102. package/dist/tui/bin.js.map +1 -1
  103. package/dist/tui/index.d.ts +5 -71
  104. package/dist/tui/index.js +3 -3
  105. package/dist/{types-Dl5L4r8Z.d.ts → types-CaOXqRTq.d.ts} +16230 -17376
  106. package/dist/workspace-store/index.d.ts +2 -27
  107. package/dist/workspace-store/index.js +2 -2
  108. package/dist/workspace-store/index.js.map +1 -1
  109. package/dist/{workspace-streams-JLjh5DC6.d.ts → workspace-streams-BiS4ABah.d.ts} +19 -32
  110. package/package.json +2 -2
  111. package/skills/agent-graphs/SKILL.md +10 -3
  112. package/skills/agent-graphs/references/authoring.md +18 -0
  113. package/skills/profile-authoring/SKILL.md +3 -3
  114. package/skills/supervise/SKILL.md +2 -2
  115. package/dist/activation-BDP6Eivv.js +0 -234
  116. package/dist/activation-BDP6Eivv.js.map +0 -1
  117. package/dist/coder-yhVWbdWc.js +0 -40
  118. package/dist/coder-yhVWbdWc.js.map +0 -1
  119. package/dist/coordination-driver-BHkFVqIq.js.map +0 -1
  120. package/dist/delegation-status-CF4D0NZ_.js +0 -358
  121. package/dist/delegation-status-CF4D0NZ_.js.map +0 -1
  122. package/dist/durable-file-B_eJr6Mb.js.map +0 -1
  123. package/dist/graph-C4RFlWAJ.js.map +0 -1
  124. package/dist/graph-registry-DAI6KNXB.js.map +0 -1
  125. package/dist/improvement-cycle-D1I4hQvf.js.map +0 -1
  126. package/dist/integrations-DopfCC2a.d.ts +0 -190
  127. package/dist/integrations-dFi-ALk7.js +0 -132
  128. package/dist/integrations-dFi-ALk7.js.map +0 -1
  129. package/dist/kb-gate-C8z2juK8.d.ts +0 -80
  130. package/dist/kb-gate-DpaSwXVx.js +0 -80
  131. package/dist/kb-gate-DpaSwXVx.js.map +0 -1
  132. package/dist/loop-runner-bin-DOuBIJ2O.d.ts +0 -164
  133. package/dist/loop-runner-bin-Dv5QvYDH.js +0 -246
  134. package/dist/loop-runner-bin-Dv5QvYDH.js.map +0 -1
  135. package/dist/memory-server-DXQ8IxGR.js +0 -234
  136. package/dist/memory-server-DXQ8IxGR.js.map +0 -1
  137. package/dist/openai-tools-DoQ32vpe.js +0 -44
  138. package/dist/openai-tools-DoQ32vpe.js.map +0 -1
  139. package/dist/openai-tools-Oxk4KQrY.d.ts +0 -24
  140. package/dist/prepare-CER-ZkPp.js.map +0 -1
  141. package/dist/profile-gNUsHNIJ.js.map +0 -1
  142. package/dist/protected-model-port-BuRsviSL.js +0 -766
  143. package/dist/protected-model-port-BuRsviSL.js.map +0 -1
  144. package/dist/provision-supervisor-DGegCUH4.js.map +0 -1
  145. package/dist/run-layout-Cu8H7aeh.js.map +0 -1
  146. package/dist/runtime-BOGpotnH.js.map +0 -1
  147. package/dist/sandbox-profile-compat-QTkLe1Z6.js.map +0 -1
  148. package/dist/search-executor-Cm1WZmL-.js.map +0 -1
  149. package/dist/server-hZWM-G8w.js.map +0 -1
  150. package/dist/substrate-B0TYNrXn.js.map +0 -1
  151. package/dist/supervise-CvAKVfue.js.map +0 -1
  152. package/dist/supervisor-Rz8AGpYb.js.map +0 -1
  153. package/dist/tool-server-Dqer2M4_.js.map +0 -1
  154. package/dist/top-app-BaMw1W2z.js +0 -1212
  155. package/dist/top-app-BaMw1W2z.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,16 +1,15 @@
1
- import { Ar as sanitizeRuntimeStreamEvent, Cr as padSpanId, Di as executableAgentProfileSnapshot, Dr as createRuntimeStreamEventCollector, Er as createRuntimeEventCollector, Ma as providerMessageText, Ni as runtimeFailureCause, Oa as defaultRedactorIdentityMaterial, Or as sanitizeAgentRuntimeEvent, Pi as settlementFailureCause, Sr as loopEventToOtelSpan, Tr as toOtelAttributes, _r as buildRuntimeEventOtelSpans, cr as priceTokens, gr as buildLoopSpanNodes, hr as buildLoopOtelSpans, ka as resolveRedactor, kr as sanitizeKnowledgeReadinessReport, lr as routerTokenPrice, ur as ROUTER_PRICE_SOURCE, vr as createOpenInferenceFileExporter, wr as padTraceId, xr as generateSpanId, yr as createOtelExporter } from "./supervisor-Rz8AGpYb.js";
2
- import { a as JudgeError, c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, f as RuntimeRunStateError, i as ConfigError, l as RetainedInteractiveBindingError, m as ValidationError, o as NotFoundError, r as BackendTransportError, s as PlannerError, t as AgentEvalError, u as RetainedRunAdmissionError } from "./errors-DodWX-cb.js";
3
- import { $ as createIterableBackend, Q as streamAgentTurn, X as strategyAuthorMethod, Y as optimizerMethod, at as startOrResumeRuntimeSession, et as createSandboxPromptBackend, i as isSearchEnvironmentFault, it as nowIso, l as sharedBoxLane, nt as InMemoryRuntimeSessionStore, o as routerLane, ot as touchSession, r as dedicatedLane, rt as newRuntimeSession, t as SearchEnvironmentFault, tt as normalizeBackendStreamEvent, u as subscriptionLane, y as decideSearchImprovement } from "./search-executor-Cm1WZmL-.js";
4
- import { B as omitTopLevelDigest, F as canonicalCandidateDigest$1, P as canonicalCandidateBytes$1, R as embeddedCandidateArtifact, l as captureAgentCandidateWorkspace, m as persistCandidateOutputArtifact, z as immutableCandidateValue } from "./sandbox-profile-compat-QTkLe1Z6.js";
1
+ import { $i as providerMessageText, Li as defaultRedactorIdentityMaterial, Ri as resolveRedactor, _n as sanitizeKnowledgeReadinessReport, dn as padSpanId, fn as padTraceId, gn as sanitizeAgentRuntimeEvent, hn as createRuntimeStreamEventCollector, li as executableAgentProfileSnapshot, mn as createRuntimeEventCollector, or as priceTokens, pi as runtimeFailureCause, rn as buildLoopOtelSpans, sn as createOtelExporter, sr as ROUTER_PRICE_SOURCE, un as loopEventToOtelSpan, vn as sanitizeRuntimeStreamEvent } from "./supervisor-DHrUJhEZ.js";
2
+ import { a as JudgeError, f as RuntimeRunStateError, i as ConfigError, m as ValidationError, o as NotFoundError, r as BackendTransportError, t as AgentEvalError } from "./errors-DodWX-cb.js";
3
+ import { B as InMemoryRuntimeSessionStore, C as optimizerMethod, H as nowIso, I as streamAgentTurn, L as createIterableBackend, R as createSandboxPromptBackend, U as startOrResumeRuntimeSession, V as newRuntimeSession, W as touchSession, z as normalizeBackendStreamEvent } from "./structural-rollout-DpLCXzaL.js";
4
+ import { B as omitTopLevelDigest, F as canonicalCandidateDigest$1, P as canonicalCandidateBytes$1, R as embeddedCandidateArtifact, l as captureAgentCandidateWorkspace, st as sleep, v as persistCandidateOutputArtifact, z as immutableCandidateValue } from "./sandbox-profile-compat-BzVBFqrz.js";
5
5
  import { t as assertExecutableAgentProfile } from "./model-policy-CyCUwHed.js";
6
- import { a as createRuntimeUsageTotals, i as addRuntimeUsage, o as isUsageAmount, t as createAgentImprovementActivationResult } from "./activation-BDP6Eivv.js";
7
- import { $t as McpSpawnFault, en as connectStdioMcp } from "./runtime-BOGpotnH.js";
8
- import { i as notifyRuntimeHookEvent, n as defineRuntimeHooks, r as notifyRuntimeDecisionPoint, t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
9
- import { $ as commandVerifier, B as assertCandidateValidator, G as rawTraceDistiller, H as parseExecutionRef, J as normalizeRolloutPolicy, K as ROLLOUT_POLICY_EXTENSION, L as improve, Q as agenticGenerator, R as createCommandProfileTrainer, U as privateValuePaths, W as withMethodRuntimeControls, X as serializeRolloutPolicy, Y as parseRolloutPolicy, Z as structuralRolloutPolicyFromProfile, et as defaultBuildPrompt, q as applyRolloutPolicyToProfile, z as searchMethod } from "./improvement-cycle-D1I4hQvf.js";
10
- import { t as sealAgentCandidateBundle } from "./bundle-BPGjESee.js";
11
- import { r as supervise } from "./supervise-CvAKVfue.js";
12
- import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-Dv5QvYDH.js";
13
- import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "./openai-tools-DoQ32vpe.js";
6
+ import { c as withMethodRuntimeControls, d as commandVerifier, f as addRuntimeUsage, i as assertCandidateValidator, m as isUsageAmount, n as createCommandProfileTrainer, o as parseExecutionRef, p as createRuntimeUsageTotals, r as searchMethod, s as privateValuePaths, t as improve, u as agenticGenerator } from "./improve-BOXTLWJ3.js";
7
+ import { n as defineRuntimeHooks, t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
8
+ import { t as supervise } from "./supervise-qAwXmPtD.js";
9
+ import { n as createAgentImprovementActivationResult } from "./activation-CVSFxis9.js";
10
+ import { l as sharedBoxLane, o as routerLane, r as dedicatedLane, t as SearchEnvironmentFault, u as subscriptionLane, y as decideSearchImprovement } from "./search-executor-zMumiak_.js";
11
+ import { t as sealAgentCandidateBundle } from "./bundle-DVOhBTic.js";
12
+ import { n as auditLoopRunner } from "./loop-runner-pmPIHFVY.js";
14
13
  import { agentCandidateKnowledgeSchema, agentCandidateWorkspaceManifestMaterialSchema, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sha256DigestSchema } from "@tangle-network/agent-interface";
15
14
  import { FAILURE_CLASSES, acquisitionPlansForKnowledgeGaps, blockingKnowledgeEval, canonicalJson, runAgentControlLoop, scoreKnowledgeReadiness, userQuestionsForKnowledgeGaps } from "@tangle-network/agent-eval";
16
15
  import { z } from "zod";
@@ -102,6 +101,85 @@ function rebindEvent(event, context) {
102
101
  };
103
102
  }
104
103
  //#endregion
104
+ //#region src/conversation/headers.ts
105
+ /**
106
+ *
107
+ * Cross-gateway forwarding headers — the wire-level contract that makes
108
+ * agent-to-agent communication composable across organizational boundaries.
109
+ * Every header here is read on inbound and re-emitted on outbound, so a chain
110
+ * `caller → A's gateway → A's runtime → B's gateway → B's runtime` ends with
111
+ * B billing the original user, the depth counter monotonically incremented,
112
+ * and the run/turn correlation IDs preserved end-to-end.
113
+ *
114
+ * The actual depth refusal (HTTP 413 at MAX_DEPTH) is enforced by
115
+ * `agent-gateway`'s middleware; this module owns the names + the propagation
116
+ * rules so both sides agree.
117
+ *
118
+ * Full protocol: `docs/agent-bus-protocol.md`.
119
+ *
120
+ * @stable
121
+ */
122
+ /** Standard names — lowercased so Headers maps interop on every runtime. */
123
+ const FORWARD_HEADERS = {
124
+ /** Forwarded original-user identity (`Bearer sk-tan-<user>`); downstream gateways bill against this. */
125
+ authorization: "x-tangle-forwarded-authorization",
126
+ /** Monotonically incremented on every gateway hop. Refused at MAX_DEPTH. */
127
+ depth: "x-tangle-forwarded-depth",
128
+ /** Top-level conversation run identifier, propagated through every nested call. */
129
+ runId: "x-tangle-runid",
130
+ /** This call's turn within the run; deterministic + stable across retries. */
131
+ turnId: "x-tangle-turnid",
132
+ /** When the call is *inside* another turn (recursion), the parent turn's id. */
133
+ parentTurnId: "x-tangle-parent-turnid",
134
+ /** Logical conversation peer label at the sending side, for trace stitching. */
135
+ speaker: "x-tangle-speaker"
136
+ };
137
+ /**
138
+ * Lowercase a header lookup so we read the same key regardless of source
139
+ * casing (Hono, fetch's `Headers`, raw Node IncomingMessage, …).
140
+ */
141
+ function lc(name) {
142
+ return name.toLowerCase();
143
+ }
144
+ /**
145
+ * Read the depth counter off an inbound request. Missing → 0 (caller is the
146
+ * origin). Non-integer → throws — silent coercion would let a bad caller
147
+ * reset depth and bypass the limit.
148
+ */
149
+ function readDepth(headers) {
150
+ const raw = pickHeader(headers, FORWARD_HEADERS.depth);
151
+ if (raw === void 0 || raw === "") return 0;
152
+ const n = Number(raw);
153
+ if (!Number.isInteger(n) || n < 0) throw new Error(`invalid ${FORWARD_HEADERS.depth} header value '${raw}' — must be a non-negative integer`);
154
+ return n;
155
+ }
156
+ /**
157
+ * Build the headers to emit on an outbound participant call, given the
158
+ * conversation's propagation context. Depth is incremented from the inbound
159
+ * value; runId / turnId / speaker stamp the current hop; the user's
160
+ * `Authorization` is preserved verbatim so the downstream gateway bills the
161
+ * right wallet.
162
+ */
163
+ function buildForwardHeaders(input) {
164
+ const out = {
165
+ [FORWARD_HEADERS.depth]: String(input.inboundDepth + 1),
166
+ [FORWARD_HEADERS.runId]: input.runId,
167
+ [FORWARD_HEADERS.turnId]: input.turnId,
168
+ [FORWARD_HEADERS.speaker]: input.speaker
169
+ };
170
+ if (input.forwardedAuthorization !== void 0) out[FORWARD_HEADERS.authorization] = input.forwardedAuthorization;
171
+ if (input.parentTurnId !== void 0) out[FORWARD_HEADERS.parentTurnId] = input.parentTurnId;
172
+ return out;
173
+ }
174
+ function pickHeader(headers, name) {
175
+ const target = lc(name);
176
+ for (const key of Object.keys(headers)) if (lc(key) === target) {
177
+ const value = headers[key];
178
+ if (Array.isArray(value)) return value[0];
179
+ return value;
180
+ }
181
+ }
182
+ //#endregion
105
183
  //#region src/conversation/call-policy.ts
106
184
  /** Thrown when the circuit breaker is open for a participant and no retry is allowed yet. */
107
185
  var CircuitOpenError = class extends Error {
@@ -208,89 +286,6 @@ function computeBackoff(spec, attempt) {
208
286
  if (typeof spec === "function") return Math.max(0, spec(attempt));
209
287
  return Math.max(0, spec);
210
288
  }
211
- /** Resolve after `ms` milliseconds — used for retry backoff in conversation call policy. */
212
- function sleep(ms) {
213
- return new Promise((resolve) => setTimeout(resolve, ms));
214
- }
215
- //#endregion
216
- //#region src/conversation/headers.ts
217
- /**
218
- *
219
- * Cross-gateway forwarding headers — the wire-level contract that makes
220
- * agent-to-agent communication composable across organizational boundaries.
221
- * Every header here is read on inbound and re-emitted on outbound, so a chain
222
- * `caller → A's gateway → A's runtime → B's gateway → B's runtime` ends with
223
- * B billing the original user, the depth counter monotonically incremented,
224
- * and the run/turn correlation IDs preserved end-to-end.
225
- *
226
- * The actual depth refusal (HTTP 413 at MAX_DEPTH) is enforced by
227
- * `agent-gateway`'s middleware; this module owns the names + the propagation
228
- * rules so both sides agree.
229
- *
230
- * Full protocol: `docs/agent-bus-protocol.md`.
231
- *
232
- * @stable
233
- */
234
- /** Standard names — lowercased so Headers maps interop on every runtime. */
235
- const FORWARD_HEADERS = {
236
- /** Forwarded original-user identity (`Bearer sk-tan-<user>`); downstream gateways bill against this. */
237
- authorization: "x-tangle-forwarded-authorization",
238
- /** Monotonically incremented on every gateway hop. Refused at MAX_DEPTH. */
239
- depth: "x-tangle-forwarded-depth",
240
- /** Top-level conversation run identifier, propagated through every nested call. */
241
- runId: "x-tangle-runid",
242
- /** This call's turn within the run; deterministic + stable across retries. */
243
- turnId: "x-tangle-turnid",
244
- /** When the call is *inside* another turn (recursion), the parent turn's id. */
245
- parentTurnId: "x-tangle-parent-turnid",
246
- /** Logical conversation peer label at the sending side, for trace stitching. */
247
- speaker: "x-tangle-speaker"
248
- };
249
- /**
250
- * Lowercase a header lookup so we read the same key regardless of source
251
- * casing (Hono, fetch's `Headers`, raw Node IncomingMessage, …).
252
- */
253
- function lc(name) {
254
- return name.toLowerCase();
255
- }
256
- /**
257
- * Read the depth counter off an inbound request. Missing → 0 (caller is the
258
- * origin). Non-integer → throws — silent coercion would let a bad caller
259
- * reset depth and bypass the limit.
260
- */
261
- function readDepth(headers) {
262
- const raw = pickHeader(headers, FORWARD_HEADERS.depth);
263
- if (raw === void 0 || raw === "") return 0;
264
- const n = Number(raw);
265
- if (!Number.isInteger(n) || n < 0) throw new Error(`invalid ${FORWARD_HEADERS.depth} header value '${raw}' — must be a non-negative integer`);
266
- return n;
267
- }
268
- /**
269
- * Build the headers to emit on an outbound participant call, given the
270
- * conversation's propagation context. Depth is incremented from the inbound
271
- * value; runId / turnId / speaker stamp the current hop; the user's
272
- * `Authorization` is preserved verbatim so the downstream gateway bills the
273
- * right wallet.
274
- */
275
- function buildForwardHeaders(input) {
276
- const out = {
277
- [FORWARD_HEADERS.depth]: String(input.inboundDepth + 1),
278
- [FORWARD_HEADERS.runId]: input.runId,
279
- [FORWARD_HEADERS.turnId]: input.turnId,
280
- [FORWARD_HEADERS.speaker]: input.speaker
281
- };
282
- if (input.forwardedAuthorization !== void 0) out[FORWARD_HEADERS.authorization] = input.forwardedAuthorization;
283
- if (input.parentTurnId !== void 0) out[FORWARD_HEADERS.parentTurnId] = input.parentTurnId;
284
- return out;
285
- }
286
- function pickHeader(headers, name) {
287
- const target = lc(name);
288
- for (const key of Object.keys(headers)) if (lc(key) === target) {
289
- const value = headers[key];
290
- if (Array.isArray(value)) return value[0];
291
- return value;
292
- }
293
- }
294
289
  //#endregion
295
290
  //#region src/conversation/turn-id.ts
296
291
  /**
@@ -1053,145 +1048,6 @@ function runPersonaDispatch(config) {
1053
1048
  };
1054
1049
  }
1055
1050
  //#endregion
1056
- //#region src/durable/sql-adapter.ts
1057
- /**
1058
- * Adapt a Cloudflare D1 binding to the SqlAdapter shape. Lives here so D1
1059
- * consumers don't have to write the wrapper themselves; the runtime never
1060
- * imports `@cloudflare/workers-types` directly (peer-style typing).
1061
- */
1062
- function d1ToSqlAdapter(db) {
1063
- return {
1064
- async exec(sql, params = []) {
1065
- const stmt = db.prepare(sql);
1066
- const meta = (await (params.length > 0 ? stmt.bind(...params) : stmt).run()).meta;
1067
- return { rowsAffected: meta?.rows_written ?? meta?.changes ?? 0 };
1068
- },
1069
- async query(sql, params = []) {
1070
- const stmt = db.prepare(sql);
1071
- return (await (params.length > 0 ? stmt.bind(...params) : stmt).all()).results ?? [];
1072
- }
1073
- };
1074
- }
1075
- //#endregion
1076
- //#region src/improvement/build-prompts.ts
1077
- /** Render findings as the ranked-evidence block every build prompt ends with. */
1078
- function findingLines(findings) {
1079
- return findings.map((f) => {
1080
- const where = f.subject ? ` [${f.subject}]` : "";
1081
- const action = f.recommended_action ? ` → ${f.recommended_action}` : "";
1082
- return `- (${f.severity})${where} ${f.claim}${action}`;
1083
- });
1084
- }
1085
- /** Build the starting instruction for a coder agent tasked with implementing a new tool. */
1086
- function toolBuildPrompt(args) {
1087
- return [
1088
- "You are building a new TOOL for this codebase — a capability the agent measurably lacks,",
1089
- "evidenced by the failure findings at the bottom. The tool is an experiment: after it is",
1090
- "built and verified, its marginal lift is measured on held-out tasks, and only a real lift",
1091
- "promotes it.",
1092
- "",
1093
- optimizerMethod,
1094
- "",
1095
- "THE SURFACE — what a deliverable tool looks like here:",
1096
- "- ONE small, self-contained module PLUS tests that exercise its contract (what callers rely",
1097
- " on), not its internals. The tests are the experiment for sub-goal correctness — write the",
1098
- " test that would fail if your hypothesis about the gap were wrong.",
1099
- "- It must compile and its tests must pass — they run automatically; on failure you get the",
1100
- " verifier output and another attempt, resuming on top of your own edits (fix in place, do",
1101
- " not start over).",
1102
- "- Match the codebase grain: reuse its existing helpers, style, and test framework; a tool",
1103
- " that fights the codebase is the wrong tool even if it passes.",
1104
- "- Do not commit; leave the changes in the working tree.",
1105
- "",
1106
- "FINDINGS — ranked evidence from real failed runs (the gaps the tool must close):",
1107
- ...findingLines(args.findings)
1108
- ].join("\n");
1109
- }
1110
- /** Build the starting instruction for a coder agent tasked with implementing a new MCP server. */
1111
- function mcpBuildPrompt(args) {
1112
- return [
1113
- "You are building a new MCP SERVER (Model Context Protocol) exposing tool(s) that close the",
1114
- "capability gaps evidenced by the failure findings at the bottom, so any harness can mount",
1115
- "them. The server is an experiment: after it is built and boot-verified, its marginal lift is",
1116
- "measured on held-out tasks, and only a real lift promotes it.",
1117
- "",
1118
- optimizerMethod,
1119
- "",
1120
- "RESEARCH FIRST — ADOPT BEFORE BUILD: you may discover and ADOPT an existing external MCP",
1121
- "server if it fits the gaps better than building one. Registries and vendor docs list",
1122
- "maintained servers for most common capabilities (web search, fetch, GitHub, filesystems,",
1123
- "databases). To adopt, deliver a short adoption note instead of an implementation: the",
1124
- "server's launch command or HTTP endpoint, and the API key it needs BY NAME (e.g.",
1125
- "EXA_API_KEY) — never a key value; provisioning injects the value at materialize time. If",
1126
- "your environment has no web access, decide from what you already know and say so.",
1127
- "",
1128
- "THE SURFACE — what a deliverable MCP server looks like here (checked by BOOTING it):",
1129
- "- it starts over stdio and answers the MCP `initialize` handshake,",
1130
- "- `tools/list` returns at least one tool with a valid input schema,",
1131
- "- newline-delimited JSON-RPC 2.0, protocol version 2024-11-05,",
1132
- "- a clear start command (a package.json `start` script or an obvious entrypoint).",
1133
- "Design the tool surface for the FINDINGS, not for generality: each exposed tool should map to",
1134
- "a named failure mechanism, with a description that tells the agent when to reach for it (a",
1135
- "tool the agent never calls measures zero). If the boot-and-probe fails you get the error and",
1136
- "another attempt, resuming on top of your own edits. Do not commit; leave the changes in the",
1137
- "working tree.",
1138
- "",
1139
- "FINDINGS — ranked evidence from real failed runs (the capabilities the server must provide):",
1140
- ...findingLines(args.findings)
1141
- ].join("\n");
1142
- }
1143
- //#endregion
1144
- //#region src/improvement/mcp-serve-verifier.ts
1145
- /**
1146
- * `mcpServeVerifier` — the intrinsic verifier for a built MCP server: the
1147
- * boot-and-probe checker named in docs/artifact-lifecycle-frontier.md. A
1148
- * generated MCP server is only a candidate if it actually *serves* — so this
1149
- * boots it over stdio (the default local MCP transport) and runs the real
1150
- * handshake: `initialize` → `notifications/initialized` → `tools/list`, and
1151
- * asserts the server answers with at least `minTools` tools.
1152
- *
1153
- * The spawn + handshake is the SHARED same-host stdio connection
1154
- * (`connectStdioMcp`) — the same code path that later serves the built server
1155
- * LIVE to a scored run (`materializeLocalMcp`), so "verified it serves" and
1156
- * "served while scored" can never drift apart.
1157
- *
1158
- * Outcomes follow the `Verifier` contract: a server that fails to start, exits
1159
- * early, errors the handshake, times out, or exposes no tools is a FAILED
1160
- * candidate (`{ok:false}`, fed back into the next generation shot); a missing
1161
- * start binary or spawn fault THROWS (a setup bug, never a silent fallback).
1162
- */
1163
- /** Build a `Verifier` that boots a generated MCP server over stdio and checks it exposes tools. */
1164
- function mcpServeVerifier(spec) {
1165
- const minTools = spec.minTools ?? 1;
1166
- return async (worktreePath) => {
1167
- let conn;
1168
- try {
1169
- conn = await connectStdioMcp({
1170
- command: spec.command,
1171
- ...spec.args ? { args: spec.args } : {},
1172
- cwd: worktreePath,
1173
- ...spec.env ? { env: spec.env } : {},
1174
- ...spec.timeoutMs !== void 0 ? { timeoutMs: spec.timeoutMs } : {}
1175
- });
1176
- } catch (err) {
1177
- if (err instanceof McpSpawnFault) throw new Error(`mcpServeVerifier: ${err.message}`);
1178
- return {
1179
- ok: false,
1180
- feedback: err instanceof Error ? err.message : String(err)
1181
- };
1182
- }
1183
- try {
1184
- if (conn.tools.length < minTools) return {
1185
- ok: false,
1186
- feedback: `tools/list returned ${conn.tools.length} tool(s), need >= ${minTools}`
1187
- };
1188
- return { ok: true };
1189
- } finally {
1190
- await conn.close();
1191
- }
1192
- };
1193
- }
1194
- //#endregion
1195
1051
  //#region src/improvement/official-optimizers.ts
1196
1052
  const defaultMaxFindingsChars = 5e4;
1197
1053
  const pythonClientDocs = "https://github.com/tangle-network/agent-eval/tree/main/clients/python";
@@ -1518,63 +1374,6 @@ function createProfileImprovementHarness(options) {
1518
1374
  });
1519
1375
  }
1520
1376
  //#endregion
1521
- //#region src/improvement/prompt-instructions-profile-components.ts
1522
- /** Stable component-name prefix used for `profile.prompt.instructions`. */
1523
- const PROMPT_INSTRUCTION_COMPONENT_PREFIX = "prompt.instruction:";
1524
- const COMPONENT_INDEX_WIDTH = 6;
1525
- function componentName(index) {
1526
- return `${PROMPT_INSTRUCTION_COMPONENT_PREFIX}${String(index).padStart(COMPONENT_INDEX_WIDTH, "0")}`;
1527
- }
1528
- function orderedInstructionValues(components) {
1529
- const entries = Object.entries(components).sort(([left], [right]) => left.localeCompare(right));
1530
- if (entries.length === 0) throw new ConfigError("promptInstructionsProfileComponents: at least one prompt instruction is required");
1531
- for (const [index, [name, value]] of entries.entries()) {
1532
- const expected = componentName(index);
1533
- if (name !== expected) throw new ConfigError(`promptInstructionsProfileComponents: expected component ${JSON.stringify(expected)}, got ${JSON.stringify(name)}`);
1534
- if (typeof value !== "string") throw new ConfigError(`promptInstructionsProfileComponents: component ${JSON.stringify(name)} must be a string`);
1535
- }
1536
- return entries.map(([, value]) => value);
1537
- }
1538
- /**
1539
- * Canonical `ImproveProfileComponents` mapping for the ordered
1540
- * `AgentProfile.prompt.instructions` list.
1541
- *
1542
- * Use it with `surface: 'agent-profile'` when an optimizer should rewrite the
1543
- * exact instruction texts without being allowed to change their count, order,
1544
- * labels, or any unrelated profile field:
1545
- *
1546
- * ```ts
1547
- * await improve(profile, {
1548
- * surface: 'agent-profile',
1549
- * profileComponents: promptInstructionsProfileComponents,
1550
- * // method, scenarios, judge, executionRef, agent, ...
1551
- * })
1552
- * ```
1553
- *
1554
- * Component names are zero-padded and stable. Runtime's existing component
1555
- * materializer requires every candidate to preserve the exact key set and
1556
- * verifies that `apply(read(profile))` reproduces the baseline profile. A
1557
- * profile with no prompt instructions is refused rather than inventing a
1558
- * sentinel instruction that could accidentally ship.
1559
- */
1560
- const promptInstructionsProfileComponents = Object.freeze({
1561
- read(profile) {
1562
- const instructions = profile.prompt?.instructions ?? [];
1563
- if (instructions.length === 0) throw new ConfigError("promptInstructionsProfileComponents: profile.prompt.instructions must contain at least one instruction");
1564
- return Object.fromEntries(instructions.map((instruction, index) => [componentName(index), instruction]));
1565
- },
1566
- apply(profile, components) {
1567
- const instructions = orderedInstructionValues(components);
1568
- return agentProfileSchema.parse({
1569
- ...profile,
1570
- prompt: {
1571
- ...profile.prompt,
1572
- instructions
1573
- }
1574
- });
1575
- }
1576
- });
1577
- //#endregion
1578
1377
  //#region src/improvement/reflective-generator.ts
1579
1378
  /**
1580
1379
  *
@@ -2023,19 +1822,6 @@ function completionTime(transition, now) {
2023
1822
  }
2024
1823
  //#endregion
2025
1824
  //#region src/knowledge/supervised-update.ts
2026
- /** Standing prompt for a supervisor that grows a shared knowledge base through spawned researchers. */
2027
- const RESEARCH_SUPERVISOR_SYSTEM_PROMPT = [
2028
- "You are a research supervisor. You do not answer the research question yourself.",
2029
- "You create and manage researcher workers that improve one shared knowledge base until it is ready.",
2030
- "",
2031
- "Each round:",
2032
- "1. Read the goal and the gaps the readiness check still reports.",
2033
- "2. Decompose the open work into independent sub-topics.",
2034
- "3. Spawn one researcher per sub-topic; split by sub-topic, never duplicate work.",
2035
- "4. Wait for researchers to settle, steer or re-spawn thin sub-topics, then stop when the check passes.",
2036
- "",
2037
- "Conserve the shared budget. Prefer a small number of well-scoped researchers over a large fanout that re-covers the same ground."
2038
- ].join("\n");
2039
1825
  /** Build the completion check a supervised KB update uses to stop only when the KB is ready. */
2040
1826
  function knowledgeReadinessDeliverable(options) {
2041
1827
  return {
@@ -3089,6 +2875,6 @@ function stripNewlines(value) {
3089
2875
  return value.replace(/[\r\n]/g, " ");
3090
2876
  }
3091
2877
  //#endregion
3092
- export { AgentEvalError, BackendTransportError, ConfigError, DEFAULT_ROUTER_BASE_URL, DELEGATED_LOOP_MODES, InMemoryRuntimeSessionStore, JudgeError, NotFoundError, OfficialOptimizerUnavailableError, PROMPT_INSTRUCTION_COMPONENT_PREFIX, PlannerError, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, ROLLOUT_POLICY_EXTENSION, ROUTER_PRICE_SOURCE, RetainedInteractiveAdmissionError, RetainedInteractiveBindingError, RetainedRunAdmissionError, RetainedRunDispatchBindingError, RuntimeRunStateError, SearchEnvironmentFault, ValidationError, agenticGenerator, applyRolloutPolicyToProfile, applyRunRecordDefaults, auditLoopRunner, buildKnowledgeImprovementExperimentBundles, buildLoopOtelSpans, buildLoopSpanNodes, buildRuntimeEventOtelSpans, cleanModelId, commandVerifier, composeRuntimeHooks, createAgentKnowledgeReadinessCheck, createCommandProfileTrainer, createConversationBackend, createIterableBackend, createKnowledgeImprovementActivationExecutor, createOpenInferenceFileExporter, createOtelExporter, createProfileExecutionBackend, createProfileImprovementHarness, createRuntimeEventCollector, createRuntimeStreamEventCollector, createSandboxPromptBackend, createSupervisedKnowledgeUpdater, d1ToSqlAdapter, decideKnowledgeReadiness, decideSearchImprovement, dedicatedLane, defaultBuildPrompt, defineConversation, defineRuntimeHooks, findingLines, formatSupervisedKnowledgeTask, generateSpanId, getModels, improve, isDelegatedLoopMode, isSearchEnvironmentFault, isolatedCheckBoxEvidenceSchema, isolatedCheckResultSchema, knowledgeReadinessDeliverable, loopEventToOtelSpan, mcpBuildPrompt, mcpServeVerifier, mcpToolsForRuntimeMcp, mcpToolsForRuntimeMcpSubset, normalizeRolloutPolicy, notifyRuntimeDecisionPoint, notifyRuntimeHookEvent, officialGepa, officialSkillOpt, optimizerMethod, padSpanId, padTraceId, parseLoopRunnerArgv, parseRolloutPolicy, priceTokens, promptInstructionsProfileComponents, rawTraceDistiller, readinessServerSentEvent, reflectiveGenerator, reflectiveProfileProposer, researchLoopRunner, resolveChatModel, resolveRouterBaseUrl, routerLane, routerTokenPrice, runAgentTask, runAgentTaskStream, runConversation, runConversationStream, runDelegatedLoop, runKnowledgeImprovementJob, runLoopRunnerCli, runPersonaConversation, runPersonaDispatch, runSupervisedKnowledgeUpdate, runtimeFailureCause, runtimeStreamServerSentEvent, sanitizeAgentRuntimeEvent, sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent, searchMethod, serializeRolloutPolicy, settlementFailureCause, sharedBoxLane, startRuntimeRun, strategyAuthorMethod, structuralRolloutPolicyFromProfile, subscriptionLane, toOtelAttributes, toolBuildPrompt, validateChatModelId, worktreeLoopRunner };
2878
+ export { AgentEvalError, BackendTransportError, ConfigError, DEFAULT_ROUTER_BASE_URL, InMemoryRuntimeSessionStore, JudgeError, NotFoundError, ROUTER_PRICE_SOURCE, RuntimeRunStateError, SearchEnvironmentFault, ValidationError, agenticGenerator, applyRunRecordDefaults, auditLoopRunner, buildKnowledgeImprovementExperimentBundles, buildLoopOtelSpans, cleanModelId, commandVerifier, composeRuntimeHooks, createCommandProfileTrainer, createConversationBackend, createIterableBackend, createKnowledgeImprovementActivationExecutor, createOtelExporter, createProfileExecutionBackend, createProfileImprovementHarness, createRuntimeEventCollector, createRuntimeStreamEventCollector, createSandboxPromptBackend, decideKnowledgeReadiness, decideSearchImprovement, dedicatedLane, defineRuntimeHooks, getModels, improve, isolatedCheckBoxEvidenceSchema, isolatedCheckResultSchema, loopEventToOtelSpan, officialGepa, officialSkillOpt, optimizerMethod, padSpanId, padTraceId, priceTokens, readinessServerSentEvent, reflectiveGenerator, reflectiveProfileProposer, resolveChatModel, resolveRouterBaseUrl, routerLane, runAgentTask, runAgentTaskStream, runConversation, runConversationStream, runKnowledgeImprovementJob, runPersonaConversation, runPersonaDispatch, runtimeStreamServerSentEvent, sanitizeAgentRuntimeEvent, sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent, searchMethod, sharedBoxLane, startRuntimeRun, subscriptionLane, validateChatModelId };
3093
2879
 
3094
2880
  //# sourceMappingURL=index.js.map