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