@tangle-network/agent-eval 0.120.2 → 0.120.3

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 (171) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/analyst/index.d.ts +3111 -0
  3. package/dist/analyst/index.js +403 -0
  4. package/dist/analyst/index.js.map +1 -0
  5. package/dist/authenticity/index.d.ts +161 -0
  6. package/dist/authenticity/index.js +215 -0
  7. package/dist/authenticity/index.js.map +1 -0
  8. package/dist/belief-state/index.d.ts +1301 -0
  9. package/dist/belief-state/index.js +2152 -0
  10. package/dist/belief-state/index.js.map +1 -0
  11. package/dist/benchmarks/index.d.ts +974 -0
  12. package/dist/benchmarks/index.js +60 -0
  13. package/dist/benchmarks/index.js.map +1 -0
  14. package/dist/builder-eval/index.d.ts +695 -0
  15. package/dist/builder-eval/index.js +366 -0
  16. package/dist/builder-eval/index.js.map +1 -0
  17. package/dist/campaign/index.d.ts +7454 -0
  18. package/dist/campaign/index.js +272 -0
  19. package/dist/campaign/index.js.map +1 -0
  20. package/dist/chunk-3CDFMEMO.js +3878 -0
  21. package/dist/chunk-3CDFMEMO.js.map +1 -0
  22. package/dist/chunk-3RF76KTD.js +84 -0
  23. package/dist/chunk-3RF76KTD.js.map +1 -0
  24. package/dist/chunk-3XH4Y2SS.js +750 -0
  25. package/dist/chunk-3XH4Y2SS.js.map +1 -0
  26. package/dist/chunk-3YYRZDON.js +45 -0
  27. package/dist/chunk-3YYRZDON.js.map +1 -0
  28. package/dist/chunk-5BYTIDZ7.js +550 -0
  29. package/dist/chunk-5BYTIDZ7.js.map +1 -0
  30. package/dist/chunk-5CVUPHJ4.js +2668 -0
  31. package/dist/chunk-5CVUPHJ4.js.map +1 -0
  32. package/dist/chunk-ARU2PZFM.js +312 -0
  33. package/dist/chunk-ARU2PZFM.js.map +1 -0
  34. package/dist/chunk-BOD4O7OF.js +40 -0
  35. package/dist/chunk-BOD4O7OF.js.map +1 -0
  36. package/dist/chunk-CVJP5TMD.js +766 -0
  37. package/dist/chunk-CVJP5TMD.js.map +1 -0
  38. package/dist/chunk-DPZAEKA6.js +880 -0
  39. package/dist/chunk-DPZAEKA6.js.map +1 -0
  40. package/dist/chunk-DTJ6QUQB.js +131 -0
  41. package/dist/chunk-DTJ6QUQB.js.map +1 -0
  42. package/dist/chunk-GGE4NNQT.js +65 -0
  43. package/dist/chunk-GGE4NNQT.js.map +1 -0
  44. package/dist/chunk-H5UD2323.js +286 -0
  45. package/dist/chunk-H5UD2323.js.map +1 -0
  46. package/dist/chunk-HHWE3POT.js +94 -0
  47. package/dist/chunk-HHWE3POT.js.map +1 -0
  48. package/dist/chunk-HKUCJ437.js +787 -0
  49. package/dist/chunk-HKUCJ437.js.map +1 -0
  50. package/dist/chunk-JHCHEVET.js +274 -0
  51. package/dist/chunk-JHCHEVET.js.map +1 -0
  52. package/dist/chunk-K4DBDHLK.js +158 -0
  53. package/dist/chunk-K4DBDHLK.js.map +1 -0
  54. package/dist/chunk-K6N6XJJX.js +306 -0
  55. package/dist/chunk-K6N6XJJX.js.map +1 -0
  56. package/dist/chunk-MA6HLL3S.js +65 -0
  57. package/dist/chunk-MA6HLL3S.js.map +1 -0
  58. package/dist/chunk-MAZ26DC7.js +99 -0
  59. package/dist/chunk-MAZ26DC7.js.map +1 -0
  60. package/dist/chunk-MOXWMGPC.js +577 -0
  61. package/dist/chunk-MOXWMGPC.js.map +1 -0
  62. package/dist/chunk-NJC7U437.js +626 -0
  63. package/dist/chunk-NJC7U437.js.map +1 -0
  64. package/dist/chunk-NMN4WGSJ.js +1030 -0
  65. package/dist/chunk-NMN4WGSJ.js.map +1 -0
  66. package/dist/chunk-NPCTHQIO.js +91 -0
  67. package/dist/chunk-NPCTHQIO.js.map +1 -0
  68. package/dist/chunk-ONWEPEDO.js +57 -0
  69. package/dist/chunk-ONWEPEDO.js.map +1 -0
  70. package/dist/chunk-OYZAPX5G.js +1526 -0
  71. package/dist/chunk-OYZAPX5G.js.map +1 -0
  72. package/dist/chunk-P5MGQ2FY.js +7958 -0
  73. package/dist/chunk-P5MGQ2FY.js.map +1 -0
  74. package/dist/chunk-PC4UYEBM.js +166 -0
  75. package/dist/chunk-PC4UYEBM.js.map +1 -0
  76. package/dist/chunk-PJQFMIOX.js +1182 -0
  77. package/dist/chunk-PJQFMIOX.js.map +1 -0
  78. package/dist/chunk-PXD6ZFNY.js +1107 -0
  79. package/dist/chunk-PXD6ZFNY.js.map +1 -0
  80. package/dist/chunk-PXE2VKMX.js +140 -0
  81. package/dist/chunk-PXE2VKMX.js.map +1 -0
  82. package/dist/chunk-PZ5AY32C.js +10 -0
  83. package/dist/chunk-PZ5AY32C.js.map +1 -0
  84. package/dist/chunk-QBRSJK47.js +622 -0
  85. package/dist/chunk-QBRSJK47.js.map +1 -0
  86. package/dist/chunk-S3UZOQ5Y.js +328 -0
  87. package/dist/chunk-S3UZOQ5Y.js.map +1 -0
  88. package/dist/chunk-SQQED7ZH.js +998 -0
  89. package/dist/chunk-SQQED7ZH.js.map +1 -0
  90. package/dist/chunk-SYV364BL.js +1266 -0
  91. package/dist/chunk-SYV364BL.js.map +1 -0
  92. package/dist/chunk-T4SQEITX.js +95 -0
  93. package/dist/chunk-T4SQEITX.js.map +1 -0
  94. package/dist/chunk-TT4KNT67.js +124 -0
  95. package/dist/chunk-TT4KNT67.js.map +1 -0
  96. package/dist/chunk-U5CHZ5M3.js +357 -0
  97. package/dist/chunk-U5CHZ5M3.js.map +1 -0
  98. package/dist/chunk-ULOKLHIQ.js +1937 -0
  99. package/dist/chunk-ULOKLHIQ.js.map +1 -0
  100. package/dist/chunk-VI2UW6B6.js +162 -0
  101. package/dist/chunk-VI2UW6B6.js.map +1 -0
  102. package/dist/chunk-VQMK5FMP.js +247 -0
  103. package/dist/chunk-VQMK5FMP.js.map +1 -0
  104. package/dist/chunk-VSMTAMNK.js +53 -0
  105. package/dist/chunk-VSMTAMNK.js.map +1 -0
  106. package/dist/chunk-VZSRQ272.js +149 -0
  107. package/dist/chunk-VZSRQ272.js.map +1 -0
  108. package/dist/chunk-WW2A73HW.js +159 -0
  109. package/dist/chunk-WW2A73HW.js.map +1 -0
  110. package/dist/chunk-X4UCIOTZ.js +136 -0
  111. package/dist/chunk-X4UCIOTZ.js.map +1 -0
  112. package/dist/chunk-XJYR7XFV.js +317 -0
  113. package/dist/chunk-XJYR7XFV.js.map +1 -0
  114. package/dist/chunk-ZET2UAYW.js +89 -0
  115. package/dist/chunk-ZET2UAYW.js.map +1 -0
  116. package/dist/chunk-ZMXDQ4K7.js +870 -0
  117. package/dist/chunk-ZMXDQ4K7.js.map +1 -0
  118. package/dist/chunk-ZZUXHH3R.js +99 -0
  119. package/dist/chunk-ZZUXHH3R.js.map +1 -0
  120. package/dist/cli.d.ts +1 -0
  121. package/dist/cli.js +112 -0
  122. package/dist/cli.js.map +1 -0
  123. package/dist/contract/index.d.ts +4972 -0
  124. package/dist/contract/index.js +1654 -0
  125. package/dist/contract/index.js.map +1 -0
  126. package/dist/control.d.ts +1013 -0
  127. package/dist/control.js +34 -0
  128. package/dist/control.js.map +1 -0
  129. package/dist/fuzz.d.ts +759 -0
  130. package/dist/fuzz.js +714 -0
  131. package/dist/fuzz.js.map +1 -0
  132. package/dist/hosted/index.d.ts +730 -0
  133. package/dist/hosted/index.js +14 -0
  134. package/dist/hosted/index.js.map +1 -0
  135. package/dist/index.d.ts +16780 -0
  136. package/dist/index.js +12168 -0
  137. package/dist/index.js.map +1 -0
  138. package/dist/matrix/index.d.ts +155 -0
  139. package/dist/matrix/index.js +8 -0
  140. package/dist/matrix/index.js.map +1 -0
  141. package/dist/meta-eval/index.d.ts +1030 -0
  142. package/dist/meta-eval/index.js +417 -0
  143. package/dist/meta-eval/index.js.map +1 -0
  144. package/dist/multishot/index.d.ts +579 -0
  145. package/dist/multishot/index.js +589 -0
  146. package/dist/multishot/index.js.map +1 -0
  147. package/dist/openapi.json +992 -0
  148. package/dist/pipelines/index.d.ts +567 -0
  149. package/dist/pipelines/index.js +515 -0
  150. package/dist/pipelines/index.js.map +1 -0
  151. package/dist/reporting.d.ts +1277 -0
  152. package/dist/reporting.js +48 -0
  153. package/dist/reporting.js.map +1 -0
  154. package/dist/rl.d.ts +4092 -0
  155. package/dist/rl.js +1724 -0
  156. package/dist/rl.js.map +1 -0
  157. package/dist/run-campaign-75RTPVV5.js +14 -0
  158. package/dist/run-campaign-75RTPVV5.js.map +1 -0
  159. package/dist/storyboard/index.d.ts +279 -0
  160. package/dist/storyboard/index.js +767 -0
  161. package/dist/storyboard/index.js.map +1 -0
  162. package/dist/trace-attributes.d.ts +52 -0
  163. package/dist/trace-attributes.js +62 -0
  164. package/dist/trace-attributes.js.map +1 -0
  165. package/dist/traces.d.ts +2343 -0
  166. package/dist/traces.js +249 -0
  167. package/dist/traces.js.map +1 -0
  168. package/dist/wire/index.d.ts +1252 -0
  169. package/dist/wire/index.js +81 -0
  170. package/dist/wire/index.js.map +1 -0
  171. package/package.json +1 -1
@@ -0,0 +1,1107 @@
1
+ import {
2
+ NotFoundError
3
+ } from "./chunk-ONWEPEDO.js";
4
+ import {
5
+ INPUT_VALUE,
6
+ LLM_MODEL_ATTR_KEYS,
7
+ OUTPUT_VALUE,
8
+ SPAN_KIND_ATTR_KEYS,
9
+ TOOL_ARGS_CAPTURED,
10
+ TOOL_LATENCY_MS,
11
+ TOOL_NAME,
12
+ TOOL_NAME_ATTR_KEYS
13
+ } from "./chunk-K4DBDHLK.js";
14
+
15
+ // src/trace/otlp-attributes.ts
16
+ var TOOL_SPAN_ATTRIBUTE_KEYS = [
17
+ TOOL_NAME,
18
+ TOOL_ARGS_CAPTURED,
19
+ TOOL_LATENCY_MS,
20
+ INPUT_VALUE,
21
+ OUTPUT_VALUE
22
+ ];
23
+ function toolSpanOtlpAttributes(span) {
24
+ const argsCaptured = span.argsCaptured !== false;
25
+ const attributes = {
26
+ [TOOL_NAME]: span.toolName,
27
+ [TOOL_ARGS_CAPTURED]: argsCaptured
28
+ };
29
+ if (span.latencyMs !== void 0) attributes[TOOL_LATENCY_MS] = span.latencyMs;
30
+ if (argsCaptured) attributes[INPUT_VALUE] = stringifyTraceValue(span.args);
31
+ if (span.result !== void 0) attributes[OUTPUT_VALUE] = stringifyTraceValue(span.result);
32
+ return attributes;
33
+ }
34
+ function applyToolSpanOtlpAttributes(attributes, span) {
35
+ for (const key of TOOL_SPAN_ATTRIBUTE_KEYS) delete attributes[key];
36
+ Object.assign(attributes, toolSpanOtlpAttributes(span));
37
+ }
38
+ function traceSpanKindToOpenInferenceKind(kind) {
39
+ switch (kind) {
40
+ case "llm":
41
+ return "LLM";
42
+ case "tool":
43
+ return "TOOL";
44
+ case "retrieval":
45
+ return "CHAIN";
46
+ case "judge":
47
+ return "GUARDRAIL";
48
+ case "sandbox":
49
+ return "CHAIN";
50
+ case "agent":
51
+ return "AGENT";
52
+ default:
53
+ return "SPAN";
54
+ }
55
+ }
56
+ function stringifyTraceValue(value) {
57
+ if (value === void 0) return "null";
58
+ if (typeof value === "string") return value;
59
+ try {
60
+ return JSON.stringify(value) ?? String(value);
61
+ } catch {
62
+ return String(value);
63
+ }
64
+ }
65
+
66
+ // src/trace-analyst/otlp-span.ts
67
+ function projectOtlpFlatLine(raw) {
68
+ const trace_id = stringField(raw, "trace_id") ?? stringField(raw, "traceId");
69
+ const span_id = stringField(raw, "span_id") ?? stringField(raw, "spanId");
70
+ if (!trace_id || !span_id) return null;
71
+ const rawParentId = stringField(raw, "parent_span_id") ?? stringField(raw, "parentSpanId") ?? null;
72
+ const parent_id = normalizeParentSpanId(trace_id, span_id, rawParentId);
73
+ const name = stringField(raw, "name") ?? "unknown";
74
+ const start_time = stringField(raw, "start_time") ?? stringField(raw, "startTime") ?? "";
75
+ const end_time = stringField(raw, "end_time") ?? stringField(raw, "endTime") ?? start_time;
76
+ const status = readOtlpStatus(raw);
77
+ const attributes = extractOtlpAttributes(raw);
78
+ const service_name = asString(attributes["service.name"]) ?? asString(attributes["resource.attributes.service.name"]) ?? null;
79
+ const agent_name = asString(attributes["agent.name"]) ?? asString(attributes["inference.agent.name"]) ?? asString(attributes["inference.agent_name"]) ?? null;
80
+ const model_name = firstStringAttr(attributes, LLM_MODEL_ATTR_KEYS);
81
+ const tool_name = firstStringAttr(attributes, TOOL_NAME_ATTR_KEYS);
82
+ const kind = inferOtlpKind(attributes);
83
+ let duration_ms = 0;
84
+ if (start_time && end_time) {
85
+ const a = spanEpochMillis(start_time);
86
+ const b = spanEpochMillis(end_time);
87
+ if (a !== null && b !== null) duration_ms = Math.max(0, b - a);
88
+ }
89
+ return {
90
+ trace_id,
91
+ span_id,
92
+ parent_span_id: parent_id && parent_id.length > 0 ? parent_id : null,
93
+ name,
94
+ kind,
95
+ start_time,
96
+ end_time,
97
+ duration_ms,
98
+ status: status.code,
99
+ status_message: status.message,
100
+ service_name,
101
+ agent_name,
102
+ model_name,
103
+ tool_name,
104
+ attributes
105
+ };
106
+ }
107
+ function normalizeParentSpanId(traceId, spanId, parentId) {
108
+ if (!parentId) return null;
109
+ const prefix = `${traceId}:`;
110
+ return spanId.startsWith(prefix) && !parentId.startsWith(prefix) ? `${prefix}${parentId}` : parentId;
111
+ }
112
+ function readOtlpStatus(raw) {
113
+ const status = raw.status;
114
+ if (status && typeof status === "object" && !Array.isArray(status)) {
115
+ const codeRaw = status.code;
116
+ const code = codeRaw === "STATUS_CODE_OK" || codeRaw === "OK" ? "OK" : codeRaw === "STATUS_CODE_ERROR" || codeRaw === "ERROR" ? "ERROR" : "UNSET";
117
+ const messageRaw = status.message;
118
+ const message = typeof messageRaw === "string" && messageRaw.length > 0 ? messageRaw : void 0;
119
+ return { code, message };
120
+ }
121
+ return { code: "UNSET", message: void 0 };
122
+ }
123
+ function inferOtlpKind(attrs) {
124
+ const opik = firstStringAttr(attrs, SPAN_KIND_ATTR_KEYS);
125
+ if (opik) {
126
+ const upper = opik.toUpperCase();
127
+ if (upper === "AGENT" || upper === "LLM" || upper === "TOOL" || upper === "CHAIN" || upper === "GUARDRAIL" || upper === "SPAN") {
128
+ return upper;
129
+ }
130
+ }
131
+ return "UNKNOWN";
132
+ }
133
+ function extractOtlpAttributes(raw) {
134
+ const out = {};
135
+ const resource = raw.resource;
136
+ if (resource && typeof resource === "object" && !Array.isArray(resource)) {
137
+ const ra = resource.attributes;
138
+ if (ra && typeof ra === "object" && !Array.isArray(ra)) {
139
+ for (const [k, v] of Object.entries(ra)) {
140
+ out[k] = v;
141
+ }
142
+ }
143
+ }
144
+ const spanAttrs = raw.attributes;
145
+ if (spanAttrs && typeof spanAttrs === "object" && !Array.isArray(spanAttrs)) {
146
+ for (const [k, v] of Object.entries(spanAttrs)) {
147
+ out[k] = v;
148
+ }
149
+ }
150
+ return out;
151
+ }
152
+ function stringField(raw, key) {
153
+ const v = raw[key];
154
+ return typeof v === "string" ? v : void 0;
155
+ }
156
+ function asString(v) {
157
+ return typeof v === "string" && v.length > 0 ? v : null;
158
+ }
159
+ function firstStringAttr(attrs, keys) {
160
+ for (const k of keys) {
161
+ const s = asString(attrs[k]);
162
+ if (s !== null) return s;
163
+ }
164
+ return null;
165
+ }
166
+ function spanEpochMillis(ts) {
167
+ if (!ts) return null;
168
+ if (/^\d+$/.test(ts)) return Number(ts);
169
+ const n = Date.parse(ts);
170
+ return Number.isNaN(n) ? null : n;
171
+ }
172
+ function compareSpanTime(a, b) {
173
+ return (spanEpochMillis(a) ?? 0) - (spanEpochMillis(b) ?? 0);
174
+ }
175
+
176
+ // src/trace-analyst/types.ts
177
+ var DEFAULT_TRACE_ANALYST_BUDGETS = {
178
+ perCallByteCeiling: 15e4,
179
+ perAttributeViewBudget: 4096,
180
+ perAttributeSpanBudget: 16384,
181
+ perMatchTextBudget: 1024
182
+ };
183
+ var TRACE_ANALYST_TRUNCATION_MARKER_PREFIX = "[trace-analyst truncated:";
184
+
185
+ // src/trace-analyst/store-otlp.ts
186
+ import { readFile, stat } from "fs/promises";
187
+
188
+ // src/trace-analyst/store.ts
189
+ function compileSearchRegex(pattern) {
190
+ let source = pattern;
191
+ let flags = "m";
192
+ if (source.startsWith("(?i)")) {
193
+ source = source.slice(4);
194
+ flags += "i";
195
+ }
196
+ return new RegExp(source, flags);
197
+ }
198
+ function truncateForBudget(value, byteCap) {
199
+ const original = Buffer.byteLength(value, "utf8");
200
+ if (original <= byteCap) return value;
201
+ const ratio = byteCap / original;
202
+ let cut = Math.max(0, Math.floor(value.length * ratio));
203
+ while (cut > 0 && Buffer.byteLength(value.slice(0, cut), "utf8") > byteCap) {
204
+ cut -= 1;
205
+ }
206
+ return `${value.slice(0, cut)}
207
+ [trace-analyst truncated: original ${original} bytes]`;
208
+ }
209
+
210
+ // src/trace-analyst/store-otlp.ts
211
+ var INDEX_YIELD_LINES = 5e3;
212
+ function yieldToEventLoop() {
213
+ return new Promise((resolve) => setImmediate(resolve));
214
+ }
215
+ var DEFAULT_MAX_TRACE_FILE_BYTES = 256 * 1024 * 1024;
216
+ var OtlpFileTraceStore = class {
217
+ path;
218
+ perAttributeViewBudget;
219
+ perAttributeSpanBudget;
220
+ perCallByteCeiling;
221
+ perMatchTextBudget;
222
+ maxFileBytes;
223
+ indexPromise;
224
+ /** Cached UTF-8 buffer of the file. We pin it once because every
225
+ * read needs slice access and re-reading on each call balloons the
226
+ * syscall count. */
227
+ bufferPromise;
228
+ constructor(opts) {
229
+ this.path = opts.path;
230
+ this.perAttributeViewBudget = opts.perAttributeViewBudget ?? DEFAULT_TRACE_ANALYST_BUDGETS.perAttributeViewBudget;
231
+ this.perAttributeSpanBudget = opts.perAttributeSpanBudget ?? DEFAULT_TRACE_ANALYST_BUDGETS.perAttributeSpanBudget;
232
+ this.perCallByteCeiling = opts.perCallByteCeiling ?? DEFAULT_TRACE_ANALYST_BUDGETS.perCallByteCeiling;
233
+ this.perMatchTextBudget = opts.perMatchTextBudget ?? DEFAULT_TRACE_ANALYST_BUDGETS.perMatchTextBudget;
234
+ this.maxFileBytes = opts.maxFileBytes ?? DEFAULT_MAX_TRACE_FILE_BYTES;
235
+ }
236
+ // ─── Public API ────────────────────────────────────────────────────
237
+ async getOverview(filters) {
238
+ const idx = await this.index();
239
+ const matched = await this.matchedTraces(idx, filters);
240
+ const services = /* @__PURE__ */ new Set();
241
+ const agents = /* @__PURE__ */ new Set();
242
+ const models = /* @__PURE__ */ new Set();
243
+ const tools = /* @__PURE__ */ new Set();
244
+ let rawBytes = 0;
245
+ let earliest = null;
246
+ let latest = null;
247
+ let errorTraceCount = 0;
248
+ let errorSpanCount = 0;
249
+ const clusters = /* @__PURE__ */ new Map();
250
+ for (const t of matched) {
251
+ if (t.service_name) services.add(t.service_name);
252
+ if (t.agent_name) agents.add(t.agent_name);
253
+ for (const m of t.models) models.add(m);
254
+ for (const tn of t.tools) tools.add(tn);
255
+ rawBytes += t.raw_jsonl_bytes;
256
+ if (!earliest || compareSpanTime(t.start_time, earliest) < 0) earliest = t.start_time;
257
+ if (!latest || compareSpanTime(t.end_time, latest) > 0) latest = t.end_time;
258
+ if (t.has_errors) {
259
+ errorTraceCount += 1;
260
+ for (const s of t.spans) {
261
+ if (s.status !== "ERROR") continue;
262
+ errorSpanCount += 1;
263
+ accumulateErrorCluster(clusters, t.trace_id, s);
264
+ }
265
+ }
266
+ }
267
+ const sample_trace_ids = matched.slice(0, 20).map((t) => t.trace_id);
268
+ return {
269
+ total_traces: matched.length,
270
+ raw_jsonl_bytes: rawBytes,
271
+ services: [...services].sort(),
272
+ agents: [...agents].sort(),
273
+ models: [...models].sort(),
274
+ tool_names: [...tools].sort(),
275
+ sample_trace_ids,
276
+ errors: { trace_count: errorTraceCount, span_count: errorSpanCount },
277
+ error_clusters: finalizeErrorClusters(clusters, errorTraceCount),
278
+ time_range: earliest && latest ? { earliest, latest } : null
279
+ };
280
+ }
281
+ async queryTraces(opts) {
282
+ if (!Number.isInteger(opts.limit) || opts.limit < 1 || opts.limit > 200) {
283
+ throw new RangeError(`queryTraces.limit must be 1..200, got ${opts.limit}`);
284
+ }
285
+ const offset = opts.offset ?? 0;
286
+ if (!Number.isInteger(offset) || offset < 0) {
287
+ throw new RangeError(`queryTraces.offset must be >=0, got ${offset}`);
288
+ }
289
+ const idx = await this.index();
290
+ const matched = await this.matchedTraces(idx, opts.filters);
291
+ const slice = matched.slice(offset, offset + opts.limit);
292
+ return {
293
+ traces: slice.map((t) => this.toSummary(t)),
294
+ total: matched.length,
295
+ has_more: offset + slice.length < matched.length
296
+ };
297
+ }
298
+ async countTraces(filters) {
299
+ const idx = await this.index();
300
+ const matched = await this.matchedTraces(idx, filters);
301
+ return matched.length;
302
+ }
303
+ async viewTrace(opts) {
304
+ const idx = await this.index();
305
+ const trace = idx.byTrace.get(opts.trace_id);
306
+ if (!trace) {
307
+ throw new TraceNotFoundError(opts.trace_id);
308
+ }
309
+ const cap = opts.per_attribute_byte_cap ?? this.perAttributeViewBudget;
310
+ const buf = await this.buffer();
311
+ const spans = [];
312
+ let runningBytes = 0;
313
+ let span_response_bytes_max = 0;
314
+ const counter = { value: 0 };
315
+ for (const s of trace.spans) {
316
+ const projected = this.projectSpan(buf, trace.trace_id, s, cap, counter);
317
+ const bytes = Buffer.byteLength(JSON.stringify(projected), "utf8");
318
+ span_response_bytes_max = Math.max(span_response_bytes_max, bytes);
319
+ runningBytes += bytes;
320
+ if (runningBytes > this.perCallByteCeiling) {
321
+ return {
322
+ trace_id: trace.trace_id,
323
+ oversized: this.buildOversizedSummary(trace, span_response_bytes_max)
324
+ };
325
+ }
326
+ spans.push(projected);
327
+ }
328
+ return { trace_id: trace.trace_id, spans };
329
+ }
330
+ async viewSpans(opts) {
331
+ const idx = await this.index();
332
+ const trace = idx.byTrace.get(opts.trace_id);
333
+ if (!trace) throw new TraceNotFoundError(opts.trace_id);
334
+ if (opts.span_ids.length === 0) {
335
+ return {
336
+ trace_id: trace.trace_id,
337
+ spans: [],
338
+ missing_span_ids: [],
339
+ truncated_attribute_count: 0
340
+ };
341
+ }
342
+ if (opts.span_ids.length > 100) {
343
+ throw new RangeError(`viewSpans.span_ids cap is 100, got ${opts.span_ids.length}`);
344
+ }
345
+ const cap = opts.per_attribute_byte_cap ?? this.perAttributeSpanBudget;
346
+ const wantSet = new Set(opts.span_ids);
347
+ const found = trace.spans.filter((s) => wantSet.has(s.span_id));
348
+ const missing = opts.span_ids.filter((id) => !found.some((f2) => f2.span_id === id));
349
+ const buf = await this.buffer();
350
+ const spans = [];
351
+ const counter = { value: 0 };
352
+ let runningBytes = 0;
353
+ for (const s of found) {
354
+ const projected = this.projectSpan(buf, trace.trace_id, s, cap, counter);
355
+ const bytes = Buffer.byteLength(JSON.stringify(projected), "utf8");
356
+ runningBytes += bytes;
357
+ if (runningBytes > this.perCallByteCeiling) {
358
+ break;
359
+ }
360
+ spans.push(projected);
361
+ }
362
+ return {
363
+ trace_id: trace.trace_id,
364
+ spans,
365
+ missing_span_ids: missing,
366
+ truncated_attribute_count: counter.value
367
+ };
368
+ }
369
+ async searchTrace(opts) {
370
+ const max_matches = opts.max_matches ?? 50;
371
+ if (!Number.isInteger(max_matches) || max_matches < 1 || max_matches > 500) {
372
+ throw new RangeError(`searchTrace.max_matches must be 1..500, got ${max_matches}`);
373
+ }
374
+ const idx = await this.index();
375
+ const trace = idx.byTrace.get(opts.trace_id);
376
+ if (!trace) throw new TraceNotFoundError(opts.trace_id);
377
+ const re = compileSearchRegex(opts.regex_pattern);
378
+ const buf = await this.buffer();
379
+ const hits = [];
380
+ let total = 0;
381
+ let capped = false;
382
+ for (const s of trace.spans) {
383
+ const remaining = max_matches - hits.length;
384
+ const localHits = await this.scanSpanForMatches(
385
+ buf,
386
+ trace.trace_id,
387
+ s,
388
+ re,
389
+ this.perMatchTextBudget,
390
+ remaining
391
+ );
392
+ total += localHits.total;
393
+ for (const h of localHits.records) {
394
+ if (hits.length >= max_matches) break;
395
+ hits.push(h);
396
+ }
397
+ if (hits.length >= max_matches) {
398
+ capped = true;
399
+ break;
400
+ }
401
+ }
402
+ return {
403
+ trace_id: trace.trace_id,
404
+ hits,
405
+ // Uncapped: every span scanned to completion, so `total` is exact.
406
+ total_matches: capped ? hits.length : total,
407
+ has_more: capped || total > hits.length
408
+ };
409
+ }
410
+ async searchSpan(opts) {
411
+ const max_matches = opts.max_matches ?? 50;
412
+ if (!Number.isInteger(max_matches) || max_matches < 1 || max_matches > 500) {
413
+ throw new RangeError(`searchSpan.max_matches must be 1..500, got ${max_matches}`);
414
+ }
415
+ const idx = await this.index();
416
+ const trace = idx.byTrace.get(opts.trace_id);
417
+ if (!trace) throw new TraceNotFoundError(opts.trace_id);
418
+ const span = trace.spans.find((s) => s.span_id === opts.span_id);
419
+ if (!span) {
420
+ throw new SpanNotFoundError(opts.trace_id, opts.span_id);
421
+ }
422
+ const re = compileSearchRegex(opts.regex_pattern);
423
+ const buf = await this.buffer();
424
+ const localHits = await this.scanSpanForMatches(
425
+ buf,
426
+ trace.trace_id,
427
+ span,
428
+ re,
429
+ this.perMatchTextBudget,
430
+ max_matches
431
+ );
432
+ return {
433
+ trace_id: trace.trace_id,
434
+ span_id: span.span_id,
435
+ hits: localHits.records,
436
+ total_matches: localHits.total,
437
+ has_more: localHits.total > localHits.records.length
438
+ };
439
+ }
440
+ // ─── Index building ────────────────────────────────────────────────
441
+ /** Force the index to materialise. Useful to amortise startup cost
442
+ * before the first agent call. */
443
+ async ensureIndexed() {
444
+ await this.index();
445
+ }
446
+ async buffer() {
447
+ if (!this.bufferPromise) {
448
+ this.bufferPromise = this.readGuarded();
449
+ }
450
+ return this.bufferPromise;
451
+ }
452
+ /** Stat-then-read so an oversized file fails loud BEFORE we allocate a
453
+ * multi-hundred-MB Buffer and OOM the process. A missing file surfaces
454
+ * as TraceFileMissingError; any other stat/read error propagates. */
455
+ async readGuarded() {
456
+ let stats;
457
+ try {
458
+ stats = await stat(this.path);
459
+ } catch (err) {
460
+ if (err?.code === "ENOENT") {
461
+ throw new TraceFileMissingError(this.path);
462
+ }
463
+ throw err;
464
+ }
465
+ if (stats.size > this.maxFileBytes) {
466
+ throw new TraceFileTooLargeError(this.path, stats.size, this.maxFileBytes);
467
+ }
468
+ return readFile(this.path);
469
+ }
470
+ async index() {
471
+ if (!this.indexPromise) {
472
+ this.indexPromise = this.buildIndex();
473
+ }
474
+ return this.indexPromise;
475
+ }
476
+ async buildIndex() {
477
+ const buf = await this.buffer();
478
+ const byTrace = /* @__PURE__ */ new Map();
479
+ let cursor = 0;
480
+ let sinceYield = 0;
481
+ while (cursor < buf.length) {
482
+ if (++sinceYield >= INDEX_YIELD_LINES) {
483
+ sinceYield = 0;
484
+ await yieldToEventLoop();
485
+ }
486
+ const newlineIndex = buf.indexOf(10, cursor);
487
+ const lineEnd = newlineIndex === -1 ? buf.length : newlineIndex;
488
+ const lineLength = lineEnd - cursor;
489
+ if (lineLength === 0) {
490
+ cursor = lineEnd + 1;
491
+ continue;
492
+ }
493
+ const lineSlice = buf.subarray(cursor, lineEnd).toString("utf8");
494
+ const lineOffset = cursor;
495
+ cursor = lineEnd + 1;
496
+ let parsed;
497
+ try {
498
+ parsed = JSON.parse(lineSlice);
499
+ } catch {
500
+ continue;
501
+ }
502
+ if (!parsed || typeof parsed !== "object") continue;
503
+ const span = projectOtlpFlatLine(parsed);
504
+ if (!span) continue;
505
+ let entry = byTrace.get(span.trace_id);
506
+ if (!entry) {
507
+ entry = {
508
+ trace_id: span.trace_id,
509
+ service_name: span.service_name,
510
+ agent_name: span.agent_name,
511
+ span_count: 0,
512
+ has_errors: false,
513
+ start_time: span.start_time,
514
+ end_time: span.end_time,
515
+ duration_ms: 0,
516
+ raw_jsonl_bytes: 0,
517
+ models: /* @__PURE__ */ new Set(),
518
+ tools: /* @__PURE__ */ new Set(),
519
+ spans: []
520
+ };
521
+ byTrace.set(span.trace_id, entry);
522
+ } else {
523
+ if (!entry.service_name && span.service_name) entry.service_name = span.service_name;
524
+ if (!entry.agent_name && span.agent_name) entry.agent_name = span.agent_name;
525
+ }
526
+ const indexEntry = {
527
+ span_id: span.span_id,
528
+ parent_span_id: span.parent_span_id,
529
+ name: span.name,
530
+ kind: span.kind,
531
+ start_time: span.start_time,
532
+ end_time: span.end_time,
533
+ duration_ms: span.duration_ms,
534
+ status: span.status,
535
+ status_message: span.status_message,
536
+ service_name: span.service_name,
537
+ agent_name: span.agent_name,
538
+ model_name: span.model_name,
539
+ tool_name: span.tool_name,
540
+ line_byte_offset: lineOffset,
541
+ line_byte_length: lineLength
542
+ };
543
+ entry.spans.push(indexEntry);
544
+ entry.span_count += 1;
545
+ entry.raw_jsonl_bytes += lineLength + 1;
546
+ if (span.status === "ERROR") entry.has_errors = true;
547
+ if (compareSpanTime(span.start_time, entry.start_time) < 0) entry.start_time = span.start_time;
548
+ if (compareSpanTime(span.end_time, entry.end_time) > 0) entry.end_time = span.end_time;
549
+ if (span.model_name) entry.models.add(span.model_name);
550
+ if (span.tool_name) entry.tools.add(span.tool_name);
551
+ }
552
+ let totalRawBytes = 0;
553
+ for (const t of byTrace.values()) {
554
+ totalRawBytes += t.raw_jsonl_bytes;
555
+ t.spans.sort(
556
+ (a, b) => compareSpanTime(a.start_time, b.start_time) || a.line_byte_offset - b.line_byte_offset
557
+ );
558
+ const startMs = spanEpochMillis(t.start_time);
559
+ const endMs = spanEpochMillis(t.end_time);
560
+ t.duration_ms = startMs === null || endMs === null ? 0 : Math.max(0, endMs - startMs);
561
+ }
562
+ const sortedTraceIds = [...byTrace.keys()].sort();
563
+ return { byTrace, totalRawBytes, sortedTraceIds };
564
+ }
565
+ // ─── Filter pipeline ───────────────────────────────────────────────
566
+ async matchedTraces(idx, filters) {
567
+ const traces = idx.sortedTraceIds.map((id) => idx.byTrace.get(id)).filter(isPresent);
568
+ if (!filters) return traces;
569
+ const indexedFiltered = traces.filter((t) => {
570
+ if (filters.has_errors !== void 0 && t.has_errors !== filters.has_errors) return false;
571
+ if (filters.service_names && filters.service_names.length > 0) {
572
+ if (!t.service_name || !filters.service_names.includes(t.service_name)) return false;
573
+ }
574
+ if (filters.agent_names && filters.agent_names.length > 0) {
575
+ if (!t.agent_name || !filters.agent_names.includes(t.agent_name)) return false;
576
+ }
577
+ if (filters.model_names && filters.model_names.length > 0) {
578
+ if (![...t.models].some((m) => filters.model_names.includes(m))) return false;
579
+ }
580
+ if (filters.tool_names && filters.tool_names.length > 0) {
581
+ if (![...t.tools].some((tn) => filters.tool_names.includes(tn))) return false;
582
+ }
583
+ if (filters.start_time_after && t.start_time < filters.start_time_after) return false;
584
+ if (filters.start_time_before && t.start_time > filters.start_time_before) return false;
585
+ return true;
586
+ });
587
+ if (!filters.regex_pattern) return indexedFiltered;
588
+ const re = compileSearchRegex(filters.regex_pattern);
589
+ const buf = await this.buffer();
590
+ const out = [];
591
+ for (const t of indexedFiltered) {
592
+ let matched = false;
593
+ for (const s of t.spans) {
594
+ const slice = buf.subarray(s.line_byte_offset, s.line_byte_offset + s.line_byte_length);
595
+ if (re.test(slice.toString("utf8"))) {
596
+ matched = true;
597
+ break;
598
+ }
599
+ }
600
+ if (matched) out.push(t);
601
+ }
602
+ return out;
603
+ }
604
+ toSummary(t) {
605
+ return {
606
+ trace_id: t.trace_id,
607
+ service_name: t.service_name,
608
+ agent_name: t.agent_name,
609
+ span_count: t.span_count,
610
+ has_errors: t.has_errors,
611
+ start_time: t.start_time,
612
+ end_time: t.end_time,
613
+ duration_ms: t.duration_ms,
614
+ raw_jsonl_bytes: t.raw_jsonl_bytes,
615
+ models: [...t.models].sort(),
616
+ tools: [...t.tools].sort()
617
+ };
618
+ }
619
+ // ─── Span projection (lazy attribute reads) ────────────────────────
620
+ projectSpan(buf, trace_id, s, perAttrCap, counter) {
621
+ const slice = buf.subarray(s.line_byte_offset, s.line_byte_offset + s.line_byte_length).toString("utf8");
622
+ let raw = {};
623
+ try {
624
+ const parsed = JSON.parse(slice);
625
+ if (parsed && typeof parsed === "object") raw = parsed;
626
+ } catch {
627
+ }
628
+ const attrs = extractOtlpAttributes(raw);
629
+ const projected = {};
630
+ for (const [k, v] of Object.entries(attrs)) {
631
+ if (typeof v === "string") {
632
+ const trunc = truncateForBudget(v, perAttrCap);
633
+ if (trunc !== v) counter.value += 1;
634
+ projected[k] = trunc;
635
+ } else if (Array.isArray(v) || v && typeof v === "object") {
636
+ const json = JSON.stringify(v);
637
+ const trunc = truncateForBudget(json, perAttrCap);
638
+ if (trunc !== json) {
639
+ counter.value += 1;
640
+ projected[k] = trunc;
641
+ } else {
642
+ projected[k] = v;
643
+ }
644
+ } else {
645
+ projected[k] = v;
646
+ }
647
+ }
648
+ return {
649
+ trace_id,
650
+ span_id: s.span_id,
651
+ parent_span_id: s.parent_span_id,
652
+ name: s.name,
653
+ kind: s.kind,
654
+ start_time: s.start_time,
655
+ end_time: s.end_time,
656
+ duration_ms: s.duration_ms,
657
+ status: s.status,
658
+ status_message: s.status_message,
659
+ service_name: s.service_name,
660
+ agent_name: s.agent_name,
661
+ model_name: s.model_name,
662
+ tool_name: s.tool_name,
663
+ attributes: projected
664
+ };
665
+ }
666
+ buildOversizedSummary(t, span_response_bytes_max) {
667
+ const counts = /* @__PURE__ */ new Map();
668
+ let errorCount = 0;
669
+ for (const s of t.spans) {
670
+ counts.set(s.name, (counts.get(s.name) ?? 0) + 1);
671
+ if (s.status === "ERROR") errorCount += 1;
672
+ }
673
+ const top = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20);
674
+ return {
675
+ span_count: t.span_count,
676
+ top_span_names: top,
677
+ span_response_bytes_max,
678
+ error_span_count: errorCount
679
+ };
680
+ }
681
+ async scanSpanForMatches(buf, trace_id, s, re, textBudget, recordCap) {
682
+ const slice = buf.subarray(s.line_byte_offset, s.line_byte_offset + s.line_byte_length).toString("utf8");
683
+ const records = [];
684
+ const globalRe = new RegExp(re.source, re.flags.includes("g") ? re.flags : `${re.flags}g`);
685
+ let total = 0;
686
+ let hasMore = false;
687
+ let m = globalRe.exec(slice);
688
+ while (m !== null) {
689
+ total += 1;
690
+ if (m.index === globalRe.lastIndex) globalRe.lastIndex += 1;
691
+ if (records.length >= recordCap) {
692
+ hasMore = true;
693
+ break;
694
+ }
695
+ const before = slice.slice(Math.max(0, m.index - textBudget / 2), m.index);
696
+ const after = slice.slice(
697
+ m.index + m[0].length,
698
+ m.index + m[0].length + Math.floor(textBudget / 2)
699
+ );
700
+ records.push({
701
+ trace_id,
702
+ span_id: s.span_id,
703
+ span_name: s.name,
704
+ span_kind: s.kind,
705
+ attribute_path: bestAttributePathForOffset(slice, m.index) ?? "span.raw",
706
+ matched_text: truncateForBudget(m[0], textBudget),
707
+ context_before: truncateForBudget(before, textBudget),
708
+ context_after: truncateForBudget(after, textBudget),
709
+ match_offset: m.index
710
+ });
711
+ m = globalRe.exec(slice);
712
+ }
713
+ return { records, total, hasMore };
714
+ }
715
+ };
716
+ var TraceFileMissingError = class extends NotFoundError {
717
+ constructor(path) {
718
+ super(`trace file not found: ${path}`);
719
+ }
720
+ };
721
+ var TraceFileTooLargeError = class extends Error {
722
+ path;
723
+ size_bytes;
724
+ max_bytes;
725
+ constructor(path, size_bytes, max_bytes) {
726
+ super(
727
+ `trace file ${path} is ${size_bytes} bytes, over the ${max_bytes}-byte limit; raise OtlpFileTraceStoreOptions.maxFileBytes or pre-split the file`
728
+ );
729
+ this.path = path;
730
+ this.size_bytes = size_bytes;
731
+ this.max_bytes = max_bytes;
732
+ }
733
+ };
734
+ var TraceNotFoundError = class extends NotFoundError {
735
+ trace_id;
736
+ constructor(trace_id) {
737
+ super(`trace not found: ${trace_id}`);
738
+ this.trace_id = trace_id;
739
+ }
740
+ };
741
+ var SpanNotFoundError = class extends NotFoundError {
742
+ trace_id;
743
+ span_id;
744
+ constructor(trace_id, span_id) {
745
+ super(`span ${span_id} not found in trace ${trace_id}`);
746
+ this.trace_id = trace_id;
747
+ this.span_id = span_id;
748
+ }
749
+ };
750
+ function isPresent(v) {
751
+ return v !== void 0;
752
+ }
753
+ function isUnescapedQuote(slice, idx) {
754
+ if (slice[idx] !== '"') return false;
755
+ let backslashes = 0;
756
+ let b = idx - 1;
757
+ while (b >= 0 && slice[b] === "\\") {
758
+ backslashes += 1;
759
+ b -= 1;
760
+ }
761
+ return backslashes % 2 === 0;
762
+ }
763
+ function prevUnescapedQuote(slice, from) {
764
+ for (let i = from; i >= 0; i -= 1) {
765
+ if (slice[i] === '"' && isUnescapedQuote(slice, i)) return i;
766
+ }
767
+ return -1;
768
+ }
769
+ function bestAttributePathForOffset(slice, offset) {
770
+ const valueQuote = prevUnescapedQuote(slice, Math.min(offset, slice.length - 1));
771
+ if (valueQuote < 1) return null;
772
+ let j = valueQuote - 1;
773
+ while (j >= 0 && slice[j] !== ":") j -= 1;
774
+ if (j < 1) return null;
775
+ const keyClose = prevUnescapedQuote(slice, j - 1);
776
+ if (keyClose < 1) return null;
777
+ const keyOpen = prevUnescapedQuote(slice, keyClose - 1);
778
+ if (keyOpen < 0) return null;
779
+ return slice.slice(keyOpen + 1, keyClose);
780
+ }
781
+ var ERROR_CLUSTER_MAX = 50;
782
+ var ERROR_CLUSTER_EXEMPLARS = 5;
783
+ var SIGNATURE_MAX_CHARS = 160;
784
+ function normalizeErrorSignature(message, spanName) {
785
+ const raw = (message ?? "").trim();
786
+ const base = raw.length > 0 ? raw : `(${spanName || "error"} \u2014 no message)`;
787
+ const norm = base.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, "<id>").replace(/\b[0-9a-f]{12,}\b/gi, "<id>").replace(/(?:\/[\w.\-@]+){2,}/g, "<path>").replace(/\b\d+(?:\.\d+)?(ms|s|m|h|kb|mb|gb)?\b/gi, (_m, u) => u ? `#${u}` : "#").replace(/\s+/g, " ").trim();
788
+ return norm.length > SIGNATURE_MAX_CHARS ? `${norm.slice(0, SIGNATURE_MAX_CHARS)}\u2026` : norm;
789
+ }
790
+ function bump(map, key) {
791
+ if (!key) return;
792
+ map.set(key, (map.get(key) ?? 0) + 1);
793
+ }
794
+ function topKey(map) {
795
+ let best = null;
796
+ let bestN = 0;
797
+ for (const [k, n] of map)
798
+ if (n > bestN) {
799
+ best = k;
800
+ bestN = n;
801
+ }
802
+ return best;
803
+ }
804
+ function accumulateErrorCluster(clusters, traceId, span) {
805
+ const signature = normalizeErrorSignature(span.status_message, span.name);
806
+ let acc = clusters.get(signature);
807
+ if (!acc) {
808
+ acc = {
809
+ signature,
810
+ sample: (span.status_message ?? span.name ?? "").slice(0, 500),
811
+ traceIds: /* @__PURE__ */ new Set(),
812
+ spanIds: [],
813
+ spanCount: 0,
814
+ spanNames: /* @__PURE__ */ new Map(),
815
+ toolNames: /* @__PURE__ */ new Map()
816
+ };
817
+ clusters.set(signature, acc);
818
+ }
819
+ acc.traceIds.add(traceId);
820
+ acc.spanCount += 1;
821
+ if (acc.spanIds.length < ERROR_CLUSTER_EXEMPLARS && !acc.spanIds.includes(span.span_id)) {
822
+ acc.spanIds.push(span.span_id);
823
+ }
824
+ bump(acc.spanNames, span.name);
825
+ bump(acc.toolNames, span.tool_name);
826
+ }
827
+ function finalizeErrorClusters(clusters, errorTraceCount) {
828
+ const out = [...clusters.values()].map(
829
+ (acc) => ({
830
+ signature: acc.signature,
831
+ status_message_sample: acc.sample,
832
+ span_name: topKey(acc.spanNames),
833
+ tool_name: topKey(acc.toolNames),
834
+ trace_count: acc.traceIds.size,
835
+ span_count: acc.spanCount,
836
+ prevalence: errorTraceCount > 0 ? acc.traceIds.size / errorTraceCount : 0,
837
+ exemplar_trace_ids: [...acc.traceIds].slice(0, ERROR_CLUSTER_EXEMPLARS),
838
+ exemplar_span_ids: acc.spanIds.slice(0, ERROR_CLUSTER_EXEMPLARS)
839
+ })
840
+ );
841
+ out.sort((a, b) => b.trace_count - a.trace_count || b.span_count - a.span_count);
842
+ return out.slice(0, ERROR_CLUSTER_MAX);
843
+ }
844
+
845
+ // src/trace-analyst/tools.ts
846
+ import { f, fn } from "@ax-llm/ax";
847
+ var NAMESPACE = "traces";
848
+ var filtersField = f.json("Filter set. ALL fields are AND-composed. Leave empty to scan everything.").optional();
849
+ function buildTraceAnalystTools(opts) {
850
+ const { store } = opts;
851
+ const getDatasetOverview = fn("getDatasetOverview").description(
852
+ "Dataset rollup: total traces, raw_jsonl_bytes, services, agents, models, tools, and sample_trace_ids (real ids passable to view/search). Always call this FIRST without a regex_pattern."
853
+ ).namespace(NAMESPACE).arg("filters", filtersField).returns(f.json("DatasetOverview")).handler(async ({ filters }) => store.getOverview(parseFilters(filters))).build();
854
+ const queryTraces = fn("queryTraces").description(
855
+ "Paginated trace summaries. Each summary carries raw_jsonl_bytes \u2014 use it to size traces BEFORE calling viewTrace. Narrow with indexed filters before adding regex_pattern."
856
+ ).namespace(NAMESPACE).arg("filters", filtersField).arg("limit", f.number("Page size, 1..200")).arg("offset", f.number("Page offset; default 0").optional()).returns(f.json("QueryTracesPage")).handler(
857
+ async ({ filters, limit, offset }) => store.queryTraces({
858
+ filters: parseFilters(filters),
859
+ limit: assertPageLimit(limit),
860
+ offset: assertOffset(offset)
861
+ })
862
+ ).build();
863
+ const countTraces = fn("countTraces").description(
864
+ "Count traces matching `filters`. Use as a cheap pre-flight before opting into a regex_pattern scan."
865
+ ).namespace(NAMESPACE).arg("filters", filtersField).returns(f.number("count")).handler(async ({ filters }) => store.countTraces(parseFilters(filters))).build();
866
+ const viewTrace = fn("viewTrace").description(
867
+ "Return ALL spans for a single trace, with each attribute capped at ~4KB. If the response would exceed the per-call ceiling the result carries `oversized` instead of `spans` \u2014 DO NOT retry with the same trace_id; switch to searchTrace / viewSpans."
868
+ ).namespace(NAMESPACE).arg("trace_id", f.string("Real trace id from a prior overview/query")).returns(f.json("ViewTraceResult")).handler(
869
+ async ({ trace_id }) => store.viewTrace({ trace_id: assertString(trace_id, "trace_id") })
870
+ ).build();
871
+ const viewSpans = fn("viewSpans").description(
872
+ "Surgical read of specific spans within a trace, with each attribute capped at ~16KB (4\xD7 the discovery cap). Use after searchTrace narrows to specific span_ids."
873
+ ).namespace(NAMESPACE).arg("trace_id", f.string("Real trace id")).arg("span_ids", f.string("Span ids to fetch").array()).returns(f.json("ViewSpansResult")).handler(
874
+ async ({ trace_id, span_ids }) => store.viewSpans({
875
+ trace_id: assertString(trace_id, "trace_id"),
876
+ span_ids: assertStringArray(span_ids, "span_ids")
877
+ })
878
+ ).build();
879
+ const searchTrace = fn("searchTrace").description(
880
+ "Regex search across all spans of one trace. Returns `{trace_id, hits: SpanMatchRecord[], total_matches, has_more}`. **Iterate `result.hits`, NOT `result.matches`** \u2014 the field is `hits`. Each hit has `{span_id, span_name, span_kind, attribute_path, matched_text, context_before, context_after, match_offset}`. Bounded regardless of trace size by max_matches (1..500, default 50). If has_more=true, REFINE the regex rather than blindly raising max_matches."
881
+ ).namespace(NAMESPACE).arg("trace_id", f.string("Real trace id")).arg("regex_pattern", f.string("JS-compatible regex, multiline")).arg("max_matches", f.number("Max records returned, 1..500; default 50").optional()).returns(f.json("SearchTraceResult")).handler(
882
+ async ({ trace_id, regex_pattern, max_matches }) => store.searchTrace({
883
+ trace_id: assertString(trace_id, "trace_id"),
884
+ regex_pattern: assertRegex(regex_pattern),
885
+ max_matches: assertMaxMatches(max_matches)
886
+ })
887
+ ).build();
888
+ const searchSpan = fn("searchSpan").description(
889
+ "Regex search inside a single span. Use when viewSpans returned a 16KB-truncated payload and you need to narrow further. Returns `{trace_id, span_id, hits: SpanMatchRecord[], total_matches, has_more}` \u2014 iterate `result.hits`, NOT `result.matches`."
890
+ ).namespace(NAMESPACE).arg("trace_id", f.string("Real trace id")).arg("span_id", f.string("Real span id within trace")).arg("regex_pattern", f.string("JS-compatible regex, multiline")).arg("max_matches", f.number("Max records, 1..500; default 50").optional()).returns(f.json("SearchSpanResult")).handler(
891
+ async ({ trace_id, span_id, regex_pattern, max_matches }) => store.searchSpan({
892
+ trace_id: assertString(trace_id, "trace_id"),
893
+ span_id: assertString(span_id, "span_id"),
894
+ regex_pattern: assertRegex(regex_pattern),
895
+ max_matches: assertMaxMatches(max_matches)
896
+ })
897
+ ).build();
898
+ return [
899
+ getDatasetOverview,
900
+ queryTraces,
901
+ countTraces,
902
+ viewTrace,
903
+ viewSpans,
904
+ searchTrace,
905
+ searchSpan
906
+ ];
907
+ }
908
+ function traceAnalystFunctionGroup(opts) {
909
+ return {
910
+ namespace: NAMESPACE,
911
+ title: "Trace Analysis",
912
+ selectionCriteria: "Use for any inspection of OTLP-shaped trace data.",
913
+ description: "Discovery \u2192 narrow \u2192 deep-read tools over a JSONL trace dataset. Always call getDatasetOverview first.",
914
+ functions: buildTraceAnalystTools(opts)
915
+ };
916
+ }
917
+ function parseFilters(input) {
918
+ if (input == null) return void 0;
919
+ if (typeof input !== "object" || Array.isArray(input)) {
920
+ throw new TypeError(`filters must be an object, got ${typeof input}`);
921
+ }
922
+ const f2 = input;
923
+ const out = {};
924
+ if (typeof f2.has_errors === "boolean") out.has_errors = f2.has_errors;
925
+ out.service_names = stringArrayOrUndefined(f2.service_names, "service_names");
926
+ out.agent_names = stringArrayOrUndefined(f2.agent_names, "agent_names");
927
+ out.model_names = stringArrayOrUndefined(f2.model_names, "model_names");
928
+ out.tool_names = stringArrayOrUndefined(f2.tool_names, "tool_names");
929
+ if (typeof f2.start_time_after === "string") out.start_time_after = f2.start_time_after;
930
+ if (typeof f2.start_time_before === "string") out.start_time_before = f2.start_time_before;
931
+ if (typeof f2.regex_pattern === "string") {
932
+ if (f2.regex_pattern.length === 0) {
933
+ throw new TypeError("filters.regex_pattern cannot be empty");
934
+ }
935
+ out.regex_pattern = f2.regex_pattern;
936
+ }
937
+ return out;
938
+ }
939
+ function stringArrayOrUndefined(v, label) {
940
+ if (v === void 0 || v === null) return void 0;
941
+ if (!Array.isArray(v)) throw new TypeError(`${label} must be an array of strings`);
942
+ if (v.some((x) => typeof x !== "string")) {
943
+ throw new TypeError(`${label} entries must be strings`);
944
+ }
945
+ return v;
946
+ }
947
+ function assertPageLimit(limit) {
948
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 200) {
949
+ throw new RangeError(`limit must be an integer 1..200`);
950
+ }
951
+ return limit;
952
+ }
953
+ function assertOffset(offset) {
954
+ if (offset === void 0) return void 0;
955
+ if (typeof offset !== "number" || !Number.isInteger(offset) || offset < 0) {
956
+ throw new RangeError(`offset must be a non-negative integer`);
957
+ }
958
+ return offset;
959
+ }
960
+ function assertRegex(pattern) {
961
+ if (typeof pattern !== "string" || pattern.length === 0) {
962
+ throw new TypeError(`regex_pattern must be a non-empty string`);
963
+ }
964
+ new RegExp(pattern, "m");
965
+ return pattern;
966
+ }
967
+ function assertMaxMatches(n) {
968
+ if (n === void 0) return void 0;
969
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > 500) {
970
+ throw new RangeError(`max_matches must be an integer 1..500`);
971
+ }
972
+ return n;
973
+ }
974
+ function assertString(v, label) {
975
+ if (typeof v !== "string" || v.length === 0) {
976
+ throw new TypeError(`${label} must be a non-empty string`);
977
+ }
978
+ return v;
979
+ }
980
+ function assertStringArray(v, label) {
981
+ if (!Array.isArray(v)) throw new TypeError(`${label} must be an array of strings`);
982
+ if (v.some((x) => typeof x !== "string")) {
983
+ throw new TypeError(`${label} entries must be strings`);
984
+ }
985
+ return v;
986
+ }
987
+
988
+ // src/trace-analyst/loop.ts
989
+ import {
990
+ AxJSRuntime,
991
+ agent
992
+ } from "@ax-llm/ax";
993
+ var TRACE_ANALYSIS_FINAL_TASK = "Submit the completed trace analysis.";
994
+ var TRACE_ANALYSIS_COMPLETION_INSTRUCTION = `This host consumes your executor result directly; there is no downstream responder for this run. Ignore generic executor guidance that says a responder will format the answer. You must produce the final report and findings yourself.
995
+
996
+ When the analysis is complete, call \`await final(${JSON.stringify(TRACE_ANALYSIS_FINAL_TASK)}, { report, findings })\` exactly once. Do not return a one-argument string from \`final(...)\`.`;
997
+ async function runTraceAnalysisLoop(options) {
998
+ validateLoopLimits(options);
999
+ const config = {
1000
+ agentIdentity: { name: options.id, description: options.description },
1001
+ contextFields: [],
1002
+ runtime: new AxJSRuntime({
1003
+ permissions: [],
1004
+ blockDynamicImport: true,
1005
+ allowedModules: [],
1006
+ freezeIntrinsics: true,
1007
+ blockShadowRealm: true,
1008
+ preventGlobalThisExtensions: false
1009
+ }),
1010
+ maxSubAgentCalls: options.maxSubqueries,
1011
+ maxTurns: options.maxTurns,
1012
+ maxRuntimeChars: options.maxRuntimeChars,
1013
+ maxBatchedLlmQueryConcurrency: options.maxParallelSubqueries,
1014
+ promptLevel: "detailed",
1015
+ contextPolicy: { preset: "full", budget: "balanced" },
1016
+ functions: options.tools,
1017
+ executorOptions: {
1018
+ description: `${options.prompt.trim()}
1019
+
1020
+ ${TRACE_ANALYSIS_COMPLETION_INSTRUCTION}`,
1021
+ ...options.model ? { model: options.model } : {},
1022
+ showThoughts: false,
1023
+ thinkingTokenBudget: "none"
1024
+ },
1025
+ ...options.onTurn ? { actorTurnCallback: options.onTurn } : {},
1026
+ bubbleErrors: [TraceFileMissingError]
1027
+ };
1028
+ const analyst = options.findingType === "string" ? agent("question:string -> report:string, findings:string[]", config) : agent("question:string -> report:string, findings:json[]", config);
1029
+ const state = await analyst.executor.run(
1030
+ options.ai,
1031
+ { question: options.question },
1032
+ options.signal ? { abortSignal: options.signal } : void 0
1033
+ );
1034
+ let completed;
1035
+ try {
1036
+ completed = options.findingType === "string" ? readTraceAnalysisCompletion(state.executorResult, "string") : readTraceAnalysisCompletion(state.executorResult, "object");
1037
+ } catch (error) {
1038
+ throw new Error(`Trace analyst '${options.id}' stopped without a structured final result`, {
1039
+ cause: error
1040
+ });
1041
+ }
1042
+ return {
1043
+ ...completed,
1044
+ usage: analyst.executor.getUsage(),
1045
+ chatLog: analyst.executor.getChatLog(),
1046
+ turnCount: state.turnCount
1047
+ };
1048
+ }
1049
+ function readTraceAnalysisCompletion(value, findingType) {
1050
+ if (!value || typeof value !== "object") {
1051
+ throw new Error("Trace analyst did not return a structured final result");
1052
+ }
1053
+ const completion = value;
1054
+ if (completion.type !== "final" || !Array.isArray(completion.args) || completion.args.length !== 2 || completion.args[0] !== TRACE_ANALYSIS_FINAL_TASK) {
1055
+ throw new Error("Trace analyst did not return a structured final result");
1056
+ }
1057
+ const payload = completion.args[1];
1058
+ if (!payload || typeof payload !== "object") {
1059
+ throw new Error("Trace analyst final result must contain report and findings");
1060
+ }
1061
+ const { report, findings } = payload;
1062
+ if (typeof report !== "string" || !Array.isArray(findings)) {
1063
+ throw new Error("Trace analyst final result must contain report and findings");
1064
+ }
1065
+ if (findingType === "string") {
1066
+ if (findings.some((finding) => typeof finding !== "string")) {
1067
+ throw new Error("Trace analyst final result must contain string findings");
1068
+ }
1069
+ return { report, findings };
1070
+ }
1071
+ if (findings.some((finding) => !finding || typeof finding !== "object" || Array.isArray(finding))) {
1072
+ throw new Error("Trace analyst final result must contain object findings");
1073
+ }
1074
+ return { report, findings };
1075
+ }
1076
+ function validateLoopLimits(options) {
1077
+ if (!Number.isSafeInteger(options.maxSubqueries) || options.maxSubqueries < 0) {
1078
+ throw new TypeError("maxSubqueries must be a non-negative integer");
1079
+ }
1080
+ if (!Number.isSafeInteger(options.maxParallelSubqueries) || options.maxParallelSubqueries < 1) {
1081
+ throw new TypeError("maxParallelSubqueries must be a positive integer");
1082
+ }
1083
+ }
1084
+
1085
+ export {
1086
+ applyToolSpanOtlpAttributes,
1087
+ traceSpanKindToOpenInferenceKind,
1088
+ projectOtlpFlatLine,
1089
+ readOtlpStatus,
1090
+ inferOtlpKind,
1091
+ extractOtlpAttributes,
1092
+ stringField,
1093
+ asString,
1094
+ firstStringAttr,
1095
+ spanEpochMillis,
1096
+ compareSpanTime,
1097
+ DEFAULT_TRACE_ANALYST_BUDGETS,
1098
+ TRACE_ANALYST_TRUNCATION_MARKER_PREFIX,
1099
+ OtlpFileTraceStore,
1100
+ TraceFileMissingError,
1101
+ TraceNotFoundError,
1102
+ SpanNotFoundError,
1103
+ runTraceAnalysisLoop,
1104
+ buildTraceAnalystTools,
1105
+ traceAnalystFunctionGroup
1106
+ };
1107
+ //# sourceMappingURL=chunk-PXD6ZFNY.js.map