@m4trix/trace-viewer 0.16.0 → 0.17.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.
- package/README.md +30 -0
- package/dist/cli.js +1862 -21
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +222 -4
- package/dist/index.js +1833 -5
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { TraceStore, S3PayloadStoreAdapter, DynamoStructureStoreAdapter, resolveS3PayloadStoreOptionsFromEnv, resolveDynamoStructureStoreOptionsFromEnv, TraceViewerApi, FsPayloadStoreAdapter, FsStructureStoreAdapter } from '@m4trix/tracing';
|
|
2
2
|
import { resolve, relative, sep, extname, join, dirname } from 'path';
|
|
3
|
-
import {
|
|
3
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
4
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
4
5
|
import { z } from 'zod';
|
|
6
|
+
import { initTRPC } from '@trpc/server';
|
|
5
7
|
import { existsSync, statSync, readFileSync } from 'fs';
|
|
6
8
|
import http from 'http';
|
|
7
9
|
import { fileURLToPath } from 'url';
|
|
@@ -40,6 +42,7 @@ var CliParseError = class extends Error {
|
|
|
40
42
|
};
|
|
41
43
|
function parseCliArgs(argv) {
|
|
42
44
|
const args = argv.slice(2);
|
|
45
|
+
let command = "serve";
|
|
43
46
|
let adapter = "fs";
|
|
44
47
|
let path = DEFAULT_FS_RELATIVE_PATH;
|
|
45
48
|
let port = DEFAULT_PORT;
|
|
@@ -76,29 +79,40 @@ function parseCliArgs(argv) {
|
|
|
76
79
|
if (a.startsWith("-")) {
|
|
77
80
|
throw new CliParseError(`Unknown flag "${a}"`);
|
|
78
81
|
}
|
|
82
|
+
if (a === "mcp" || a === "serve") {
|
|
83
|
+
command = a;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
throw new CliParseError(`Unknown command "${a}" (expected serve | mcp)`);
|
|
79
87
|
}
|
|
80
88
|
if (adapter === "aws-stack") {
|
|
81
89
|
path = void 0;
|
|
82
90
|
} else if (!path) {
|
|
83
91
|
path = DEFAULT_FS_RELATIVE_PATH;
|
|
84
92
|
}
|
|
85
|
-
return { adapter, path, port };
|
|
93
|
+
return { command, adapter, path, port };
|
|
86
94
|
}
|
|
87
95
|
function cliHelpText(program) {
|
|
88
96
|
return `
|
|
89
97
|
${program} \u2014 local trace viewer (filesystem traces)
|
|
90
98
|
|
|
91
99
|
Usage:
|
|
92
|
-
${program} [--adapter fs|aws-stack] [--path <dir>] [--port <n>]
|
|
100
|
+
${program} [serve] [--adapter fs|aws-stack] [--path <dir>] [--port <n>]
|
|
101
|
+
${program} mcp [--adapter fs|aws-stack] [--path <dir>]
|
|
102
|
+
|
|
103
|
+
Commands:
|
|
104
|
+
serve Start the web viewer (default)
|
|
105
|
+
mcp Serve an MCP server over stdio for coding agents
|
|
93
106
|
|
|
94
107
|
Options:
|
|
95
108
|
--adapter fs|aws-stack Storage backend (default: fs)
|
|
96
109
|
--path <dir> Trace root for fs adapter (default: ${DEFAULT_FS_RELATIVE_PATH})
|
|
97
|
-
--port <n> HTTP port (default: ${DEFAULT_PORT})
|
|
110
|
+
--port <n> HTTP port for serve (default: ${DEFAULT_PORT})
|
|
98
111
|
-h, --help Show this help
|
|
99
112
|
|
|
100
113
|
Examples:
|
|
101
114
|
${program} --adapter fs --path ./tmp/tracing-example --port ${DEFAULT_PORT}
|
|
115
|
+
claude mcp add m4trix-traces -- npx ${program} mcp --path "$PWD/tmp/tracing-example"
|
|
102
116
|
`.trim();
|
|
103
117
|
}
|
|
104
118
|
function createFsTraceViewerApi(traceRootPath) {
|
|
@@ -109,6 +123,1820 @@ function createFsTraceViewerApi(traceRootPath) {
|
|
|
109
123
|
});
|
|
110
124
|
return TraceViewerApi.from(traceStore);
|
|
111
125
|
}
|
|
126
|
+
|
|
127
|
+
// src/app/lib/payload-mapper/json-path.ts
|
|
128
|
+
var IDENT = /^[A-Za-z_$][\w$-]*/;
|
|
129
|
+
function parsePath(path) {
|
|
130
|
+
const src = path.trim();
|
|
131
|
+
if (!src.startsWith("$")) return { ok: false, error: `Path must start with "$": ${path}` };
|
|
132
|
+
const segments = [];
|
|
133
|
+
let i = 1;
|
|
134
|
+
while (i < src.length) {
|
|
135
|
+
const ch = src[i];
|
|
136
|
+
if (ch === ".") {
|
|
137
|
+
const rest = src.slice(i + 1);
|
|
138
|
+
if (rest.startsWith("*")) {
|
|
139
|
+
segments.push({ type: "wildcard" });
|
|
140
|
+
i += 2;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const m = IDENT.exec(rest);
|
|
144
|
+
if (!m) return { ok: false, error: `Expected key after "." at ${i} in ${path}` };
|
|
145
|
+
segments.push({ type: "key", key: m[0] });
|
|
146
|
+
i += 1 + m[0].length;
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (ch === "[") {
|
|
150
|
+
const close = findBracketClose(src, i);
|
|
151
|
+
if (close < 0) return { ok: false, error: `Unclosed "[" at ${i} in ${path}` };
|
|
152
|
+
const inner = src.slice(i + 1, close).trim();
|
|
153
|
+
if (inner === "*") {
|
|
154
|
+
segments.push({ type: "wildcard" });
|
|
155
|
+
} else if (/^-?\d+$/.test(inner)) {
|
|
156
|
+
segments.push({ type: "index", index: Number(inner) });
|
|
157
|
+
} else if (inner.length >= 2 && (inner[0] === "'" || inner[0] === '"') && inner[inner.length - 1] === inner[0]) {
|
|
158
|
+
segments.push({ type: "key", key: inner.slice(1, -1) });
|
|
159
|
+
} else {
|
|
160
|
+
return { ok: false, error: `Unsupported bracket expression "[${inner}]" in ${path}` };
|
|
161
|
+
}
|
|
162
|
+
i = close + 1;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
return { ok: false, error: `Unexpected "${ch}" at ${i} in ${path}` };
|
|
166
|
+
}
|
|
167
|
+
return { ok: true, segments };
|
|
168
|
+
}
|
|
169
|
+
function findBracketClose(src, open) {
|
|
170
|
+
let quote = null;
|
|
171
|
+
for (let j = open + 1; j < src.length; j++) {
|
|
172
|
+
const c = src[j];
|
|
173
|
+
if (quote) {
|
|
174
|
+
if (c === quote) quote = null;
|
|
175
|
+
} else if (c === "'" || c === '"') {
|
|
176
|
+
quote = c;
|
|
177
|
+
} else if (c === "]") {
|
|
178
|
+
return j;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return -1;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// src/mcp/json-utils.ts
|
|
185
|
+
var IDENT2 = /^[A-Za-z_$][\w$-]*$/;
|
|
186
|
+
var MAX_DECODE_DEPTH = 64;
|
|
187
|
+
function isRecord(value) {
|
|
188
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
189
|
+
}
|
|
190
|
+
function appendKey(path, key) {
|
|
191
|
+
return IDENT2.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`;
|
|
192
|
+
}
|
|
193
|
+
function appendIndex(path, index) {
|
|
194
|
+
return `${path}[${index}]`;
|
|
195
|
+
}
|
|
196
|
+
function tryParseJsonString(value) {
|
|
197
|
+
const trimmed = value.trim();
|
|
198
|
+
if (trimmed.length < 2) return void 0;
|
|
199
|
+
const first = trimmed[0];
|
|
200
|
+
const last = trimmed[trimmed.length - 1];
|
|
201
|
+
if (!(first === "{" && last === "}" || first === "[" && last === "]")) return void 0;
|
|
202
|
+
try {
|
|
203
|
+
return JSON.parse(trimmed);
|
|
204
|
+
} catch {
|
|
205
|
+
return void 0;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function decodeJsonStrings(value, depth = 0) {
|
|
209
|
+
if (depth > MAX_DECODE_DEPTH) return value;
|
|
210
|
+
if (typeof value === "string") {
|
|
211
|
+
const parsed = tryParseJsonString(value);
|
|
212
|
+
return parsed === void 0 ? value : decodeJsonStrings(parsed, depth + 1);
|
|
213
|
+
}
|
|
214
|
+
if (Array.isArray(value)) return value.map((item) => decodeJsonStrings(item, depth + 1));
|
|
215
|
+
if (isRecord(value)) {
|
|
216
|
+
const out = {};
|
|
217
|
+
for (const [key, item] of Object.entries(value)) out[key] = decodeJsonStrings(item, depth + 1);
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
return value;
|
|
221
|
+
}
|
|
222
|
+
function flattenLeaves(value, path = "$", out = []) {
|
|
223
|
+
if (value === null || value === void 0) return out;
|
|
224
|
+
if (typeof value === "string") {
|
|
225
|
+
out.push({ path, text: value });
|
|
226
|
+
} else if (typeof value === "number" || typeof value === "boolean") {
|
|
227
|
+
out.push({ path, text: String(value) });
|
|
228
|
+
} else if (Array.isArray(value)) {
|
|
229
|
+
value.forEach((item, index) => {
|
|
230
|
+
flattenLeaves(item, appendIndex(path, index), out);
|
|
231
|
+
});
|
|
232
|
+
} else if (isRecord(value)) {
|
|
233
|
+
for (const [key, item] of Object.entries(value)) flattenLeaves(item, appendKey(path, key), out);
|
|
234
|
+
}
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
function evaluateWithPaths(scope, path) {
|
|
238
|
+
const parsed = parsePath(path);
|
|
239
|
+
if (!parsed.ok) return parsed;
|
|
240
|
+
let current = [{ path: "$", value: scope }];
|
|
241
|
+
for (const segment of parsed.segments) {
|
|
242
|
+
current = current.flatMap((match) => stepSegment(match, segment));
|
|
243
|
+
if (current.length === 0) break;
|
|
244
|
+
}
|
|
245
|
+
return { ok: true, matches: current.filter((match) => match.value !== void 0) };
|
|
246
|
+
}
|
|
247
|
+
function stepSegment(match, segment) {
|
|
248
|
+
const { value, path } = match;
|
|
249
|
+
if (value === null || typeof value !== "object") return [];
|
|
250
|
+
if (segment.type === "key") {
|
|
251
|
+
if (Array.isArray(value) || !Object.hasOwn(value, segment.key)) return [];
|
|
252
|
+
return [
|
|
253
|
+
{
|
|
254
|
+
path: appendKey(path, segment.key),
|
|
255
|
+
value: value[segment.key]
|
|
256
|
+
}
|
|
257
|
+
];
|
|
258
|
+
}
|
|
259
|
+
if (segment.type === "index") {
|
|
260
|
+
if (!Array.isArray(value)) return [];
|
|
261
|
+
const index = segment.index < 0 ? value.length + segment.index : segment.index;
|
|
262
|
+
if (index < 0 || index >= value.length) return [];
|
|
263
|
+
return [{ path: appendIndex(path, index), value: value[index] }];
|
|
264
|
+
}
|
|
265
|
+
if (Array.isArray(value)) {
|
|
266
|
+
return value.map((item, index) => ({ path: appendIndex(path, index), value: item }));
|
|
267
|
+
}
|
|
268
|
+
return Object.entries(value).map(([key, item]) => ({ path: appendKey(path, key), value: item }));
|
|
269
|
+
}
|
|
270
|
+
function oneLine(text) {
|
|
271
|
+
return text.replace(/\s*\n\s*/g, " \u23CE ");
|
|
272
|
+
}
|
|
273
|
+
function truncate(text, maxChars) {
|
|
274
|
+
if (text.length <= maxChars) return text;
|
|
275
|
+
return `${text.slice(0, Math.max(0, maxChars - 1))}\u2026`;
|
|
276
|
+
}
|
|
277
|
+
function safeStringify(value, indent) {
|
|
278
|
+
try {
|
|
279
|
+
return JSON.stringify(value, null, indent) ?? String(value);
|
|
280
|
+
} catch {
|
|
281
|
+
return String(value);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function payloadSize(value) {
|
|
285
|
+
return safeStringify(value).length;
|
|
286
|
+
}
|
|
287
|
+
function describeScalar(value, maxStringChars) {
|
|
288
|
+
if (value === null) return "null";
|
|
289
|
+
if (typeof value === "string") {
|
|
290
|
+
return `string(${value.length}) ${JSON.stringify(truncate(oneLine(value), maxStringChars))}`;
|
|
291
|
+
}
|
|
292
|
+
return `${typeof value} ${String(value)}`;
|
|
293
|
+
}
|
|
294
|
+
function outlinePayload(value, rootPath = "$", options = {}) {
|
|
295
|
+
const maxDepth = options.maxDepth ?? 4;
|
|
296
|
+
const maxLines = options.maxLines ?? 120;
|
|
297
|
+
const maxStringChars = options.maxStringChars ?? 80;
|
|
298
|
+
const maxArrayItems = options.maxArrayItems ?? 3;
|
|
299
|
+
const lines = [];
|
|
300
|
+
let truncated = false;
|
|
301
|
+
const visit = (node, path, depth) => {
|
|
302
|
+
if (lines.length >= maxLines) {
|
|
303
|
+
truncated = true;
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
const indent = " ".repeat(depth);
|
|
307
|
+
if (Array.isArray(node)) {
|
|
308
|
+
lines.push(`${indent}${path} array[${node.length}]`);
|
|
309
|
+
if (depth >= maxDepth) return;
|
|
310
|
+
node.slice(0, maxArrayItems).forEach((item, index) => {
|
|
311
|
+
visit(item, appendIndex(path, index), depth + 1);
|
|
312
|
+
});
|
|
313
|
+
if (node.length > maxArrayItems) {
|
|
314
|
+
lines.push(`${indent} \u2026 ${node.length - maxArrayItems} more items`);
|
|
315
|
+
}
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (isRecord(node)) {
|
|
319
|
+
const keys = Object.keys(node);
|
|
320
|
+
lines.push(`${indent}${path} object{${keys.length}}`);
|
|
321
|
+
if (depth >= maxDepth) return;
|
|
322
|
+
for (const key of keys) visit(node[key], appendKey(path, key), depth + 1);
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
lines.push(`${indent}${path} ${describeScalar(node, maxStringChars)}`);
|
|
326
|
+
};
|
|
327
|
+
visit(value, rootPath, 0);
|
|
328
|
+
if (truncated) lines.push(`\u2026 outline truncated at ${maxLines} lines; narrow it with \`path\`.`);
|
|
329
|
+
return lines.join("\n");
|
|
330
|
+
}
|
|
331
|
+
function previewPayload(value, maxChars) {
|
|
332
|
+
const json = safeStringify(value);
|
|
333
|
+
if (json.length <= maxChars) return json;
|
|
334
|
+
const outline = outlinePayload(value, "$", { maxDepth: 3, maxLines: 40 });
|
|
335
|
+
return `(${json.length} chars; outline shown \u2014 use get_payload for content)
|
|
336
|
+
${truncate(outline, maxChars)}`;
|
|
337
|
+
}
|
|
338
|
+
function snippetAround(text, start, length, context = 90) {
|
|
339
|
+
const from = Math.max(0, start - context);
|
|
340
|
+
const to = Math.min(text.length, start + length + context);
|
|
341
|
+
return `${from > 0 ? "\u2026" : ""}${oneLine(text.slice(from, to))}${to < text.length ? "\u2026" : ""}`;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/mcp/trace-access.ts
|
|
345
|
+
var MAX_TRACE_SCAN = 2e3;
|
|
346
|
+
var SCAN_PAGE_SIZE = 200;
|
|
347
|
+
var TraceToolError = class extends Error {
|
|
348
|
+
constructor(message) {
|
|
349
|
+
super(message);
|
|
350
|
+
this.name = "TraceToolError";
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
function shortId(id) {
|
|
354
|
+
return id.length > 12 ? id.slice(0, 8) : id;
|
|
355
|
+
}
|
|
356
|
+
function compareRunsByStartTime(left, right) {
|
|
357
|
+
return left.startTime.localeCompare(right.startTime) || left.runId.localeCompare(right.runId);
|
|
358
|
+
}
|
|
359
|
+
async function scanTraces(api, query, visit, maxScan = MAX_TRACE_SCAN) {
|
|
360
|
+
let cursor;
|
|
361
|
+
let scanned = 0;
|
|
362
|
+
while (scanned < maxScan) {
|
|
363
|
+
const page = await api.listTraces({
|
|
364
|
+
...query,
|
|
365
|
+
limit: Math.min(SCAN_PAGE_SIZE, maxScan - scanned),
|
|
366
|
+
...cursor ? { cursor } : {}
|
|
367
|
+
});
|
|
368
|
+
for (const trace of page.traces) {
|
|
369
|
+
scanned += 1;
|
|
370
|
+
if (!visit(trace)) return { scanned, exhausted: false };
|
|
371
|
+
}
|
|
372
|
+
if (!page.nextCursor || page.traces.length === 0) return { scanned, exhausted: true };
|
|
373
|
+
cursor = page.nextCursor;
|
|
374
|
+
}
|
|
375
|
+
return { scanned, exhausted: false };
|
|
376
|
+
}
|
|
377
|
+
async function resolveTrace(api, traceRef) {
|
|
378
|
+
const ref = traceRef.trim();
|
|
379
|
+
if (!ref) throw new TraceToolError("traceId is required.");
|
|
380
|
+
if (ref === "latest") {
|
|
381
|
+
const { traces } = await api.listTraces({ limit: 1 });
|
|
382
|
+
const latest = traces[0];
|
|
383
|
+
if (!latest) throw new TraceToolError("No traces found in the trace store.");
|
|
384
|
+
return requireRecord(api, latest.traceId);
|
|
385
|
+
}
|
|
386
|
+
const exact = await api.getTrace(ref).catch(() => null);
|
|
387
|
+
if (exact) return exact;
|
|
388
|
+
const candidates = [];
|
|
389
|
+
await scanTraces(api, {}, (trace) => {
|
|
390
|
+
if (trace.traceId.startsWith(ref)) candidates.push(trace.traceId);
|
|
391
|
+
return candidates.length < 6;
|
|
392
|
+
});
|
|
393
|
+
if (candidates.length === 0) throw new TraceToolError(`Trace "${ref}" not found.`);
|
|
394
|
+
if (candidates.length > 1) {
|
|
395
|
+
throw new TraceToolError(
|
|
396
|
+
`Trace prefix "${ref}" is ambiguous: ${candidates.join(", ")}. Use a longer prefix.`
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
return requireRecord(api, candidates[0]);
|
|
400
|
+
}
|
|
401
|
+
async function requireRecord(api, traceId) {
|
|
402
|
+
const record = await api.getTrace(traceId);
|
|
403
|
+
if (!record) throw new TraceToolError(`Trace "${traceId}" not found.`);
|
|
404
|
+
return record;
|
|
405
|
+
}
|
|
406
|
+
function resolveRun(record, runRef) {
|
|
407
|
+
const ref = runRef.trim();
|
|
408
|
+
const exact = record.runs.find((run) => run.runId === ref);
|
|
409
|
+
if (exact) return exact;
|
|
410
|
+
const candidates = record.runs.filter((run) => run.runId.startsWith(ref));
|
|
411
|
+
if (candidates.length === 1) return candidates[0];
|
|
412
|
+
if (candidates.length === 0) {
|
|
413
|
+
throw new TraceToolError(`Run "${ref}" not found in trace ${record.trace.traceId}.`);
|
|
414
|
+
}
|
|
415
|
+
throw new TraceToolError(
|
|
416
|
+
`Run prefix "${ref}" is ambiguous: ${candidates.map((run) => run.runId).join(", ")}.`
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
function buildRunForest(record) {
|
|
420
|
+
const byId = /* @__PURE__ */ new Map();
|
|
421
|
+
for (const run of record.runs) byId.set(run.runId, { ...run, depth: 0, children: [] });
|
|
422
|
+
const roots = [];
|
|
423
|
+
const orphanRunIds = [];
|
|
424
|
+
for (const node of byId.values()) {
|
|
425
|
+
const parent = node.parentRunId ? byId.get(node.parentRunId) : void 0;
|
|
426
|
+
if (parent) {
|
|
427
|
+
parent.children.push(node);
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
roots.push(node);
|
|
431
|
+
if (node.parentRunId) orphanRunIds.push(node.runId);
|
|
432
|
+
}
|
|
433
|
+
const assignDepth = (node, depth) => {
|
|
434
|
+
node.depth = depth;
|
|
435
|
+
node.children.sort(compareRunsByStartTime);
|
|
436
|
+
for (const child of node.children) assignDepth(child, depth + 1);
|
|
437
|
+
};
|
|
438
|
+
roots.sort((left, right) => {
|
|
439
|
+
if (left.runId === record.trace.rootRunId) return -1;
|
|
440
|
+
if (right.runId === record.trace.rootRunId) return 1;
|
|
441
|
+
return compareRunsByStartTime(left, right);
|
|
442
|
+
});
|
|
443
|
+
for (const root of roots) assignDepth(root, 0);
|
|
444
|
+
return { roots, byId, orphanRunIds };
|
|
445
|
+
}
|
|
446
|
+
function runAncestry(forest, runId) {
|
|
447
|
+
const chain = [];
|
|
448
|
+
const seen = /* @__PURE__ */ new Set();
|
|
449
|
+
let current = forest.byId.get(runId);
|
|
450
|
+
while (current && !seen.has(current.runId)) {
|
|
451
|
+
seen.add(current.runId);
|
|
452
|
+
chain.unshift(current);
|
|
453
|
+
current = current.parentRunId ? forest.byId.get(current.parentRunId) : void 0;
|
|
454
|
+
}
|
|
455
|
+
return chain;
|
|
456
|
+
}
|
|
457
|
+
function walkForest(forest, visit) {
|
|
458
|
+
const stack = [...forest.roots].reverse();
|
|
459
|
+
while (stack.length > 0) {
|
|
460
|
+
const node = stack.pop();
|
|
461
|
+
visit(node);
|
|
462
|
+
for (let i = node.children.length - 1; i >= 0; i--) stack.push(node.children[i]);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
function statusIcon(status) {
|
|
466
|
+
switch (status) {
|
|
467
|
+
case "success":
|
|
468
|
+
return "\u2713";
|
|
469
|
+
case "error":
|
|
470
|
+
return "\u2717";
|
|
471
|
+
default:
|
|
472
|
+
return "\u2026";
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
function formatMs(ms) {
|
|
476
|
+
if (ms === void 0 || !Number.isFinite(ms)) return "";
|
|
477
|
+
if (ms < 1e3) return `${Math.round(ms)}ms`;
|
|
478
|
+
if (ms < 6e4) return `${(ms / 1e3).toFixed(ms < 1e4 ? 2 : 1)}s`;
|
|
479
|
+
return `${Math.floor(ms / 6e4)}m${Math.round(ms % 6e4 / 1e3)}s`;
|
|
480
|
+
}
|
|
481
|
+
function formatTokens(tokens) {
|
|
482
|
+
if (!tokens) return "";
|
|
483
|
+
const cached = tokens.cached ? ` cached ${tokens.cached}` : "";
|
|
484
|
+
return `tok ${tokens.input}/${tokens.output}${cached}`;
|
|
485
|
+
}
|
|
486
|
+
function formatMetadata(metadata, maxEntries = 6) {
|
|
487
|
+
if (!metadata) return "";
|
|
488
|
+
const entries = Object.entries(metadata);
|
|
489
|
+
const shown = entries.slice(0, maxEntries).map(([key, value]) => `${key}=${String(value)}`);
|
|
490
|
+
if (entries.length > maxEntries) shown.push(`+${entries.length - maxEntries}`);
|
|
491
|
+
return shown.join(" ");
|
|
492
|
+
}
|
|
493
|
+
function formatTraceRow(trace) {
|
|
494
|
+
return [
|
|
495
|
+
trace.traceId,
|
|
496
|
+
`${statusIcon(trace.status)} ${trace.status}`,
|
|
497
|
+
trace.name,
|
|
498
|
+
trace.startTime,
|
|
499
|
+
formatMs(trace.latencyMs),
|
|
500
|
+
`${trace.runCount} runs`,
|
|
501
|
+
formatTokens(trace.tokens),
|
|
502
|
+
trace.costUsd !== void 0 ? `$${trace.costUsd.toFixed(4)}` : "",
|
|
503
|
+
trace.projectId ? `project=${trace.projectId}` : "",
|
|
504
|
+
formatMetadata(trace.metadata),
|
|
505
|
+
trace.annotation ? "[annotated]" : ""
|
|
506
|
+
].filter(Boolean).join(" ");
|
|
507
|
+
}
|
|
508
|
+
function formatRunLabel(run, options = {}) {
|
|
509
|
+
const errorChars = options.errorChars ?? 160;
|
|
510
|
+
const error = run.error && errorChars > 0 ? ` error: ${clip(run.error.message, errorChars)}` : "";
|
|
511
|
+
return [
|
|
512
|
+
`${statusIcon(run.status)} ${run.type} ${run.name}`,
|
|
513
|
+
formatMs(run.latencyMs),
|
|
514
|
+
formatTokens(run.tokens),
|
|
515
|
+
`[${shortId(run.runId)}]`
|
|
516
|
+
].filter(Boolean).join(" ").concat(error);
|
|
517
|
+
}
|
|
518
|
+
function clip(text, maxChars) {
|
|
519
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
520
|
+
return flat.length > maxChars ? `${flat.slice(0, maxChars - 1)}\u2026` : flat;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// src/mcp/analyze.ts
|
|
524
|
+
var ERROR_KEY = /(^|[.[\]"'])(error|errors|err|exception|error_message|errorMessage|stderr)["'\]]*$/i;
|
|
525
|
+
var ERROR_TEXT = /^(error|exception)\b|Traceback \(most recent call last\)|^\w*Error: /i;
|
|
526
|
+
var FALSY_TEXT = /* @__PURE__ */ new Set(["", "false", "0", "null", "none", "undefined"]);
|
|
527
|
+
var CALL_TYPES = /* @__PURE__ */ new Set(["tool", "llm", "chat_model", "retriever"]);
|
|
528
|
+
function analyzeTrace(record, forest, indexed, options = {}) {
|
|
529
|
+
const topN = options.topN ?? 5;
|
|
530
|
+
const repeatThreshold = options.repeatThreshold ?? 3;
|
|
531
|
+
const runs = [];
|
|
532
|
+
walkForest(forest, (node) => runs.push(node));
|
|
533
|
+
const pathOf = (runId) => runAncestry(forest, runId).map((node) => node.name).join(" \u203A ");
|
|
534
|
+
const sections = [];
|
|
535
|
+
const trace = record.trace;
|
|
536
|
+
sections.push(
|
|
537
|
+
`Trace ${trace.traceId} "${trace.name}" \u2014 ${trace.status}, ${runs.length} runs, ${formatMs(trace.latencyMs) || "no latency"}${indexed ? ", payloads loaded" : ", payloads NOT loaded (call load_trace_payloads for payload checks)"}`
|
|
538
|
+
);
|
|
539
|
+
const errorRuns = runs.filter((run) => run.status === "error");
|
|
540
|
+
if (errorRuns.length > 0) {
|
|
541
|
+
const hasErrorDescendant = (node) => node.children.some((child) => child.status === "error" || hasErrorDescendant(child));
|
|
542
|
+
const rootCauses = errorRuns.filter((run) => !hasErrorDescendant(run));
|
|
543
|
+
const lines = rootCauses.slice(0, topN * 2).map((run) => {
|
|
544
|
+
const error = run.error ? `${run.error.type ? `${run.error.type}: ` : ""}${run.error.message}` : "no error message recorded";
|
|
545
|
+
return `- ${formatRunLabel(run, { errorChars: 0 })}
|
|
546
|
+
path: ${pathOf(run.runId)}
|
|
547
|
+
error: ${truncate(oneLine(error), 500)}`;
|
|
548
|
+
});
|
|
549
|
+
sections.push(
|
|
550
|
+
`## Errors (${errorRuns.length} error runs, ${rootCauses.length} root cause${rootCauses.length === 1 ? "" : "s"})
|
|
551
|
+
${lines.join("\n")}`
|
|
552
|
+
);
|
|
553
|
+
} else if (trace.status === "error") {
|
|
554
|
+
sections.push("## Errors\n- Trace is marked error but no run has error status.");
|
|
555
|
+
}
|
|
556
|
+
if (trace.status === "success" && errorRuns.length > 0) {
|
|
557
|
+
sections.push(
|
|
558
|
+
"## Status mismatch\n- Trace succeeded although runs failed: errors were caught/retried upstream. Check that the fallback behaved as intended."
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
const unfinished = runs.filter((run) => run.status === "running");
|
|
562
|
+
if (unfinished.length > 0) {
|
|
563
|
+
const state = trace.status === "running" ? "trace is still running" : "trace finished, so these runs never ended (crash, lost callback, or missing flush)";
|
|
564
|
+
sections.push(
|
|
565
|
+
`## Unfinished runs (${unfinished.length}; ${state})
|
|
566
|
+
${unfinished.slice(0, topN * 2).map(
|
|
567
|
+
(run) => `- ${formatRunLabel(run)} started ${run.startTime}
|
|
568
|
+
path: ${pathOf(run.runId)}`
|
|
569
|
+
).join("\n")}`
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
if (forest.orphanRunIds.length > 0) {
|
|
573
|
+
sections.push(
|
|
574
|
+
`## Orphan runs (${forest.orphanRunIds.length}; parent run missing from store)
|
|
575
|
+
${forest.orphanRunIds.slice(0, topN * 2).map((runId) => {
|
|
576
|
+
const run = forest.byId.get(runId);
|
|
577
|
+
return `- ${formatRunLabel(run)} parent=${shortId(run.parentRunId ?? "")}`;
|
|
578
|
+
}).join("\n")}`
|
|
579
|
+
);
|
|
580
|
+
}
|
|
581
|
+
sections.push(latencySection(forest, runs, topN));
|
|
582
|
+
const tokenSection = tokenHotspots(runs, topN);
|
|
583
|
+
if (tokenSection) sections.push(tokenSection);
|
|
584
|
+
const repeats = repeatedCalls(runs, indexed, repeatThreshold, topN);
|
|
585
|
+
if (repeats) sections.push(repeats);
|
|
586
|
+
if (indexed) {
|
|
587
|
+
const hidden = hiddenErrors(runs, indexed, topN * 2, pathOf);
|
|
588
|
+
if (hidden) sections.push(hidden);
|
|
589
|
+
}
|
|
590
|
+
return sections.join("\n\n");
|
|
591
|
+
}
|
|
592
|
+
function latencySection(forest, runs, topN) {
|
|
593
|
+
const lines = [];
|
|
594
|
+
const root = forest.roots[0];
|
|
595
|
+
if (root?.latencyMs !== void 0) {
|
|
596
|
+
const chain = [];
|
|
597
|
+
let current = root;
|
|
598
|
+
while (current) {
|
|
599
|
+
chain.push(`${current.name} (${formatMs(current.latencyMs) || "?"})`);
|
|
600
|
+
current = [...current.children].filter((child) => child.latencyMs !== void 0).sort((left, right) => (right.latencyMs ?? 0) - (left.latencyMs ?? 0))[0];
|
|
601
|
+
}
|
|
602
|
+
lines.push(`critical path: ${chain.join(" \u203A ")}`);
|
|
603
|
+
}
|
|
604
|
+
const selfTimes = runs.filter((run) => run.latencyMs !== void 0).map((run) => {
|
|
605
|
+
const childTime = run.children.reduce((sum, child) => sum + (child.latencyMs ?? 0), 0);
|
|
606
|
+
return { run, self: Math.max(0, (run.latencyMs ?? 0) - childTime) };
|
|
607
|
+
}).filter((item) => item.self > 0).sort((left, right) => right.self - left.self).slice(0, topN);
|
|
608
|
+
if (selfTimes.length > 0) {
|
|
609
|
+
lines.push("largest self time (latency not explained by child runs):");
|
|
610
|
+
for (const { run, self } of selfTimes)
|
|
611
|
+
lines.push(`- ${formatMs(self)} self ${formatRunLabel(run)}`);
|
|
612
|
+
}
|
|
613
|
+
return `## Latency
|
|
614
|
+
${lines.join("\n") || "no latency data"}`;
|
|
615
|
+
}
|
|
616
|
+
function tokenHotspots(runs, topN) {
|
|
617
|
+
const withTokens = runs.filter((run) => run.tokens);
|
|
618
|
+
if (withTokens.length === 0) return null;
|
|
619
|
+
const hasTokenDescendant = (node) => node.children.some((child) => child.tokens !== void 0 || hasTokenDescendant(child));
|
|
620
|
+
const leaves = withTokens.filter((run) => !hasTokenDescendant(run));
|
|
621
|
+
const total = leaves.reduce(
|
|
622
|
+
(sum, run) => ({
|
|
623
|
+
input: sum.input + (run.tokens?.input ?? 0),
|
|
624
|
+
output: sum.output + (run.tokens?.output ?? 0)
|
|
625
|
+
}),
|
|
626
|
+
{ input: 0, output: 0 }
|
|
627
|
+
);
|
|
628
|
+
const top = [...leaves].sort((left, right) => totalTokens(right) - totalTokens(left)).slice(0, topN).map((run) => `- ${formatRunLabel(run)}`);
|
|
629
|
+
return `## Tokens (${leaves.length} runs, input ${total.input}, output ${total.output})
|
|
630
|
+
${top.join("\n")}`;
|
|
631
|
+
}
|
|
632
|
+
function totalTokens(run) {
|
|
633
|
+
return (run.tokens?.input ?? 0) + (run.tokens?.output ?? 0);
|
|
634
|
+
}
|
|
635
|
+
function repeatedCalls(runs, indexed, threshold, topN) {
|
|
636
|
+
const groups = /* @__PURE__ */ new Map();
|
|
637
|
+
for (const run of runs) {
|
|
638
|
+
if (!CALL_TYPES.has(run.type)) continue;
|
|
639
|
+
const input = indexed && run.inputRef ? indexed.payloads.get(run.inputRef)?.value : void 0;
|
|
640
|
+
const key = indexed ? `${run.type}\0${run.name}\0${safeStringify(input)}` : `${run.type}\0${run.name}`;
|
|
641
|
+
const group = groups.get(key) ?? [];
|
|
642
|
+
group.push(run);
|
|
643
|
+
groups.set(key, group);
|
|
644
|
+
}
|
|
645
|
+
const minCount = indexed ? threshold : threshold * 2;
|
|
646
|
+
const flagged = [...groups.values()].filter((group) => group.length >= minCount).sort((left, right) => right.length - left.length).slice(0, topN);
|
|
647
|
+
if (flagged.length === 0) return null;
|
|
648
|
+
const label = indexed ? "identical input" : "same name (load payloads to compare inputs)";
|
|
649
|
+
const lines = flagged.map((group) => {
|
|
650
|
+
const first = group[0];
|
|
651
|
+
const ids = group.slice(0, 6).map((run) => shortId(run.runId)).join(", ");
|
|
652
|
+
return `- ${group.length}\xD7 ${first.type} ${first.name} \u2014 ${ids}${group.length > 6 ? ", \u2026" : ""}`;
|
|
653
|
+
});
|
|
654
|
+
return `## Repeated calls (${label}; possible loop or missing cache)
|
|
655
|
+
${lines.join("\n")}`;
|
|
656
|
+
}
|
|
657
|
+
function hiddenErrors(runs, indexed, limit, pathOf) {
|
|
658
|
+
const seen = /* @__PURE__ */ new Set();
|
|
659
|
+
const lines = [];
|
|
660
|
+
for (const run of runs) {
|
|
661
|
+
if (run.status === "error" || !run.outputRef) continue;
|
|
662
|
+
const payload = indexed.payloads.get(run.outputRef);
|
|
663
|
+
if (!payload) continue;
|
|
664
|
+
for (const leaf of payload.leaves) {
|
|
665
|
+
const text = leaf.text.trim();
|
|
666
|
+
const errorish = ERROR_KEY.test(leaf.path) && !FALSY_TEXT.has(text.toLowerCase()) || ERROR_TEXT.test(text) || /\.(is_error|isError)$/.test(leaf.path) && text === "true" || /\.status$/.test(leaf.path) && text.toLowerCase() === "error";
|
|
667
|
+
if (!errorish || seen.has(text)) continue;
|
|
668
|
+
seen.add(text);
|
|
669
|
+
lines.push(
|
|
670
|
+
`- ${formatRunLabel(run)} output ${leaf.path}
|
|
671
|
+
path: ${pathOf(run.runId)}
|
|
672
|
+
value: ${truncate(oneLine(text), 300)}`
|
|
673
|
+
);
|
|
674
|
+
if (lines.length >= limit) break;
|
|
675
|
+
}
|
|
676
|
+
if (lines.length >= limit) break;
|
|
677
|
+
}
|
|
678
|
+
if (lines.length === 0) return null;
|
|
679
|
+
return `## Error-like values in successful runs (handled or swallowed errors)
|
|
680
|
+
${lines.join("\n")}`;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// src/mcp/conversation.ts
|
|
684
|
+
var LANGCHAIN_ROLE_BY_CLASS = {
|
|
685
|
+
HumanMessage: "user",
|
|
686
|
+
AIMessage: "assistant",
|
|
687
|
+
SystemMessage: "system",
|
|
688
|
+
ToolMessage: "tool",
|
|
689
|
+
FunctionMessage: "function",
|
|
690
|
+
ChatMessage: "chat"
|
|
691
|
+
};
|
|
692
|
+
var LANGCHAIN_ROLE_BY_TYPE = {
|
|
693
|
+
human: "user",
|
|
694
|
+
ai: "assistant",
|
|
695
|
+
system: "system",
|
|
696
|
+
tool: "tool",
|
|
697
|
+
function: "function",
|
|
698
|
+
developer: "developer"
|
|
699
|
+
};
|
|
700
|
+
var MAX_WALK_DEPTH = 8;
|
|
701
|
+
function normalizeMessage(value) {
|
|
702
|
+
if (!isRecord(value)) return null;
|
|
703
|
+
if (value.lc === 1 && value.type === "constructor" && Array.isArray(value.id) && isRecord(value.kwargs)) {
|
|
704
|
+
const className = String(value.id[value.id.length - 1] ?? "").replace(/Chunk$/, "");
|
|
705
|
+
if (!className.endsWith("Message")) return null;
|
|
706
|
+
const role = LANGCHAIN_ROLE_BY_CLASS[className] ?? (typeof value.kwargs.role === "string" ? value.kwargs.role : className);
|
|
707
|
+
return fromFields(role, value.kwargs);
|
|
708
|
+
}
|
|
709
|
+
if (typeof value.role === "string" && ("content" in value || "tool_calls" in value)) {
|
|
710
|
+
return fromFields(value.role, value);
|
|
711
|
+
}
|
|
712
|
+
if (typeof value.type === "string" && LANGCHAIN_ROLE_BY_TYPE[value.type] && "content" in value) {
|
|
713
|
+
return fromFields(LANGCHAIN_ROLE_BY_TYPE[value.type], value);
|
|
714
|
+
}
|
|
715
|
+
return null;
|
|
716
|
+
}
|
|
717
|
+
function fromFields(role, fields) {
|
|
718
|
+
const { text, toolCalls: contentToolCalls, toolResultIds } = renderContent(fields.content);
|
|
719
|
+
const additional = isRecord(fields.additional_kwargs) ? fields.additional_kwargs : void 0;
|
|
720
|
+
const toolCalls = [
|
|
721
|
+
...contentToolCalls,
|
|
722
|
+
...normalizeToolCalls(fields.tool_calls),
|
|
723
|
+
...Array.isArray(fields.tool_calls) && fields.tool_calls.length > 0 ? [] : normalizeToolCalls(additional?.tool_calls)
|
|
724
|
+
];
|
|
725
|
+
const toolCallId = (typeof fields.tool_call_id === "string" ? fields.tool_call_id : void 0) ?? toolResultIds[0];
|
|
726
|
+
return {
|
|
727
|
+
role,
|
|
728
|
+
...typeof fields.name === "string" && fields.name ? { name: fields.name } : {},
|
|
729
|
+
text,
|
|
730
|
+
toolCalls,
|
|
731
|
+
...toolCallId ? { toolCallId } : {}
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
function renderContent(content) {
|
|
735
|
+
if (typeof content === "string") return { text: content, toolCalls: [], toolResultIds: [] };
|
|
736
|
+
if (!Array.isArray(content)) {
|
|
737
|
+
return {
|
|
738
|
+
text: content === void 0 || content === null ? "" : safeStringify(content),
|
|
739
|
+
toolCalls: [],
|
|
740
|
+
toolResultIds: []
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
const parts = [];
|
|
744
|
+
const toolCalls = [];
|
|
745
|
+
const toolResultIds = [];
|
|
746
|
+
for (const part of content) {
|
|
747
|
+
if (typeof part === "string") {
|
|
748
|
+
parts.push(part);
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
if (!isRecord(part)) continue;
|
|
752
|
+
switch (part.type) {
|
|
753
|
+
case "text":
|
|
754
|
+
case "input_text":
|
|
755
|
+
case "output_text":
|
|
756
|
+
parts.push(String(part.text ?? ""));
|
|
757
|
+
break;
|
|
758
|
+
case "thinking":
|
|
759
|
+
case "reasoning":
|
|
760
|
+
parts.push(`[thinking] ${String(part.thinking ?? part.text ?? part.reasoning ?? "")}`);
|
|
761
|
+
break;
|
|
762
|
+
case "tool_use":
|
|
763
|
+
toolCalls.push({
|
|
764
|
+
name: String(part.name ?? "unknown"),
|
|
765
|
+
args: part.input,
|
|
766
|
+
...typeof part.id === "string" ? { id: part.id } : {}
|
|
767
|
+
});
|
|
768
|
+
break;
|
|
769
|
+
case "tool_result": {
|
|
770
|
+
if (typeof part.tool_use_id === "string") toolResultIds.push(part.tool_use_id);
|
|
771
|
+
const inner = renderContent(part.content).text;
|
|
772
|
+
parts.push(`${part.is_error ? "[tool_result error] " : ""}${inner}`);
|
|
773
|
+
break;
|
|
774
|
+
}
|
|
775
|
+
case "image":
|
|
776
|
+
case "image_url":
|
|
777
|
+
case "input_image":
|
|
778
|
+
parts.push("[image]");
|
|
779
|
+
break;
|
|
780
|
+
default:
|
|
781
|
+
parts.push(safeStringify(part));
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return { text: parts.join("\n"), toolCalls, toolResultIds };
|
|
785
|
+
}
|
|
786
|
+
function normalizeToolCalls(value) {
|
|
787
|
+
if (!Array.isArray(value)) return [];
|
|
788
|
+
return value.filter(isRecord).map((call) => {
|
|
789
|
+
const fn = isRecord(call.function) ? call.function : void 0;
|
|
790
|
+
const name = String(call.name ?? fn?.name ?? "unknown");
|
|
791
|
+
let args = call.args ?? call.input ?? fn?.arguments;
|
|
792
|
+
if (typeof args === "string") {
|
|
793
|
+
try {
|
|
794
|
+
args = JSON.parse(args);
|
|
795
|
+
} catch {
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
return { name, args, ...typeof call.id === "string" ? { id: call.id } : {} };
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
function extractMessageSequences(value) {
|
|
802
|
+
const sequences = [];
|
|
803
|
+
const visit = (node, path, depth) => {
|
|
804
|
+
if (depth > MAX_WALK_DEPTH || node === null || typeof node !== "object") return;
|
|
805
|
+
if (Array.isArray(node)) {
|
|
806
|
+
const messages = node.map(normalizeMessage);
|
|
807
|
+
const count = messages.filter(Boolean).length;
|
|
808
|
+
if (count > 0 && count * 2 >= node.length) {
|
|
809
|
+
sequences.push({
|
|
810
|
+
path,
|
|
811
|
+
messages: messages.filter((message) => message !== null)
|
|
812
|
+
});
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
node.forEach((item, index) => {
|
|
816
|
+
visit(item, appendIndex(path, index), depth + 1);
|
|
817
|
+
});
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
const single = normalizeMessage(node);
|
|
821
|
+
if (single) {
|
|
822
|
+
sequences.push({ path, messages: [single] });
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
for (const [key, item] of Object.entries(node)) visit(item, appendKey(path, key), depth + 1);
|
|
826
|
+
};
|
|
827
|
+
visit(value, "$", 0);
|
|
828
|
+
return sequences;
|
|
829
|
+
}
|
|
830
|
+
function formatMessages(messages, options = {}) {
|
|
831
|
+
const maxChars = options.maxCharsPerMessage ?? 2e3;
|
|
832
|
+
return messages.map((message, index) => {
|
|
833
|
+
const head = [
|
|
834
|
+
`#${index} ${message.role}`,
|
|
835
|
+
message.name ? `(${message.name})` : "",
|
|
836
|
+
message.toolCallId ? `[tool_call_id ${message.toolCallId}]` : ""
|
|
837
|
+
].filter(Boolean).join(" ");
|
|
838
|
+
const lines = [`${head}: ${truncate(message.text, maxChars)}`];
|
|
839
|
+
for (const call of message.toolCalls) {
|
|
840
|
+
const id = call.id ? ` id=${call.id}` : "";
|
|
841
|
+
lines.push(
|
|
842
|
+
` \u21B3 tool_call ${call.name}${id} ${truncate(oneLine(safeStringify(call.args)), 400)}`
|
|
843
|
+
);
|
|
844
|
+
}
|
|
845
|
+
return lines.join("\n");
|
|
846
|
+
}).join("\n");
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// src/mcp/diff.ts
|
|
850
|
+
function diffJson(before, after, maxChanges = 200) {
|
|
851
|
+
const changes = [];
|
|
852
|
+
let truncated = false;
|
|
853
|
+
const push = (change) => {
|
|
854
|
+
if (changes.length >= maxChanges) {
|
|
855
|
+
truncated = true;
|
|
856
|
+
return false;
|
|
857
|
+
}
|
|
858
|
+
changes.push(change);
|
|
859
|
+
return true;
|
|
860
|
+
};
|
|
861
|
+
const visit = (left, right, path) => {
|
|
862
|
+
if (truncated) return;
|
|
863
|
+
if (Array.isArray(left) && Array.isArray(right)) {
|
|
864
|
+
const length = Math.max(left.length, right.length);
|
|
865
|
+
for (let i = 0; i < length && !truncated; i++) {
|
|
866
|
+
const childPath = appendIndex(path, i);
|
|
867
|
+
if (i >= left.length) push({ kind: "added", path: childPath, after: right[i] });
|
|
868
|
+
else if (i >= right.length) push({ kind: "removed", path: childPath, before: left[i] });
|
|
869
|
+
else visit(left[i], right[i], childPath);
|
|
870
|
+
}
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
if (isRecord(left) && isRecord(right)) {
|
|
874
|
+
const keys = /* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)]);
|
|
875
|
+
for (const key of keys) {
|
|
876
|
+
if (truncated) return;
|
|
877
|
+
const childPath = appendKey(path, key);
|
|
878
|
+
if (!Object.hasOwn(left, key)) push({ kind: "added", path: childPath, after: right[key] });
|
|
879
|
+
else if (!Object.hasOwn(right, key))
|
|
880
|
+
push({ kind: "removed", path: childPath, before: left[key] });
|
|
881
|
+
else visit(left[key], right[key], childPath);
|
|
882
|
+
}
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
if (!Object.is(left, right) && safeStringify(left) !== safeStringify(right)) {
|
|
886
|
+
push({ kind: "changed", path, before: left, after: right });
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
visit(before, after, "$");
|
|
890
|
+
return { changes, truncated };
|
|
891
|
+
}
|
|
892
|
+
function brief(value, maxChars) {
|
|
893
|
+
return truncate(oneLine(safeStringify(value)), maxChars);
|
|
894
|
+
}
|
|
895
|
+
function formatJsonChanges(changes, maxValueChars = 200) {
|
|
896
|
+
return changes.map((change) => {
|
|
897
|
+
switch (change.kind) {
|
|
898
|
+
case "added":
|
|
899
|
+
return `+ ${change.path}: ${brief(change.after, maxValueChars)}`;
|
|
900
|
+
case "removed":
|
|
901
|
+
return `- ${change.path}: ${brief(change.before, maxValueChars)}`;
|
|
902
|
+
default:
|
|
903
|
+
return `~ ${change.path}: ${brief(change.before, maxValueChars)} \u2192 ${brief(change.after, maxValueChars)}`;
|
|
904
|
+
}
|
|
905
|
+
}).join("\n");
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// src/mcp/payload-index.ts
|
|
909
|
+
var DEFAULT_MAX_CHARS = 2e8;
|
|
910
|
+
var DEFAULT_CONCURRENCY = 8;
|
|
911
|
+
function payloadRefsOf(run) {
|
|
912
|
+
const refs = [];
|
|
913
|
+
if (run.inputRef) refs.push({ ref: run.inputRef, side: "input" });
|
|
914
|
+
if (run.outputRef) refs.push({ ref: run.outputRef, side: "output" });
|
|
915
|
+
return refs;
|
|
916
|
+
}
|
|
917
|
+
var PayloadIndex = class {
|
|
918
|
+
constructor(api, options = {}) {
|
|
919
|
+
this.api = api;
|
|
920
|
+
this.maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;
|
|
921
|
+
this.concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
|
|
922
|
+
}
|
|
923
|
+
traces = /* @__PURE__ */ new Map();
|
|
924
|
+
maxChars;
|
|
925
|
+
concurrency;
|
|
926
|
+
/** Loaded traces, most recently used last. */
|
|
927
|
+
loadedTraces() {
|
|
928
|
+
return [...this.traces.values()];
|
|
929
|
+
}
|
|
930
|
+
get(traceId) {
|
|
931
|
+
return this.traces.get(traceId);
|
|
932
|
+
}
|
|
933
|
+
totalSize() {
|
|
934
|
+
let total = 0;
|
|
935
|
+
for (const entry of this.traces.values()) total += entry.size;
|
|
936
|
+
return total;
|
|
937
|
+
}
|
|
938
|
+
isFullyLoaded(record) {
|
|
939
|
+
const entry = this.traces.get(record.trace.traceId);
|
|
940
|
+
if (!entry) return false;
|
|
941
|
+
return record.runs.every(
|
|
942
|
+
(run) => payloadRefsOf(run).every(({ ref }) => entry.payloads.has(ref))
|
|
943
|
+
);
|
|
944
|
+
}
|
|
945
|
+
/** Cached payload for a ref, if its trace is loaded. */
|
|
946
|
+
getPayload(traceId, ref) {
|
|
947
|
+
return this.traces.get(traceId)?.payloads.get(ref);
|
|
948
|
+
}
|
|
949
|
+
unload(traceId) {
|
|
950
|
+
return this.traces.delete(traceId);
|
|
951
|
+
}
|
|
952
|
+
async loadTrace(record) {
|
|
953
|
+
const traceId = record.trace.traceId;
|
|
954
|
+
const existing = this.traces.get(traceId);
|
|
955
|
+
const entry = existing ?? {
|
|
956
|
+
trace: record.trace,
|
|
957
|
+
runs: /* @__PURE__ */ new Map(),
|
|
958
|
+
payloads: /* @__PURE__ */ new Map(),
|
|
959
|
+
size: 0,
|
|
960
|
+
failures: []
|
|
961
|
+
};
|
|
962
|
+
entry.trace = record.trace;
|
|
963
|
+
entry.runs = new Map(record.runs.map((run) => [run.runId, run]));
|
|
964
|
+
const pending = record.runs.flatMap(
|
|
965
|
+
(run) => payloadRefsOf(run).filter(({ ref }) => !entry.payloads.has(ref)).map(({ ref, side }) => ({ ref, side, runId: run.runId }))
|
|
966
|
+
);
|
|
967
|
+
const alreadyLoaded = record.runs.reduce((sum, run) => sum + payloadRefsOf(run).length, 0) - pending.length;
|
|
968
|
+
const failed = [];
|
|
969
|
+
let loaded = 0;
|
|
970
|
+
await forEachConcurrent(pending, this.concurrency, async (item) => {
|
|
971
|
+
try {
|
|
972
|
+
const raw = await this.api.getPayload(item.ref);
|
|
973
|
+
const value = decodeJsonStrings(raw);
|
|
974
|
+
const size = payloadSize(raw);
|
|
975
|
+
entry.payloads.set(item.ref, {
|
|
976
|
+
ref: item.ref,
|
|
977
|
+
runId: item.runId,
|
|
978
|
+
side: item.side,
|
|
979
|
+
value,
|
|
980
|
+
leaves: flattenLeaves(value),
|
|
981
|
+
size
|
|
982
|
+
});
|
|
983
|
+
entry.size += size;
|
|
984
|
+
loaded += 1;
|
|
985
|
+
} catch (error) {
|
|
986
|
+
failed.push({
|
|
987
|
+
ref: item.ref,
|
|
988
|
+
message: error instanceof Error ? error.message : String(error)
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
entry.failures = failed;
|
|
993
|
+
this.traces.delete(traceId);
|
|
994
|
+
this.traces.set(traceId, entry);
|
|
995
|
+
const evicted = this.evict(traceId);
|
|
996
|
+
return {
|
|
997
|
+
traceId,
|
|
998
|
+
traceName: record.trace.name,
|
|
999
|
+
status: record.trace.status,
|
|
1000
|
+
loaded,
|
|
1001
|
+
alreadyLoaded,
|
|
1002
|
+
failed,
|
|
1003
|
+
size: entry.size,
|
|
1004
|
+
evicted
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
evict(keepTraceId) {
|
|
1008
|
+
const evicted = [];
|
|
1009
|
+
let total = this.totalSize();
|
|
1010
|
+
for (const [traceId, entry] of this.traces) {
|
|
1011
|
+
if (total <= this.maxChars) break;
|
|
1012
|
+
if (traceId === keepTraceId) continue;
|
|
1013
|
+
this.traces.delete(traceId);
|
|
1014
|
+
total -= entry.size;
|
|
1015
|
+
evicted.push(traceId);
|
|
1016
|
+
}
|
|
1017
|
+
return evicted;
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
async function forEachConcurrent(items, concurrency, task) {
|
|
1021
|
+
let next = 0;
|
|
1022
|
+
const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
|
|
1023
|
+
while (next < items.length) {
|
|
1024
|
+
const item = items[next++];
|
|
1025
|
+
await task(item);
|
|
1026
|
+
}
|
|
1027
|
+
});
|
|
1028
|
+
await Promise.all(workers);
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
// src/mcp/run-query.ts
|
|
1032
|
+
function runMatchesFilter(run, filter, namePattern) {
|
|
1033
|
+
if (filter.type?.length && !filter.type.includes(run.type)) return false;
|
|
1034
|
+
if (namePattern && !namePattern.test(run.name)) return false;
|
|
1035
|
+
if (filter.status && run.status !== filter.status) return false;
|
|
1036
|
+
if (filter.errorContains) {
|
|
1037
|
+
const message = run.error?.message.toLowerCase() ?? "";
|
|
1038
|
+
if (!message.includes(filter.errorContains.toLowerCase())) return false;
|
|
1039
|
+
}
|
|
1040
|
+
if (filter.minLatencyMs !== void 0 && (run.latencyMs ?? -1) < filter.minLatencyMs)
|
|
1041
|
+
return false;
|
|
1042
|
+
if (filter.minTokens !== void 0) {
|
|
1043
|
+
const tokens = run.tokens ? run.tokens.input + run.tokens.output : -1;
|
|
1044
|
+
if (tokens < filter.minTokens) return false;
|
|
1045
|
+
}
|
|
1046
|
+
if (filter.maxDepth !== void 0 && run.depth > filter.maxDepth) return false;
|
|
1047
|
+
return metadataMatches(run.metadata, filter.metadata);
|
|
1048
|
+
}
|
|
1049
|
+
function metadataMatches(metadata, expected) {
|
|
1050
|
+
if (!expected) return true;
|
|
1051
|
+
return Object.entries(expected).every(
|
|
1052
|
+
([key, value]) => metadata?.[key] !== void 0 && String(metadata[key]) === String(value)
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
function traceMatchesFilter(trace, filter, namePattern) {
|
|
1056
|
+
if (filter.status && trace.status !== filter.status) return false;
|
|
1057
|
+
if (filter.projectId && trace.projectId !== filter.projectId) return false;
|
|
1058
|
+
if (namePattern && !namePattern.test(trace.name)) return false;
|
|
1059
|
+
if (filter.minLatencyMs !== void 0 && (trace.latencyMs ?? -1) < filter.minLatencyMs)
|
|
1060
|
+
return false;
|
|
1061
|
+
if (filter.annotated !== void 0 && trace.annotation !== void 0 !== filter.annotated)
|
|
1062
|
+
return false;
|
|
1063
|
+
return metadataMatches(trace.metadata, filter.metadata);
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
// src/mcp/search.ts
|
|
1067
|
+
function compileSearchPattern(query) {
|
|
1068
|
+
const flags = query.caseSensitive ? "" : "i";
|
|
1069
|
+
const source = query.regex ? query.query : query.query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1070
|
+
return new RegExp(source, flags);
|
|
1071
|
+
}
|
|
1072
|
+
function searchPayloads(traces, query) {
|
|
1073
|
+
const pattern = compileSearchPattern(query);
|
|
1074
|
+
const runNamePattern = query.runName ? new RegExp(query.runName, "i") : null;
|
|
1075
|
+
const runTypes = query.runType?.length ? new Set(query.runType) : null;
|
|
1076
|
+
const side = query.side ?? "both";
|
|
1077
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1078
|
+
let totalOccurrences = 0;
|
|
1079
|
+
let searchedPayloads = 0;
|
|
1080
|
+
for (const entry of traces) {
|
|
1081
|
+
const payloads = [...entry.payloads.values()].map((payload) => {
|
|
1082
|
+
const run = entry.runs.get(payload.runId);
|
|
1083
|
+
const at = run && payload.side === "output" ? run.endTime ?? run.startTime : run?.startTime;
|
|
1084
|
+
return { payload, run, at: at ?? "" };
|
|
1085
|
+
}).filter(
|
|
1086
|
+
(item) => item.run !== void 0
|
|
1087
|
+
).sort(
|
|
1088
|
+
(left, right) => left.at.localeCompare(right.at) || (left.payload.side === right.payload.side ? 0 : left.payload.side === "input" ? -1 : 1) || compareRunsByStartTime(left.run, right.run)
|
|
1089
|
+
);
|
|
1090
|
+
for (const { payload, run } of payloads) {
|
|
1091
|
+
if (side !== "both" && payload.side !== side) continue;
|
|
1092
|
+
if (runTypes && !runTypes.has(run.type)) continue;
|
|
1093
|
+
if (runNamePattern && !runNamePattern.test(run.name)) continue;
|
|
1094
|
+
searchedPayloads += 1;
|
|
1095
|
+
for (const leaf of payload.leaves) {
|
|
1096
|
+
if (query.pathPrefix && !leaf.path.startsWith(query.pathPrefix)) continue;
|
|
1097
|
+
const match = pattern.exec(leaf.text);
|
|
1098
|
+
if (!match) continue;
|
|
1099
|
+
totalOccurrences += 1;
|
|
1100
|
+
const occurrence = {
|
|
1101
|
+
traceId: entry.trace.traceId,
|
|
1102
|
+
run,
|
|
1103
|
+
side: payload.side,
|
|
1104
|
+
path: leaf.path
|
|
1105
|
+
};
|
|
1106
|
+
const group = groups.get(leaf.text);
|
|
1107
|
+
if (group) {
|
|
1108
|
+
group.occurrences.push(occurrence);
|
|
1109
|
+
continue;
|
|
1110
|
+
}
|
|
1111
|
+
groups.set(leaf.text, {
|
|
1112
|
+
snippet: snippetAround(leaf.text, match.index, match[0].length),
|
|
1113
|
+
valueLength: leaf.text.length,
|
|
1114
|
+
first: occurrence,
|
|
1115
|
+
occurrences: [occurrence]
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
return { groups: [...groups.values()], totalOccurrences, searchedPayloads };
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
// src/mcp/tree-outline.ts
|
|
1124
|
+
var DEFAULT_HIDE_PATTERN = "^(ChannelWrite<.*>|Branch<.*>|__start__|__end__)$";
|
|
1125
|
+
function renderTreeOutline(roots, options = {}) {
|
|
1126
|
+
const maxNodes = options.maxNodes ?? 200;
|
|
1127
|
+
const maxDepth = options.maxDepth ?? Number.POSITIVE_INFINITY;
|
|
1128
|
+
const lines = [];
|
|
1129
|
+
let shown = 0;
|
|
1130
|
+
let hidden = 0;
|
|
1131
|
+
let omitted = 0;
|
|
1132
|
+
const countSubtree = (node) => 1 + node.children.reduce((sum, child) => sum + countSubtree(child), 0);
|
|
1133
|
+
const visit = (node, level) => {
|
|
1134
|
+
const isHidden = node.status !== "error" && options.hide?.test(node.name) === true;
|
|
1135
|
+
if (isHidden) {
|
|
1136
|
+
hidden += 1;
|
|
1137
|
+
for (const child of node.children) visit(child, level);
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
if (shown >= maxNodes) {
|
|
1141
|
+
omitted += countSubtree(node);
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
shown += 1;
|
|
1145
|
+
lines.push(`${" ".repeat(level)}${formatRunLabel(node)}`);
|
|
1146
|
+
if (level + 1 > maxDepth) {
|
|
1147
|
+
const below = node.children.reduce((sum, child) => sum + countSubtree(child), 0);
|
|
1148
|
+
if (below > 0) {
|
|
1149
|
+
lines.push(`${" ".repeat(level + 1)}\u2026 ${below} runs below max depth`);
|
|
1150
|
+
omitted += below;
|
|
1151
|
+
}
|
|
1152
|
+
return;
|
|
1153
|
+
}
|
|
1154
|
+
for (const child of node.children) visit(child, level + 1);
|
|
1155
|
+
};
|
|
1156
|
+
for (const root of roots) visit(root, 0);
|
|
1157
|
+
if (shown >= maxNodes && omitted > 0) {
|
|
1158
|
+
lines.push(`\u2026 output capped at ${maxNodes} runs; use focusRunId or maxDepth to narrow.`);
|
|
1159
|
+
}
|
|
1160
|
+
return { text: lines.join("\n"), shown, hidden, omitted };
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
// src/mcp/trace-tools.ts
|
|
1164
|
+
var MAX_AUTO_LOAD_TRACES = 20;
|
|
1165
|
+
function compileUserRegex(pattern, label, flags = "i") {
|
|
1166
|
+
try {
|
|
1167
|
+
return new RegExp(pattern, flags);
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
throw new TraceToolError(
|
|
1170
|
+
`Invalid ${label} regex: ${error instanceof Error ? error.message : String(error)}`
|
|
1171
|
+
);
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
function plural(count, word) {
|
|
1175
|
+
return `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
1176
|
+
}
|
|
1177
|
+
var TraceTools = class {
|
|
1178
|
+
constructor(api, options = {}) {
|
|
1179
|
+
this.api = api;
|
|
1180
|
+
this.index = new PayloadIndex(api, options.index);
|
|
1181
|
+
}
|
|
1182
|
+
index;
|
|
1183
|
+
async listTraces(input) {
|
|
1184
|
+
const limit = input.limit ?? 20;
|
|
1185
|
+
const offset = input.offset ?? 0;
|
|
1186
|
+
const namePattern = input.name ? compileUserRegex(input.name, "name") : null;
|
|
1187
|
+
const matches = [];
|
|
1188
|
+
const { scanned, exhausted } = await scanTraces(
|
|
1189
|
+
this.api,
|
|
1190
|
+
{
|
|
1191
|
+
...input.status ? { status: input.status } : {},
|
|
1192
|
+
...input.projectId ? { projectId: input.projectId } : {},
|
|
1193
|
+
...input.since ? { startAfter: input.since } : {},
|
|
1194
|
+
...input.until ? { startBefore: input.until } : {}
|
|
1195
|
+
},
|
|
1196
|
+
(trace) => {
|
|
1197
|
+
if (traceMatchesFilter(trace, input, namePattern)) matches.push(trace);
|
|
1198
|
+
return matches.length <= offset + limit;
|
|
1199
|
+
}
|
|
1200
|
+
);
|
|
1201
|
+
const page = matches.slice(offset, offset + limit);
|
|
1202
|
+
if (page.length === 0) {
|
|
1203
|
+
return offset > 0 ? `No traces at offset ${offset}.` : "No traces match.";
|
|
1204
|
+
}
|
|
1205
|
+
const hasMore = matches.length > offset + limit;
|
|
1206
|
+
const lines = page.map((trace) => {
|
|
1207
|
+
const loaded = this.index.get(trace.traceId) ? " [payloads loaded]" : "";
|
|
1208
|
+
return `${formatTraceRow(trace)}${loaded}`;
|
|
1209
|
+
});
|
|
1210
|
+
const footer = hasMore ? `More traces available: call again with offset=${offset + limit}.` : !exhausted && scanned >= MAX_TRACE_SCAN ? `Scan stopped after ${MAX_TRACE_SCAN} traces; narrow with since/until/status.` : "";
|
|
1211
|
+
return [`${plural(page.length, "trace")} (newest first, offset ${offset}):`, ...lines, footer].filter(Boolean).join("\n");
|
|
1212
|
+
}
|
|
1213
|
+
async getTrace(input) {
|
|
1214
|
+
const record = await resolveTrace(this.api, input.traceId);
|
|
1215
|
+
const forest = buildRunForest(record);
|
|
1216
|
+
const hide = input.hide === void 0 ? DEFAULT_HIDE_PATTERN : input.hide;
|
|
1217
|
+
const hidePattern = hide ? compileUserRegex(hide, "hide", "") : null;
|
|
1218
|
+
let roots = forest.roots;
|
|
1219
|
+
let focusLine = "";
|
|
1220
|
+
if (input.focusRunId) {
|
|
1221
|
+
const run = resolveRun(record, input.focusRunId);
|
|
1222
|
+
const node = forest.byId.get(run.runId);
|
|
1223
|
+
roots = [node];
|
|
1224
|
+
focusLine = `focus: ${runAncestry(forest, run.runId).map((ancestor) => ancestor.name).join(" \u203A ")}`;
|
|
1225
|
+
}
|
|
1226
|
+
const outline = renderTreeOutline(roots, {
|
|
1227
|
+
hide: hidePattern,
|
|
1228
|
+
maxDepth: input.maxDepth,
|
|
1229
|
+
maxNodes: input.maxNodes
|
|
1230
|
+
});
|
|
1231
|
+
const notes = [
|
|
1232
|
+
outline.hidden > 0 ? `${plural(outline.hidden, "run")} hidden by pattern /${hide}/ (pass hide: "" to show all)` : "",
|
|
1233
|
+
forest.orphanRunIds.length > 0 ? `${plural(forest.orphanRunIds.length, "orphan run")} shown as extra roots` : "",
|
|
1234
|
+
this.index.get(record.trace.traceId) ? "payloads loaded" : ""
|
|
1235
|
+
].filter(Boolean);
|
|
1236
|
+
const header = [
|
|
1237
|
+
formatTraceRow(record.trace),
|
|
1238
|
+
record.trace.annotation ? `annotation: ${truncate(safeStringify(record.trace.annotation), 600)}` : "",
|
|
1239
|
+
focusLine,
|
|
1240
|
+
notes.length > 0 ? `(${notes.join("; ")})` : ""
|
|
1241
|
+
].filter(Boolean);
|
|
1242
|
+
return `${header.join("\n")}
|
|
1243
|
+
|
|
1244
|
+
${outline.text}`;
|
|
1245
|
+
}
|
|
1246
|
+
async findRuns(input) {
|
|
1247
|
+
const limit = input.limit ?? 50;
|
|
1248
|
+
const namePattern = input.name ? compileUserRegex(input.name, "name") : null;
|
|
1249
|
+
const records = await this.resolveTraceScope(input.traceIds, input.traceLimit ?? 20);
|
|
1250
|
+
const sections = [];
|
|
1251
|
+
let total = 0;
|
|
1252
|
+
let shown = 0;
|
|
1253
|
+
for (const record of records) {
|
|
1254
|
+
const forest = buildRunForest(record);
|
|
1255
|
+
const lines = [];
|
|
1256
|
+
walkForest(forest, (node) => {
|
|
1257
|
+
if (!runMatchesFilter(node, input, namePattern)) return;
|
|
1258
|
+
total += 1;
|
|
1259
|
+
if (shown >= limit) return;
|
|
1260
|
+
shown += 1;
|
|
1261
|
+
const parent = node.parentRunId ? forest.byId.get(node.parentRunId) : void 0;
|
|
1262
|
+
lines.push(
|
|
1263
|
+
`- ${formatRunLabel(node)} depth ${node.depth}${parent ? ` parent ${parent.name}` : ""}`
|
|
1264
|
+
);
|
|
1265
|
+
});
|
|
1266
|
+
if (lines.length > 0) {
|
|
1267
|
+
sections.push(
|
|
1268
|
+
`trace ${record.trace.traceId} "${record.trace.name}" (${record.trace.status})
|
|
1269
|
+
${lines.join("\n")}`
|
|
1270
|
+
);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
if (total === 0) return `No runs match in ${plural(records.length, "trace")}.`;
|
|
1274
|
+
const footer = total > shown ? `
|
|
1275
|
+
${total - shown} more matches; raise limit or narrow the filter.` : "";
|
|
1276
|
+
return `${plural(total, "matching run")} in ${plural(records.length, "searched trace")}:
|
|
1277
|
+
|
|
1278
|
+
${sections.join("\n\n")}${footer}`;
|
|
1279
|
+
}
|
|
1280
|
+
async getRun(input) {
|
|
1281
|
+
const previewChars = input.previewChars ?? 1500;
|
|
1282
|
+
const record = await resolveTrace(this.api, input.traceId);
|
|
1283
|
+
const run = resolveRun(record, input.runId);
|
|
1284
|
+
const forest = buildRunForest(record);
|
|
1285
|
+
const node = forest.byId.get(run.runId);
|
|
1286
|
+
const lines = [
|
|
1287
|
+
formatRunLabel(run, { errorChars: 0 }),
|
|
1288
|
+
`runId: ${run.runId}`,
|
|
1289
|
+
`traceId: ${run.traceId}`,
|
|
1290
|
+
`path: ${runAncestry(forest, run.runId).map((ancestor) => ancestor.name).join(" \u203A ")}`,
|
|
1291
|
+
`time: ${run.startTime} \u2192 ${run.endTime ?? "(not ended)"}${run.latencyMs !== void 0 ? ` (${formatMs(run.latencyMs)})` : ""}`,
|
|
1292
|
+
run.tokens ? `tokens: ${formatTokens(run.tokens)}` : "",
|
|
1293
|
+
run.costUsd !== void 0 ? `cost: $${run.costUsd}` : "",
|
|
1294
|
+
run.error ? `error: ${run.error.type ? `${run.error.type}: ` : ""}${run.error.message}` : "",
|
|
1295
|
+
run.metadata ? `metadata: ${formatMetadata(run.metadata, 50)}` : "",
|
|
1296
|
+
run.annotation ? `annotation: ${truncate(safeStringify(run.annotation), 1e3)}` : "",
|
|
1297
|
+
run.extra ? `extra: ${truncate(safeStringify(run.extra), 600)}` : ""
|
|
1298
|
+
];
|
|
1299
|
+
if (node.children.length > 0) {
|
|
1300
|
+
lines.push(`children (${node.children.length}):`);
|
|
1301
|
+
for (const child of node.children.slice(0, 30)) lines.push(` ${formatRunLabel(child)}`);
|
|
1302
|
+
if (node.children.length > 30) lines.push(` \u2026 ${node.children.length - 30} more`);
|
|
1303
|
+
}
|
|
1304
|
+
for (const side of ["input", "output"]) {
|
|
1305
|
+
const ref = side === "input" ? run.inputRef : run.outputRef;
|
|
1306
|
+
if (!ref) {
|
|
1307
|
+
lines.push(`${side}: (none)`);
|
|
1308
|
+
continue;
|
|
1309
|
+
}
|
|
1310
|
+
try {
|
|
1311
|
+
const value = await this.loadPayloadValue(record.trace.traceId, ref);
|
|
1312
|
+
lines.push(`${side}: ${previewPayload(value, previewChars)}`);
|
|
1313
|
+
} catch (error) {
|
|
1314
|
+
lines.push(
|
|
1315
|
+
`${side}: failed to load ${ref}: ${error instanceof Error ? error.message : String(error)}`
|
|
1316
|
+
);
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
return lines.filter(Boolean).join("\n");
|
|
1320
|
+
}
|
|
1321
|
+
async getPayload(input) {
|
|
1322
|
+
const maxChars = input.maxChars ?? 12e3;
|
|
1323
|
+
const offset = input.offset ?? 0;
|
|
1324
|
+
const mode = input.mode ?? "auto";
|
|
1325
|
+
const { ref, traceId, label } = await this.resolvePayloadRef(input);
|
|
1326
|
+
const value = await this.loadPayloadValue(traceId, ref);
|
|
1327
|
+
let target = value;
|
|
1328
|
+
let targetPath = "$";
|
|
1329
|
+
if (input.path && input.path.trim() !== "$") {
|
|
1330
|
+
const result = evaluateWithPaths(value, input.path);
|
|
1331
|
+
if (!result.ok) throw new TraceToolError(result.error);
|
|
1332
|
+
if (result.matches.length === 0) {
|
|
1333
|
+
return `${label}
|
|
1334
|
+
Path ${input.path} matched nothing. Top-level structure:
|
|
1335
|
+
${outlinePayload(value, "$", { maxDepth: 1 })}`;
|
|
1336
|
+
}
|
|
1337
|
+
if (result.matches.length === 1) {
|
|
1338
|
+
target = result.matches[0].value;
|
|
1339
|
+
targetPath = result.matches[0].path;
|
|
1340
|
+
} else {
|
|
1341
|
+
const listed = result.matches.slice(0, 50).map((match) => `${match.path}: ${previewPayload(match.value, 300)}`);
|
|
1342
|
+
const more = result.matches.length > 50 ? `
|
|
1343
|
+
\u2026 ${result.matches.length - 50} more matches` : "";
|
|
1344
|
+
return truncate(
|
|
1345
|
+
`${label}
|
|
1346
|
+
${result.matches.length} matches for ${input.path}:
|
|
1347
|
+
${listed.join("\n")}${more}`,
|
|
1348
|
+
maxChars
|
|
1349
|
+
);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
const header = `${label}${targetPath !== "$" ? ` at ${targetPath}` : ""}`;
|
|
1353
|
+
if (mode === "outline") {
|
|
1354
|
+
return `${header}
|
|
1355
|
+
${outlinePayload(target, targetPath, { maxDepth: input.outlineDepth ?? 4 })}`;
|
|
1356
|
+
}
|
|
1357
|
+
const body = typeof target === "string" ? target : safeStringify(target, 2);
|
|
1358
|
+
if (mode === "auto" && offset === 0 && body.length > maxChars) {
|
|
1359
|
+
return `${header} \u2014 ${body.length} chars, too large for one response. Outline below; fetch parts with \`path\`, or use mode "json" with offset to page.
|
|
1360
|
+
${outlinePayload(target, targetPath, { maxDepth: input.outlineDepth ?? 4 })}`;
|
|
1361
|
+
}
|
|
1362
|
+
const slice = body.slice(offset, offset + maxChars);
|
|
1363
|
+
const end = offset + slice.length;
|
|
1364
|
+
const footer = end < body.length ? `
|
|
1365
|
+
\u2026 [chars ${offset}\u2013${end} of ${body.length}; continue with offset=${end}]` : "";
|
|
1366
|
+
const range = offset > 0 ? ` (from char ${offset})` : "";
|
|
1367
|
+
return `${header}${range}
|
|
1368
|
+
${slice}${footer}`;
|
|
1369
|
+
}
|
|
1370
|
+
async loadTracePayloads(input) {
|
|
1371
|
+
const records = await this.resolveTraceScope(input.traceIds, input.limit ?? 10, {
|
|
1372
|
+
...input.status ? { status: input.status } : {},
|
|
1373
|
+
...input.projectId ? { projectId: input.projectId } : {}
|
|
1374
|
+
});
|
|
1375
|
+
if (records.length === 0) return "No traces to load.";
|
|
1376
|
+
const results = [];
|
|
1377
|
+
for (const record of records) results.push(await this.index.loadTrace(record));
|
|
1378
|
+
const lines = results.map((result) => {
|
|
1379
|
+
const failed = result.failed.length > 0 ? `, ${result.failed.length} failed (${result.failed[0].message})` : "";
|
|
1380
|
+
return `- ${result.traceId} "${result.traceName}" (${result.status}): ${result.loaded} loaded, ${result.alreadyLoaded} cached${failed}, ${Math.round(result.size / 1024)} KB`;
|
|
1381
|
+
});
|
|
1382
|
+
const evicted = results.flatMap((result) => result.evicted);
|
|
1383
|
+
if (evicted.length > 0)
|
|
1384
|
+
lines.push(`evicted to stay within memory budget: ${evicted.map(shortId).join(", ")}`);
|
|
1385
|
+
lines.push(
|
|
1386
|
+
`index: ${plural(this.index.loadedTraces().length, "trace")}, ${Math.round(this.index.totalSize() / 1024)} KB. Use search_payloads to search them.`
|
|
1387
|
+
);
|
|
1388
|
+
return lines.join("\n");
|
|
1389
|
+
}
|
|
1390
|
+
async searchPayloads(input) {
|
|
1391
|
+
if (!input.query) throw new TraceToolError("query must not be empty.");
|
|
1392
|
+
if (input.regex) compileUserRegex(input.query, "query");
|
|
1393
|
+
if (input.runName) compileUserRegex(input.runName, "runName");
|
|
1394
|
+
let scope = this.index.loadedTraces();
|
|
1395
|
+
let loadNote = "";
|
|
1396
|
+
if (input.traceIds && input.traceIds.length > 0) {
|
|
1397
|
+
if (input.traceIds.length > MAX_AUTO_LOAD_TRACES) {
|
|
1398
|
+
throw new TraceToolError(`Pass at most ${MAX_AUTO_LOAD_TRACES} traceIds per search.`);
|
|
1399
|
+
}
|
|
1400
|
+
const records = await this.resolveTraceScope(input.traceIds, MAX_AUTO_LOAD_TRACES);
|
|
1401
|
+
for (const record of records) {
|
|
1402
|
+
if (!this.index.isFullyLoaded(record)) await this.index.loadTrace(record);
|
|
1403
|
+
}
|
|
1404
|
+
scope = records.map((record) => this.index.get(record.trace.traceId)).filter((entry) => entry !== void 0);
|
|
1405
|
+
} else if (scope.length === 0) {
|
|
1406
|
+
return 'No payloads loaded yet. Call load_trace_payloads first, or pass traceIds (e.g. ["latest"]) to load and search specific traces.';
|
|
1407
|
+
} else {
|
|
1408
|
+
loadNote = ` (all ${plural(scope.length, "loaded trace")}; other traces are not searched)`;
|
|
1409
|
+
}
|
|
1410
|
+
const result = searchPayloads(scope, input);
|
|
1411
|
+
const failures = scope.reduce((sum, entry) => sum + entry.failures.length, 0);
|
|
1412
|
+
const failureNote = failures > 0 ? `
|
|
1413
|
+
warning: ${plural(failures, "payload")} failed to load and were not searched.` : "";
|
|
1414
|
+
if (result.groups.length === 0) {
|
|
1415
|
+
return `No matches in ${plural(result.searchedPayloads, "payload")} across ${plural(scope.length, "trace")}${loadNote}.${failureNote}`;
|
|
1416
|
+
}
|
|
1417
|
+
const maxGroups = input.maxGroups ?? 30;
|
|
1418
|
+
const offset = input.offset ?? 0;
|
|
1419
|
+
const perGroup = input.maxOccurrencesPerGroup ?? 5;
|
|
1420
|
+
const page = result.groups.slice(offset, offset + maxGroups);
|
|
1421
|
+
const blocks = page.map((group, index) => {
|
|
1422
|
+
const { first } = group;
|
|
1423
|
+
const parents = this.index.get(first.traceId)?.runs;
|
|
1424
|
+
const lines = [
|
|
1425
|
+
`[${offset + index + 1}] "${group.snippet}" (${group.valueLength} chars, ${group.occurrences.length}\xD7)`,
|
|
1426
|
+
` first: trace ${shortId(first.traceId)} \xB7 ${first.run.type} ${first.run.name} [${shortId(first.run.runId)}] \xB7 ${first.side} ${first.path}`,
|
|
1427
|
+
` in ${ancestryLabel(first.run, parents)}`
|
|
1428
|
+
];
|
|
1429
|
+
const rest = group.occurrences.slice(1);
|
|
1430
|
+
for (const occurrence of rest.slice(0, perGroup)) {
|
|
1431
|
+
lines.push(
|
|
1432
|
+
` also: trace ${shortId(occurrence.traceId)} \xB7 ${occurrence.run.type} ${occurrence.run.name} [${shortId(occurrence.run.runId)}] \xB7 ${occurrence.side} ${occurrence.path}`
|
|
1433
|
+
);
|
|
1434
|
+
}
|
|
1435
|
+
if (rest.length > perGroup) lines.push(` \u2026 ${rest.length - perGroup} more occurrences`);
|
|
1436
|
+
return lines.join("\n");
|
|
1437
|
+
});
|
|
1438
|
+
const more = result.groups.length > offset + maxGroups ? `
|
|
1439
|
+
${result.groups.length - offset - maxGroups} more distinct values; continue with offset=${offset + maxGroups}.` : "";
|
|
1440
|
+
return `${plural(result.groups.length, "distinct matching value")} (${plural(result.totalOccurrences, "occurrence")}) in ${plural(result.searchedPayloads, "payload")} across ${plural(scope.length, "trace")}${loadNote}:
|
|
1441
|
+
|
|
1442
|
+
${blocks.join("\n")}${more}${failureNote}`;
|
|
1443
|
+
}
|
|
1444
|
+
async analyzeTrace(input) {
|
|
1445
|
+
const record = await resolveTrace(this.api, input.traceId);
|
|
1446
|
+
if (input.loadPayloads ?? true) await this.index.loadTrace(record);
|
|
1447
|
+
const indexed = this.index.isFullyLoaded(record) ? this.index.get(record.trace.traceId) : void 0;
|
|
1448
|
+
return analyzeTrace(record, buildRunForest(record), indexed);
|
|
1449
|
+
}
|
|
1450
|
+
async getConversation(input) {
|
|
1451
|
+
const record = await resolveTrace(this.api, input.traceId);
|
|
1452
|
+
const run = resolveRun(record, input.runId);
|
|
1453
|
+
const sides = input.side === "input" ? ["input"] : input.side === "output" ? ["output"] : ["input", "output"];
|
|
1454
|
+
const maxMessages = input.maxMessages ?? 100;
|
|
1455
|
+
const blocks = [formatRunLabel(run)];
|
|
1456
|
+
let found = 0;
|
|
1457
|
+
for (const side of sides) {
|
|
1458
|
+
const ref = side === "input" ? run.inputRef : run.outputRef;
|
|
1459
|
+
if (!ref) continue;
|
|
1460
|
+
const value = await this.loadPayloadValue(record.trace.traceId, ref);
|
|
1461
|
+
for (const sequence of extractMessageSequences(value)) {
|
|
1462
|
+
found += 1;
|
|
1463
|
+
const { messages } = sequence;
|
|
1464
|
+
const skipped = Math.max(0, messages.length - maxMessages);
|
|
1465
|
+
const shown = messages.slice(skipped);
|
|
1466
|
+
const header = `[${side} ${sequence.path}] ${plural(messages.length, "message")}${skipped > 0 ? ` (first ${skipped} omitted)` : ""}`;
|
|
1467
|
+
const formatted = formatMessages(shown, { maxCharsPerMessage: input.maxCharsPerMessage });
|
|
1468
|
+
blocks.push(`${header}
|
|
1469
|
+
${skipped > 0 ? renumber(formatted, skipped) : formatted}`);
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
if (found === 0) {
|
|
1473
|
+
blocks.push(
|
|
1474
|
+
'No chat messages recognized in this run. Use get_payload with mode "outline" to inspect its structure.'
|
|
1475
|
+
);
|
|
1476
|
+
}
|
|
1477
|
+
return blocks.join("\n\n");
|
|
1478
|
+
}
|
|
1479
|
+
async compare(input) {
|
|
1480
|
+
const recordA = await resolveTrace(this.api, input.a.traceId);
|
|
1481
|
+
const recordB = await resolveTrace(this.api, input.b.traceId);
|
|
1482
|
+
if (Boolean(input.a.runId) !== Boolean(input.b.runId)) {
|
|
1483
|
+
throw new TraceToolError(
|
|
1484
|
+
"Pass runId for both sides (run comparison) or for neither (trace comparison)."
|
|
1485
|
+
);
|
|
1486
|
+
}
|
|
1487
|
+
if (input.a.runId && input.b.runId) {
|
|
1488
|
+
return this.compareRuns(
|
|
1489
|
+
recordA,
|
|
1490
|
+
resolveRun(recordA, input.a.runId),
|
|
1491
|
+
recordB,
|
|
1492
|
+
resolveRun(recordB, input.b.runId),
|
|
1493
|
+
input
|
|
1494
|
+
);
|
|
1495
|
+
}
|
|
1496
|
+
return compareTraceStructure(recordA, recordB);
|
|
1497
|
+
}
|
|
1498
|
+
async annotate(input) {
|
|
1499
|
+
const record = await resolveTrace(this.api, input.traceId);
|
|
1500
|
+
const merge = input.merge ?? true;
|
|
1501
|
+
if (input.runId) {
|
|
1502
|
+
const run = resolveRun(record, input.runId);
|
|
1503
|
+
const updated2 = await this.api.patchRunAnnotation({
|
|
1504
|
+
traceId: record.trace.traceId,
|
|
1505
|
+
runId: run.runId,
|
|
1506
|
+
annotation: input.annotation,
|
|
1507
|
+
merge
|
|
1508
|
+
});
|
|
1509
|
+
if (!updated2) throw new TraceToolError(`Run ${run.runId} could not be annotated.`);
|
|
1510
|
+
return `Annotated run ${updated2.runId} (${updated2.name}): ${safeStringify(updated2.annotation ?? {})}`;
|
|
1511
|
+
}
|
|
1512
|
+
const updated = await this.api.patchTraceAnnotation({
|
|
1513
|
+
traceId: record.trace.traceId,
|
|
1514
|
+
annotation: input.annotation,
|
|
1515
|
+
merge
|
|
1516
|
+
});
|
|
1517
|
+
if (!updated) throw new TraceToolError(`Trace ${record.trace.traceId} could not be annotated.`);
|
|
1518
|
+
return `Annotated trace ${updated.traceId} (${updated.name}): ${safeStringify(updated.annotation ?? {})}`;
|
|
1519
|
+
}
|
|
1520
|
+
async compareRuns(recordA, runA, recordB, runB, input) {
|
|
1521
|
+
const maxChanges = input.maxChanges ?? 100;
|
|
1522
|
+
const lines = [
|
|
1523
|
+
`A: ${formatRunLabel(runA)} (trace ${shortId(runA.traceId)})`,
|
|
1524
|
+
`B: ${formatRunLabel(runB)} (trace ${shortId(runB.traceId)})`
|
|
1525
|
+
];
|
|
1526
|
+
const fields = [
|
|
1527
|
+
"type",
|
|
1528
|
+
"name",
|
|
1529
|
+
"status",
|
|
1530
|
+
"latencyMs",
|
|
1531
|
+
"tokens",
|
|
1532
|
+
"costUsd",
|
|
1533
|
+
"error",
|
|
1534
|
+
"metadata"
|
|
1535
|
+
];
|
|
1536
|
+
const fieldChanges = fields.filter((field) => safeStringify(runA[field]) !== safeStringify(runB[field])).map(
|
|
1537
|
+
(field) => `~ ${field}: ${truncate(safeStringify(runA[field]) ?? "undefined", 200)} \u2192 ${truncate(safeStringify(runB[field]) ?? "undefined", 200)}`
|
|
1538
|
+
);
|
|
1539
|
+
lines.push(
|
|
1540
|
+
"",
|
|
1541
|
+
fieldChanges.length > 0 ? `run fields:
|
|
1542
|
+
${fieldChanges.join("\n")}` : "run fields: identical"
|
|
1543
|
+
);
|
|
1544
|
+
const sides = input.side === "input" ? ["input"] : input.side === "output" ? ["output"] : ["input", "output"];
|
|
1545
|
+
for (const side of sides) {
|
|
1546
|
+
const refA = side === "input" ? runA.inputRef : runA.outputRef;
|
|
1547
|
+
const refB = side === "input" ? runB.inputRef : runB.outputRef;
|
|
1548
|
+
if (!refA && !refB) continue;
|
|
1549
|
+
const valueA = refA ? await this.loadPayloadValue(recordA.trace.traceId, refA) : void 0;
|
|
1550
|
+
const valueB = refB ? await this.loadPayloadValue(recordB.trace.traceId, refB) : void 0;
|
|
1551
|
+
const { changes, truncated } = diffJson(valueA, valueB, maxChanges);
|
|
1552
|
+
lines.push(
|
|
1553
|
+
"",
|
|
1554
|
+
changes.length === 0 ? `${side}: identical` : `${side}: ${plural(changes.length, "change")}${truncated ? " (truncated; raise maxChanges or compare narrower runs)" : ""}
|
|
1555
|
+
${formatJsonChanges(changes)}`
|
|
1556
|
+
);
|
|
1557
|
+
}
|
|
1558
|
+
return lines.join("\n");
|
|
1559
|
+
}
|
|
1560
|
+
async resolveTraceScope(traceIds, limit, query = {}) {
|
|
1561
|
+
if (traceIds && traceIds.length > 0) {
|
|
1562
|
+
const records2 = [];
|
|
1563
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1564
|
+
for (const traceId of traceIds) {
|
|
1565
|
+
const record = await resolveTrace(this.api, traceId);
|
|
1566
|
+
if (seen.has(record.trace.traceId)) continue;
|
|
1567
|
+
seen.add(record.trace.traceId);
|
|
1568
|
+
records2.push(record);
|
|
1569
|
+
}
|
|
1570
|
+
return records2;
|
|
1571
|
+
}
|
|
1572
|
+
const traceIdsToLoad = [];
|
|
1573
|
+
await scanTraces(this.api, query, (trace) => {
|
|
1574
|
+
traceIdsToLoad.push(trace.traceId);
|
|
1575
|
+
return traceIdsToLoad.length < limit;
|
|
1576
|
+
});
|
|
1577
|
+
const records = await Promise.all(traceIdsToLoad.map((traceId) => this.api.getTrace(traceId)));
|
|
1578
|
+
return records.filter((record) => record !== null);
|
|
1579
|
+
}
|
|
1580
|
+
async resolvePayloadRef(input) {
|
|
1581
|
+
if (input.ref) return { ref: input.ref, traceId: void 0, label: `payload ${input.ref}` };
|
|
1582
|
+
if (!input.traceId || !input.runId) {
|
|
1583
|
+
throw new TraceToolError("Pass either ref, or traceId + runId (+ side).");
|
|
1584
|
+
}
|
|
1585
|
+
const record = await resolveTrace(this.api, input.traceId);
|
|
1586
|
+
const run = resolveRun(record, input.runId);
|
|
1587
|
+
const side = input.side ?? "output";
|
|
1588
|
+
const ref = side === "input" ? run.inputRef : run.outputRef;
|
|
1589
|
+
if (!ref) {
|
|
1590
|
+
throw new TraceToolError(
|
|
1591
|
+
`Run ${run.runId} (${run.name}) has no ${side} payload${run.status === "running" ? " yet (still running)" : ""}.`
|
|
1592
|
+
);
|
|
1593
|
+
}
|
|
1594
|
+
return {
|
|
1595
|
+
ref,
|
|
1596
|
+
traceId: record.trace.traceId,
|
|
1597
|
+
label: `${side} of ${run.type} ${run.name} [${shortId(run.runId)}]`
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
/** Decoded payload from the index when loaded, otherwise fetched directly (not cached). */
|
|
1601
|
+
async loadPayloadValue(traceId, ref) {
|
|
1602
|
+
if (traceId) {
|
|
1603
|
+
const cached = this.index.getPayload(traceId, ref);
|
|
1604
|
+
if (cached) return cached.value;
|
|
1605
|
+
} else {
|
|
1606
|
+
for (const entry of this.index.loadedTraces()) {
|
|
1607
|
+
const cached = entry.payloads.get(ref);
|
|
1608
|
+
if (cached) return cached.value;
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
try {
|
|
1612
|
+
return decodeJsonStrings(await this.api.getPayload(ref));
|
|
1613
|
+
} catch (error) {
|
|
1614
|
+
throw new TraceToolError(
|
|
1615
|
+
`Failed to load payload ${ref}: ${error instanceof Error ? error.message : String(error)}`
|
|
1616
|
+
);
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
};
|
|
1620
|
+
function ancestryLabel(run, runs) {
|
|
1621
|
+
const names = [];
|
|
1622
|
+
let current = run.parentRunId ? runs?.get(run.parentRunId) : void 0;
|
|
1623
|
+
while (current && names.length < 3) {
|
|
1624
|
+
names.unshift(current.name);
|
|
1625
|
+
current = current.parentRunId ? runs?.get(current.parentRunId) : void 0;
|
|
1626
|
+
}
|
|
1627
|
+
if (names.length === 0) return "(trace root)";
|
|
1628
|
+
return `${current ? "\u2026 \u203A " : ""}${names.join(" \u203A ")}`;
|
|
1629
|
+
}
|
|
1630
|
+
function renumber(formatted, offset) {
|
|
1631
|
+
return formatted.replace(/^#(\d+) /gm, (_, index) => `#${Number(index) + offset} `);
|
|
1632
|
+
}
|
|
1633
|
+
function compareTraceStructure(recordA, recordB) {
|
|
1634
|
+
const keyed = (record) => {
|
|
1635
|
+
const forest = buildRunForest(record);
|
|
1636
|
+
const counts = /* @__PURE__ */ new Map();
|
|
1637
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
1638
|
+
walkForest(forest, (node) => {
|
|
1639
|
+
const base = `${node.type} ${node.name}`;
|
|
1640
|
+
const occurrence = counts.get(base) ?? 0;
|
|
1641
|
+
counts.set(base, occurrence + 1);
|
|
1642
|
+
byKey.set(`${base} #${occurrence + 1}`, node);
|
|
1643
|
+
});
|
|
1644
|
+
return byKey;
|
|
1645
|
+
};
|
|
1646
|
+
const runsA = keyed(recordA);
|
|
1647
|
+
const runsB = keyed(recordB);
|
|
1648
|
+
const onlyA = [...runsA.keys()].filter((key) => !runsB.has(key));
|
|
1649
|
+
const onlyB = [...runsB.keys()].filter((key) => !runsA.has(key));
|
|
1650
|
+
const statusChanges = [];
|
|
1651
|
+
const latencyChanges = [];
|
|
1652
|
+
const tokenChanges = [];
|
|
1653
|
+
for (const [key, runA] of runsA) {
|
|
1654
|
+
const runB = runsB.get(key);
|
|
1655
|
+
if (!runB) continue;
|
|
1656
|
+
const pair = `[${shortId(runA.runId)} \u2194 ${shortId(runB.runId)}]`;
|
|
1657
|
+
if (runA.status !== runB.status) {
|
|
1658
|
+
statusChanges.push(
|
|
1659
|
+
`- ${key}: ${runA.status} \u2192 ${runB.status} ${pair}${runB.error ? ` error: ${truncate(runB.error.message, 160)}` : ""}`
|
|
1660
|
+
);
|
|
1661
|
+
}
|
|
1662
|
+
const latencyA = runA.latencyMs ?? 0;
|
|
1663
|
+
const latencyB = runB.latencyMs ?? 0;
|
|
1664
|
+
if (Math.abs(latencyA - latencyB) >= 100 && Math.max(latencyA, latencyB) >= 2 * Math.max(1, Math.min(latencyA, latencyB))) {
|
|
1665
|
+
latencyChanges.push(`- ${key}: ${formatMs(latencyA)} \u2192 ${formatMs(latencyB)} ${pair}`);
|
|
1666
|
+
}
|
|
1667
|
+
const tokensA = (runA.tokens?.input ?? 0) + (runA.tokens?.output ?? 0);
|
|
1668
|
+
const tokensB = (runB.tokens?.input ?? 0) + (runB.tokens?.output ?? 0);
|
|
1669
|
+
if (tokensA !== tokensB && Math.abs(tokensA - tokensB) >= 0.2 * Math.max(tokensA, tokensB)) {
|
|
1670
|
+
tokenChanges.push(`- ${key}: ${tokensA} \u2192 ${tokensB} tokens ${pair}`);
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
const list = (title, items) => items.length === 0 ? "" : `${title} (${items.length}):
|
|
1674
|
+
${items.slice(0, 30).join("\n")}${items.length > 30 ? `
|
|
1675
|
+
\u2026 ${items.length - 30} more` : ""}`;
|
|
1676
|
+
const sections = [
|
|
1677
|
+
`A: ${formatTraceRow(recordA.trace)}`,
|
|
1678
|
+
`B: ${formatTraceRow(recordB.trace)}`,
|
|
1679
|
+
list("status changes", statusChanges),
|
|
1680
|
+
list(
|
|
1681
|
+
"runs only in A",
|
|
1682
|
+
onlyA.map((key) => `- ${key} [${shortId(runsA.get(key).runId)}]`)
|
|
1683
|
+
),
|
|
1684
|
+
list(
|
|
1685
|
+
"runs only in B",
|
|
1686
|
+
onlyB.map((key) => `- ${key} [${shortId(runsB.get(key).runId)}]`)
|
|
1687
|
+
),
|
|
1688
|
+
list("latency changes (\u22652\xD7)", latencyChanges),
|
|
1689
|
+
list("token changes (\u226520%)", tokenChanges)
|
|
1690
|
+
].filter(Boolean);
|
|
1691
|
+
if (sections.length === 2)
|
|
1692
|
+
sections.push("Same run structure, statuses, latency and token profile.");
|
|
1693
|
+
sections.push(
|
|
1694
|
+
"Diff payloads of a matched pair with compare({ a: { traceId, runId }, b: { traceId, runId } })."
|
|
1695
|
+
);
|
|
1696
|
+
return sections.join("\n\n");
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
// src/mcp/server.ts
|
|
1700
|
+
var MAX_RESPONSE_CHARS = 6e4;
|
|
1701
|
+
var SERVER_INSTRUCTIONS = `
|
|
1702
|
+
Debug LLM / LangGraph traces recorded by @m4trix/tracing.
|
|
1703
|
+
|
|
1704
|
+
Workflow:
|
|
1705
|
+
1. list_traces (or pass traceId "latest" anywhere) to pick a trace.
|
|
1706
|
+
2. get_trace for the run tree, analyze_trace for errors, slow spans, token hotspots, loops and swallowed errors.
|
|
1707
|
+
3. get_run / get_conversation / get_payload to drill into one run. Use get_payload mode "outline" first for big payloads, then fetch a precise JSONPath.
|
|
1708
|
+
4. To search payload contents, call load_trace_payloads (or pass traceIds to search_payloads), then search_payloads.
|
|
1709
|
+
Identical values are grouped and attributed to the run where they first appeared \u2014 use this to find where a bad value originated.
|
|
1710
|
+
5. compare two runs (payload diff) or two traces (structure diff) to find regressions.
|
|
1711
|
+
|
|
1712
|
+
Trace and run ids may be given as unique prefixes (the 8-char ids shown in outputs work).
|
|
1713
|
+
Payload strings that contain JSON are decoded, so JSONPaths can reach into them.
|
|
1714
|
+
`.trim();
|
|
1715
|
+
var scalar = z.union([z.string(), z.number(), z.boolean()]);
|
|
1716
|
+
var traceIdField = z.string().min(1).describe('Trace id, unique prefix, or "latest".');
|
|
1717
|
+
var runIdField = z.string().min(1).describe("Run id or unique prefix within the trace.");
|
|
1718
|
+
var sideField = z.enum(["input", "output"]);
|
|
1719
|
+
var statusField = z.enum(["running", "success", "error"]);
|
|
1720
|
+
var readOnly = { readOnlyHint: true, openWorldHint: false };
|
|
1721
|
+
async function respond(task) {
|
|
1722
|
+
try {
|
|
1723
|
+
const text = await task();
|
|
1724
|
+
return { content: [{ type: "text", text: truncate(text, MAX_RESPONSE_CHARS) }] };
|
|
1725
|
+
} catch (error) {
|
|
1726
|
+
const message = error instanceof TraceToolError ? error.message : `Unexpected error: ${error instanceof Error ? error.message : String(error)}`;
|
|
1727
|
+
return { content: [{ type: "text", text: message }], isError: true };
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
function createTraceMcpServer(options) {
|
|
1731
|
+
const tools = new TraceTools(options.traceViewerApi, { index: options.index });
|
|
1732
|
+
const server = new McpServer(
|
|
1733
|
+
{ name: "m4trix-traces", version: options.version ?? "0.0.0" },
|
|
1734
|
+
{ instructions: SERVER_INSTRUCTIONS }
|
|
1735
|
+
);
|
|
1736
|
+
server.registerTool(
|
|
1737
|
+
"list_traces",
|
|
1738
|
+
{
|
|
1739
|
+
title: "List traces",
|
|
1740
|
+
description: "List recorded traces, newest first, with status, latency, run count, tokens and metadata. Filters combine with AND.",
|
|
1741
|
+
inputSchema: {
|
|
1742
|
+
status: statusField.optional(),
|
|
1743
|
+
projectId: z.string().optional(),
|
|
1744
|
+
name: z.string().optional().describe("Case-insensitive regex against the trace name."),
|
|
1745
|
+
metadata: z.record(scalar).optional().describe('Exact match on trace metadata, e.g. { "env": "dev" }.'),
|
|
1746
|
+
since: z.string().optional().describe("ISO timestamp; only traces started after it."),
|
|
1747
|
+
until: z.string().optional().describe("ISO timestamp; only traces started before it."),
|
|
1748
|
+
minLatencyMs: z.number().nonnegative().optional(),
|
|
1749
|
+
annotated: z.boolean().optional(),
|
|
1750
|
+
limit: z.number().int().positive().max(200).optional().describe("Default 20."),
|
|
1751
|
+
offset: z.number().int().nonnegative().optional()
|
|
1752
|
+
},
|
|
1753
|
+
annotations: readOnly
|
|
1754
|
+
},
|
|
1755
|
+
(input) => respond(() => tools.listTraces(input))
|
|
1756
|
+
);
|
|
1757
|
+
server.registerTool(
|
|
1758
|
+
"get_trace",
|
|
1759
|
+
{
|
|
1760
|
+
title: "Get trace run tree",
|
|
1761
|
+
description: "Trace summary plus its run tree as an indented outline (status, type, name, latency, tokens, short run id, error). LangGraph plumbing spans are hidden by default; error runs are never hidden.",
|
|
1762
|
+
inputSchema: {
|
|
1763
|
+
traceId: traceIdField,
|
|
1764
|
+
focusRunId: z.string().optional().describe("Only render the subtree under this run."),
|
|
1765
|
+
maxDepth: z.number().int().nonnegative().optional(),
|
|
1766
|
+
maxNodes: z.number().int().positive().max(2e3).optional().describe("Default 200."),
|
|
1767
|
+
hide: z.string().optional().describe(
|
|
1768
|
+
`Regex of run names to hide (children are promoted). Default ${DEFAULT_HIDE_PATTERN}; "" shows everything.`
|
|
1769
|
+
)
|
|
1770
|
+
},
|
|
1771
|
+
annotations: readOnly
|
|
1772
|
+
},
|
|
1773
|
+
(input) => respond(() => tools.getTrace(input))
|
|
1774
|
+
);
|
|
1775
|
+
server.registerTool(
|
|
1776
|
+
"find_runs",
|
|
1777
|
+
{
|
|
1778
|
+
title: "Find runs",
|
|
1779
|
+
description: "Find runs by structural fields (type, name, status, error message, latency, tokens, metadata) across one or more traces. Does not read payloads.",
|
|
1780
|
+
inputSchema: {
|
|
1781
|
+
traceIds: z.array(z.string().min(1)).optional().describe("Defaults to the newest traceLimit traces."),
|
|
1782
|
+
traceLimit: z.number().int().positive().max(500).optional().describe("Default 20."),
|
|
1783
|
+
type: z.array(z.string()).optional().describe('Run types, e.g. ["tool", "chat_model"].'),
|
|
1784
|
+
name: z.string().optional().describe("Case-insensitive regex against run names."),
|
|
1785
|
+
status: statusField.optional(),
|
|
1786
|
+
errorContains: z.string().optional(),
|
|
1787
|
+
minLatencyMs: z.number().nonnegative().optional(),
|
|
1788
|
+
minTokens: z.number().nonnegative().optional(),
|
|
1789
|
+
metadata: z.record(scalar).optional(),
|
|
1790
|
+
maxDepth: z.number().int().nonnegative().optional(),
|
|
1791
|
+
limit: z.number().int().positive().max(500).optional().describe("Default 50.")
|
|
1792
|
+
},
|
|
1793
|
+
annotations: readOnly
|
|
1794
|
+
},
|
|
1795
|
+
(input) => respond(() => tools.findRuns(input))
|
|
1796
|
+
);
|
|
1797
|
+
server.registerTool(
|
|
1798
|
+
"get_run",
|
|
1799
|
+
{
|
|
1800
|
+
title: "Get run details",
|
|
1801
|
+
description: "Full details of one run: ancestry path, timing, tokens, full error, metadata, children, and short previews of its input/output payloads.",
|
|
1802
|
+
inputSchema: {
|
|
1803
|
+
traceId: traceIdField,
|
|
1804
|
+
runId: runIdField,
|
|
1805
|
+
previewChars: z.number().int().positive().max(2e4).optional().describe("Default 1500 per payload.")
|
|
1806
|
+
},
|
|
1807
|
+
annotations: readOnly
|
|
1808
|
+
},
|
|
1809
|
+
(input) => respond(() => tools.getRun(input))
|
|
1810
|
+
);
|
|
1811
|
+
server.registerTool(
|
|
1812
|
+
"get_payload",
|
|
1813
|
+
{
|
|
1814
|
+
title: "Get payload",
|
|
1815
|
+
description: 'Read a run input/output payload. mode "outline" lists paths, types and sizes; "json" returns content (paged with offset); "auto" returns json when it fits, else the outline. Use `path` (JSONPath subset: $.a.b, [0], [-1], [*], .*) to read only part of it.',
|
|
1816
|
+
inputSchema: {
|
|
1817
|
+
traceId: traceIdField.optional(),
|
|
1818
|
+
runId: runIdField.optional(),
|
|
1819
|
+
side: sideField.optional().describe("Default output."),
|
|
1820
|
+
ref: z.string().optional().describe("Raw payload ref, alternative to traceId + runId + side."),
|
|
1821
|
+
path: z.string().optional(),
|
|
1822
|
+
mode: z.enum(["auto", "json", "outline"]).optional(),
|
|
1823
|
+
offset: z.number().int().nonnegative().optional(),
|
|
1824
|
+
maxChars: z.number().int().positive().max(5e4).optional().describe("Default 12000."),
|
|
1825
|
+
outlineDepth: z.number().int().positive().max(12).optional().describe("Default 4.")
|
|
1826
|
+
},
|
|
1827
|
+
annotations: readOnly
|
|
1828
|
+
},
|
|
1829
|
+
(input) => respond(() => tools.getPayload(input))
|
|
1830
|
+
);
|
|
1831
|
+
server.registerTool(
|
|
1832
|
+
"load_trace_payloads",
|
|
1833
|
+
{
|
|
1834
|
+
title: "Load trace payloads",
|
|
1835
|
+
description: "Load all input/output payloads of traces into the in-memory search index (required before search_payloads can search them). Pass traceIds, or omit them to load the newest `limit` traces matching status/projectId. Reloading a trace only fetches new payloads.",
|
|
1836
|
+
inputSchema: {
|
|
1837
|
+
traceIds: z.array(z.string().min(1)).optional(),
|
|
1838
|
+
status: statusField.optional(),
|
|
1839
|
+
projectId: z.string().optional(),
|
|
1840
|
+
limit: z.number().int().positive().max(100).optional().describe("Default 10 when traceIds is omitted.")
|
|
1841
|
+
},
|
|
1842
|
+
annotations: readOnly
|
|
1843
|
+
},
|
|
1844
|
+
(input) => respond(() => tools.loadTracePayloads(input))
|
|
1845
|
+
);
|
|
1846
|
+
server.registerTool(
|
|
1847
|
+
"search_payloads",
|
|
1848
|
+
{
|
|
1849
|
+
title: "Search payloads",
|
|
1850
|
+
description: "Full-text or regex search over loaded payload values. Results are grouped by identical value and point to the run, side and JSONPath where each value first appeared. Passing traceIds loads those traces automatically and searches only them; otherwise all loaded traces are searched.",
|
|
1851
|
+
inputSchema: {
|
|
1852
|
+
query: z.string().min(1),
|
|
1853
|
+
regex: z.boolean().optional(),
|
|
1854
|
+
caseSensitive: z.boolean().optional(),
|
|
1855
|
+
traceIds: z.array(z.string().min(1)).max(20).optional(),
|
|
1856
|
+
runType: z.array(z.string()).optional(),
|
|
1857
|
+
runName: z.string().optional().describe("Case-insensitive regex against run names."),
|
|
1858
|
+
side: z.enum(["input", "output", "both"]).optional(),
|
|
1859
|
+
pathPrefix: z.string().optional().describe('Only leaves under this path, e.g. "$.messages".'),
|
|
1860
|
+
maxGroups: z.number().int().positive().max(200).optional().describe("Default 30."),
|
|
1861
|
+
offset: z.number().int().nonnegative().optional(),
|
|
1862
|
+
maxOccurrencesPerGroup: z.number().int().nonnegative().max(100).optional().describe("Default 5.")
|
|
1863
|
+
},
|
|
1864
|
+
annotations: readOnly
|
|
1865
|
+
},
|
|
1866
|
+
(input) => respond(() => tools.searchPayloads(input))
|
|
1867
|
+
);
|
|
1868
|
+
server.registerTool(
|
|
1869
|
+
"analyze_trace",
|
|
1870
|
+
{
|
|
1871
|
+
title: "Analyze trace",
|
|
1872
|
+
description: "Debugging report for a trace: root-cause error runs with ancestry, unfinished and orphan runs, critical path and self time, token hotspots, repeated identical calls (loops), and error-like values inside successful runs.",
|
|
1873
|
+
inputSchema: {
|
|
1874
|
+
traceId: traceIdField,
|
|
1875
|
+
loadPayloads: z.boolean().optional().describe("Load payloads for payload-based checks. Default true.")
|
|
1876
|
+
},
|
|
1877
|
+
annotations: readOnly
|
|
1878
|
+
},
|
|
1879
|
+
(input) => respond(() => tools.analyzeTrace(input))
|
|
1880
|
+
);
|
|
1881
|
+
server.registerTool(
|
|
1882
|
+
"get_conversation",
|
|
1883
|
+
{
|
|
1884
|
+
title: "Get conversation",
|
|
1885
|
+
description: "Render the chat messages in a run input/output (OpenAI, Anthropic and LangChain message shapes) as a readable transcript including tool calls and tool call ids.",
|
|
1886
|
+
inputSchema: {
|
|
1887
|
+
traceId: traceIdField,
|
|
1888
|
+
runId: runIdField,
|
|
1889
|
+
side: z.enum(["input", "output", "both"]).optional(),
|
|
1890
|
+
maxMessages: z.number().int().positive().max(1e3).optional().describe("Keeps the last N per sequence. Default 100."),
|
|
1891
|
+
maxCharsPerMessage: z.number().int().positive().max(5e4).optional().describe("Default 2000.")
|
|
1892
|
+
},
|
|
1893
|
+
annotations: readOnly
|
|
1894
|
+
},
|
|
1895
|
+
(input) => respond(() => tools.getConversation(input))
|
|
1896
|
+
);
|
|
1897
|
+
const compareTarget = z.object({ traceId: traceIdField, runId: z.string().optional() });
|
|
1898
|
+
server.registerTool(
|
|
1899
|
+
"compare",
|
|
1900
|
+
{
|
|
1901
|
+
title: "Compare runs or traces",
|
|
1902
|
+
description: "With runId on both sides: diff run fields and input/output payloads path by path. Without runIds: align the two traces run by run (type, name, occurrence) and report status, structure, latency and token differences.",
|
|
1903
|
+
inputSchema: {
|
|
1904
|
+
a: compareTarget,
|
|
1905
|
+
b: compareTarget,
|
|
1906
|
+
side: z.enum(["input", "output", "both"]).optional(),
|
|
1907
|
+
maxChanges: z.number().int().positive().max(2e3).optional().describe("Default 100 per side.")
|
|
1908
|
+
},
|
|
1909
|
+
annotations: readOnly
|
|
1910
|
+
},
|
|
1911
|
+
(input) => respond(() => tools.compare(input))
|
|
1912
|
+
);
|
|
1913
|
+
server.registerTool(
|
|
1914
|
+
"annotate",
|
|
1915
|
+
{
|
|
1916
|
+
title: "Annotate trace or run",
|
|
1917
|
+
description: 'Write an annotation onto a trace (or one run with runId); it is persisted in the trace store and shown in the trace viewer. This modifies stored data: before calling, ask the user for permission and show them the exact annotation you intend to write. Annotations are merged into existing ones by default; prefer a single namespaced key such as { "agent_notes": "\u2026" }.',
|
|
1918
|
+
inputSchema: {
|
|
1919
|
+
traceId: traceIdField,
|
|
1920
|
+
runId: runIdField.optional(),
|
|
1921
|
+
annotation: z.record(z.unknown()),
|
|
1922
|
+
merge: z.boolean().optional().describe("Default true. false replaces the whole annotation.")
|
|
1923
|
+
},
|
|
1924
|
+
annotations: {
|
|
1925
|
+
readOnlyHint: false,
|
|
1926
|
+
destructiveHint: false,
|
|
1927
|
+
idempotentHint: true,
|
|
1928
|
+
openWorldHint: false
|
|
1929
|
+
}
|
|
1930
|
+
},
|
|
1931
|
+
(input) => respond(() => tools.annotate(input))
|
|
1932
|
+
);
|
|
1933
|
+
return server;
|
|
1934
|
+
}
|
|
1935
|
+
async function startTraceMcpStdioServer(options) {
|
|
1936
|
+
const server = createTraceMcpServer(options);
|
|
1937
|
+
await server.connect(new StdioServerTransport());
|
|
1938
|
+
return server;
|
|
1939
|
+
}
|
|
112
1940
|
var t = initTRPC.context().create();
|
|
113
1941
|
var listInput = z.object({
|
|
114
1942
|
limit: z.number().int().positive().max(500).optional(),
|
|
@@ -217,6 +2045,6 @@ function startTraceViewerServer(options) {
|
|
|
217
2045
|
return server;
|
|
218
2046
|
}
|
|
219
2047
|
|
|
220
|
-
export { CliParseError, DEFAULT_FS_RELATIVE_PATH, DEFAULT_PORT, appRouter, cliHelpText, createAwsStackTraceViewerApi, createFsTraceViewerApi, parseCliArgs, startTraceViewerServer };
|
|
2048
|
+
export { CliParseError, DEFAULT_FS_RELATIVE_PATH, DEFAULT_PORT, TraceTools, appRouter, cliHelpText, createAwsStackTraceViewerApi, createFsTraceViewerApi, createTraceMcpServer, parseCliArgs, startTraceMcpStdioServer, startTraceViewerServer };
|
|
221
2049
|
//# sourceMappingURL=index.js.map
|
|
222
2050
|
//# sourceMappingURL=index.js.map
|