@tangle-network/agent-runtime 0.105.0 → 0.106.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 (218) hide show
  1. package/README.md +2 -2
  2. package/dist/activation-CRjVfOiy.js +203 -0
  3. package/dist/activation-CRjVfOiy.js.map +1 -0
  4. package/dist/activation-DyWB0K6E.d.ts +98 -0
  5. package/dist/agent.d.ts +216 -234
  6. package/dist/agent.js +615 -547
  7. package/dist/agent.js.map +1 -1
  8. package/dist/analyst-loop-DGdtVENg.js +517 -0
  9. package/dist/analyst-loop-DGdtVENg.js.map +1 -0
  10. package/dist/analyst-loop.d.ts +10 -43
  11. package/dist/analyst-loop.js +2 -11
  12. package/dist/backends-Dy8NujB4.js +713 -0
  13. package/dist/backends-Dy8NujB4.js.map +1 -0
  14. package/dist/candidate-execution/index.d.ts +4 -192
  15. package/dist/candidate-execution/index.js +5 -66
  16. package/dist/candidate-execution-DqMbv1rU.js +488 -0
  17. package/dist/candidate-execution-DqMbv1rU.js.map +1 -0
  18. package/dist/coder-yhVWbdWc.js +40 -0
  19. package/dist/coder-yhVWbdWc.js.map +1 -0
  20. package/dist/conversation-XucG_K3l.js +1265 -0
  21. package/dist/conversation-XucG_K3l.js.map +1 -0
  22. package/dist/conversation.d.ts +2 -804
  23. package/dist/conversation.js +2 -55
  24. package/dist/environment-provider-CfLUmKmf.js +1168 -0
  25. package/dist/environment-provider-CfLUmKmf.js.map +1 -0
  26. package/dist/environment-provider-IUGU3epE.d.ts +964 -0
  27. package/dist/environment-provider.d.ts +2 -78
  28. package/dist/environment-provider.js +2 -18
  29. package/dist/errors-DEAvWQPy.js +111 -0
  30. package/dist/errors-DEAvWQPy.js.map +1 -0
  31. package/dist/improvement-adapter-Cr5TBSji.d.ts +166 -0
  32. package/dist/improvement-cycle-C095kS_g.js +2624 -0
  33. package/dist/improvement-cycle-C095kS_g.js.map +1 -0
  34. package/dist/index-BGdxAwfO.d.ts +838 -0
  35. package/dist/index-C-FYUuFG.d.ts +193 -0
  36. package/dist/index-CbNM40xG.d.ts +140 -0
  37. package/dist/index-DruSKs3Z.d.ts +7224 -0
  38. package/dist/index-Efjb3nrQ.d.ts +671 -0
  39. package/dist/index.d.ts +14 -1058
  40. package/dist/index.js +2106 -2082
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +768 -889
  43. package/dist/intelligence.js +1466 -1367
  44. package/dist/intelligence.js.map +1 -1
  45. package/dist/{kb-gate-CwHO0vz6.d.ts → kb-gate-C8z2juK8.d.ts} +33 -31
  46. package/dist/kb-gate-DpaSwXVx.js +80 -0
  47. package/dist/kb-gate-DpaSwXVx.js.map +1 -0
  48. package/dist/knowledge-Ku-mPP4f.js +433 -0
  49. package/dist/knowledge-Ku-mPP4f.js.map +1 -0
  50. package/dist/knowledge.d.ts +2 -150
  51. package/dist/knowledge.js +2 -40
  52. package/dist/local-harness-Dh8PJ0ot.d.ts +455 -0
  53. package/dist/loop-runner-bin-BXsFEUcf.d.ts +162 -0
  54. package/dist/loop-runner-bin-BwjQ1NfH.js +268 -0
  55. package/dist/loop-runner-bin-BwjQ1NfH.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -15
  57. package/dist/loop-runner-bin.js +2 -24
  58. package/dist/loops.d.ts +5 -4164
  59. package/dist/loops.js +8 -419
  60. package/dist/mcp/bin.d.ts +1 -1
  61. package/dist/mcp/bin.js +116 -146
  62. package/dist/mcp/bin.js.map +1 -1
  63. package/dist/mcp/index.d.ts +295 -436
  64. package/dist/mcp/index.js +1242 -1177
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/mcp/memory-bin.d.ts +1 -1
  67. package/dist/mcp/memory-bin.js +37 -16
  68. package/dist/mcp/memory-bin.js.map +1 -1
  69. package/dist/memory-server-DL6cE2Ag.js +234 -0
  70. package/dist/memory-server-DL6cE2Ag.js.map +1 -0
  71. package/dist/model-resolution-Btd9iIKV.js +98 -0
  72. package/dist/model-resolution-Btd9iIKV.js.map +1 -0
  73. package/dist/openai-tools-B68JaOCx.d.ts +24 -0
  74. package/dist/openai-tools-CKLy1C7M.js +44 -0
  75. package/dist/openai-tools-CKLy1C7M.js.map +1 -0
  76. package/dist/otel-export-D34IQW1C.js +843 -0
  77. package/dist/otel-export-D34IQW1C.js.map +1 -0
  78. package/dist/platform.d.ts +188 -185
  79. package/dist/platform.js +185 -218
  80. package/dist/platform.js.map +1 -1
  81. package/dist/prepare-B53sPV7M.js +4292 -0
  82. package/dist/prepare-B53sPV7M.js.map +1 -0
  83. package/dist/primeintellect/index.d.ts +149 -145
  84. package/dist/primeintellect/index.js +626 -1003
  85. package/dist/primeintellect/index.js.map +1 -1
  86. package/dist/profiles.d.ts +296 -490
  87. package/dist/profiles.js +722 -749
  88. package/dist/profiles.js.map +1 -1
  89. package/dist/protected-model-port-BLPH5VVv.js +722 -0
  90. package/dist/protected-model-port-BLPH5VVv.js.map +1 -0
  91. package/dist/protected-model-port-BP6Z4eau.d.ts +283 -0
  92. package/dist/protected-redaction--F3v1oo8.js +200 -0
  93. package/dist/protected-redaction--F3v1oo8.js.map +1 -0
  94. package/dist/redact-D-u-rrcn.js +82 -0
  95. package/dist/redact-D-u-rrcn.js.map +1 -0
  96. package/dist/redact-kbIOjfjM.d.ts +452 -0
  97. package/dist/researcher-CoVqNhfI.js +433 -0
  98. package/dist/researcher-CoVqNhfI.js.map +1 -0
  99. package/dist/runtime-BG0BziaP.js +5408 -0
  100. package/dist/runtime-BG0BziaP.js.map +1 -0
  101. package/dist/sandbox-events-DeI5xX8P.js +316 -0
  102. package/dist/sandbox-events-DeI5xX8P.js.map +1 -0
  103. package/dist/spawn-journal-CwPvKUTa.js +456 -0
  104. package/dist/spawn-journal-CwPvKUTa.js.map +1 -0
  105. package/dist/structural-rollout-IXUEplky.js +1445 -0
  106. package/dist/structural-rollout-IXUEplky.js.map +1 -0
  107. package/dist/substrate-B0TYNrXn.js +27 -0
  108. package/dist/substrate-B0TYNrXn.js.map +1 -0
  109. package/dist/{substrate-Dyiqmd3o.d.ts → substrate-BcnuSHXm.d.ts} +57 -54
  110. package/dist/supervise-BiRutHS9.js +7321 -0
  111. package/dist/supervise-BiRutHS9.js.map +1 -0
  112. package/dist/supervisor-DTKhF-RV.js +3826 -0
  113. package/dist/supervisor-DTKhF-RV.js.map +1 -0
  114. package/dist/testing.d.ts +4 -3
  115. package/dist/testing.js +2478 -2637
  116. package/dist/testing.js.map +1 -1
  117. package/dist/tool-server-RcWgLIsL.js +141 -0
  118. package/dist/tool-server-RcWgLIsL.js.map +1 -0
  119. package/dist/trace-propagation-CJJC7SVB.js +57 -0
  120. package/dist/trace-propagation-CJJC7SVB.js.map +1 -0
  121. package/dist/types-BaIpb0XT.d.ts +492 -0
  122. package/dist/types-BevOjfTY.d.ts +765 -0
  123. package/dist/types-C9j4qg6l.d.ts +500 -0
  124. package/dist/types-Cja5OTGh.d.ts +190 -0
  125. package/dist/util-MVgdwuIS.js +145 -0
  126. package/dist/util-MVgdwuIS.js.map +1 -0
  127. package/dist/workspace-archive-BosQiotA.js +575 -0
  128. package/dist/workspace-archive-BosQiotA.js.map +1 -0
  129. package/package.json +43 -56
  130. package/skills/build-with-agent-runtime/SKILL.md +1 -0
  131. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  132. package/dist/analyst-loop.js.map +0 -1
  133. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  134. package/dist/candidate-execution/index.js.map +0 -1
  135. package/dist/chunk-2KGAN2HM.js +0 -1256
  136. package/dist/chunk-2KGAN2HM.js.map +0 -1
  137. package/dist/chunk-2VZYRB55.js +0 -834
  138. package/dist/chunk-2VZYRB55.js.map +0 -1
  139. package/dist/chunk-3MDZX7YU.js +0 -125
  140. package/dist/chunk-3MDZX7YU.js.map +0 -1
  141. package/dist/chunk-5IBQAPVB.js +0 -29
  142. package/dist/chunk-5IBQAPVB.js.map +0 -1
  143. package/dist/chunk-5QOB7H74.js +0 -387
  144. package/dist/chunk-5QOB7H74.js.map +0 -1
  145. package/dist/chunk-C5RTIBNZ.js +0 -48
  146. package/dist/chunk-C5RTIBNZ.js.map +0 -1
  147. package/dist/chunk-CTRA64LY.js +0 -680
  148. package/dist/chunk-CTRA64LY.js.map +0 -1
  149. package/dist/chunk-DPEUKJRO.js +0 -27
  150. package/dist/chunk-DPEUKJRO.js.map +0 -1
  151. package/dist/chunk-FD2MBMOH.js +0 -494
  152. package/dist/chunk-FD2MBMOH.js.map +0 -1
  153. package/dist/chunk-H5QPIZNX.js +0 -907
  154. package/dist/chunk-H5QPIZNX.js.map +0 -1
  155. package/dist/chunk-HLKC4UYB.js +0 -3514
  156. package/dist/chunk-HLKC4UYB.js.map +0 -1
  157. package/dist/chunk-HNP72PNU.js +0 -192
  158. package/dist/chunk-HNP72PNU.js.map +0 -1
  159. package/dist/chunk-ISPWRSEC.js +0 -408
  160. package/dist/chunk-ISPWRSEC.js.map +0 -1
  161. package/dist/chunk-KRBFHMV6.js +0 -1228
  162. package/dist/chunk-KRBFHMV6.js.map +0 -1
  163. package/dist/chunk-M22PL4GH.js +0 -171
  164. package/dist/chunk-M22PL4GH.js.map +0 -1
  165. package/dist/chunk-NURIQBJQ.js +0 -72
  166. package/dist/chunk-NURIQBJQ.js.map +0 -1
  167. package/dist/chunk-OPVWXJ2H.js +0 -75
  168. package/dist/chunk-OPVWXJ2H.js.map +0 -1
  169. package/dist/chunk-PZZKQVQV.js +0 -52
  170. package/dist/chunk-PZZKQVQV.js.map +0 -1
  171. package/dist/chunk-Q2JSAVQ3.js +0 -671
  172. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  173. package/dist/chunk-RDOAVVHY.js +0 -699
  174. package/dist/chunk-RDOAVVHY.js.map +0 -1
  175. package/dist/chunk-SGKPNBXE.js +0 -60
  176. package/dist/chunk-SGKPNBXE.js.map +0 -1
  177. package/dist/chunk-SMQXZGLZ.js +0 -351
  178. package/dist/chunk-SMQXZGLZ.js.map +0 -1
  179. package/dist/chunk-UHEZW5BU.js +0 -2918
  180. package/dist/chunk-UHEZW5BU.js.map +0 -1
  181. package/dist/chunk-UPWGXKXB.js +0 -254
  182. package/dist/chunk-UPWGXKXB.js.map +0 -1
  183. package/dist/chunk-VISA6CI3.js +0 -200
  184. package/dist/chunk-VISA6CI3.js.map +0 -1
  185. package/dist/chunk-WMTCUOQL.js +0 -474
  186. package/dist/chunk-WMTCUOQL.js.map +0 -1
  187. package/dist/chunk-WRTOVNN4.js +0 -4728
  188. package/dist/chunk-WRTOVNN4.js.map +0 -1
  189. package/dist/chunk-WSTRQZYQ.js +0 -5576
  190. package/dist/chunk-WSTRQZYQ.js.map +0 -1
  191. package/dist/chunk-XBG2W2VW.js +0 -6434
  192. package/dist/chunk-XBG2W2VW.js.map +0 -1
  193. package/dist/chunk-YEJR7IXO.js +0 -68
  194. package/dist/chunk-YEJR7IXO.js.map +0 -1
  195. package/dist/chunk-YJZA2BIK.js +0 -1338
  196. package/dist/chunk-YJZA2BIK.js.map +0 -1
  197. package/dist/completion-gate-BMy5LGoP.d.ts +0 -256
  198. package/dist/conversation.js.map +0 -1
  199. package/dist/coordination-BZZSVYpZ.d.ts +0 -2570
  200. package/dist/environment-provider.js.map +0 -1
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-BDNcl6jI.d.ts +0 -175
  204. package/dist/loop-runner-bin-68aoM9-7.d.ts +0 -199
  205. package/dist/loop-runner-bin.js.map +0 -1
  206. package/dist/loops.js.map +0 -1
  207. package/dist/openai-tools-fnj6SRVg.d.ts +0 -46
  208. package/dist/protected-model-port-B4t-OQjL.d.ts +0 -271
  209. package/dist/redact-BuFjxBUJ.d.ts +0 -481
  210. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  211. package/dist/structural-rollout-DEh6CEsa.d.ts +0 -446
  212. package/dist/supervise-4_48wwvy.d.ts +0 -379
  213. package/dist/types-BCoemcXU.d.ts +0 -802
  214. package/dist/types-BwoZWq-i.d.ts +0 -510
  215. package/dist/types-Cbp72qyu.d.ts +0 -491
  216. package/dist/types-CmYCMbFT.d.ts +0 -203
  217. package/dist/types-CvNwMzQt.d.ts +0 -957
  218. package/dist/worktree-fanout-DxhAWr5Z.d.ts +0 -999
@@ -0,0 +1,517 @@
1
+ import { n as AnalystError } from "./errors-DEAvWQPy.js";
2
+ import { n as extractLlmCallEvent } from "./sandbox-events-DeI5xX8P.js";
3
+ import { DEFAULT_TRACE_ANALYST_BUDGETS, TRACE_ANALYST_TRUNCATION_MARKER_PREFIX, diffFindings } from "@tangle-network/agent-eval";
4
+ //#region src/analyst-loop/iterations-to-trace-store.ts
5
+ /**
6
+ *
7
+ * The read seam that closes the autonomous loop: project a round's `Iteration[]`
8
+ * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the
9
+ * read interface the trace analysts query. `runAnalystLoop` has had zero consumers
10
+ * because nothing turned a loop's iterations into a store — this is that bridge.
11
+ *
12
+ * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`
13
+ * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an
14
+ * analyst can walk a shot's trace, cluster its errors, and emit findings the driver
15
+ * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event
16
+ * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration
17
+ * surfaces a real ERROR span carrying the real message.
18
+ *
19
+ * @experimental
20
+ */
21
+ const bytesOf = (v) => Buffer.byteLength(JSON.stringify(v) ?? "", "utf8");
22
+ const iso = (ms) => new Date(ms).toISOString();
23
+ /** Normalize volatile tokens out of a status message so semantically identical failures
24
+ * collapse to one signature (digits, hex/uuids, paths, durations → placeholders). */
25
+ function normalizeSignature(message) {
26
+ return message.replace(/0x[0-9a-fA-F]+/g, "HEX").replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, "UUID").replace(/(\/[\w.-]+){2,}/g, "PATH").replace(/\b\d+(\.\d+)?(ms|s|m|h)\b/g, "DUR").replace(/\b\d+\b/g, "#").replace(/\s+/g, " ").trim().slice(0, 200);
27
+ }
28
+ function spanKindFor(event, agentRunName) {
29
+ const llm = extractLlmCallEvent(event, agentRunName);
30
+ if (llm) return {
31
+ kind: "LLM",
32
+ model: llm.model ?? null,
33
+ tool: null
34
+ };
35
+ const type = String(event?.type ?? "");
36
+ if (/tool/i.test(type)) {
37
+ const d = event?.data;
38
+ return {
39
+ kind: "TOOL",
40
+ model: null,
41
+ tool: typeof d?.name === "string" ? d.name : typeof d?.tool === "string" ? d.tool : type
42
+ };
43
+ }
44
+ return {
45
+ kind: "SPAN",
46
+ model: null,
47
+ tool: null
48
+ };
49
+ }
50
+ function errorMessageOf(event) {
51
+ const type = String(event?.type ?? "");
52
+ const d = event?.data;
53
+ if (/error|fail/i.test(type) || d?.error) {
54
+ const m = d?.error ?? d?.message;
55
+ return typeof m === "string" ? m : `${type} error`;
56
+ }
57
+ }
58
+ /** Project one iteration → one trace: root AGENT span + a child span per event. */
59
+ function projectIteration(iter) {
60
+ const traceId = (iter.events.find((e) => (e?.data)?.sandboxId)?.data)?.sandboxId ?? `iter-${iter.index}`;
61
+ const start = iso(iter.startedAt);
62
+ const end = iso(iter.endedAt || iter.startedAt);
63
+ const durationMs = Math.max(0, (iter.endedAt || iter.startedAt) - iter.startedAt);
64
+ const rootId = `${traceId}:root`;
65
+ const iterErrored = Boolean(iter.error) || iter.verdict?.valid === false;
66
+ const spans = [{
67
+ trace_id: traceId,
68
+ span_id: rootId,
69
+ parent_span_id: null,
70
+ name: iter.agentRunName,
71
+ kind: "AGENT",
72
+ start_time: start,
73
+ end_time: end,
74
+ duration_ms: durationMs,
75
+ status: iter.error ? "ERROR" : "OK",
76
+ status_message: iter.error?.message,
77
+ service_name: "agent-runtime",
78
+ agent_name: iter.agentRunName,
79
+ model_name: null,
80
+ tool_name: null,
81
+ attributes: {
82
+ "iteration.index": iter.index,
83
+ "verdict.valid": iter.verdict?.valid,
84
+ "verdict.score": iter.verdict?.score,
85
+ "output.preview": iter.output === void 0 ? void 0 : String(iter.output).slice(0, 2e3)
86
+ }
87
+ }];
88
+ const models = /* @__PURE__ */ new Set();
89
+ const tools = /* @__PURE__ */ new Set();
90
+ iter.events.forEach((event, i) => {
91
+ const { kind, model, tool } = spanKindFor(event, iter.agentRunName);
92
+ if (model) models.add(model);
93
+ if (tool) tools.add(tool);
94
+ const errMsg = errorMessageOf(event);
95
+ spans.push({
96
+ trace_id: traceId,
97
+ span_id: `${traceId}:e${i}`,
98
+ parent_span_id: rootId,
99
+ name: String(event?.type ?? "event"),
100
+ kind,
101
+ start_time: start,
102
+ end_time: end,
103
+ duration_ms: 0,
104
+ status: errMsg ? "ERROR" : "OK",
105
+ status_message: errMsg,
106
+ service_name: "agent-runtime",
107
+ agent_name: iter.agentRunName,
108
+ model_name: model,
109
+ tool_name: tool,
110
+ attributes: event?.data ?? {}
111
+ });
112
+ });
113
+ const hasErrors = spans.some((s) => s.status === "ERROR") || iterErrored;
114
+ const summary = {
115
+ trace_id: traceId,
116
+ service_name: "agent-runtime",
117
+ agent_name: iter.agentRunName,
118
+ span_count: spans.length,
119
+ has_errors: hasErrors,
120
+ start_time: start,
121
+ end_time: end,
122
+ duration_ms: durationMs,
123
+ raw_jsonl_bytes: bytesOf(spans),
124
+ models: [...models],
125
+ tools: [...tools]
126
+ };
127
+ return {
128
+ summary,
129
+ spans,
130
+ rawBytes: summary.raw_jsonl_bytes
131
+ };
132
+ }
133
+ function matchesFilters(t, f) {
134
+ if (!f) return true;
135
+ if (f.has_errors !== void 0 && t.summary.has_errors !== f.has_errors) return false;
136
+ if (f.service_names?.length && !f.service_names.includes(t.summary.service_name ?? "")) return false;
137
+ if (f.agent_names?.length && !f.agent_names.includes(t.summary.agent_name ?? "")) return false;
138
+ if (f.model_names?.length && !f.model_names.some((m) => t.summary.models.includes(m))) return false;
139
+ if (f.tool_names?.length && !f.tool_names.some((tn) => t.summary.tools.includes(tn))) return false;
140
+ if (f.start_time_after && t.summary.start_time < f.start_time_after) return false;
141
+ if (f.start_time_before && t.summary.start_time > f.start_time_before) return false;
142
+ if (f.regex_pattern && !new RegExp(f.regex_pattern).test(JSON.stringify(t.spans))) return false;
143
+ return true;
144
+ }
145
+ function capAttributes(attributes, perAttrCap) {
146
+ let truncated = 0;
147
+ const capped = {};
148
+ for (const [k, v] of Object.entries(attributes)) {
149
+ const s = typeof v === "string" ? v : JSON.stringify(v);
150
+ if (typeof s === "string" && s.length > perAttrCap) {
151
+ truncated += 1;
152
+ capped[k] = `${TRACE_ANALYST_TRUNCATION_MARKER_PREFIX} ${s.length}b]${s.slice(0, perAttrCap)}`;
153
+ } else capped[k] = v;
154
+ }
155
+ return {
156
+ capped,
157
+ truncated
158
+ };
159
+ }
160
+ /**
161
+ * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an
162
+ * empty round — there is nothing for an analyst to read, and a silent empty store would
163
+ * mask a broken capture path.
164
+ */
165
+ function iterationsToTraceStore(iterations, budgets = DEFAULT_TRACE_ANALYST_BUDGETS) {
166
+ if (iterations.length === 0) throw new AnalystError("iterationsToTraceStore: no iterations to analyze (empty round)");
167
+ const traces = iterations.map((it) => projectIteration(it));
168
+ const byId = new Map(traces.map((t) => [t.summary.trace_id, t]));
169
+ const buildClusters = (set) => {
170
+ const map = /* @__PURE__ */ new Map();
171
+ for (const t of set) for (const s of t.spans) {
172
+ if (s.status !== "ERROR" || !s.status_message) continue;
173
+ const sig = normalizeSignature(s.status_message);
174
+ const c = map.get(sig) ?? {
175
+ signature: sig,
176
+ status_message_sample: s.status_message,
177
+ span_name: s.name,
178
+ tool_name: s.tool_name,
179
+ trace_count: 0,
180
+ span_count: 0,
181
+ prevalence: 0,
182
+ exemplar_trace_ids: [],
183
+ exemplar_span_ids: []
184
+ };
185
+ c.span_count += 1;
186
+ if (!c.exemplar_trace_ids.includes(t.summary.trace_id) && c.exemplar_trace_ids.length < 10) {
187
+ c.exemplar_trace_ids.push(t.summary.trace_id);
188
+ c.trace_count += 1;
189
+ }
190
+ if (c.exemplar_span_ids.length < 10) c.exemplar_span_ids.push(s.span_id);
191
+ map.set(sig, c);
192
+ }
193
+ const errorTraces = set.filter((t) => t.summary.has_errors).length || 1;
194
+ return [...map.values()].map((c) => ({
195
+ ...c,
196
+ prevalence: c.trace_count / errorTraces
197
+ })).sort((a, b) => b.trace_count - a.trace_count);
198
+ };
199
+ return {
200
+ async getOverview(filters) {
201
+ const set = traces.filter((t) => matchesFilters(t, filters));
202
+ const services = /* @__PURE__ */ new Set();
203
+ const agents = /* @__PURE__ */ new Set();
204
+ const models = /* @__PURE__ */ new Set();
205
+ const tools = /* @__PURE__ */ new Set();
206
+ let errorSpans = 0;
207
+ for (const t of set) {
208
+ if (t.summary.service_name) services.add(t.summary.service_name);
209
+ if (t.summary.agent_name) agents.add(t.summary.agent_name);
210
+ for (const m of t.summary.models) models.add(m);
211
+ for (const tn of t.summary.tools) tools.add(tn);
212
+ errorSpans += t.spans.filter((s) => s.status === "ERROR").length;
213
+ }
214
+ const times = set.map((t) => t.summary.start_time).sort();
215
+ return {
216
+ total_traces: set.length,
217
+ raw_jsonl_bytes: set.reduce((n, t) => n + t.rawBytes, 0),
218
+ services: [...services],
219
+ agents: [...agents],
220
+ models: [...models],
221
+ tool_names: [...tools],
222
+ sample_trace_ids: set.slice(0, 20).map((t) => t.summary.trace_id),
223
+ errors: {
224
+ trace_count: set.filter((t) => t.summary.has_errors).length,
225
+ span_count: errorSpans
226
+ },
227
+ error_clusters: buildClusters(set),
228
+ time_range: times.length ? {
229
+ earliest: times[0],
230
+ latest: times[times.length - 1]
231
+ } : null
232
+ };
233
+ },
234
+ async queryTraces(opts) {
235
+ const set = traces.filter((t) => matchesFilters(t, opts.filters));
236
+ const offset = opts.offset ?? 0;
237
+ return {
238
+ traces: set.slice(offset, offset + opts.limit).map((t) => t.summary),
239
+ total: set.length,
240
+ has_more: offset + opts.limit < set.length
241
+ };
242
+ },
243
+ async countTraces(filters) {
244
+ return traces.filter((t) => matchesFilters(t, filters)).length;
245
+ },
246
+ async viewTrace(opts) {
247
+ const t = byId.get(opts.trace_id);
248
+ if (!t) return {
249
+ trace_id: opts.trace_id,
250
+ spans: []
251
+ };
252
+ const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeViewBudget;
253
+ const projected = t.spans.map((s) => ({
254
+ ...s,
255
+ attributes: capAttributes(s.attributes, cap).capped
256
+ }));
257
+ if (bytesOf(projected) > budgets.perCallByteCeiling) {
258
+ const names = /* @__PURE__ */ new Map();
259
+ for (const s of t.spans) names.set(s.name, (names.get(s.name) ?? 0) + 1);
260
+ return {
261
+ trace_id: opts.trace_id,
262
+ oversized: {
263
+ span_count: t.spans.length,
264
+ top_span_names: [...names.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20),
265
+ span_response_bytes_max: Math.max(...t.spans.map((s) => bytesOf(s))),
266
+ error_span_count: t.spans.filter((s) => s.status === "ERROR").length
267
+ }
268
+ };
269
+ }
270
+ return {
271
+ trace_id: opts.trace_id,
272
+ spans: projected
273
+ };
274
+ },
275
+ async viewSpans(opts) {
276
+ const t = byId.get(opts.trace_id);
277
+ const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget;
278
+ const want = new Set(opts.span_ids);
279
+ const found = (t?.spans ?? []).filter((s) => want.has(s.span_id));
280
+ let truncated = 0;
281
+ const spans = found.map((s) => {
282
+ const { capped, truncated: n } = capAttributes(s.attributes, cap);
283
+ truncated += n;
284
+ return {
285
+ ...s,
286
+ attributes: capped
287
+ };
288
+ });
289
+ const foundIds = new Set(found.map((s) => s.span_id));
290
+ return {
291
+ trace_id: opts.trace_id,
292
+ spans,
293
+ missing_span_ids: opts.span_ids.filter((id) => !foundIds.has(id)),
294
+ truncated_attribute_count: truncated
295
+ };
296
+ },
297
+ async searchTrace(opts) {
298
+ const t = byId.get(opts.trace_id);
299
+ const max = opts.max_matches ?? 50;
300
+ const hits = [];
301
+ for (const s of t?.spans ?? []) for (const hit of searchSpanAttrs(s, opts.regex_pattern, budgets.perMatchTextBudget)) {
302
+ if (hits.length >= max) break;
303
+ hits.push(hit);
304
+ }
305
+ return {
306
+ trace_id: opts.trace_id,
307
+ hits,
308
+ total_matches: hits.length,
309
+ has_more: hits.length >= max
310
+ };
311
+ },
312
+ async searchSpan(opts) {
313
+ const t = byId.get(opts.trace_id);
314
+ const max = opts.max_matches ?? 50;
315
+ const span = (t?.spans ?? []).find((s) => s.span_id === opts.span_id);
316
+ const hits = span ? searchSpanAttrs(span, opts.regex_pattern, budgets.perMatchTextBudget).slice(0, max) : [];
317
+ return {
318
+ trace_id: opts.trace_id,
319
+ span_id: opts.span_id,
320
+ hits,
321
+ total_matches: hits.length,
322
+ has_more: false
323
+ };
324
+ }
325
+ };
326
+ }
327
+ function searchSpanAttrs(span, pattern, textCap) {
328
+ const re = new RegExp(pattern, "g");
329
+ const hits = [];
330
+ for (const [k, v] of Object.entries(span.attributes)) {
331
+ const text = typeof v === "string" ? v : JSON.stringify(v);
332
+ if (typeof text !== "string") continue;
333
+ re.lastIndex = 0;
334
+ const m = re.exec(text);
335
+ if (!m) continue;
336
+ const at = m.index;
337
+ hits.push({
338
+ trace_id: span.trace_id,
339
+ span_id: span.span_id,
340
+ span_name: span.name,
341
+ span_kind: span.kind,
342
+ attribute_path: `attributes.${k}`,
343
+ matched_text: m[0].slice(0, textCap),
344
+ context_before: text.slice(Math.max(0, at - textCap / 2), at),
345
+ context_after: text.slice(at + m[0].length, at + m[0].length + textCap / 2),
346
+ match_offset: at
347
+ });
348
+ }
349
+ return hits;
350
+ }
351
+ //#endregion
352
+ //#region src/analyst-loop/run-analyst-loop.ts
353
+ /** Analyze a run and apply accepted knowledge and agent-surface proposals. */
354
+ async function runAnalystLoop(opts) {
355
+ const log = opts.log ?? defaultLog;
356
+ const strategy = opts.priorFindingsStrategy ?? "per-kind";
357
+ const emit = makeEmitter(opts.onEvent);
358
+ const startedAt = Date.now();
359
+ const baselineRunId = resolveBaselineRunId(opts);
360
+ const priorAll = baselineRunId ? opts.findingsStore?.loadRun(baselineRunId) ?? [] : [];
361
+ log("baseline resolved", {
362
+ baselineRunId,
363
+ prior_findings: priorAll.length
364
+ });
365
+ await emit({
366
+ type: "baseline-resolved",
367
+ runId: opts.runId,
368
+ baselineRunId,
369
+ priorFindingCount: priorAll.length
370
+ });
371
+ const analystResult = await runRegistry(opts, buildPriorFindingsInput(priorAll, strategy, opts.registry.list()), emit);
372
+ log("analyst run complete", {
373
+ findings: analystResult.findings.length,
374
+ cost_usd: analystResult.total_cost_usd,
375
+ per_analyst: analystResult.per_analyst.map((s) => ({
376
+ id: s.analyst_id,
377
+ status: s.status,
378
+ n: s.findings_count
379
+ }))
380
+ });
381
+ if (opts.findingsStore && analystResult.findings.length > 0) {
382
+ await opts.findingsStore.append(opts.runId, analystResult.findings);
383
+ await emit({
384
+ type: "findings-persisted",
385
+ runId: opts.runId,
386
+ count: analystResult.findings.length
387
+ });
388
+ }
389
+ let diff = null;
390
+ if (baselineRunId && analystResult.findings.length > 0) {
391
+ diff = diffFindings(priorAll.map((f) => ({ ...f })), analystResult.findings.map((f) => ({
392
+ ...f,
393
+ run_id: opts.runId
394
+ })));
395
+ log("diff vs baseline", {
396
+ appeared: diff.appeared.length,
397
+ disappeared: diff.disappeared.length,
398
+ persisted: diff.persisted.length,
399
+ changed: diff.changed.length
400
+ });
401
+ await emit({
402
+ type: "diff-computed",
403
+ runId: opts.runId,
404
+ baselineRunId,
405
+ appeared: diff.appeared.length,
406
+ disappeared: diff.disappeared.length,
407
+ persisted: diff.persisted.length,
408
+ changed: diff.changed.length
409
+ });
410
+ }
411
+ let knowledge = null;
412
+ if (opts.knowledgeProposalSource) knowledge = await runKnowledgeProposalSource(opts, analystResult.findings, log, emit);
413
+ let improvement = null;
414
+ if (opts.improvementProposalSource) improvement = await runImprovementProposalSource(opts, analystResult.findings, log, emit);
415
+ await emit({
416
+ type: "loop-completed",
417
+ runId: opts.runId,
418
+ durationMs: Date.now() - startedAt
419
+ });
420
+ return {
421
+ runId: opts.runId,
422
+ baselineRunId,
423
+ analystResult,
424
+ diff,
425
+ knowledge,
426
+ improvement
427
+ };
428
+ }
429
+ function makeEmitter(onEvent) {
430
+ if (!onEvent) return async () => {};
431
+ return async (event) => {
432
+ await onEvent(event);
433
+ };
434
+ }
435
+ async function runRegistry(opts, priorFindings, emit) {
436
+ const reg = opts.registry;
437
+ if (typeof reg.runStream === "function" && opts.onEvent) {
438
+ let final = null;
439
+ for await (const ev of reg.runStream(opts.runId, opts.inputs, { priorFindings })) {
440
+ await emit({
441
+ type: "analyst",
442
+ runId: opts.runId,
443
+ event: ev
444
+ });
445
+ if (ev.type === "run-completed") final = ev.result;
446
+ }
447
+ if (!final) throw new Error("runAnalystLoop: registry.runStream ended without run-completed event");
448
+ return final;
449
+ }
450
+ return opts.registry.run(opts.runId, opts.inputs, { priorFindings });
451
+ }
452
+ function resolveBaselineRunId(opts) {
453
+ if (opts.baselineRunId === null) return null;
454
+ if (typeof opts.baselineRunId === "string") return opts.baselineRunId;
455
+ if (!opts.findingsStore) return null;
456
+ const all = opts.findingsStore.loadAll();
457
+ let last = null;
458
+ for (const row of all) {
459
+ if (row.run_id === opts.runId) continue;
460
+ last = row.run_id;
461
+ }
462
+ return last;
463
+ }
464
+ function buildPriorFindingsInput(prior, strategy, registry) {
465
+ if (strategy === "none" || prior.length === 0) return void 0;
466
+ const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest);
467
+ if (strategy === "wildcard") return { "*": stripped };
468
+ return stripped;
469
+ }
470
+ async function runKnowledgeProposalSource(opts, findings, log, emit) {
471
+ const batch = await opts.knowledgeProposalSource.proposeFromFindings(findings);
472
+ log("knowledge.proposeFromFindings", {
473
+ proposals: batch.proposals.length,
474
+ skipped: batch.skipped,
475
+ errors: batch.errors.length
476
+ });
477
+ await emit({
478
+ type: "knowledge-proposed",
479
+ runId: opts.runId,
480
+ proposalCount: batch.proposals.length,
481
+ skipped: batch.skipped,
482
+ errors: batch.errors.length
483
+ });
484
+ return {
485
+ proposals: batch.proposals,
486
+ skipped: batch.skipped,
487
+ errors: batch.errors
488
+ };
489
+ }
490
+ async function runImprovementProposalSource(opts, findings, log, emit) {
491
+ const batch = await opts.improvementProposalSource.proposeFromFindings(findings);
492
+ log("improvement.proposeFromFindings", {
493
+ edits: batch.edits.length,
494
+ skipped: batch.skipped,
495
+ errors: batch.errors.length
496
+ });
497
+ await emit({
498
+ type: "improvement-proposed",
499
+ runId: opts.runId,
500
+ editCount: batch.edits.length,
501
+ skipped: batch.skipped,
502
+ errors: batch.errors.length
503
+ });
504
+ return {
505
+ edits: batch.edits,
506
+ skipped: batch.skipped,
507
+ errors: batch.errors
508
+ };
509
+ }
510
+ function defaultLog(msg, fields) {
511
+ if (fields) console.log(`[analyst-loop] ${msg}`, fields);
512
+ else console.log(`[analyst-loop] ${msg}`);
513
+ }
514
+ //#endregion
515
+ export { iterationsToTraceStore as n, runAnalystLoop as t };
516
+
517
+ //# sourceMappingURL=analyst-loop-DGdtVENg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analyst-loop-DGdtVENg.js","names":[],"sources":["../src/analyst-loop/iterations-to-trace-store.ts","../src/analyst-loop/run-analyst-loop.ts"],"sourcesContent":["/**\n *\n * The read seam that closes the autonomous loop: project a round's `Iteration[]`\n * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the\n * read interface the trace analysts query. `runAnalystLoop` has had zero consumers\n * because nothing turned a loop's iterations into a store — this is that bridge.\n *\n * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`\n * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an\n * analyst can walk a shot's trace, cluster its errors, and emit findings the driver\n * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event\n * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration\n * surfaces a real ERROR span carrying the real message.\n *\n * @experimental\n */\n\nimport {\n type DatasetOverview,\n DEFAULT_TRACE_ANALYST_BUDGETS,\n type QueryTracesPage,\n type SearchSpanResult,\n type SearchTraceResult,\n type SpanMatchRecord,\n TRACE_ANALYST_TRUNCATION_MARKER_PREFIX,\n type TraceAnalysisStore,\n type TraceAnalystByteBudgets,\n type TraceAnalystFilters,\n type TraceAnalystSpan,\n type TraceAnalystSpanKind,\n type TraceAnalystTraceSummary,\n type ViewSpansResult,\n type ViewTraceResult,\n} from '@tangle-network/agent-eval'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { AnalystError } from '../errors'\nimport { extractLlmCallEvent } from '../runtime/sandbox-events'\nimport type { Iteration } from '../runtime/types'\n\n/** ErrorCluster isn't re-exported from the agent-eval root; derive it from the overview. */\ntype ErrorCluster = DatasetOverview['error_clusters'][number]\n\ninterface ProjectedTrace {\n summary: TraceAnalystTraceSummary\n spans: TraceAnalystSpan[]\n /** raw JSONL bytes of this trace's spans — the byte-budget accounting unit. */\n rawBytes: number\n}\n\nconst bytesOf = (v: unknown): number => Buffer.byteLength(JSON.stringify(v) ?? '', 'utf8')\nconst iso = (ms: number): string => new Date(ms).toISOString()\n\n/** Normalize volatile tokens out of a status message so semantically identical failures\n * collapse to one signature (digits, hex/uuids, paths, durations → placeholders). */\nfunction normalizeSignature(message: string): string {\n return message\n .replace(/0x[0-9a-fA-F]+/g, 'HEX')\n .replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, 'UUID')\n .replace(/(\\/[\\w.-]+){2,}/g, 'PATH')\n .replace(/\\b\\d+(\\.\\d+)?(ms|s|m|h)\\b/g, 'DUR')\n .replace(/\\b\\d+\\b/g, '#')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 200)\n}\n\nfunction spanKindFor(\n event: SandboxEvent,\n agentRunName: string,\n): {\n kind: TraceAnalystSpanKind\n model: string | null\n tool: string | null\n} {\n const llm = extractLlmCallEvent(event, agentRunName)\n if (llm) return { kind: 'LLM', model: llm.model ?? null, tool: null }\n const type = String(event?.type ?? '')\n if (/tool/i.test(type)) {\n const d = event?.data as { name?: unknown; tool?: unknown } | undefined\n const tool = typeof d?.name === 'string' ? d.name : typeof d?.tool === 'string' ? d.tool : type\n return { kind: 'TOOL', model: null, tool }\n }\n return { kind: 'SPAN', model: null, tool: null }\n}\n\nfunction errorMessageOf(event: SandboxEvent): string | undefined {\n const type = String(event?.type ?? '')\n const d = event?.data as { error?: unknown; message?: unknown } | undefined\n if (/error|fail/i.test(type) || d?.error) {\n const m = d?.error ?? d?.message\n return typeof m === 'string' ? m : `${type} error`\n }\n return undefined\n}\n\n/** Project one iteration → one trace: root AGENT span + a child span per event. */\nfunction projectIteration<Task, Output>(iter: Iteration<Task, Output>): ProjectedTrace {\n const traceId =\n (\n iter.events.find((e) => (e?.data as { sandboxId?: string } | undefined)?.sandboxId)?.data as\n | { sandboxId?: string }\n | undefined\n )?.sandboxId ?? `iter-${iter.index}`\n const start = iso(iter.startedAt)\n const end = iso(iter.endedAt || iter.startedAt)\n const durationMs = Math.max(0, (iter.endedAt || iter.startedAt) - iter.startedAt)\n const rootId = `${traceId}:root`\n const iterErrored = Boolean(iter.error) || iter.verdict?.valid === false\n const spans: TraceAnalystSpan[] = [\n {\n trace_id: traceId,\n span_id: rootId,\n parent_span_id: null,\n name: iter.agentRunName,\n kind: 'AGENT',\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n status: iter.error ? 'ERROR' : 'OK',\n status_message: iter.error?.message,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: null,\n tool_name: null,\n attributes: {\n 'iteration.index': iter.index,\n 'verdict.valid': iter.verdict?.valid,\n 'verdict.score': iter.verdict?.score,\n 'output.preview':\n iter.output === undefined ? undefined : String(iter.output).slice(0, 2000),\n },\n },\n ]\n const models = new Set<string>()\n const tools = new Set<string>()\n iter.events.forEach((event, i) => {\n const { kind, model, tool } = spanKindFor(event, iter.agentRunName)\n if (model) models.add(model)\n if (tool) tools.add(tool)\n const errMsg = errorMessageOf(event)\n spans.push({\n trace_id: traceId,\n span_id: `${traceId}:e${i}`,\n parent_span_id: rootId,\n name: String(event?.type ?? 'event'),\n kind,\n start_time: start,\n end_time: end,\n duration_ms: 0,\n status: errMsg ? 'ERROR' : 'OK',\n status_message: errMsg,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: model,\n tool_name: tool,\n attributes: (event?.data as Record<string, unknown> | undefined) ?? {},\n })\n })\n const hasErrors = spans.some((s) => s.status === 'ERROR') || iterErrored\n const summary: TraceAnalystTraceSummary = {\n trace_id: traceId,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n span_count: spans.length,\n has_errors: hasErrors,\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n raw_jsonl_bytes: bytesOf(spans),\n models: [...models],\n tools: [...tools],\n }\n return { summary, spans, rawBytes: summary.raw_jsonl_bytes }\n}\n\nfunction matchesFilters(t: ProjectedTrace, f?: TraceAnalystFilters): boolean {\n if (!f) return true\n if (f.has_errors !== undefined && t.summary.has_errors !== f.has_errors) return false\n if (f.service_names?.length && !f.service_names.includes(t.summary.service_name ?? ''))\n return false\n if (f.agent_names?.length && !f.agent_names.includes(t.summary.agent_name ?? '')) return false\n if (f.model_names?.length && !f.model_names.some((m) => t.summary.models.includes(m)))\n return false\n if (f.tool_names?.length && !f.tool_names.some((tn) => t.summary.tools.includes(tn))) return false\n if (f.start_time_after && t.summary.start_time < f.start_time_after) return false\n if (f.start_time_before && t.summary.start_time > f.start_time_before) return false\n if (f.regex_pattern && !new RegExp(f.regex_pattern).test(JSON.stringify(t.spans))) return false\n return true\n}\n\nfunction capAttributes(\n attributes: Record<string, unknown>,\n perAttrCap: number,\n): { capped: Record<string, unknown>; truncated: number } {\n let truncated = 0\n const capped: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attributes)) {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof s === 'string' && s.length > perAttrCap) {\n truncated += 1\n capped[k] = `${TRACE_ANALYST_TRUNCATION_MARKER_PREFIX} ${s.length}b]${s.slice(0, perAttrCap)}`\n } else {\n capped[k] = v\n }\n }\n return { capped, truncated }\n}\n\n/**\n * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an\n * empty round — there is nothing for an analyst to read, and a silent empty store would\n * mask a broken capture path.\n */\nexport function iterationsToTraceStore<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n budgets: TraceAnalystByteBudgets = DEFAULT_TRACE_ANALYST_BUDGETS,\n): TraceAnalysisStore {\n if (iterations.length === 0) {\n throw new AnalystError('iterationsToTraceStore: no iterations to analyze (empty round)')\n }\n const traces = iterations.map((it) => projectIteration(it))\n const byId = new Map(traces.map((t) => [t.summary.trace_id, t]))\n\n const buildClusters = (set: ProjectedTrace[]): ErrorCluster[] => {\n const map = new Map<string, ErrorCluster>()\n for (const t of set) {\n for (const s of t.spans) {\n if (s.status !== 'ERROR' || !s.status_message) continue\n const sig = normalizeSignature(s.status_message)\n const c = map.get(sig) ?? {\n signature: sig,\n status_message_sample: s.status_message,\n span_name: s.name,\n tool_name: s.tool_name,\n trace_count: 0,\n span_count: 0,\n prevalence: 0,\n exemplar_trace_ids: [],\n exemplar_span_ids: [],\n }\n c.span_count += 1\n if (\n !c.exemplar_trace_ids.includes(t.summary.trace_id) &&\n c.exemplar_trace_ids.length < 10\n ) {\n c.exemplar_trace_ids.push(t.summary.trace_id)\n c.trace_count += 1\n }\n if (c.exemplar_span_ids.length < 10) c.exemplar_span_ids.push(s.span_id)\n map.set(sig, c)\n }\n }\n const errorTraces = set.filter((t) => t.summary.has_errors).length || 1\n const clusters = [...map.values()].map((c) => ({\n ...c,\n prevalence: c.trace_count / errorTraces,\n }))\n return clusters.sort((a, b) => b.trace_count - a.trace_count)\n }\n\n return {\n async getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview> {\n const set = traces.filter((t) => matchesFilters(t, filters))\n const services = new Set<string>()\n const agents = new Set<string>()\n const models = new Set<string>()\n const tools = new Set<string>()\n let errorSpans = 0\n for (const t of set) {\n if (t.summary.service_name) services.add(t.summary.service_name)\n if (t.summary.agent_name) agents.add(t.summary.agent_name)\n for (const m of t.summary.models) models.add(m)\n for (const tn of t.summary.tools) tools.add(tn)\n errorSpans += t.spans.filter((s) => s.status === 'ERROR').length\n }\n const times = set.map((t) => t.summary.start_time).sort()\n return {\n total_traces: set.length,\n raw_jsonl_bytes: set.reduce((n, t) => n + t.rawBytes, 0),\n services: [...services],\n agents: [...agents],\n models: [...models],\n tool_names: [...tools],\n sample_trace_ids: set.slice(0, 20).map((t) => t.summary.trace_id),\n errors: {\n trace_count: set.filter((t) => t.summary.has_errors).length,\n span_count: errorSpans,\n },\n error_clusters: buildClusters(set),\n time_range: times.length ? { earliest: times[0]!, latest: times[times.length - 1]! } : null,\n }\n },\n\n async queryTraces(opts): Promise<QueryTracesPage> {\n const set = traces.filter((t) => matchesFilters(t, opts.filters))\n const offset = opts.offset ?? 0\n const page = set.slice(offset, offset + opts.limit)\n return {\n traces: page.map((t) => t.summary),\n total: set.length,\n has_more: offset + opts.limit < set.length,\n }\n },\n\n async countTraces(filters?: TraceAnalystFilters): Promise<number> {\n return traces.filter((t) => matchesFilters(t, filters)).length\n },\n\n async viewTrace(opts): Promise<ViewTraceResult> {\n const t = byId.get(opts.trace_id)\n if (!t) return { trace_id: opts.trace_id, spans: [] }\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeViewBudget\n const projected = t.spans.map((s) => ({\n ...s,\n attributes: capAttributes(s.attributes, cap).capped,\n }))\n if (bytesOf(projected) > budgets.perCallByteCeiling) {\n const names = new Map<string, number>()\n for (const s of t.spans) names.set(s.name, (names.get(s.name) ?? 0) + 1)\n return {\n trace_id: opts.trace_id,\n oversized: {\n span_count: t.spans.length,\n top_span_names: [...names.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20),\n span_response_bytes_max: Math.max(...t.spans.map((s) => bytesOf(s))),\n error_span_count: t.spans.filter((s) => s.status === 'ERROR').length,\n },\n }\n }\n return { trace_id: opts.trace_id, spans: projected }\n },\n\n async viewSpans(opts): Promise<ViewSpansResult> {\n const t = byId.get(opts.trace_id)\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget\n const want = new Set(opts.span_ids)\n const found = (t?.spans ?? []).filter((s) => want.has(s.span_id))\n let truncated = 0\n const spans = found.map((s) => {\n const { capped, truncated: n } = capAttributes(s.attributes, cap)\n truncated += n\n return { ...s, attributes: capped }\n })\n const foundIds = new Set(found.map((s) => s.span_id))\n return {\n trace_id: opts.trace_id,\n spans,\n missing_span_ids: opts.span_ids.filter((id) => !foundIds.has(id)),\n truncated_attribute_count: truncated,\n }\n },\n\n async searchTrace(opts): Promise<SearchTraceResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const hits: SpanMatchRecord[] = []\n for (const s of t?.spans ?? []) {\n for (const hit of searchSpanAttrs(s, opts.regex_pattern, budgets.perMatchTextBudget)) {\n if (hits.length >= max) break\n hits.push(hit)\n }\n }\n return {\n trace_id: opts.trace_id,\n hits,\n total_matches: hits.length,\n has_more: hits.length >= max,\n }\n },\n\n async searchSpan(opts): Promise<SearchSpanResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const span = (t?.spans ?? []).find((s) => s.span_id === opts.span_id)\n const hits = span\n ? searchSpanAttrs(span, opts.regex_pattern, budgets.perMatchTextBudget).slice(0, max)\n : []\n return {\n trace_id: opts.trace_id,\n span_id: opts.span_id,\n hits,\n total_matches: hits.length,\n has_more: false,\n }\n },\n }\n}\n\nfunction searchSpanAttrs(\n span: TraceAnalystSpan,\n pattern: string,\n textCap: number,\n): SpanMatchRecord[] {\n const re = new RegExp(pattern, 'g')\n const hits: SpanMatchRecord[] = []\n for (const [k, v] of Object.entries(span.attributes)) {\n const text = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof text !== 'string') continue\n re.lastIndex = 0\n const m = re.exec(text)\n if (!m) continue\n const at = m.index\n hits.push({\n trace_id: span.trace_id,\n span_id: span.span_id,\n span_name: span.name,\n span_kind: span.kind,\n attribute_path: `attributes.${k}`,\n matched_text: m[0].slice(0, textCap),\n context_before: text.slice(Math.max(0, at - textCap / 2), at),\n context_after: text.slice(at + m[0].length, at + m[0].length + textCap / 2),\n match_offset: at,\n })\n }\n return hits\n}\n","/**\n * `runAnalystLoop` — the one call agent apps reach for to close the\n * recursive-self-improvement loop.\n *\n * 1. Load baseline findings (last run, or the slice the caller specifies)\n * 2. Run the analyst registry with priorFindings injected\n * 3. Persist the new run's findings to the ledger\n * 4. Diff the new run against the baseline\n * 5. Hand the findings to the knowledge proposal source\n * 6. Hand the findings to the agent-surface proposal source\n * 7. Return a single report the consumer renders / persists / acts on.\n *\n * Proposal sources are optional: the loop also works as a plain\n * \"run + diff + report\" primitive.\n */\n\nimport type { AnalystFinding, AnalystRunResult, FindingsDiff } from '@tangle-network/agent-eval'\nimport { diffFindings } from '@tangle-network/agent-eval'\n\nimport type {\n AnalystLoopEvent,\n AnalystRegistryStreamingLike,\n ImprovementReport,\n KnowledgeReport,\n RunAnalystLoopOpts,\n RunAnalystLoopResult,\n} from './types'\n\n/** Analyze a run and apply accepted knowledge and agent-surface proposals. */\nexport async function runAnalystLoop<TProposal = unknown, TEdit = unknown>(\n opts: RunAnalystLoopOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit>> {\n const log = opts.log ?? defaultLog\n const strategy = opts.priorFindingsStrategy ?? 'per-kind'\n const emit = makeEmitter(opts.onEvent)\n const startedAt = Date.now()\n\n // 1. Resolve baseline + load prior findings.\n const baselineRunId = resolveBaselineRunId(opts)\n const priorAll: ReadonlyArray<AnalystFinding & { run_id: string }> = baselineRunId\n ? (opts.findingsStore?.loadRun(baselineRunId) ?? [])\n : []\n log('baseline resolved', { baselineRunId, prior_findings: priorAll.length })\n await emit({\n type: 'baseline-resolved',\n runId: opts.runId,\n baselineRunId,\n priorFindingCount: priorAll.length,\n })\n\n // 2. Run the registry. Strategy controls how analysts see priors.\n // When the registry exposes runStream, forward each event verbatim\n // so subscribers see per-analyst progress in real time.\n const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list())\n const analystResult = await runRegistry(opts, priorFindings, emit)\n log('analyst run complete', {\n findings: analystResult.findings.length,\n cost_usd: analystResult.total_cost_usd,\n per_analyst: analystResult.per_analyst.map((s) => ({\n id: s.analyst_id,\n status: s.status,\n n: s.findings_count,\n })),\n })\n\n // 3. Persist the new run before proposal generation so the ledger remains\n // the source of truth if a proposal source throws.\n if (opts.findingsStore && analystResult.findings.length > 0) {\n await opts.findingsStore.append(opts.runId, analystResult.findings)\n await emit({\n type: 'findings-persisted',\n runId: opts.runId,\n count: analystResult.findings.length,\n })\n }\n\n // 4. Diff vs baseline.\n let diff: FindingsDiff | null = null\n if (baselineRunId && analystResult.findings.length > 0) {\n diff = diffFindings(\n priorAll.map((f) => ({ ...f })),\n analystResult.findings.map((f) => ({ ...f, run_id: opts.runId })),\n )\n log('diff vs baseline', {\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n await emit({\n type: 'diff-computed',\n runId: opts.runId,\n baselineRunId,\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n }\n\n // 5. Knowledge proposals. This loop never writes live knowledge.\n let knowledge: KnowledgeReport<TProposal> | null = null\n if (opts.knowledgeProposalSource) {\n knowledge = await runKnowledgeProposalSource(opts, analystResult.findings, log, emit)\n }\n\n // 6. Agent-surface proposals. This loop never writes live agent state.\n let improvement: ImprovementReport<TEdit> | null = null\n if (opts.improvementProposalSource) {\n improvement = await runImprovementProposalSource(opts, analystResult.findings, log, emit)\n }\n\n await emit({\n type: 'loop-completed',\n runId: opts.runId,\n durationMs: Date.now() - startedAt,\n })\n\n return {\n runId: opts.runId,\n baselineRunId,\n analystResult,\n diff,\n knowledge,\n improvement,\n }\n}\n\ntype Emitter = (event: AnalystLoopEvent) => Promise<void>\n\nfunction makeEmitter(onEvent: RunAnalystLoopOpts['onEvent']): Emitter {\n if (!onEvent) return async () => {}\n return async (event) => {\n await onEvent(event)\n }\n}\n\nasync function runRegistry(\n opts: RunAnalystLoopOpts,\n priorFindings: ReturnType<typeof buildPriorFindingsInput>,\n emit: Emitter,\n): Promise<AnalystRunResult> {\n const reg = opts.registry as AnalystRegistryStreamingLike\n if (typeof reg.runStream === 'function' && opts.onEvent) {\n let final: AnalystRunResult | null = null\n for await (const ev of reg.runStream(opts.runId, opts.inputs, { priorFindings })) {\n await emit({ type: 'analyst', runId: opts.runId, event: ev })\n if (ev.type === 'run-completed') final = ev.result\n }\n if (!final) {\n throw new Error('runAnalystLoop: registry.runStream ended without run-completed event')\n }\n return final\n }\n return opts.registry.run(opts.runId, opts.inputs, { priorFindings })\n}\n\nfunction resolveBaselineRunId(opts: RunAnalystLoopOpts): string | null {\n if (opts.baselineRunId === null) return null\n if (typeof opts.baselineRunId === 'string') return opts.baselineRunId\n if (!opts.findingsStore) return null\n const all = opts.findingsStore.loadAll()\n let last: string | null = null\n for (const row of all) {\n if (row.run_id === opts.runId) continue\n last = row.run_id\n }\n return last\n}\n\nfunction buildPriorFindingsInput(\n prior: ReadonlyArray<AnalystFinding & { run_id: string }>,\n strategy: 'per-kind' | 'wildcard' | 'none',\n registry: ReadonlyArray<{ id: string }>,\n): ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>> | undefined {\n if (strategy === 'none' || prior.length === 0) return undefined\n const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest as AnalystFinding)\n if (strategy === 'wildcard') {\n return { '*': stripped }\n }\n void registry\n return stripped\n}\n\nasync function runKnowledgeProposalSource<TProposal>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<KnowledgeReport<TProposal>> {\n const source = opts.knowledgeProposalSource!\n const batch = await source.proposeFromFindings(findings)\n log('knowledge.proposeFromFindings', {\n proposals: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'knowledge-proposed',\n runId: opts.runId,\n proposalCount: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n return {\n proposals: batch.proposals as TProposal[],\n skipped: batch.skipped,\n errors: batch.errors,\n }\n}\n\nasync function runImprovementProposalSource<TEdit>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<ImprovementReport<TEdit>> {\n const source = opts.improvementProposalSource!\n const batch = await source.proposeFromFindings(findings)\n log('improvement.proposeFromFindings', {\n edits: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'improvement-proposed',\n runId: opts.runId,\n editCount: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n return {\n edits: batch.edits as TEdit[],\n skipped: batch.skipped,\n errors: batch.errors,\n }\n}\n\nfunction defaultLog(msg: string, fields?: Record<string, unknown>): void {\n if (fields) console.log(`[analyst-loop] ${msg}`, fields)\n else console.log(`[analyst-loop] ${msg}`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,WAAW,MAAuB,OAAO,WAAW,KAAK,UAAU,CAAC,KAAK,IAAI,MAAM;AACzF,MAAM,OAAO,OAAuB,IAAI,KAAK,EAAE,CAAC,CAAC,YAAY;;;AAI7D,SAAS,mBAAmB,SAAyB;CACnD,OAAO,QACJ,QAAQ,mBAAmB,KAAK,CAAC,CACjC,QAAQ,gFAAgF,MAAM,CAAC,CAC/F,QAAQ,oBAAoB,MAAM,CAAC,CACnC,QAAQ,8BAA8B,KAAK,CAAC,CAC5C,QAAQ,YAAY,GAAG,CAAC,CACx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E,KAAK,SAAS;CAGzB,OAAO;AACT;AAEA,eAAe,2BACb,MACA,UACA,KACA,MACqC;CAErC,MAAM,QAAQ,MADC,KAAK,wBACO,oBAAoB,QAAQ;CACvD,IAAI,iCAAiC;EACnC,WAAW,MAAM,UAAU;EAC3B,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CACD,MAAM,KAAK;EACT,MAAM;EACN,OAAO,KAAK;EACZ,eAAe,MAAM,UAAU;EAC/B,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CAED,OAAO;EACL,WAAW,MAAM;EACjB,SAAS,MAAM;EACf,QAAQ,MAAM;CAChB;AACF;AAEA,eAAe,6BACb,MACA,UACA,KACA,MACmC;CAEnC,MAAM,QAAQ,MADC,KAAK,0BACO,oBAAoB,QAAQ;CACvD,IAAI,mCAAmC;EACrC,OAAO,MAAM,MAAM;EACnB,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CACD,MAAM,KAAK;EACT,MAAM;EACN,OAAO,KAAK;EACZ,WAAW,MAAM,MAAM;EACvB,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CAED,OAAO;EACL,OAAO,MAAM;EACb,SAAS,MAAM;EACf,QAAQ,MAAM;CAChB;AACF;AAEA,SAAS,WAAW,KAAa,QAAwC;CACvE,IAAI,QAAQ,QAAQ,IAAI,kBAAkB,OAAO,MAAM;MAClD,QAAQ,IAAI,kBAAkB,KAAK;AAC1C"}
@@ -1,50 +1,17 @@
1
- import { TraceAnalystByteBudgets, TraceAnalysisStore } from '@tangle-network/agent-eval';
2
- import { I as Iteration } from './types-BCoemcXU.js';
3
- import { R as RunAnalystLoopOpts, a as RunAnalystLoopResult } from './types-CmYCMbFT.js';
4
- export { A as AnalystLoopEvent, b as AnalystRegistryLike, c as AnalystRegistryStreamingLike, F as FindingsStoreLike, d as ImprovementEditBatch, I as ImprovementProposalSource, e as ImprovementReport, K as KnowledgeProposalBatch, f as KnowledgeProposalSource, g as KnowledgeReport } from './types-CmYCMbFT.js';
5
- import '@tangle-network/sandbox';
6
- import './types-BwoZWq-i.js';
7
-
8
- /**
9
- *
10
- * The read seam that closes the autonomous loop: project a round's `Iteration[]`
11
- * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the
12
- * read interface the trace analysts query. `runAnalystLoop` has had zero consumers
13
- * because nothing turned a loop's iterations into a store — this is that bridge.
14
- *
15
- * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`
16
- * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an
17
- * analyst can walk a shot's trace, cluster its errors, and emit findings the driver
18
- * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event
19
- * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration
20
- * surfaces a real ERROR span carrying the real message.
21
- *
22
- * @experimental
23
- */
24
-
1
+ import { a as ImprovementEditBatch, c as KnowledgeProposalBatch, d as RunAnalystLoopOpts, f as RunAnalystLoopResult, i as FindingsStoreLike, l as KnowledgeProposalSource, n as AnalystRegistryLike, o as ImprovementProposalSource, r as AnalystRegistryStreamingLike, s as ImprovementReport, t as AnalystLoopEvent, u as KnowledgeReport } from "./types-Cja5OTGh.js";
2
+ import { a as Iteration } from "./types-BevOjfTY.js";
3
+ import { TraceAnalysisStore, TraceAnalystByteBudgets } from "@tangle-network/agent-eval";
4
+ //#region src/analyst-loop/iterations-to-trace-store.d.ts
25
5
  /**
26
6
  * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an
27
7
  * empty round — there is nothing for an analyst to read, and a silent empty store would
28
8
  * mask a broken capture path.
29
9
  */
30
10
  declare function iterationsToTraceStore<Task, Output>(iterations: ReadonlyArray<Iteration<Task, Output>>, budgets?: TraceAnalystByteBudgets): TraceAnalysisStore;
31
-
32
- /**
33
- * `runAnalystLoop` the one call agent apps reach for to close the
34
- * recursive-self-improvement loop.
35
- *
36
- * 1. Load baseline findings (last run, or the slice the caller specifies)
37
- * 2. Run the analyst registry with priorFindings injected
38
- * 3. Persist the new run's findings to the ledger
39
- * 4. Diff the new run against the baseline
40
- * 5. Hand the findings to the knowledge proposal source
41
- * 6. Hand the findings to the agent-surface proposal source
42
- * 7. Return a single report the consumer renders / persists / acts on.
43
- *
44
- * Proposal sources are optional: the loop also works as a plain
45
- * "run + diff + report" primitive.
46
- */
47
-
11
+ //#endregion
12
+ //#region src/analyst-loop/run-analyst-loop.d.ts
13
+ /** Analyze a run and apply accepted knowledge and agent-surface proposals. */
48
14
  declare function runAnalystLoop<TProposal = unknown, TEdit = unknown>(opts: RunAnalystLoopOpts): Promise<RunAnalystLoopResult<TProposal, TEdit>>;
49
-
50
- export { RunAnalystLoopOpts, RunAnalystLoopResult, iterationsToTraceStore, runAnalystLoop };
15
+ //#endregion
16
+ export { type AnalystLoopEvent, type AnalystRegistryLike, type AnalystRegistryStreamingLike, type FindingsStoreLike, type ImprovementEditBatch, type ImprovementProposalSource, type ImprovementReport, type KnowledgeProposalBatch, type KnowledgeProposalSource, type KnowledgeReport, type RunAnalystLoopOpts, type RunAnalystLoopResult, iterationsToTraceStore, runAnalystLoop };
17
+ //# sourceMappingURL=analyst-loop.d.ts.map
@@ -1,11 +1,2 @@
1
- import {
2
- iterationsToTraceStore,
3
- runAnalystLoop
4
- } from "./chunk-FD2MBMOH.js";
5
- import "./chunk-M22PL4GH.js";
6
- import "./chunk-YEJR7IXO.js";
7
- export {
8
- iterationsToTraceStore,
9
- runAnalystLoop
10
- };
11
- //# sourceMappingURL=analyst-loop.js.map
1
+ import { n as iterationsToTraceStore, t as runAnalystLoop } from "./analyst-loop-DGdtVENg.js";
2
+ export { iterationsToTraceStore, runAnalystLoop };