autotel-terminal 25.0.0 → 26.0.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/dist/cli.cjs CHANGED
@@ -1,3072 +1,301 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';
3
-
4
- var fs = require('fs');
5
- var http = require('http');
6
- var path = require('path');
7
- var react = require('react');
8
- var ink = require('ink');
9
- var autotel = require('autotel');
10
- var tracerProvider = require('autotel/tracer-provider');
11
- var ai = require('ai');
12
- var zod = require('zod');
13
- var core = require('@json-render/core');
14
- var catalog = require('@json-render/ink/catalog');
15
- var ink$1 = require('@json-render/ink');
16
- require('autotel/exporters');
17
- var jsxRuntime = require('react/jsx-runtime');
18
-
19
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
20
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
21
-
22
- var path__default = /*#__PURE__*/_interopDefault(path);
23
-
24
- // src/streaming-processor.ts
25
- var StreamingSpanProcessor = class {
26
- wrappedProcessor;
27
- subscribers = /* @__PURE__ */ new Set();
28
- /**
29
- * Create a new streaming span processor
30
- *
31
- * @param wrappedProcessor - The processor to wrap and forward spans to.
32
- * If null, spans are only emitted to subscribers (no forwarding).
33
- */
34
- constructor(wrappedProcessor = null) {
35
- this.wrappedProcessor = wrappedProcessor;
36
- }
37
- onStart(span, parentContext) {
38
- if (this.wrappedProcessor) {
39
- this.wrappedProcessor.onStart(span, parentContext);
40
- }
41
- }
42
- onEnd(span) {
43
- for (const subscriber of this.subscribers) {
44
- try {
45
- subscriber(span);
46
- } catch (error) {
47
- console.error("[autotel-terminal] Subscriber error:", error);
48
- }
49
- }
50
- if (this.wrappedProcessor) {
51
- this.wrappedProcessor.onEnd(span);
52
- }
53
- }
54
- /**
55
- * Subscribe to span end events
56
- *
57
- * @param callback - Function called when a span ends
58
- * @returns Unsubscribe function
59
- *
60
- * @example
61
- * ```typescript
62
- * const unsubscribe = processor.subscribe((span) => {
63
- * console.log('Span ended:', span.name)
64
- * })
65
- *
66
- * // Later, unsubscribe
67
- * unsubscribe()
68
- * ```
69
- */
70
- subscribe(callback) {
71
- this.subscribers.add(callback);
72
- return () => this.subscribers.delete(callback);
73
- }
74
- async forceFlush() {
75
- if (this.wrappedProcessor) {
76
- return this.wrappedProcessor.forceFlush();
77
- }
78
- }
79
- async shutdown() {
80
- this.subscribers.clear();
81
- if (this.wrappedProcessor) {
82
- return this.wrappedProcessor.shutdown();
83
- }
84
- }
85
- };
86
- function timeToMs([seconds, nanoseconds]) {
87
- return seconds * 1e3 + nanoseconds / 1e6;
88
- }
89
- function mapStatus(code) {
90
- if (code === autotel.SpanStatusCode.OK) {
91
- return "OK";
92
- }
93
- if (code === autotel.SpanStatusCode.ERROR) {
94
- return "ERROR";
95
- }
96
- return "UNSET";
97
- }
98
- function mapKind(kind) {
99
- const kindMap = {
100
- [autotel.SpanKind.INTERNAL]: "INTERNAL",
101
- [autotel.SpanKind.SERVER]: "SERVER",
102
- [autotel.SpanKind.CLIENT]: "CLIENT",
103
- [autotel.SpanKind.PRODUCER]: "PRODUCER",
104
- [autotel.SpanKind.CONSUMER]: "CONSUMER"
105
- };
106
- return kindMap[kind] ?? "UNKNOWN";
107
- }
108
- function createTerminalSpanStream(processor) {
109
- return {
110
- onSpanEnd(callback) {
111
- return processor.subscribe((span) => {
112
- const spanContext = span.spanContext();
113
- const parentSpanId = "parentSpanId" in span && typeof span.parentSpanId === "string" ? span.parentSpanId : void 0;
114
- const startTime = timeToMs(span.startTime);
115
- const endTime = timeToMs(span.endTime);
116
- const durationMs = endTime - startTime;
117
- const resourceAttrs = span.resource?.attributes ?? {};
118
- const spanAttrs = span.attributes;
119
- const mergedAttrs = {};
120
- for (const [k, v] of Object.entries(resourceAttrs)) {
121
- mergedAttrs[k] = v;
122
- }
123
- for (const [k, v] of Object.entries(spanAttrs)) {
124
- mergedAttrs[k] = v;
125
- }
126
- const spanEvents = span.events?.length ? span.events.map((e) => ({
127
- name: e.name,
128
- timeMs: timeToMs(e.time),
129
- attributes: e.attributes
130
- })) : void 0;
131
- const spanLinks = span.links?.length ? span.links.map((l) => ({
132
- traceId: l.context.traceId,
133
- spanId: l.context.spanId,
134
- attributes: l.attributes
135
- })) : void 0;
136
- const event = {
137
- name: span.name,
138
- spanId: spanContext.spanId,
139
- traceId: spanContext.traceId,
140
- parentSpanId,
141
- startTime,
142
- endTime,
143
- durationMs,
144
- status: mapStatus(span.status.code),
145
- kind: mapKind(span.kind),
146
- attributes: mergedAttrs,
147
- ...spanEvents ? { events: spanEvents } : {},
148
- ...spanLinks ? { links: spanLinks } : {}
149
- };
150
- callback(event);
151
- });
152
- }
153
- };
154
- }
155
-
156
- // src/lib/trace-model.ts
157
- function spanServiceName(span) {
158
- const svc = span.attributes?.["service.name"];
159
- return typeof svc === "string" ? svc : "unknown";
160
- }
161
- function buildTraceMap(spans, maxTraces = 50) {
162
- const byTrace = /* @__PURE__ */ new Map();
163
- for (const s of spans) {
164
- const list = byTrace.get(s.traceId) ?? [];
165
- list.push(s);
166
- byTrace.set(s.traceId, list);
167
- }
168
- const entries = [...byTrace.entries()].toSorted((a, b) => {
169
- const maxA = Math.max(...a[1].map((x) => x.endTime));
170
- const maxB = Math.max(...b[1].map((x) => x.endTime));
171
- return maxB - maxA;
172
- });
173
- const limited = entries.slice(0, maxTraces);
174
- return new Map(limited);
175
- }
176
- function buildTraceSummaries(traceMap) {
177
- const summaries = [];
178
- for (const [traceId, traceSpans] of traceMap) {
179
- const spanIds = new Set(traceSpans.map((s) => s.spanId));
180
- const root = traceSpans.find((s) => !s.parentSpanId || !spanIds.has(s.parentSpanId)) ?? traceSpans[0];
181
- const durationMs = root ? root.durationMs : 0;
182
- const hasError = traceSpans.some((s) => s.status === "ERROR");
183
- const lastEndTime = Math.max(...traceSpans.map((s) => s.endTime));
184
- const services = [...new Set(traceSpans.map((s) => spanServiceName(s)))];
185
- summaries.push({
186
- traceId,
187
- rootName: root?.name ?? "unknown",
188
- durationMs,
189
- hasError,
190
- spanCount: traceSpans.length,
191
- lastEndTime,
192
- spans: traceSpans,
193
- services
194
- });
195
- }
196
- return summaries;
197
- }
198
- function buildTraceTree(spans) {
199
- const byId = /* @__PURE__ */ new Map();
200
- for (const s of spans) {
201
- byId.set(s.spanId, s);
202
- }
203
- const roots = [];
204
- function addNode(span, depth) {
205
- const children = spans.filter((s) => s.parentSpanId === span.spanId).map((s) => addNode(s, depth + 1));
206
- return { span, depth, children };
207
- }
208
- const rootSpans = spans.filter(
209
- (s) => !s.parentSpanId || !byId.has(s.parentSpanId)
210
- );
211
- for (const s of rootSpans) {
212
- roots.push(addNode(s, 0));
213
- }
214
- return roots;
215
- }
216
- function flattenTraceTree(nodes) {
217
- const out = [];
218
- function walk(n) {
219
- out.push(n);
220
- for (const c of n.children) walk(c);
221
- }
222
- for (const n of nodes) walk(n);
223
- return out;
224
- }
225
- function sortSpansForWaterfall(spans) {
226
- const byId = /* @__PURE__ */ new Map();
227
- for (const s of spans) byId.set(s.spanId, s);
228
- function depth(s) {
229
- if (!s.parentSpanId || !byId.has(s.parentSpanId)) return 0;
230
- const parent = byId.get(s.parentSpanId);
231
- return 1 + depth(parent);
232
- }
233
- const withDepth = spans.map((s) => ({ span: s, depth: depth(s) }));
234
- withDepth.sort((a, b) => {
235
- if (a.span.startTime !== b.span.startTime)
236
- return a.span.startTime - b.span.startTime;
237
- return a.depth - b.depth;
238
- });
239
- return withDepth;
240
- }
241
- function filterBySearch(spans, searchQuery, errorsOnly) {
242
- let list = spans;
243
- if (searchQuery.trim() === "") return list;
244
- const q = searchQuery.toLowerCase();
245
- return list.filter((s) => s.name.toLowerCase().includes(q));
246
- }
247
- function filterTraceSummaries(summaries, searchQuery, errorsOnly) {
248
- let list = summaries;
249
- if (searchQuery.trim() === "") return list;
250
- const q = searchQuery.toLowerCase();
251
- return list.filter(
252
- (s) => s.spans.some((sp) => sp.name.toLowerCase().includes(q))
253
- );
254
- }
255
- function computeStats(spans) {
256
- const total = spans.length;
257
- const errors = spans.filter((s) => s.status === "ERROR").length;
258
- const avg = total ? spans.reduce((a, s) => a + s.durationMs, 0) / total : 0;
259
- const p95 = total ? (() => {
260
- const sorted = spans.map((s) => s.durationMs).toSorted((a, b) => a - b);
261
- return sorted[Math.floor(sorted.length * 0.95)] ?? 0;
262
- })() : 0;
263
- return { total, errors, avg, p95 };
264
- }
265
- function computePerSpanNameStats(spans) {
266
- const byName = /* @__PURE__ */ new Map();
267
- for (const s of spans) {
268
- const cur = byName.get(s.name) ?? { count: 0, totalMs: 0 };
269
- cur.count += 1;
270
- cur.totalMs += s.durationMs;
271
- byName.set(s.name, cur);
272
- }
273
- const result = /* @__PURE__ */ new Map();
274
- for (const [name, { count, totalMs }] of byName) {
275
- result.set(name, { count, totalMs, avgMs: totalMs / count });
276
- }
277
- return { byName: result };
278
- }
279
-
280
- // src/lib/format.ts
281
- function formatDurationMs(n) {
282
- if (n < 1e3) return `${n.toFixed(0)}ms`;
283
- return `${(n / 1e3).toFixed(2)}s`;
284
- }
285
- function formatRelative(epochMs) {
286
- const now = Date.now();
287
- const diffMs = now - epochMs;
288
- if (diffMs < 0) return "just now";
289
- if (diffMs < 1e3) return "just now";
290
- if (diffMs < 6e4) return `${Math.floor(diffMs / 1e3)}s ago`;
291
- if (diffMs < 36e5) return `${Math.floor(diffMs / 6e4)}m ago`;
292
- return `${Math.floor(diffMs / 36e5)}h ago`;
293
- }
294
- function truncate(s, width) {
295
- if (s.length <= width) return s;
296
- return s.slice(0, Math.max(0, width - 1)) + "\u2026";
297
- }
298
- function buildWaterfallBar(spanStart, spanDuration, traceStart, traceDuration, width) {
299
- if (traceDuration <= 0) return " ".repeat(width);
300
- const offsetRatio = (spanStart - traceStart) / traceDuration;
301
- const widthRatio = spanDuration / traceDuration;
302
- const barStart = Math.max(0, Math.floor(offsetRatio * width));
303
- const barLen = Math.max(1, Math.round(widthRatio * width));
304
- const clampedStart = Math.min(barStart, width - 1);
305
- const clampedLen = Math.min(barLen, width - clampedStart);
306
- const trailing = Math.max(0, width - clampedStart - clampedLen);
307
- return " ".repeat(clampedStart) + "\u2588".repeat(clampedLen) + " ".repeat(trailing);
308
- }
309
- function buildTimeRuler(totalMs, width) {
310
- const left = "0ms";
311
- const right = formatDurationMs(totalMs);
312
- const mid = formatDurationMs(totalMs / 2);
313
- const midPos = Math.floor(width / 2) - Math.floor(mid.length / 2);
314
- const rightPos = width - right.length;
315
- const chars = Array.from({ length: width }).fill(" ");
316
- for (let i = 0; i < left.length && i < width; i++) chars[i] = left[i];
317
- if (midPos > left.length + 1 && midPos + mid.length < rightPos - 1) {
318
- for (let i = 0; i < mid.length; i++) chars[midPos + i] = mid[i];
319
- }
320
- for (let i = 0; i < right.length; i++) chars[rightPos + i] = right[i];
321
- return chars.join("");
322
- }
323
-
324
- // src/lib/service-colors.ts
325
- var SERVICE_COLORS = [
326
- "cyan",
327
- "magenta",
328
- "blue",
329
- "yellow",
330
- "green",
331
- "redBright",
332
- "cyanBright",
333
- "magentaBright",
334
- "blueBright",
335
- "yellowBright",
336
- "greenBright"
337
- ];
338
- function hashString(s) {
339
- let hash = 0;
340
- for (let i = 0; i < s.length; i++) {
341
- hash = Math.trunc((hash << 5) - hash + s.codePointAt(i));
342
- }
343
- return Math.abs(hash);
344
- }
345
- function getServiceColor(serviceName) {
346
- return SERVICE_COLORS[hashString(serviceName) % SERVICE_COLORS.length];
347
- }
348
-
349
- // src/lib/log-model.ts
350
- function filterLogsBySearch(logs, searchQuery, minLevel) {
351
- let list = logs;
352
- if (searchQuery.trim() === "") return list;
353
- const q = searchQuery.toLowerCase();
354
- return list.filter((log) => {
355
- if (log.message.toLowerCase().includes(q)) return true;
356
- if (log.attributes) {
357
- for (const [k, v] of Object.entries(log.attributes)) {
358
- const s = `${k}:${String(v)}`.toLowerCase();
359
- if (s.includes(q)) return true;
360
- }
361
- }
362
- return false;
363
- });
364
- }
365
- function computeLogStats(logs) {
366
- const total = logs.length;
367
- const errors = logs.filter((l) => l.level === "error").length;
368
- return { total, errors };
369
- }
370
- function buildTraceTimeline(spans, logs) {
371
- const items = [];
372
- for (const span of spans) {
373
- items.push({
374
- type: "span",
375
- time: span.startTime,
376
- span
377
- });
378
- }
379
- for (const log of logs) {
380
- items.push({
381
- type: "log",
382
- time: log.time,
383
- log
384
- });
385
- }
386
- items.sort((a, b) => a.time - b.time);
387
- return items;
388
- }
389
-
390
- // src/log-stream.ts
391
- var InMemoryTerminalLogStream = class {
392
- subscribers = /* @__PURE__ */ new Set();
393
- onLog(callback) {
394
- this.subscribers.add(callback);
395
- return () => this.subscribers.delete(callback);
396
- }
397
- emit(event) {
398
- for (const subscriber of this.subscribers) {
399
- try {
400
- subscriber(event);
401
- } catch (error) {
402
- console.error("[autotel-terminal] Log subscriber error:", error);
403
- }
404
- }
405
- }
406
- };
407
- var globalLogStream = null;
408
- function getTerminalLogStream() {
409
- if (!globalLogStream) {
410
- globalLogStream = new InMemoryTerminalLogStream();
411
- }
412
- return globalLogStream;
413
- }
414
-
415
- // src/lib/stats-model.ts
416
- function computeServiceStats(spans) {
417
- const byService = /* @__PURE__ */ new Map();
418
- for (const span of spans) {
419
- const attrs = span.attributes ?? {};
420
- const serviceName = attrs["service.name"] ?? "unknown";
421
- const entry = byService.get(serviceName) ?? {
422
- durations: [],
423
- total: 0,
424
- errors: 0
425
- };
426
- entry.total += 1;
427
- entry.durations.push(span.durationMs);
428
- if (span.status === "ERROR") entry.errors += 1;
429
- byService.set(serviceName, entry);
430
- }
431
- const stats = [];
432
- for (const [serviceName, { durations, total, errors }] of byService) {
433
- if (total === 0) continue;
434
- const avgMs = durations.reduce((a, d) => a + d, 0) / durations.length;
435
- const sorted = durations.toSorted((a, b) => a - b);
436
- const p95Index = Math.floor(sorted.length * 0.95);
437
- const p95Ms = sorted[p95Index] ?? sorted.at(-1) ?? 0;
438
- stats.push({ serviceName, total, errors, avgMs, p95Ms });
439
- }
440
- stats.sort((a, b) => b.total - a.total);
441
- return stats;
442
- }
443
- function computeRouteStats(spans) {
444
- const byRoute = /* @__PURE__ */ new Map();
445
- for (const span of spans) {
446
- const attrs = span.attributes ?? {};
447
- const route = attrs["http.route"] ?? null;
448
- if (!route) continue;
449
- const entry = byRoute.get(route) ?? {
450
- durations: [],
451
- total: 0,
452
- errors: 0
453
- };
454
- entry.total += 1;
455
- entry.durations.push(span.durationMs);
456
- if (span.status === "ERROR") entry.errors += 1;
457
- byRoute.set(route, entry);
458
- }
459
- const stats = [];
460
- for (const [route, { durations, total, errors }] of byRoute) {
461
- if (total === 0) continue;
462
- const avgMs = durations.reduce((a, d) => a + d, 0) / durations.length;
463
- const sorted = durations.toSorted((a, b) => a - b);
464
- const p95Index = Math.floor(sorted.length * 0.95);
465
- const p95Ms = sorted[p95Index] ?? sorted.at(-1) ?? 0;
466
- stats.push({ route, total, errors, avgMs, p95Ms });
467
- }
468
- stats.sort((a, b) => b.total - a.total);
469
- return stats;
470
- }
471
- function findHotSpanNames(spans, topN) {
472
- const byName = /* @__PURE__ */ new Map();
473
- for (const span of spans) {
474
- const list = byName.get(span.name) ?? [];
475
- list.push(span.durationMs);
476
- byName.set(span.name, list);
477
- }
478
- const hot = [];
479
- for (const [name, durations] of byName) {
480
- if (durations.length === 0) continue;
481
- const avgMs = durations.reduce((a, d) => a + d, 0) / durations.length;
482
- const sorted = durations.toSorted((a, b) => a - b);
483
- const p95Index = Math.floor(sorted.length * 0.95);
484
- const p95Ms = sorted[p95Index] ?? sorted.at(-1) ?? 0;
485
- hot.push({ name, avgMs, p95Ms, count: durations.length });
486
- }
487
- hot.sort((a, b) => b.p95Ms - a.p95Ms);
488
- return hot.slice(0, topN);
489
- }
490
-
491
- // src/lib/filters.ts
492
- function getServiceName(span) {
493
- const attrs = span.attributes ?? {};
494
- return attrs["service.name"] ?? void 0;
495
- }
496
- function getRoute(span) {
497
- const attrs = span.attributes ?? {};
498
- return attrs["http.route"] ?? void 0;
499
- }
500
- function getStatusCode(span) {
501
- const attrs = span.attributes ?? {};
502
- const code = attrs["http.status_code"];
503
- if (typeof code === "number") return code;
504
- if (typeof code === "string") {
505
- const n = Number(code);
506
- return Number.isFinite(n) ? n : void 0;
507
- }
508
- return void 0;
509
- }
510
- function applySpanFilters(spans, state) {
511
- const { serviceName, route, statusGroup, errorsOnly, searchQuery, traceId } = state;
512
- const q = searchQuery?.trim().toLowerCase() ?? "";
513
- return spans.filter((span) => {
514
- const attrs = span.attributes ?? {};
515
- if (traceId && span.traceId !== traceId) return false;
516
- if (errorsOnly && span.status !== "ERROR") return false;
517
- if (serviceName) {
518
- const svc = getServiceName(span);
519
- if (svc !== serviceName) return false;
520
- }
521
- if (route) {
522
- const r = getRoute(span);
523
- if (r !== route) return false;
524
- }
525
- if (statusGroup && statusGroup !== "all") {
526
- const code = getStatusCode(span);
527
- if (!code) return false;
528
- if (statusGroup === "2xx" && (code < 200 || code >= 300)) return false;
529
- if (statusGroup === "4xx" && (code < 400 || code >= 500)) return false;
530
- if (statusGroup === "5xx" && (code < 500 || code >= 600)) return false;
531
- }
532
- if (q) {
533
- const nameMatch = span.name.toLowerCase().includes(q);
534
- const attrMatch = Object.entries(attrs).some(
535
- ([k, v]) => `${k}:${String(v)}`.toLowerCase().includes(q)
536
- );
537
- if (!nameMatch && !attrMatch) return false;
538
- }
539
- return true;
540
- });
541
- }
542
-
543
- // src/lib/error-model.ts
544
- function getServiceNameFromSpans(spans) {
545
- for (const span of spans) {
546
- const svc = span.attributes?.["service.name"];
547
- if (typeof svc === "string" && svc.trim()) return svc;
548
- }
549
- return "unknown";
550
- }
551
- function getRouteFromSpans(spans) {
552
- for (const span of spans) {
553
- const route = span.attributes?.["http.route"];
554
- if (typeof route === "string" && route.trim()) return route;
555
- }
556
- return void 0;
557
- }
558
- function getStatusCodeFromSpans(spans) {
559
- for (const span of spans) {
560
- const code = span.attributes?.["http.status_code"];
561
- if (typeof code === "number") return code;
562
- if (typeof code === "string") {
563
- const n = Number(code);
564
- if (Number.isFinite(n)) return n;
565
- }
566
- }
567
- return void 0;
568
- }
569
- function buildErrorSummaries(traceSummaries) {
570
- const out = [];
571
- for (const t2 of traceSummaries) {
572
- const errorSpans = t2.spans.filter((s) => s.status === "ERROR");
573
- if (errorSpans.length === 0) continue;
574
- out.push({
575
- traceId: t2.traceId,
576
- rootName: t2.rootName,
577
- serviceName: getServiceNameFromSpans(t2.spans),
578
- route: getRouteFromSpans(t2.spans),
579
- statusCode: getStatusCodeFromSpans(t2.spans),
580
- errorCount: errorSpans.length,
581
- lastEndTime: t2.lastEndTime
582
- });
583
- }
584
- out.sort((a, b) => b.lastEndTime - a.lastEndTime);
585
- return out;
586
- }
587
-
588
- // src/lib/topology-model.ts
589
- function getServiceName2(span) {
590
- const attrs = span.attributes ?? {};
591
- const serviceName = attrs["service.name"] ?? attrs["resource.service.name"];
592
- return serviceName || "unknown";
593
- }
594
- function getPeerService(span) {
595
- const attrs = span.attributes ?? {};
596
- const peerService = attrs["peer.service"] ?? attrs["db.system"] ?? attrs["messaging.system"] ?? attrs["http.host"];
597
- return peerService ?? null;
598
- }
599
- function buildServiceGraph(spans) {
600
- const byService = /* @__PURE__ */ new Map();
601
- for (const span of spans) {
602
- const svc = getServiceName2(span);
603
- const entry = byService.get(svc) ?? {
604
- durations: [],
605
- spanCount: 0,
606
- errorCount: 0
607
- };
608
- entry.spanCount += 1;
609
- entry.durations.push(span.durationMs);
610
- if (span.status === "ERROR") entry.errorCount += 1;
611
- byService.set(svc, entry);
612
- }
613
- const services = [];
614
- for (const [serviceName, { durations, spanCount, errorCount }] of byService) {
615
- if (spanCount === 0) continue;
616
- const avgDurationMs = durations.reduce((acc, d) => acc + d, 0) / durations.length;
617
- const sorted = durations.toSorted((a, b) => a - b);
618
- const p95Index = Math.floor(sorted.length * 0.95);
619
- const p95DurationMs = sorted[p95Index] ?? sorted.at(-1) ?? 0;
620
- services.push({
621
- serviceName,
622
- spanCount,
623
- errorCount,
624
- avgDurationMs,
625
- p95DurationMs
626
- });
627
- }
628
- const byEdge = /* @__PURE__ */ new Map();
629
- for (const span of spans) {
630
- const to = getPeerService(span);
631
- if (!to) continue;
632
- const from = getServiceName2(span);
633
- const key = `${from}\u2192${to}`;
634
- const entry = byEdge.get(key) ?? { spanCount: 0, errorCount: 0 };
635
- entry.spanCount += 1;
636
- if (span.status === "ERROR") entry.errorCount += 1;
637
- byEdge.set(key, entry);
638
- }
639
- const edges = [];
640
- for (const [key, { spanCount, errorCount }] of byEdge) {
641
- const [fromService, toService] = key.split("\u2192");
642
- edges.push({ fromService, toService, spanCount, errorCount });
643
- }
644
- services.sort((a, b) => b.spanCount - a.spanCount);
645
- edges.sort((a, b) => b.spanCount - a.spanCount);
646
- return { services, edges };
647
- }
648
-
649
- // src/lib/topology-render.ts
650
- function renderTopologyAscii(graph) {
651
- if (graph.services.length === 0) {
652
- return [" No services detected yet."];
653
- }
654
- const targetServices = new Set(graph.edges.map((e) => e.toService));
655
- const roots = graph.services.filter(
656
- (s) => !targetServices.has(s.serviceName)
657
- );
658
- const rootList = roots.length > 0 ? roots : [...graph.services];
659
- const lines = [];
660
- for (const root of rootList) {
661
- renderNode(graph, root.serviceName, "", true, lines, /* @__PURE__ */ new Set());
662
- }
663
- return lines;
664
- }
665
- function renderNode(graph, serviceName, prefix, isRoot, lines, ancestors) {
666
- const svc = graph.services.find((s) => s.serviceName === serviceName);
667
- const label = svc ? formatServiceLine(svc) : `[${serviceName}]`;
668
- if (isRoot) {
669
- lines.push(label);
670
- }
671
- if (ancestors.has(serviceName)) return;
672
- const pathAncestors = new Set(ancestors);
673
- pathAncestors.add(serviceName);
674
- const outgoing = graph.edges.filter((e) => e.fromService === serviceName);
675
- for (let i = 0; i < outgoing.length; i++) {
676
- const edge = outgoing[i];
677
- const isLast = i === outgoing.length - 1;
678
- const connector = isLast ? "\u2514" : "\u251C";
679
- const childPrefix = isLast ? " " : "\u2502 ";
680
- const downstream = graph.services.find(
681
- (s) => s.serviceName === edge.toService
682
- );
683
- const edgeLabel = formatEdgeLabel(edge);
684
- const downstreamLabel = downstream ? formatServiceLine(downstream) : `[${edge.toService}]`;
685
- lines.push(`${prefix} ${connector}\u2500\u2500${edgeLabel}\u2500\u2500\u2192 ${downstreamLabel}`);
686
- renderNode(
687
- graph,
688
- edge.toService,
689
- prefix + " " + childPrefix,
690
- false,
691
- lines,
692
- pathAncestors
693
- );
694
- }
695
- }
696
- function formatServiceLine(svc) {
697
- const errPart = svc.errorCount > 0 ? ` \xB7 ${svc.errorCount} err` : "";
698
- return `[${svc.serviceName}] ${svc.spanCount} spans${errPart} \xB7 p95 ${formatDurationMs(svc.p95DurationMs)}`;
699
- }
700
- function formatEdgeLabel(edge) {
701
- const errPart = edge.errorCount > 0 ? `, ${edge.errorCount} err` : "";
702
- return `(${edge.spanCount}${errPart})`;
703
- }
704
-
705
- // src/lib/export-model.ts
706
- function exportTraceToJson(trace, logs) {
707
- const exported = {
708
- traceId: trace.traceId,
709
- rootName: trace.rootName,
710
- durationMs: trace.durationMs,
711
- lastEndTime: trace.lastEndTime,
712
- spans: trace.spans.map((s) => ({
713
- name: s.name,
714
- spanId: s.spanId,
715
- parentSpanId: s.parentSpanId,
716
- startTime: s.startTime,
717
- endTime: s.endTime,
718
- durationMs: s.durationMs,
719
- status: s.status,
720
- kind: s.kind,
721
- attributes: s.attributes
722
- })),
723
- logs: logs.map((l) => ({
724
- time: l.time,
725
- level: l.level,
726
- message: l.message,
727
- traceId: l.traceId,
728
- spanId: l.spanId,
729
- attributes: l.attributes
730
- }))
731
- };
732
- return JSON.stringify(exported, null, 2);
733
- }
734
-
735
- // src/ai/provider.ts
736
- async function detectOllama(baseUrl = "http://127.0.0.1:11434") {
737
- try {
738
- const res = await fetch(`${baseUrl}/api/tags`, {
739
- signal: AbortSignal.timeout(1e3)
740
- });
741
- return res.ok;
742
- } catch {
743
- return false;
744
- }
745
- }
746
- function resolveConfig(options = {}) {
747
- const provider = options.provider ?? process.env.AI_PROVIDER ?? void 0;
748
- const model = options.model ?? process.env.AI_MODEL;
749
- const apiKey = options.apiKey ?? process.env.AI_API_KEY ?? (provider === "openai" ? process.env.OPENAI_API_KEY : void 0);
750
- const baseUrl = options.baseUrl ?? process.env.AI_BASE_URL;
751
- if (provider) {
752
- return {
753
- provider,
754
- model: model ?? (provider === "ollama" ? "granite4" : "gpt-4o"),
755
- apiKey,
756
- baseUrl
757
- };
758
- }
759
- return null;
760
- }
761
- var defaultAutoDetectDeps = { detectOllama };
762
- async function resolveConfigWithAutoDetect(options = {}, deps = defaultAutoDetectDeps) {
763
- const config = resolveConfig(options);
764
- if (config) return config;
765
- const ollamaUrl = options.baseUrl ?? process.env.AI_BASE_URL ?? "http://127.0.0.1:11434";
766
- if (await deps.detectOllama(ollamaUrl)) {
767
- return {
768
- provider: "ollama",
769
- model: options.model ?? process.env.AI_MODEL ?? "granite4",
770
- baseUrl: ollamaUrl
771
- };
772
- }
773
- const openaiKey = options.apiKey ?? process.env.AI_API_KEY ?? process.env.OPENAI_API_KEY;
774
- if (openaiKey) {
775
- return {
776
- provider: "openai",
777
- model: options.model ?? process.env.AI_MODEL ?? "gpt-4o",
778
- apiKey: openaiKey
779
- };
780
- }
781
- return null;
782
- }
783
- async function createAIModel(config) {
784
- switch (config.provider) {
785
- case "ollama": {
786
- const { createOllama } = await import('ai-sdk-ollama');
787
- const ollama = createOllama({
788
- baseURL: config.baseUrl ?? "http://127.0.0.1:11434"
789
- });
790
- return { model: ollama(config.model), providerType: "ollama", config };
791
- }
792
- case "openai": {
793
- const { createOpenAI } = await import('@ai-sdk/openai');
794
- const openai = createOpenAI({
795
- apiKey: config.apiKey,
796
- ...config.baseUrl ? { baseURL: config.baseUrl } : {}
797
- });
798
- return { model: openai(config.model), providerType: "openai", config };
799
- }
800
- case "openai-compatible": {
801
- const { createOpenAICompatible } = await import('@ai-sdk/openai-compatible');
802
- const provider = createOpenAICompatible({
803
- baseURL: config.baseUrl ?? "http://127.0.0.1:11434/v1",
804
- name: "custom",
805
- ...config.apiKey ? { headers: { Authorization: `Bearer ${config.apiKey}` } } : {}
806
- });
807
- return {
808
- model: provider(config.model),
809
- providerType: "openai-compatible",
810
- config
811
- };
812
- }
813
- default: {
814
- throw new Error(
815
- `Unsupported provider: "${config.provider}". Expected "ollama", "openai", or "openai-compatible".`
816
- );
817
- }
818
- }
819
- }
820
-
821
- // src/ai/system-prompt.ts
822
- function buildSystemPrompt(viewMode, contextJson) {
823
- return `You are an OpenTelemetry expert assistant analyzing live telemetry data from a running application.
824
- The user is viewing their ${viewMode} dashboard in a terminal TUI.
825
-
826
- You have tools to query the telemetry data precisely. Use them to answer questions:
827
- - getOverviewStats: high-level stats (spans, errors, latency)
828
- - listServices: all services with error rates and p95
829
- - findSlowestSpans: find slow spans, optionally by service
830
- - findErrorTraces: find traces with errors
831
- - getTraceDetail: deep dive into a specific trace
832
- - searchSpans: search spans by name
833
- - searchLogs: search logs by message content
834
- - renderUI: display rich terminal UI (tables, charts, badges)
835
-
836
- ## Workflow
837
- 1. Use data tools first to gather data
838
- 2. Use renderUI to display structured results as tables, charts, or cards
839
- 3. Add a brief text explanation after the rendered UI
840
-
841
- ## When to use renderUI
842
- Use renderUI for tables, comparisons, and metrics. Do NOT use it for short text answers.
843
-
844
- renderUI spec format: { root: "id", elements: { "id": { type: "ComponentName", props: {...}, children: [] } } }
845
-
846
- Components: Table (columns, rows), KeyValue (label, value), Badge (label, variant: success/error/warning/info), BarChart (data: [{label,value}]), Card (title, children), Heading (text), Divider, Text (text, color, bold), Box (flexDirection, children).
847
-
848
- Table example: { type: "Table", props: { columns: [{ header: "Name", key: "name" }], rows: [{ name: "api" }] }, children: [] }
849
-
850
- Keep text responses under 300 words.
851
- Use specific span names, durations, and attribute values from the data.
852
-
853
- Current dashboard summary:
854
- ${contextJson}`;
855
- }
856
- var COMPONENT_NAMES = Object.keys(catalog.standardComponentDefinitions);
857
- var t = ai.tool;
858
- function createTelemetryTools(ctx, onRenderUI) {
859
- return {
860
- getOverviewStats: t({
861
- description: "Get high-level stats: total spans, error count, average duration, p95 duration, and service count.",
862
- parameters: zod.z.object({}),
863
- execute: async () => ({
864
- totalSpans: ctx.stats.total,
865
- errors: ctx.stats.errors,
866
- avgMs: Math.round(ctx.stats.avg),
867
- p95Ms: Math.round(ctx.stats.p95),
868
- serviceCount: ctx.serviceStats.length,
869
- traceCount: ctx.traces.length
870
- })
871
- }),
872
- listServices: t({
873
- description: "List all services with their span counts, error counts, and p95 latencies.",
874
- parameters: zod.z.object({}),
875
- execute: async () => ctx.serviceStats.map((s) => ({
876
- serviceName: s.serviceName,
877
- total: s.total,
878
- errors: s.errors,
879
- avgMs: Math.round(s.avgMs),
880
- p95Ms: Math.round(s.p95Ms)
881
- }))
882
- }),
883
- findSlowestSpans: t({
884
- description: "Find the slowest spans, optionally filtered by service name. Returns span name, duration, status, and key attributes.",
885
- parameters: zod.z.object({
886
- service: zod.z.string().optional().describe("Filter by service name"),
887
- limit: zod.z.number().optional().describe("Max results (default 10)")
888
- }),
889
- execute: async ({
890
- service,
891
- limit
892
- }) => {
893
- const max = limit ?? 10;
894
- let filtered = ctx.spans;
895
- if (service) {
896
- filtered = filtered.filter(
897
- (s) => s.attributes?.["service.name"] === service
898
- );
899
- }
900
- return filtered.toSorted((a, b) => b.durationMs - a.durationMs).slice(0, max).map((s) => ({
901
- name: s.name,
902
- durationMs: Math.round(s.durationMs),
903
- status: s.status,
904
- service: s.attributes?.["service.name"] ?? "unknown",
905
- route: s.attributes?.["http.route"],
906
- traceId: s.traceId.slice(0, 8)
907
- }));
908
- }
909
- }),
910
- findErrorTraces: t({
911
- description: "Find traces that contain errors, with root span name, service, route, and error count.",
912
- parameters: zod.z.object({
913
- service: zod.z.string().optional().describe("Filter by service name"),
914
- limit: zod.z.number().optional().describe("Max results (default 10)")
915
- }),
916
- execute: async ({
917
- service,
918
- limit
919
- }) => {
920
- const max = limit ?? 10;
921
- let errors = ctx.errorSummaries;
922
- if (service) {
923
- errors = errors.filter((e) => e.serviceName === service);
924
- }
925
- return errors.slice(0, max).map((e) => ({
926
- traceId: e.traceId.slice(0, 8),
927
- rootName: e.rootName,
928
- serviceName: e.serviceName,
929
- route: e.route,
930
- errorCount: e.errorCount
931
- }));
932
- }
933
- }),
934
- getTraceDetail: t({
935
- description: "Get full detail of a specific trace by trace ID prefix. Returns all spans with their parent relationships, durations, and attributes.",
936
- parameters: zod.z.object({
937
- traceIdPrefix: zod.z.string().describe("First 8+ characters of the trace ID")
938
- }),
939
- execute: async ({ traceIdPrefix }) => {
940
- const trace = ctx.traces.find(
941
- (t2) => t2.traceId.startsWith(traceIdPrefix)
942
- );
943
- if (!trace) {
944
- return { error: `No trace found matching ${traceIdPrefix}` };
945
- }
946
- const traceLogs = ctx.logs.filter((l) => l.traceId === trace.traceId);
947
- return {
948
- traceId: trace.traceId.slice(0, 16),
949
- rootName: trace.rootName,
950
- durationMs: Math.round(trace.durationMs),
951
- hasError: trace.hasError,
952
- spanCount: trace.spanCount,
953
- spans: trace.spans.map((s) => ({
954
- name: s.name,
955
- durationMs: Math.round(s.durationMs),
956
- status: s.status,
957
- kind: s.kind,
958
- parentSpanId: s.parentSpanId?.slice(0, 8),
959
- attrs: Object.fromEntries(
960
- Object.entries(s.attributes ?? {}).filter(
961
- ([k]) => [
962
- "http.method",
963
- "http.route",
964
- "http.status_code",
965
- "db.operation",
966
- "db.system",
967
- "service.name",
968
- "error.message",
969
- "error.type"
970
- ].includes(k)
971
- )
972
- )
973
- })),
974
- logs: traceLogs.slice(0, 10).map((l) => ({
975
- level: l.level,
976
- message: l.message.slice(0, 100)
977
- }))
978
- };
979
- }
980
- }),
981
- searchSpans: t({
982
- description: "Search spans by name pattern (case-insensitive substring match). Returns matching spans with details.",
983
- parameters: zod.z.object({
984
- query: zod.z.string().describe("Search string to match against span names"),
985
- limit: zod.z.number().optional().describe("Max results (default 20)")
986
- }),
987
- execute: async ({ query, limit }) => {
988
- const max = limit ?? 20;
989
- const q = query.toLowerCase();
990
- return ctx.spans.filter((s) => s.name.toLowerCase().includes(q)).slice(0, max).map((s) => ({
991
- name: s.name,
992
- durationMs: Math.round(s.durationMs),
993
- status: s.status,
994
- traceId: s.traceId.slice(0, 8),
995
- service: s.attributes?.["service.name"] ?? "unknown"
996
- }));
997
- }
998
- }),
999
- searchLogs: t({
1000
- description: "Search logs by message content (case-insensitive). Returns matching log entries.",
1001
- parameters: zod.z.object({
1002
- query: zod.z.string().describe("Search string to match against log messages"),
1003
- level: zod.z.enum(["debug", "info", "warn", "error"]).optional().describe("Filter by log level"),
1004
- limit: zod.z.number().optional().describe("Max results (default 20)")
1005
- }),
1006
- execute: async ({
1007
- query,
1008
- level,
1009
- limit
1010
- }) => {
1011
- const max = limit ?? 20;
1012
- const q = query.toLowerCase();
1013
- let filtered = ctx.logs.filter(
1014
- (l) => l.message.toLowerCase().includes(q)
1015
- );
1016
- if (level) {
1017
- filtered = filtered.filter((l) => l.level === level);
1018
- }
1019
- return filtered.slice(0, max).map((l) => ({
1020
- level: l.level,
1021
- message: l.message.slice(0, 200),
1022
- traceId: l.traceId?.slice(0, 8),
1023
- attrs: l.attributes
1024
- }));
1025
- }
1026
- }),
1027
- renderUI: t({
1028
- description: "Render rich terminal UI (tables, charts, badges) to display structured data. Use this when showing tabular data, comparisons, or metrics \u2014 not for short text answers. Available components: Table (columns + rows), KeyValue (key-value pairs), Badge (status labels: default/info/success/warning/error), BarChart (horizontal bars with labels), Card (grouped content with title), Heading (section title), Divider (separator), Text (styled text), Box (layout container).",
1029
- parameters: zod.z.object({
1030
- spec: zod.z.object({
1031
- root: zod.z.string().describe("ID of the root element"),
1032
- elements: zod.z.record(
1033
- zod.z.string(),
1034
- zod.z.object({
1035
- type: zod.z.enum(COMPONENT_NAMES).describe("Component name"),
1036
- props: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
1037
- children: zod.z.array(zod.z.string()).describe("Child element keys")
1038
- })
1039
- ).describe("Map of element ID to component definition")
1040
- }).describe("json-render spec defining the UI to display")
1041
- }),
1042
- execute: async ({ spec }) => {
1043
- const validation = core.validateSpec(spec);
1044
- if (!validation.valid) {
1045
- return {
1046
- rendered: false,
1047
- error: validation.issues.map((i) => i.message).join("; ")
1048
- };
1049
- }
1050
- onRenderUI?.(spec);
1051
- return { rendered: true };
1052
- }
1053
- })
1054
- };
1055
- }
1056
-
1057
- // src/ai/stream.ts
1058
- async function providerStreamText(providerType, params) {
1059
- if (providerType === "ollama") {
1060
- const mod2 = await import('ai-sdk-ollama');
1061
- const result = await mod2.streamText(
1062
- params
1063
- );
1064
- return result;
1065
- }
1066
- const mod = await import('ai');
1067
- return mod.streamText(
1068
- params
1069
- );
1070
- }
1071
- var KEY_ATTR_KEYS = /* @__PURE__ */ new Set([
1072
- "http.route",
1073
- "http.method",
1074
- "db.operation",
1075
- "db.statement",
1076
- "db.system",
1077
- "code.function",
1078
- "code.filepath",
1079
- "code.lineno",
1080
- "user.id",
1081
- "order.id"
2
+ const require_src = require('./src-H7oZS-9-.cjs');
3
+ let node_fs = require("node:fs");
4
+ let node_http = require("node:http");
5
+ let node_path = require("node:path");
6
+ node_path = require_src.__toESM(node_path, 1);
7
+
8
+ //#region src/listen.ts
9
+ const LOOPBACK = new Set([
10
+ "localhost",
11
+ "127.0.0.1",
12
+ "::1"
1082
13
  ]);
1083
- var THROTTLE_MS = 50;
1084
- var MAX_TRACES = 50;
1085
- var NEW_ERROR_DISPLAY_MS = 2e3;
1086
- var RECORD_LIMIT_DEFAULT = 200;
1087
- var LIST_HEIGHT = 20;
1088
- function Dashboard({
1089
- title,
1090
- showStats,
1091
- maxSpans,
1092
- colors,
1093
- stream,
1094
- logStream,
1095
- aiConfig
1096
- }) {
1097
- const [paused, setPaused] = react.useState(false);
1098
- const [recording, setRecording] = react.useState(false);
1099
- const [spans, setSpans] = react.useState([]);
1100
- const [selected, setSelected] = react.useState(0);
1101
- const [filterErrorsOnly, setFilterErrorsOnly] = react.useState(false);
1102
- const [searchQuery, setSearchQuery] = react.useState("");
1103
- const [showHelp, setShowHelp] = react.useState(false);
1104
- const [viewMode, setViewMode] = react.useState("trace");
1105
- const [spanFilters, setSpanFilters] = react.useState({
1106
- statusGroup: "all"
1107
- });
1108
- const [drilldownTraceId, setDrilldownTraceId] = react.useState(null);
1109
- const [drilldownSelectedIndex, setDrilldownSelectedIndex] = react.useState(0);
1110
- const [drilldownScrollOffset, setDrilldownScrollOffset] = react.useState(0);
1111
- const [drilldownTab, setDrilldownTab] = react.useState("timeline");
1112
- const [newErrorCount, setNewErrorCount] = react.useState(0);
1113
- const [searchMode, setSearchMode] = react.useState(false);
1114
- const [traceIdMode, setTraceIdMode] = react.useState(false);
1115
- const [traceIdInput, setTraceIdInput] = react.useState("");
1116
- const throttleRef = react.useRef(null);
1117
- const pendingSpansRef = react.useRef([]);
1118
- const [logs, setLogs] = react.useState([]);
1119
- const [aiMessages, setAiMessages] = react.useState([]);
1120
- const [aiInput, setAiInput] = react.useState("");
1121
- const [aiState, setAiState] = react.useState({ status: "unconfigured" });
1122
- const [aiInputMode, setAiInputMode] = react.useState(false);
1123
- const [aiSpec, setAiSpec] = react.useState(null);
1124
- const aiModelRef = react.useRef(null);
1125
- const aiAbortRef = react.useRef(null);
1126
- react.useEffect(() => {
1127
- let cancelled = false;
1128
- resolveConfigWithAutoDetect(aiConfig).then(async (config) => {
1129
- if (cancelled || !config) return;
1130
- try {
1131
- const result = await createAIModel(config);
1132
- aiModelRef.current = result;
1133
- setAiState({ status: "idle" });
1134
- } catch {
1135
- setAiState({
1136
- status: "error",
1137
- message: "Failed to initialize AI model"
1138
- });
1139
- }
1140
- });
1141
- return () => {
1142
- cancelled = true;
1143
- };
1144
- }, [aiConfig]);
1145
- react.useEffect(() => {
1146
- if (!logStream) return;
1147
- const unsubscribe = logStream.onLog((event) => {
1148
- if (paused) return;
1149
- if (recording) {
1150
- setLogs((prev) => {
1151
- const next = [event, ...prev];
1152
- if (next.length >= RECORD_LIMIT_DEFAULT) {
1153
- setRecording(false);
1154
- setPaused(true);
1155
- }
1156
- return next.slice(0, RECORD_LIMIT_DEFAULT);
1157
- });
1158
- return;
1159
- }
1160
- setLogs((prev) => [event, ...prev].slice(0, maxSpans));
1161
- });
1162
- return () => {
1163
- unsubscribe();
1164
- };
1165
- }, [logStream, paused, maxSpans, recording]);
1166
- react.useEffect(() => {
1167
- const flush = () => {
1168
- const batch = pendingSpansRef.current;
1169
- pendingSpansRef.current = [];
1170
- if (batch.length === 0) return;
1171
- setSpans((prev) => {
1172
- const next = [...batch, ...prev];
1173
- return next.slice(0, maxSpans);
1174
- });
1175
- setSelected(0);
1176
- setDrilldownTraceId(null);
1177
- };
1178
- const unsubscribe = stream.onSpanEnd((span) => {
1179
- if (paused) return;
1180
- if (span.status === "ERROR") {
1181
- setNewErrorCount((n) => n + 1);
1182
- setTimeout(
1183
- () => setNewErrorCount((n) => Math.max(0, n - 1)),
1184
- NEW_ERROR_DISPLAY_MS
1185
- );
1186
- }
1187
- if (recording) {
1188
- setSpans((prev) => {
1189
- const next = [span, ...prev];
1190
- if (next.length >= RECORD_LIMIT_DEFAULT) {
1191
- setRecording(false);
1192
- setPaused(true);
1193
- }
1194
- return next.slice(0, RECORD_LIMIT_DEFAULT);
1195
- });
1196
- setSelected(0);
1197
- setDrilldownTraceId(null);
1198
- return;
1199
- }
1200
- pendingSpansRef.current = [span, ...pendingSpansRef.current];
1201
- if (throttleRef.current) return;
1202
- throttleRef.current = setTimeout(() => {
1203
- throttleRef.current = null;
1204
- flush();
1205
- }, THROTTLE_MS);
1206
- });
1207
- return () => {
1208
- if (throttleRef.current) clearTimeout(throttleRef.current);
1209
- unsubscribe();
1210
- };
1211
- }, [stream, paused, maxSpans, recording]);
1212
- const filteredSpanBuffer = react.useMemo(
1213
- () => applySpanFilters(spans, {
1214
- ...spanFilters,
1215
- errorsOnly: filterErrorsOnly,
1216
- searchQuery
1217
- }),
1218
- [spans, spanFilters, filterErrorsOnly, searchQuery]
1219
- );
1220
- const traceMap = react.useMemo(
1221
- () => buildTraceMap(filteredSpanBuffer, MAX_TRACES),
1222
- [filteredSpanBuffer]
1223
- );
1224
- const traceSummaries = react.useMemo(
1225
- () => buildTraceSummaries(traceMap),
1226
- [traceMap]
1227
- );
1228
- const filteredSummaries = react.useMemo(() => {
1229
- const base = filterTraceSummaries(traceSummaries, "");
1230
- return spanFilters.traceId ? base.filter((t2) => t2.traceId === spanFilters.traceId) : base;
1231
- }, [traceSummaries, spanFilters.traceId]);
1232
- const filteredSpans = react.useMemo(
1233
- () => filterBySearch(filteredSpanBuffer, ""),
1234
- [filteredSpanBuffer]
1235
- );
1236
- const stats = react.useMemo(() => computeStats(spans), [spans]);
1237
- const perSpanNameStats = react.useMemo(
1238
- () => computePerSpanNameStats(spans),
1239
- [spans]
1240
- );
1241
- const logStats = react.useMemo(() => computeLogStats(logs), [logs]);
1242
- const filteredLogs = react.useMemo(() => {
1243
- const traceFilteredLogs = spanFilters.traceId ? logs.filter((l) => l.traceId === spanFilters.traceId) : logs;
1244
- return filterLogsBySearch(traceFilteredLogs, searchQuery);
1245
- }, [logs, searchQuery, spanFilters.traceId]);
1246
- const serviceStats = react.useMemo(() => computeServiceStats(spans), [spans]);
1247
- const selectedServiceName = serviceStats[selected]?.serviceName ?? null;
1248
- const spansForSelectedService = react.useMemo(() => {
1249
- if (!selectedServiceName) return spans;
1250
- return spans.filter(
1251
- (s) => s.attributes?.["service.name"] === selectedServiceName
1252
- );
1253
- }, [spans, selectedServiceName]);
1254
- const selectedServiceRouteStats = react.useMemo(
1255
- () => computeRouteStats(spansForSelectedService).slice(0, 8),
1256
- [spansForSelectedService]
1257
- );
1258
- const selectedServiceHotSpans = react.useMemo(
1259
- () => findHotSpanNames(spansForSelectedService, 8),
1260
- [spansForSelectedService]
1261
- );
1262
- const selectedTraceSummary = drilldownTraceId == null ? filteredSummaries[selected] ?? null : filteredSummaries.find((t2) => t2.traceId === drilldownTraceId) ?? null;
1263
- const serviceGraph = react.useMemo(() => buildServiceGraph(spans), [spans]);
1264
- const topologyLines = react.useMemo(() => renderTopologyAscii(serviceGraph), [serviceGraph]);
1265
- const errorSummaries = react.useMemo(
1266
- () => buildErrorSummaries(traceSummaries),
1267
- [traceSummaries]
1268
- );
1269
- const filteredErrorSummaries = spanFilters.traceId ? errorSummaries.filter((e) => e.traceId === spanFilters.traceId) : errorSummaries;
1270
- const traceTree = selectedTraceSummary == null ? [] : flattenTraceTree(buildTraceTree(selectedTraceSummary.spans));
1271
- const waterfallSpans = selectedTraceSummary == null ? [] : sortSpansForWaterfall(selectedTraceSummary.spans);
1272
- const currentSpanInTrace = traceTree[drilldownSelectedIndex] ?? null;
1273
- const currentSpanInFlat = filteredSpans[selected] ?? null;
1274
- const selectedTraceSummaryForDetails = viewMode === "trace" && drilldownTraceId == null && filteredSummaries[selected] ? filteredSummaries[selected] : null;
1275
- const rootSpanOfSelectedTrace = selectedTraceSummaryForDetails != null && selectedTraceSummaryForDetails.spans.length > 0 ? selectedTraceSummaryForDetails.spans.find(
1276
- (s) => !selectedTraceSummaryForDetails.spans.some(
1277
- (p) => p.spanId === s.parentSpanId
1278
- )
1279
- ) ?? selectedTraceSummaryForDetails.spans[0] : null;
1280
- const currentSpan = viewMode === "trace" ? drilldownTraceId == null ? rootSpanOfSelectedTrace ?? null : currentSpanInTrace?.span ?? null : viewMode === "span" ? currentSpanInFlat : null;
1281
- const selectedTraceLogs = selectedTraceSummary?.traceId && logs.length > 0 ? logs.filter((l) => l.traceId === selectedTraceSummary.traceId) : [];
1282
- const timelineItems = selectedTraceSummary && (selectedTraceSummary.spans.length > 0 || selectedTraceLogs.length > 0) ? buildTraceTimeline(selectedTraceSummary.spans, selectedTraceLogs) : [];
1283
- const drilldownSpans = react.useMemo(
1284
- () => drilldownTraceId ? spans.filter((s) => s.traceId === drilldownTraceId) : [],
1285
- [spans, drilldownTraceId]
1286
- );
1287
- const drilldownTree = react.useMemo(
1288
- () => drilldownSpans.length > 0 ? flattenTraceTree(buildTraceTree(drilldownSpans)) : [],
1289
- [drilldownSpans]
1290
- );
1291
- const drilldownLogs = react.useMemo(
1292
- () => drilldownTraceId ? logs.filter((l) => l.traceId === drilldownTraceId) : [],
1293
- [logs, drilldownTraceId]
1294
- );
1295
- const drilldownTimeline = react.useMemo(
1296
- () => drilldownSpans.length > 0 || drilldownLogs.length > 0 ? buildTraceTimeline(drilldownSpans, drilldownLogs) : [],
1297
- [drilldownSpans, drilldownLogs]
1298
- );
1299
- const drilldownSummary = react.useMemo(
1300
- () => drilldownTraceId ? traceSummaries.find((t2) => t2.traceId === drilldownTraceId) ?? null : null,
1301
- [traceSummaries, drilldownTraceId]
1302
- );
1303
- const drilldownSelectedItem = react.useMemo(() => {
1304
- if (!drilldownTraceId) return null;
1305
- if (drilldownTab === "timeline") {
1306
- const item = drilldownTimeline[drilldownSelectedIndex];
1307
- if (!item) return null;
1308
- return item;
1309
- }
1310
- if (drilldownTab === "spans") {
1311
- return drilldownTree[drilldownSelectedIndex] ? {
1312
- type: "span",
1313
- span: drilldownTree[drilldownSelectedIndex].span
1314
- } : null;
1315
- }
1316
- if (drilldownTab === "logs") {
1317
- return drilldownLogs[drilldownSelectedIndex] ? { type: "log", log: drilldownLogs[drilldownSelectedIndex] } : null;
1318
- }
1319
- return null;
1320
- }, [
1321
- drilldownTraceId,
1322
- drilldownTab,
1323
- drilldownSelectedIndex,
1324
- drilldownTimeline,
1325
- drilldownTree,
1326
- drilldownLogs
1327
- ]);
1328
- const sendAIQuery = async (question) => {
1329
- const aiResult = aiModelRef.current;
1330
- if (!aiResult || aiState.status === "streaming") return;
1331
- const userMsg = { role: "user", content: question };
1332
- setAiMessages((prev) => [...prev, userMsg]);
1333
- setAiInput("");
1334
- const abort = new AbortController();
1335
- aiAbortRef.current = abort;
1336
- setAiSpec(null);
1337
- setAiState({ status: "streaming", abortController: abort });
1338
- const toolCtx = {
1339
- spans,
1340
- logs,
1341
- traces: traceSummaries,
1342
- stats,
1343
- serviceStats,
1344
- errorSummaries
1345
- };
1346
- const tools = createTelemetryTools(toolCtx, (spec) => setAiSpec(spec));
1347
- const statsContext = JSON.stringify({
1348
- viewMode,
1349
- stats: {
1350
- totalSpans: stats.total,
1351
- errors: stats.errors,
1352
- avgMs: Math.round(stats.avg),
1353
- p95Ms: Math.round(stats.p95)
1354
- },
1355
- services: serviceStats.length,
1356
- traces: traceSummaries.length
1357
- });
1358
- const drilldownContext = drilldownTraceId ? `
1359
-
1360
- Currently viewing trace ${drilldownTraceId}. This trace has ${drilldownSpans.length} spans and ${drilldownLogs.length} logs. The root span is "${drilldownSummary?.rootName ?? "unknown"}" with duration ${drilldownSummary ? formatDurationMs(drilldownSummary.durationMs) : "unknown"}.` : "";
1361
- const systemPrompt = buildSystemPrompt(viewMode, statsContext) + drilldownContext;
1362
- try {
1363
- setAiMessages((prev) => [...prev, { role: "assistant", content: "" }]);
1364
- const result = await providerStreamText(aiResult.providerType, {
1365
- model: aiResult.model,
1366
- system: systemPrompt,
1367
- messages: [...aiMessages, userMsg].map((m) => ({
1368
- role: m.role,
1369
- content: m.content
1370
- })),
1371
- tools,
1372
- maxSteps: 10,
1373
- abortSignal: abort.signal
1374
- });
1375
- let fullText = "";
1376
- for await (const chunk of result.textStream) {
1377
- if (abort.signal.aborted) break;
1378
- fullText += chunk;
1379
- const captured = fullText;
1380
- setAiMessages((prev) => {
1381
- const updated = [...prev];
1382
- const lastMsg = updated.at(-1);
1383
- if (lastMsg?.role === "assistant") {
1384
- updated[updated.length - 1] = {
1385
- role: "assistant",
1386
- content: captured
1387
- };
1388
- }
1389
- return updated;
1390
- });
1391
- }
1392
- if (!fullText.trim()) {
1393
- setAiMessages((prev) => {
1394
- const updated = [...prev];
1395
- const lastMsg = updated.at(-1);
1396
- if (lastMsg?.role === "assistant" && !lastMsg.content.trim()) {
1397
- updated[updated.length - 1] = {
1398
- role: "assistant",
1399
- content: "(No response from model \u2014 try a simpler question or a larger model)"
1400
- };
1401
- }
1402
- return updated;
1403
- });
1404
- }
1405
- setAiState({ status: "idle" });
1406
- } catch (error) {
1407
- if (abort.signal.aborted) {
1408
- setAiState({ status: "idle" });
1409
- return;
1410
- }
1411
- const errorMsg = error instanceof Error ? error.message : String(error);
1412
- process.stderr.write(`[autotel-terminal] AI error: ${errorMsg}
1413
- `);
1414
- setAiState({
1415
- status: "error",
1416
- message: errorMsg
1417
- });
1418
- } finally {
1419
- aiAbortRef.current = null;
1420
- }
1421
- };
1422
- const { isRawModeSupported } = ink.useStdin();
1423
- ink.useInput(
1424
- (input, key) => {
1425
- if (showHelp && input !== "?") {
1426
- if (input === "?") setShowHelp(false);
1427
- return;
1428
- }
1429
- if (input === "?") {
1430
- setShowHelp((h) => !h);
1431
- return;
1432
- }
1433
- if (input === "/") {
1434
- setSearchMode((m) => !m);
1435
- if (searchMode) setSearchQuery("");
1436
- return;
1437
- }
1438
- if (searchMode) {
1439
- if (key.escape || key.return) {
1440
- setSearchMode(false);
1441
- } else if (key.backspace || key.delete) {
1442
- setSearchQuery((q) => q.slice(0, -1));
1443
- } else if (key.tab) {
1444
- if (searchQuery.length >= 4) {
1445
- const match = traceSummaries.find(
1446
- (t2) => t2.traceId.toLowerCase().startsWith(searchQuery.toLowerCase())
1447
- );
1448
- if (match) {
1449
- setSpanFilters((prev) => ({ ...prev, traceId: match.traceId }));
1450
- setSearchMode(false);
1451
- setSearchQuery("");
1452
- }
1453
- }
1454
- } else if (input && input.length === 1 && !key.ctrl && !key.meta) {
1455
- setSearchQuery((q) => q + input);
1456
- }
1457
- return;
1458
- }
1459
- if (traceIdMode) {
1460
- if (key.escape) {
1461
- setTraceIdMode(false);
1462
- setTraceIdInput("");
1463
- } else if (key.return) {
1464
- if (traceIdInput.trim()) {
1465
- const match = traceSummaries.find(
1466
- (t2) => t2.traceId.toLowerCase().startsWith(traceIdInput.toLowerCase())
1467
- );
1468
- if (match) {
1469
- setSpanFilters((prev) => ({ ...prev, traceId: match.traceId }));
1470
- }
1471
- } else {
1472
- setSpanFilters((prev) => {
1473
- const { traceId: _, ...rest } = prev;
1474
- return rest;
1475
- });
1476
- }
1477
- setTraceIdMode(false);
1478
- setTraceIdInput("");
1479
- } else if (key.tab) {
1480
- if (traceIdInput.length >= 2) {
1481
- const match = traceSummaries.find(
1482
- (t2) => t2.traceId.toLowerCase().startsWith(traceIdInput.toLowerCase())
1483
- );
1484
- if (match) {
1485
- setTraceIdInput(match.traceId);
1486
- }
1487
- }
1488
- } else if (key.backspace || key.delete) {
1489
- setTraceIdInput((q) => q.slice(0, -1));
1490
- } else if (input && input.length === 1 && !key.ctrl && !key.meta) {
1491
- setTraceIdInput((q) => q + input);
1492
- }
1493
- return;
1494
- }
1495
- if (aiInputMode) {
1496
- if (key.escape) {
1497
- if (aiState.status === "streaming") {
1498
- aiAbortRef.current?.abort();
1499
- } else {
1500
- setAiInputMode(false);
1501
- setViewMode("trace");
1502
- }
1503
- return;
1504
- }
1505
- if (key.backspace || key.delete) {
1506
- setAiInput((q) => q.slice(0, -1));
1507
- return;
1508
- }
1509
- if (key.return) {
1510
- if (aiInput.trim()) {
1511
- sendAIQuery(aiInput.trim());
1512
- }
1513
- return;
1514
- }
1515
- if (input && input.length === 1 && !key.ctrl && !key.meta) {
1516
- setAiInput((q) => q + input);
1517
- }
1518
- return;
1519
- }
1520
- if (input === "a") {
1521
- if (viewMode === "ai") {
1522
- setViewMode("trace");
1523
- setAiInputMode(false);
1524
- } else {
1525
- setViewMode("ai");
1526
- if (aiState.status !== "unconfigured") {
1527
- setAiInputMode(true);
1528
- }
1529
- }
1530
- setSelected(0);
1531
- setDrilldownTraceId(null);
1532
- setDrilldownSelectedIndex(0);
1533
- setDrilldownScrollOffset(0);
1534
- return;
1535
- }
1536
- if (key.escape) {
1537
- if (drilldownTraceId == null) {
1538
- setSearchMode(false);
1539
- } else {
1540
- setDrilldownTraceId(null);
1541
- setDrilldownSelectedIndex(0);
1542
- setDrilldownScrollOffset(0);
1543
- setDrilldownTab("timeline");
1544
- }
1545
- return;
1546
- }
1547
- if (key.tab && drilldownTraceId != null) {
1548
- const tabs = [
1549
- "timeline",
1550
- "spans",
1551
- "logs"
1552
- ];
1553
- const currentIdx = tabs.indexOf(drilldownTab);
1554
- const nextIdx = key.shift ? (currentIdx - 1 + tabs.length) % tabs.length : (currentIdx + 1) % tabs.length;
1555
- setDrilldownTab(tabs[nextIdx]);
1556
- setDrilldownSelectedIndex(0);
1557
- setDrilldownScrollOffset(0);
1558
- return;
1559
- }
1560
- if (key.return && drilldownTraceId == null) {
1561
- let targetTraceId;
1562
- let preSelectIndex = 0;
1563
- if (viewMode === "trace" && filteredSummaries[selected]) {
1564
- targetTraceId = filteredSummaries[selected].traceId;
1565
- } else if (viewMode === "log" && filteredLogs[selected]?.traceId) {
1566
- targetTraceId = filteredLogs[selected].traceId;
1567
- const originLog = filteredLogs[selected];
1568
- const traceSpans = spans.filter((s) => s.traceId === targetTraceId);
1569
- const traceLogs = logs.filter((l) => l.traceId === targetTraceId);
1570
- const timeline = buildTraceTimeline(traceSpans, traceLogs);
1571
- preSelectIndex = timeline.findIndex(
1572
- (item) => item.type === "log" && item.log === originLog
1573
- );
1574
- if (preSelectIndex < 0) preSelectIndex = 0;
1575
- } else if (viewMode === "span" && filteredSpans[selected]?.traceId) {
1576
- targetTraceId = filteredSpans[selected].traceId;
1577
- const originSpan = filteredSpans[selected];
1578
- const traceSpans = spans.filter((s) => s.traceId === targetTraceId);
1579
- const traceLogs = logs.filter((l) => l.traceId === targetTraceId);
1580
- const timeline = buildTraceTimeline(traceSpans, traceLogs);
1581
- preSelectIndex = timeline.findIndex(
1582
- (item) => item.type === "span" && item.span?.spanId === originSpan.spanId
1583
- );
1584
- if (preSelectIndex < 0) preSelectIndex = 0;
1585
- }
1586
- if (targetTraceId) {
1587
- setDrilldownTraceId(targetTraceId);
1588
- setDrilldownSelectedIndex(preSelectIndex);
1589
- setDrilldownScrollOffset(Math.max(0, preSelectIndex - LIST_HEIGHT + 1));
1590
- setDrilldownTab("timeline");
1591
- return;
1592
- }
1593
- }
1594
- if (key.upArrow || key.downArrow) {
1595
- if (drilldownTraceId != null) {
1596
- const listLength = drilldownTab === "timeline" ? drilldownTimeline.length : drilldownTab === "spans" ? drilldownTree.length : drilldownLogs.length;
1597
- if (key.upArrow) {
1598
- setDrilldownSelectedIndex((prev) => {
1599
- const next = Math.max(0, prev - 1);
1600
- setDrilldownScrollOffset((off) => Math.min(next, off));
1601
- return next;
1602
- });
1603
- } else {
1604
- setDrilldownSelectedIndex((prev) => {
1605
- const next = Math.min(listLength - 1, prev + 1);
1606
- setDrilldownScrollOffset(
1607
- (off) => next >= off + LIST_HEIGHT ? next - LIST_HEIGHT + 1 : off
1608
- );
1609
- return next;
1610
- });
1611
- }
1612
- return;
1613
- }
1614
- switch (viewMode) {
1615
- case "trace": {
1616
- if (key.upArrow) {
1617
- setSelected((i) => Math.max(0, i - 1));
1618
- setDrilldownSelectedIndex(0);
1619
- } else if (key.downArrow) {
1620
- setSelected((i) => Math.min(filteredSummaries.length - 1, i + 1));
1621
- setDrilldownSelectedIndex(0);
1622
- }
1623
- break;
1624
- }
1625
- case "span": {
1626
- if (key.upArrow) {
1627
- setSelected((i) => Math.max(0, i - 1));
1628
- } else if (key.downArrow) {
1629
- setSelected((i) => Math.min(filteredSpans.length - 1, i + 1));
1630
- }
1631
- break;
1632
- }
1633
- case "log": {
1634
- if (key.upArrow) {
1635
- setSelected((i) => Math.max(0, i - 1));
1636
- } else if (key.downArrow) {
1637
- setSelected((i) => Math.min(filteredLogs.length - 1, i + 1));
1638
- }
1639
- break;
1640
- }
1641
- case "service-summary": {
1642
- if (key.upArrow) {
1643
- setSelected((i) => Math.max(0, i - 1));
1644
- } else if (key.downArrow) {
1645
- setSelected((i) => Math.min(serviceStats.length - 1, i + 1));
1646
- }
1647
- break;
1648
- }
1649
- case "errors": {
1650
- if (key.upArrow) {
1651
- setSelected((i) => Math.max(0, i - 1));
1652
- } else if (key.downArrow) {
1653
- setSelected(
1654
- (i) => Math.min(filteredErrorSummaries.length - 1, i + 1)
1655
- );
1656
- }
1657
- break;
1658
- }
1659
- }
1660
- }
1661
- if (input === "p") setPaused((p) => !p);
1662
- if (input === "e") setFilterErrorsOnly((v) => !v);
1663
- if (input === "t") {
1664
- setViewMode((m) => m === "trace" ? "span" : "trace");
1665
- setSelected(0);
1666
- setDrilldownTraceId(null);
1667
- setDrilldownSelectedIndex(0);
1668
- setDrilldownScrollOffset(0);
1669
- }
1670
- if (input === "l") {
1671
- setViewMode((m) => m === "log" ? "trace" : "log");
1672
- setSelected(0);
1673
- setDrilldownTraceId(null);
1674
- setDrilldownSelectedIndex(0);
1675
- setDrilldownScrollOffset(0);
1676
- }
1677
- if (input === "v") {
1678
- setViewMode(
1679
- (m) => m === "service-summary" ? "trace" : "service-summary"
1680
- );
1681
- setSelected(0);
1682
- setDrilldownTraceId(null);
1683
- setDrilldownSelectedIndex(0);
1684
- setDrilldownScrollOffset(0);
1685
- }
1686
- if (input === "E") {
1687
- setViewMode((m) => m === "errors" ? "trace" : "errors");
1688
- setSelected(0);
1689
- setDrilldownTraceId(null);
1690
- setDrilldownSelectedIndex(0);
1691
- setDrilldownScrollOffset(0);
1692
- }
1693
- if (input === "G") {
1694
- setViewMode((m) => m === "topology" ? "trace" : "topology");
1695
- setSelected(0);
1696
- setDrilldownTraceId(null);
1697
- setDrilldownSelectedIndex(0);
1698
- setDrilldownScrollOffset(0);
1699
- }
1700
- if (input === "c") {
1701
- setSpans([]);
1702
- setLogs([]);
1703
- setSelected(0);
1704
- setDrilldownTraceId(null);
1705
- setDrilldownSelectedIndex(0);
1706
- setDrilldownScrollOffset(0);
1707
- setNewErrorCount(0);
1708
- setSpanFilters({ statusGroup: "all" });
1709
- setRecording(false);
1710
- setPaused(false);
1711
- }
1712
- if (input === "r") {
1713
- setSpans([]);
1714
- setLogs([]);
1715
- setSelected(0);
1716
- setDrilldownTraceId(null);
1717
- setDrilldownSelectedIndex(0);
1718
- setDrilldownScrollOffset(0);
1719
- setNewErrorCount(0);
1720
- setSpanFilters({ statusGroup: "all" });
1721
- setPaused(false);
1722
- setRecording(true);
1723
- }
1724
- if (input === "x") {
1725
- setSpanFilters({ statusGroup: "all" });
1726
- setSelected(0);
1727
- setDrilldownTraceId(null);
1728
- setDrilldownSelectedIndex(0);
1729
- setDrilldownScrollOffset(0);
1730
- }
1731
- if (input === "f") {
1732
- setTraceIdMode(true);
1733
- setTraceIdInput(spanFilters.traceId ?? "");
1734
- return;
1735
- }
1736
- if (input === "H") {
1737
- setSpanFilters((prev) => {
1738
- const next = prev.statusGroup === "all" ? "2xx" : prev.statusGroup === "2xx" ? "4xx" : prev.statusGroup === "4xx" ? "5xx" : "all";
1739
- return { ...prev, statusGroup: next };
1740
- });
1741
- setSelected(0);
1742
- setDrilldownTraceId(null);
1743
- setDrilldownSelectedIndex(0);
1744
- setDrilldownScrollOffset(0);
1745
- }
1746
- if (input === "S") {
1747
- const svc = currentSpan?.attributes?.["service.name"];
1748
- if (typeof svc === "string" && svc.trim()) {
1749
- setSpanFilters((prev) => ({ ...prev, serviceName: svc }));
1750
- setSelected(0);
1751
- setDrilldownTraceId(null);
1752
- setDrilldownSelectedIndex(0);
1753
- setDrilldownScrollOffset(0);
1754
- }
1755
- }
1756
- if (input === "R") {
1757
- const route = currentSpan?.attributes?.["http.route"];
1758
- if (typeof route === "string" && route.trim()) {
1759
- setSpanFilters((prev) => ({ ...prev, route }));
1760
- setSelected(0);
1761
- setDrilldownTraceId(null);
1762
- setDrilldownSelectedIndex(0);
1763
- setDrilldownScrollOffset(0);
1764
- }
1765
- }
1766
- if (input === "T") {
1767
- let traceId;
1768
- if (drilldownTraceId) {
1769
- traceId = drilldownTraceId;
1770
- } else {
1771
- switch (viewMode) {
1772
- case "log": {
1773
- traceId = filteredLogs[selected]?.traceId;
1774
- break;
1775
- }
1776
- case "span": {
1777
- traceId = filteredSpans[selected]?.traceId;
1778
- break;
1779
- }
1780
- case "errors": {
1781
- traceId = filteredErrorSummaries[selected]?.traceId;
1782
- break;
1783
- }
1784
- }
1785
- }
1786
- if (traceId && viewMode !== "trace") {
1787
- setSpanFilters((prev) => ({ ...prev, traceId }));
1788
- setViewMode("trace");
1789
- setSelected(0);
1790
- setDrilldownTraceId(null);
1791
- setDrilldownSelectedIndex(0);
1792
- setDrilldownScrollOffset(0);
1793
- setDrilldownTab("timeline");
1794
- }
1795
- return;
1796
- }
1797
- if (input === "L") {
1798
- let traceId;
1799
- if (drilldownTraceId) {
1800
- traceId = drilldownTraceId;
1801
- } else {
1802
- switch (viewMode) {
1803
- case "trace": {
1804
- traceId = filteredSummaries[selected]?.traceId;
1805
- break;
1806
- }
1807
- case "span": {
1808
- traceId = filteredSpans[selected]?.traceId;
1809
- break;
1810
- }
1811
- case "errors": {
1812
- traceId = filteredErrorSummaries[selected]?.traceId;
1813
- break;
1814
- }
1815
- }
1816
- }
1817
- if (traceId && viewMode !== "log") {
1818
- setSpanFilters((prev) => ({ ...prev, traceId }));
1819
- setViewMode("log");
1820
- setSelected(0);
1821
- setDrilldownTraceId(null);
1822
- setDrilldownSelectedIndex(0);
1823
- setDrilldownScrollOffset(0);
1824
- setDrilldownTab("timeline");
1825
- }
1826
- return;
1827
- }
1828
- if (input === "J") {
1829
- const t2 = selectedTraceSummary;
1830
- if (!t2) return;
1831
- const json = exportTraceToJson(t2, selectedTraceLogs);
1832
- process.stdout.write(`
1833
- [autotel-terminal] trace export
1834
- ${json}
1835
- `);
1836
- }
1837
- },
1838
- { isActive: isRawModeSupported }
1839
- );
1840
- const headerRight = recording ? "[Recording]" : paused ? "[Paused]" : "[Live]";
1841
- const headerModeLabel = viewMode === "trace" ? "traces" : viewMode === "span" ? "spans" : viewMode === "log" ? "logs" : viewMode === "service-summary" ? "services" : viewMode === "topology" ? "topology" : viewMode === "ai" ? "AI" : "errors";
1842
- const showNewError = newErrorCount > 0;
1843
- function renderTreeRow(node, index) {
1844
- const isSel = drilldownTraceId != null && index === drilldownSelectedIndex;
1845
- const prefix = node.depth === 0 ? "" : " ".repeat(node.depth) + (node.children.length > 0 ? "\u251C\u2500\u2500 " : "\u2514\u2500\u2500 ");
1846
- const svcName = spanServiceName(node.span);
1847
- const svcColor = getServiceColor(svcName);
1848
- const statusColor = node.span.status === "ERROR" ? "red" : node.span.durationMs > 500 ? "yellow" : "green";
1849
- return /* @__PURE__ */ jsxRuntime.jsxs(
1850
- ink.Box,
1851
- {
1852
- flexDirection: "row",
1853
- children: [
1854
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { backgroundColor: isSel ? "blue" : void 0, color: isSel ? "white" : void 0, children: isSel ? "\u25B8 " : " " }),
1855
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: node.span.status === "ERROR" ? "red" : void 0, children: node.span.status === "ERROR" ? "\u2717" : " " }),
1856
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: prefix }),
1857
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: colors ? statusColor : void 0, children: truncate(node.span.name, 23) }),
1858
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: svcColor, children: [
1859
- " ",
1860
- truncate(svcName, 10)
1861
- ] }),
1862
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
1863
- " ",
1864
- node.span.kind ?? ""
1865
- ] }),
1866
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
1867
- " ",
1868
- formatDurationMs(node.span.durationMs)
1869
- ] })
1870
- ]
1871
- },
1872
- `${node.span.spanId}-${node.span.startTime}`
1873
- );
1874
- }
1875
- function keyAttrsAndRest(attrs) {
1876
- if (!attrs || Object.keys(attrs).length === 0)
1877
- return {
1878
- key: [],
1879
- rest: []
1880
- };
1881
- const entries = Object.entries(attrs);
1882
- const key = entries.filter(([k]) => KEY_ATTR_KEYS.has(k));
1883
- const rest = entries.filter(([k]) => !KEY_ATTR_KEYS.has(k));
1884
- return { key, rest };
1885
- }
1886
- const waterfallMaxMs = waterfallSpans.length > 0 ? Math.max(...waterfallSpans.map((w) => w.span.durationMs)) : 1;
1887
- const barWidth = 30;
1888
- return /* @__PURE__ */ jsxRuntime.jsxs(
1889
- ink.Box,
1890
- {
1891
- flexDirection: "column",
1892
- paddingX: 1,
1893
- children: [
1894
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { justifyContent: "space-between", marginBottom: 1, children: [
1895
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { bold: true, children: [
1896
- "\u{1F52D} ",
1897
- title,
1898
- " \u2014 ",
1899
- headerModeLabel
1900
- ] }, "title"),
1901
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", gap: 1, children: [
1902
- showNewError && /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: "red", children: "1 new error" }, "newError"),
1903
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: paused ? "yellow" : "green", children: headerRight }, "status")
1904
- ] })
1905
- ] }),
1906
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginBottom: 0, flexDirection: "column", children: [
1907
- searchMode ? /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: "cyan", children: [
1908
- "Search: ",
1909
- searchQuery || "(type to filter)",
1910
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: " (Tab: match traceId, Esc: cancel)" })
1911
- ] }) : traceIdMode ? /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: "yellow", children: [
1912
- "TraceId: ",
1913
- traceIdInput || "(type prefix, Tab to complete)",
1914
- traceIdInput.length >= 2 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
1915
- " \u2192 ",
1916
- traceSummaries.find(
1917
- (t2) => t2.traceId.toLowerCase().startsWith(traceIdInput.toLowerCase())
1918
- )?.traceId.slice(0, 16) ?? "no match",
1919
- "\u2026"
1920
- ] })
1921
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", justifyContent: "space-between", children: [
1922
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: drilldownTraceId == null ? "\u2191/\u2193 select \u2022 Enter open \u2022 Tab cycle tabs \u2022 Esc back \u2022 t trace \u2022 l logs \u2022 a AI \u2022 ? help" : "\u2191/\u2193 select \u2022 Tab cycle tabs \u2022 Esc back \u2022 t trace \u2022 l logs \u2022 a AI \u2022 ? help" }),
1923
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: viewMode === "trace" ? `traces ${filteredSummaries.length}/${traceSummaries.length}` : viewMode === "span" ? `spans ${filteredSpans.length}/${spans.length}` : viewMode === "service-summary" ? `services ${serviceStats.length}` : viewMode === "errors" ? `errors ${filteredErrorSummaries.length}/${errorSummaries.length}` : viewMode === "topology" ? `services ${serviceGraph.services.length} \xB7 edges ${serviceGraph.edges.length}` : viewMode === "ai" ? `messages ${aiMessages.length}` : `logs ${filteredLogs.length}/${logs.length}` })
1924
- ] }),
1925
- showHelp && /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Views: t/l/v/E/G/a \u2022 Search: / \u2022 Filters: e/S/R/H/f/x \u2022 Capture: p/r/J \u2022 Clear: c" })
1926
- ] }),
1927
- /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { marginBottom: 0, children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: spanFilters.serviceName || spanFilters.route || spanFilters.statusGroup !== "all" || spanFilters.traceId ? `filters:${spanFilters.serviceName ? ` service=${spanFilters.serviceName}` : ""}${spanFilters.route ? ` route=${spanFilters.route}` : ""}${spanFilters.statusGroup && spanFilters.statusGroup !== "all" ? ` status=${spanFilters.statusGroup}` : ""}${spanFilters.traceId ? ` trace=${spanFilters.traceId.slice(0, 8)}\u2026` : ""}` : "filters: none" }) }),
1928
- viewMode === "topology" && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", paddingX: 1, children: [
1929
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Service Topology" }),
1930
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Press G to toggle \xB7 Shows service dependencies from span data" }),
1931
- /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { flexDirection: "column", marginTop: 1, children: topologyLines.map((line, i) => {
1932
- const hasErr = line.includes(" err");
1933
- return /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: hasErr ? "red" : void 0, children: line }, `topo-${i}`);
1934
- }) })
1935
- ] }),
1936
- viewMode === "ai" && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", paddingX: 1, paddingY: 0, children: [
1937
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginBottom: 1, justifyContent: "space-between", children: [
1938
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "AI Assistant" }),
1939
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: aiState.status === "streaming" ? "(streaming...)" : aiState.status === "unconfigured" ? "(no provider)" : aiState.status === "error" ? "(error)" : "" })
1940
- ] }),
1941
- aiState.status === "unconfigured" ? /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "column", children: [
1942
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "No AI provider configured." }),
1943
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Set AI_PROVIDER and AI_MODEL env vars, or start Ollama locally." }),
1944
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Press a to close this view." })
1945
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1946
- aiMessages.length === 0 && aiState.status !== "error" && /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Ask a question about your telemetry data. Press Enter to send." }),
1947
- aiMessages.slice(-10).map((msg, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { flexDirection: "column", marginBottom: msg.role === "assistant" ? 1 : 0, children: /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: msg.role === "user" ? "cyan" : void 0, children: [
1948
- msg.role === "user" ? "> " : "",
1949
- msg.content.slice(0, 1e3),
1950
- msg.content.length > 1e3 ? "..." : ""
1951
- ] }) }, `ai-msg-${i}`)),
1952
- aiSpec && /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { flexDirection: "column", marginBottom: 1, borderStyle: "single", borderColor: "gray", paddingX: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ink$1.Renderer, { spec: aiSpec }) }),
1953
- aiState.status === "error" && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: "red", children: [
1954
- "Error: ",
1955
- aiState.message
1956
- ] }),
1957
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, borderStyle: "single", borderColor: "cyan", paddingX: 1, children: [
1958
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: "cyan", children: "> " }),
1959
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: aiInput || (aiInputMode ? "(type your question)" : "(press a to focus)") })
1960
- ] })
1961
- ] })
1962
- ] }),
1963
- viewMode !== "topology" && viewMode !== "ai" && (drilldownTraceId != null ? /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", paddingX: 1, paddingY: 0, children: [
1964
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginBottom: 0, flexDirection: "column", children: [
1965
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { bold: true, children: [
1966
- "Trace ",
1967
- drilldownTraceId.slice(0, 16),
1968
- "\u2026"
1969
- ] }),
1970
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", gap: 1, children: [
1971
- drilldownSummary?.services?.map((svc) => /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: getServiceColor(svc), children: svc }, svc)),
1972
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "\xB7" }),
1973
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: drilldownSummary?.rootName ?? "unknown" }),
1974
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "\xB7" }),
1975
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
1976
- drilldownSpans.length,
1977
- " spans"
1978
- ] }),
1979
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "\xB7" }),
1980
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
1981
- drilldownSummary?.services?.length ?? 0,
1982
- " services"
1983
- ] }),
1984
- drilldownSummary?.hasError && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: "red", children: [
1985
- " ",
1986
- "ERROR"
1987
- ] })
1988
- ] }),
1989
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", gap: 2, children: [
1990
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Duration: " }),
1991
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: "green", children: formatDurationMs(drilldownSummary?.durationMs ?? 0) })
1992
- ] })
1993
- ] }),
1994
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginBottom: 0, flexDirection: "row", gap: 2, children: [
1995
- /* @__PURE__ */ jsxRuntime.jsx(
1996
- ink.Text,
1997
- {
1998
- color: drilldownTab === "timeline" ? "blue" : void 0,
1999
- dimColor: drilldownTab !== "timeline",
2000
- bold: drilldownTab === "timeline",
2001
- children: "Timeline"
2002
- }
2003
- ),
2004
- /* @__PURE__ */ jsxRuntime.jsxs(
2005
- ink.Text,
2006
- {
2007
- color: drilldownTab === "spans" ? "blue" : void 0,
2008
- dimColor: drilldownTab !== "spans",
2009
- bold: drilldownTab === "spans",
2010
- children: [
2011
- "Spans (",
2012
- drilldownSpans.length,
2013
- ")"
2014
- ]
2015
- }
2016
- ),
2017
- /* @__PURE__ */ jsxRuntime.jsxs(
2018
- ink.Text,
2019
- {
2020
- color: drilldownTab === "logs" ? "blue" : void 0,
2021
- dimColor: drilldownTab !== "logs",
2022
- bold: drilldownTab === "logs",
2023
- children: [
2024
- "Logs (",
2025
- drilldownLogs.length,
2026
- ")"
2027
- ]
2028
- }
2029
- )
2030
- ] }),
2031
- drilldownTab === "timeline" && (() => {
2032
- const NAME_COL = 28;
2033
- const SERVICE_COL = 12;
2034
- const KIND_COL = 10;
2035
- let traceStartMs = Infinity;
2036
- for (const s of drilldownSummary?.spans ?? []) {
2037
- if (s.startTime < traceStartMs) traceStartMs = s.startTime;
2038
- }
2039
- if (traceStartMs === Infinity) traceStartMs = 0;
2040
- const traceDurMs = drilldownSummary?.durationMs ?? 1;
2041
- const WATERFALL_WIDTH = 44;
2042
- const items = drilldownTimeline.slice(drilldownScrollOffset, drilldownScrollOffset + LIST_HEIGHT);
2043
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2044
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", children: [
2045
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "".padEnd(NAME_COL + SERVICE_COL + KIND_COL + 2) }),
2046
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: buildTimeRuler(traceDurMs, WATERFALL_WIDTH) })
2047
- ] }),
2048
- items.map((item, i) => {
2049
- const isSel = i + drilldownScrollOffset === drilldownSelectedIndex;
2050
- if (item.type === "span" && item.span) {
2051
- const s = item.span;
2052
- const node = drilldownTree.find(
2053
- (n) => n.span.spanId === s.spanId
2054
- );
2055
- const depth = node?.depth ?? 0;
2056
- const indent = " ".repeat(Math.min(depth, 4));
2057
- const nameWidth = NAME_COL - Math.min(depth, 4) * 2 - 1;
2058
- const svcName = spanServiceName(s);
2059
- const svcColor = getServiceColor(svcName);
2060
- const kindStr = (s.kind ?? "").padEnd(KIND_COL);
2061
- const svcStr = truncate(svcName, SERVICE_COL - 2).padEnd(SERVICE_COL);
2062
- const errorMark = s.status === "ERROR" ? "\u2717" : " ";
2063
- const namePart = `${indent}${truncate(s.name, nameWidth - 1)}`.padEnd(NAME_COL - 1);
2064
- const bar = buildWaterfallBar(
2065
- s.startTime,
2066
- s.durationMs,
2067
- traceStartMs,
2068
- traceDurMs,
2069
- WATERFALL_WIDTH
2070
- );
2071
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", children: [
2072
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { backgroundColor: isSel ? "blue" : void 0, color: isSel ? "white" : void 0, children: [
2073
- isSel ? "\u25B8" : " ",
2074
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: s.status === "ERROR" ? "red" : void 0, children: errorMark }),
2075
- namePart
2076
- ] }),
2077
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: svcColor, children: [
2078
- " ",
2079
- svcStr
2080
- ] }),
2081
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: kindStr }),
2082
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: s.status === "ERROR" ? "red" : svcColor, children: bar }),
2083
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: s.status === "ERROR" ? "red" : svcColor, children: [
2084
- " ",
2085
- formatDurationMs(s.durationMs)
2086
- ] })
2087
- ] }, `${s.spanId}-${i}`);
2088
- } else if (item.type === "log" && item.log) {
2089
- const l = item.log;
2090
- const levelColor = l.level === "error" ? "red" : l.level === "warn" ? "yellow" : "blue";
2091
- const relTime = drilldownSummary ? `+${formatDurationMs(l.time - traceStartMs)}` : "";
2092
- const logName = ` ${l.level.toUpperCase()} ${truncate(l.message, NAME_COL - 8)}`.padEnd(NAME_COL);
2093
- const logOffset = drilldownSummary ? Math.floor((l.time - traceStartMs) / traceDurMs * WATERFALL_WIDTH) : 0;
2094
- const clampedOffset = Math.max(0, Math.min(logOffset, WATERFALL_WIDTH - 1));
2095
- const logBar = " ".repeat(clampedOffset) + "\xB7" + " ".repeat(WATERFALL_WIDTH - clampedOffset - 1);
2096
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", children: [
2097
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { backgroundColor: isSel ? "blue" : void 0, color: isSel ? "white" : void 0, children: [
2098
- isSel ? "\u25B8" : " ",
2099
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: levelColor, children: logName })
2100
- ] }),
2101
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: " ".padEnd(SERVICE_COL + KIND_COL + 1) }),
2102
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: logBar }),
2103
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2104
- " ",
2105
- relTime
2106
- ] })
2107
- ] }, `log-${i}`);
2108
- }
2109
- return null;
2110
- }),
2111
- Array.from({ length: Math.max(0, LIST_HEIGHT - items.length) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2112
- ] });
2113
- })(),
2114
- drilldownTab === "spans" && drilldownTree.slice(drilldownScrollOffset, drilldownScrollOffset + LIST_HEIGHT).map((node, i) => renderTreeRow(node, i + drilldownScrollOffset)),
2115
- drilldownTab === "spans" && Array.from({ length: Math.max(0, LIST_HEIGHT - Math.min(drilldownTree.length, LIST_HEIGHT)) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`)),
2116
- drilldownTab === "logs" && drilldownLogs.slice(drilldownScrollOffset, drilldownScrollOffset + LIST_HEIGHT).map((log, i) => {
2117
- const isSel = i + drilldownScrollOffset === drilldownSelectedIndex;
2118
- const levelColor = log.level === "error" ? "red" : log.level === "warn" ? "yellow" : log.level === "info" ? "green" : void 0;
2119
- return /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsxs(
2120
- ink.Text,
2121
- {
2122
- backgroundColor: isSel ? "blue" : void 0,
2123
- color: isSel ? "white" : void 0,
2124
- children: [
2125
- isSel ? "\u25B8" : " ",
2126
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: levelColor, children: [
2127
- " ",
2128
- log.level.toUpperCase()
2129
- ] }),
2130
- " ",
2131
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2132
- "[",
2133
- truncate(log.message, 50),
2134
- "]"
2135
- ] })
2136
- ]
2137
- }
2138
- ) }, `log-${i}`);
2139
- }),
2140
- drilldownTab === "logs" && Array.from({ length: Math.max(0, LIST_HEIGHT - Math.min(drilldownLogs.length, LIST_HEIGHT)) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`)),
2141
- drilldownSelectedItem?.type === "span" && drilldownSelectedItem.span && (() => {
2142
- const span = drilldownSelectedItem.span;
2143
- const { key: keyAttrs, rest: restAttrs } = keyAttrsAndRest(span.attributes);
2144
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", borderStyle: "single", borderColor: "gray", paddingX: 1, children: [
2145
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", gap: 2, children: [
2146
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: span.name }),
2147
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: getServiceColor(spanServiceName(span)), children: spanServiceName(span) }),
2148
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: span.kind ?? "" }),
2149
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: span.status === "ERROR" ? "red" : "green", children: span.status }),
2150
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: formatDurationMs(span.durationMs) })
2151
- ] }),
2152
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", gap: 2, children: [
2153
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2154
- "Trace: ",
2155
- span.traceId
2156
- ] }),
2157
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2158
- "Span: ",
2159
- span.spanId
2160
- ] }),
2161
- span.parentSpanId && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2162
- "Parent: ",
2163
- span.parentSpanId
2164
- ] })
2165
- ] }),
2166
- keyAttrs.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", children: [
2167
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Key attributes" }),
2168
- keyAttrs.slice(0, 6).map(([k, v]) => /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2169
- truncate(k, 18),
2170
- ": ",
2171
- truncate(String(v), 28)
2172
- ] }, k))
2173
- ] }),
2174
- restAttrs.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", children: [
2175
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Attributes" }),
2176
- restAttrs.slice(0, 8).map(([k, v]) => /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2177
- truncate(k, 18),
2178
- ": ",
2179
- truncate(String(v), 28)
2180
- ] }, k))
2181
- ] }),
2182
- span.events && span.events.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "column", marginTop: 0, children: [
2183
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { bold: true, dimColor: true, children: [
2184
- "Events (",
2185
- span.events.length,
2186
- ")"
2187
- ] }),
2188
- span.events.slice(0, 5).map((ev, i) => /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", children: [
2189
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: ev.name === "exception" ? "red" : "yellow", children: [
2190
- " ",
2191
- "\u25C6",
2192
- " ",
2193
- truncate(ev.name, 20)
2194
- ] }),
2195
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2196
- " ",
2197
- "+",
2198
- formatDurationMs(ev.timeMs - span.startTime)
2199
- ] }),
2200
- ev.attributes && Object.keys(ev.attributes).length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2201
- " ",
2202
- Object.entries(ev.attributes).slice(0, 2).map(([k, v]) => `${k}=${String(v)}`).join(" ")
2203
- ] })
2204
- ] }, `ev-${i}`))
2205
- ] }),
2206
- span.links && span.links.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "column", marginTop: 0, children: [
2207
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { bold: true, dimColor: true, children: [
2208
- "Links (",
2209
- span.links.length,
2210
- ")"
2211
- ] }),
2212
- span.links.slice(0, 5).map((lnk, i) => /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", children: [
2213
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: "cyan", children: [
2214
- " ",
2215
- "\u2192",
2216
- " trace:",
2217
- lnk.traceId.slice(0, 8),
2218
- "\u2026",
2219
- " span:",
2220
- lnk.spanId.slice(0, 8),
2221
- "\u2026"
2222
- ] }),
2223
- lnk.attributes && Object.keys(lnk.attributes).length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2224
- " ",
2225
- Object.entries(lnk.attributes).slice(0, 2).map(([k, v]) => `${k}=${String(v)}`).join(" ")
2226
- ] })
2227
- ] }, `lnk-${i}`))
2228
- ] })
2229
- ] });
2230
- })(),
2231
- drilldownSelectedItem?.type === "log" && drilldownSelectedItem.log && (() => {
2232
- const log = drilldownSelectedItem.log;
2233
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", borderStyle: "single", borderColor: "gray", paddingX: 1, children: [
2234
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", gap: 2, children: [
2235
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: log.level.toUpperCase() }),
2236
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: log.message })
2237
- ] }),
2238
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2239
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Time: " }),
2240
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: new Date(log.time).toISOString() })
2241
- ] }),
2242
- log.traceId && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2243
- "Trace: ",
2244
- log.traceId
2245
- ] }),
2246
- log.spanId && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2247
- "Span: ",
2248
- log.spanId
2249
- ] }),
2250
- log.attributes && Object.keys(log.attributes).length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", children: [
2251
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Attributes" }),
2252
- Object.entries(log.attributes).slice(0, 10).map(([k, v]) => /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2253
- truncate(k, 18),
2254
- ": ",
2255
- truncate(String(v), 40)
2256
- ] }, k))
2257
- ] })
2258
- ] });
2259
- })()
2260
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", gap: 2, children: [
2261
- /* @__PURE__ */ jsxRuntime.jsxs(
2262
- ink.Box,
2263
- {
2264
- flexDirection: "column",
2265
- width: "55%",
2266
- borderStyle: "round",
2267
- borderColor: "gray",
2268
- paddingX: 1,
2269
- paddingY: 0,
2270
- children: [
2271
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 0, marginBottom: 1, children: [
2272
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: viewMode === "trace" ? "Recent traces" : viewMode === "span" ? "Recent spans" : viewMode === "service-summary" ? "Service summary" : viewMode === "errors" ? "Recent errors" : "Recent logs" }, "list-title"),
2273
- filterErrorsOnly && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: "red", children: [
2274
- " ",
2275
- "(errors only)"
2276
- ] }, "errors-only-label"),
2277
- searchQuery && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2278
- " ",
2279
- "/",
2280
- searchQuery
2281
- ] }, "search-label")
2282
- ] }),
2283
- /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: viewMode === "trace" ? filteredSummaries.length === 0 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2284
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "column", children: [
2285
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "No traces yet. Call a traced function or hit an endpoint to see them here." }),
2286
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Tip: trace() your handlers with autotel to get spans." })
2287
- ] }),
2288
- Array.from({ length: Math.max(0, LIST_HEIGHT - 2) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2289
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2290
- filteredSummaries.slice(0, 20).map((t2, i) => {
2291
- const isSel = i === selected;
2292
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", children: [
2293
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: isSel ? "cyan" : void 0, children: isSel ? "\u25B8 " : " " }),
2294
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: t2.hasError ? "red" : "yellow", bold: isSel, children: truncate(t2.rootName, 28) }),
2295
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2296
- " ",
2297
- t2.spans.length,
2298
- " spans"
2299
- ] }),
2300
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: "green", children: [
2301
- " ",
2302
- formatDurationMs(t2.durationMs)
2303
- ] }),
2304
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2305
- " ",
2306
- formatRelative(t2.lastEndTime)
2307
- ] }),
2308
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2309
- " ",
2310
- t2.traceId.slice(0, 12),
2311
- "\u2026"
2312
- ] }),
2313
- t2.hasError && /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: "red", children: " \u25CF" })
2314
- ] }, t2.traceId);
2315
- }),
2316
- Array.from({ length: Math.max(0, LIST_HEIGHT - Math.min(filteredSummaries.length, 20)) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2317
- ] }) : viewMode === "span" ? filteredSpans.length === 0 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2318
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "column", children: [
2319
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "No spans yet. Call a traced function or hit an endpoint to see them here." }),
2320
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Tip: trace() your handlers with autotel to get spans." })
2321
- ] }),
2322
- Array.from({ length: Math.max(0, LIST_HEIGHT - 2) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2323
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2324
- filteredSpans.slice(0, 20).map((s, i) => {
2325
- const isSel = i === selected;
2326
- const svcName = spanServiceName(s);
2327
- const svcColor = getServiceColor(svcName);
2328
- const statusColor = s.status === "ERROR" ? "red" : s.durationMs > 500 ? "yellow" : "green";
2329
- return /* @__PURE__ */ jsxRuntime.jsxs(
2330
- ink.Box,
2331
- {
2332
- flexDirection: "row",
2333
- children: [
2334
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: isSel ? "cyan" : void 0, children: isSel ? "\u203A " : " " }),
2335
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: colors ? statusColor : void 0, children: truncate(s.name, 26) }),
2336
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { color: svcColor, children: [
2337
- " ",
2338
- truncate(svcName, 10)
2339
- ] }),
2340
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2341
- " ",
2342
- formatDurationMs(s.durationMs)
2343
- ] }),
2344
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2345
- " ",
2346
- formatRelative(s.endTime)
2347
- ] })
2348
- ]
2349
- },
2350
- `${s.spanId}-${s.startTime}`
2351
- );
2352
- }),
2353
- Array.from({ length: Math.max(0, LIST_HEIGHT - Math.min(filteredSpans.length, 20)) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2354
- ] }) : viewMode === "service-summary" ? serviceStats.length === 0 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2355
- /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { flexDirection: "column", children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "No service stats yet. Add `service.name` attributes to spans." }) }),
2356
- Array.from({ length: Math.max(0, LIST_HEIGHT - 1) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2357
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2358
- serviceStats.slice(0, 20).map((svc, i) => {
2359
- const isSel = i === selected;
2360
- const errorRate = svc.total ? svc.errors / svc.total * 100 : 0;
2361
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", children: [
2362
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: isSel ? "cyan" : void 0, children: isSel ? "\u203A " : " " }),
2363
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: truncate(svc.serviceName, 16) }),
2364
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2365
- " ",
2366
- svc.errors,
2367
- "/",
2368
- svc.total
2369
- ] }),
2370
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2371
- " ",
2372
- errorRate.toFixed(0),
2373
- "%"
2374
- ] }),
2375
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2376
- " p95 ",
2377
- formatDurationMs(svc.p95Ms)
2378
- ] })
2379
- ] }, svc.serviceName);
2380
- }),
2381
- Array.from({ length: Math.max(0, LIST_HEIGHT - Math.min(serviceStats.length, 20)) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2382
- ] }) : viewMode === "errors" ? filteredErrorSummaries.length === 0 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2383
- /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { flexDirection: "column", children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "No errors yet." }) }),
2384
- Array.from({ length: Math.max(0, LIST_HEIGHT - 1) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2385
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2386
- filteredErrorSummaries.slice(0, 20).map((e, i) => {
2387
- const isSel = i === selected;
2388
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", children: [
2389
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: isSel ? "cyan" : void 0, children: isSel ? "\u203A " : " " }),
2390
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: "red", children: truncate(e.rootName, 16) }),
2391
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2392
- " ",
2393
- truncate(e.serviceName, 10)
2394
- ] }),
2395
- e.route && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2396
- " ",
2397
- truncate(e.route, 14)
2398
- ] }),
2399
- typeof e.statusCode === "number" && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2400
- " ",
2401
- e.statusCode
2402
- ] }),
2403
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2404
- " (",
2405
- e.errorCount,
2406
- ")"
2407
- ] })
2408
- ] }, e.traceId);
2409
- }),
2410
- Array.from({ length: Math.max(0, LIST_HEIGHT - Math.min(filteredErrorSummaries.length, 20)) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2411
- ] }) : filteredLogs.length === 0 ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2412
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "column", children: [
2413
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "No logs yet. Emit request logs or canonical log lines to see them here." }),
2414
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Tip: hook getTerminalLogStream() into your canonical log line drain." })
2415
- ] }),
2416
- Array.from({ length: Math.max(0, LIST_HEIGHT - 2) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2417
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2418
- filteredLogs.slice(0, 20).map((log, i) => {
2419
- const isSel = i === selected;
2420
- const levelColor = log.level === "error" ? "red" : log.level === "warn" ? "yellow" : log.level === "debug" ? "gray" : "green";
2421
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", children: [
2422
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: isSel ? "cyan" : void 0, children: isSel ? "\u203A " : " " }),
2423
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { color: colors ? levelColor : void 0, children: truncate(log.level.toUpperCase(), 5) }),
2424
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }),
2425
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: truncate(log.message, 32) })
2426
- ] }, `${log.time}-${i}`);
2427
- }),
2428
- Array.from({ length: Math.max(0, LIST_HEIGHT - Math.min(filteredLogs.length, 20)) }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: " " }) }, `pad-${i}`))
2429
- ] }) })
2430
- ]
2431
- }
2432
- ),
2433
- /* @__PURE__ */ jsxRuntime.jsx(
2434
- ink.Box,
2435
- {
2436
- flexDirection: "column",
2437
- width: "45%",
2438
- borderStyle: "round",
2439
- borderColor: "gray",
2440
- paddingX: 1,
2441
- paddingY: 0,
2442
- children: /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2443
- /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { marginBottom: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Details" }) }),
2444
- viewMode === "errors" ? (() => {
2445
- const e = filteredErrorSummaries[selected] ?? null;
2446
- if (!e)
2447
- return /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Select an error to view details." });
2448
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2449
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2450
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Trace: " }),
2451
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: e.traceId })
2452
- ] }),
2453
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2454
- "Service: ",
2455
- e.serviceName,
2456
- e.route ? ` \u2022 Route: ${e.route}` : "",
2457
- typeof e.statusCode === "number" ? ` \u2022 Status: ${e.statusCode}` : ""
2458
- ] }),
2459
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2460
- "Errors: ",
2461
- e.errorCount
2462
- ] }),
2463
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Press T to jump to trace view for this trace." })
2464
- ] });
2465
- })() : viewMode === "service-summary" ? (() => {
2466
- const svc = serviceStats[selected] ?? null;
2467
- if (!svc)
2468
- return /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Select a service to view details." });
2469
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2470
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2471
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Service: " }),
2472
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: svc.serviceName })
2473
- ] }),
2474
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2475
- "Spans: ",
2476
- svc.total,
2477
- " | Errors: ",
2478
- svc.errors,
2479
- " | Avg:",
2480
- " ",
2481
- formatDurationMs(svc.avgMs),
2482
- " | P95:",
2483
- " ",
2484
- formatDurationMs(svc.p95Ms)
2485
- ] }),
2486
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", children: [
2487
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Top routes" }),
2488
- selectedServiceRouteStats.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "(no http.route)" }) : selectedServiceRouteStats.map((r) => /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2489
- truncate(r.route, 20),
2490
- " ",
2491
- r.errors,
2492
- "/",
2493
- r.total,
2494
- " p95",
2495
- " ",
2496
- formatDurationMs(r.p95Ms)
2497
- ] }, r.route))
2498
- ] }),
2499
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", children: [
2500
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Hot spans" }),
2501
- selectedServiceHotSpans.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "(no spans)" }) : selectedServiceHotSpans.map((h) => /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2502
- truncate(h.name, 20),
2503
- " p95",
2504
- " ",
2505
- formatDurationMs(h.p95Ms),
2506
- " (",
2507
- h.count,
2508
- "x)"
2509
- ] }, h.name))
2510
- ] })
2511
- ] });
2512
- })() : viewMode === "log" ? (() => {
2513
- const log = filteredLogs[selected] ?? null;
2514
- if (!log) {
2515
- return /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Select a log to view details." });
2516
- }
2517
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2518
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2519
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Level: " }),
2520
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: log.level.toUpperCase() })
2521
- ] }),
2522
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2523
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Time: " }),
2524
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: new Date(log.time).toISOString() })
2525
- ] }),
2526
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2527
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Message: " }),
2528
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: log.message })
2529
- ] }),
2530
- log.traceId && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2531
- "Trace: ",
2532
- log.traceId
2533
- ] }),
2534
- log.spanId && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2535
- "Span: ",
2536
- log.spanId
2537
- ] }),
2538
- log.attributes && Object.keys(log.attributes).length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", children: [
2539
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Attributes" }),
2540
- Object.entries(log.attributes).slice(0, 10).map(([k, v]) => /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2541
- truncate(k, 18),
2542
- ": ",
2543
- truncate(String(v), 40)
2544
- ] }, k))
2545
- ] }),
2546
- timelineItems.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", children: [
2547
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Timeline (trace)" }),
2548
- timelineItems.slice(0, 10).map((item, idx) => {
2549
- const relMs = item.time - (selectedTraceSummary?.spans[0]?.startTime ?? item.time);
2550
- if (item.type === "span" && item.span) {
2551
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2552
- "+",
2553
- relMs,
2554
- "ms span",
2555
- " ",
2556
- truncate(item.span.name, 20)
2557
- ] }, `span-${idx}`);
2558
- }
2559
- if (item.type === "log" && item.log) {
2560
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2561
- "+",
2562
- relMs,
2563
- "ms log",
2564
- " ",
2565
- truncate(item.log.message, 24)
2566
- ] }, `log-${idx}`);
2567
- }
2568
- return null;
2569
- })
2570
- ] })
2571
- ] });
2572
- })() : currentSpan ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2573
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2574
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Name: " }),
2575
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: currentSpan.name })
2576
- ] }),
2577
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2578
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Status: " }),
2579
- /* @__PURE__ */ jsxRuntime.jsx(
2580
- ink.Text,
2581
- {
2582
- color: currentSpan.status === "ERROR" ? "red" : "green",
2583
- children: currentSpan.status
2584
- }
2585
- )
2586
- ] }),
2587
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2588
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Duration: " }),
2589
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { children: [
2590
- formatDurationMs(currentSpan.durationMs),
2591
- perSpanNameStats.byName.has(currentSpan.name) && (() => {
2592
- const p = perSpanNameStats.byName.get(
2593
- currentSpan.name
2594
- );
2595
- const ratio = p.avgMs > 0 ? currentSpan.durationMs / p.avgMs : 1;
2596
- if (ratio >= 1.5)
2597
- return ` (${ratio.toFixed(1)}x avg)`;
2598
- return "";
2599
- })()
2600
- ] })
2601
- ] }),
2602
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2603
- "Trace: ",
2604
- currentSpan.traceId
2605
- ] }),
2606
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2607
- "Span: ",
2608
- currentSpan.spanId
2609
- ] }),
2610
- currentSpan.parentSpanId && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2611
- "Parent: ",
2612
- currentSpan.parentSpanId
2613
- ] }),
2614
- currentSpan.kind && /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2615
- "Kind: ",
2616
- currentSpan.kind
2617
- ] }),
2618
- (() => {
2619
- const { key: keyAttrs, rest: restAttrs } = keyAttrsAndRest(currentSpan.attributes);
2620
- return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2621
- keyAttrs.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", children: [
2622
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Key attributes" }),
2623
- keyAttrs.slice(0, 6).map(([k, v]) => /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2624
- truncate(k, 18),
2625
- ": ",
2626
- truncate(String(v), 28)
2627
- ] }, k))
2628
- ] }),
2629
- restAttrs.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", children: [
2630
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Attributes" }),
2631
- restAttrs.slice(0, 8).map(([k, v]) => /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2632
- truncate(k, 18),
2633
- ": ",
2634
- truncate(String(v), 28)
2635
- ] }, k))
2636
- ] }),
2637
- keyAttrs.length === 0 && restAttrs.length === 0 && /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "(no attributes)" })
2638
- ] });
2639
- })(),
2640
- waterfallSpans.length > 0 && drilldownTraceId != null && /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { marginTop: 1, flexDirection: "column", children: [
2641
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { bold: true, children: "Waterfall" }),
2642
- waterfallSpans.slice(0, 10).map((w) => {
2643
- const barLen = Math.round(
2644
- w.span.durationMs / waterfallMaxMs * barWidth
2645
- ) || 1;
2646
- const bar = "\u2588".repeat(barLen);
2647
- const indent = " ".repeat(w.depth);
2648
- return /* @__PURE__ */ jsxRuntime.jsxs(ink.Box, { flexDirection: "row", children: [
2649
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: indent }),
2650
- /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { children: truncate(w.span.name, 12) }),
2651
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2652
- " ",
2653
- bar
2654
- ] }),
2655
- /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2656
- " ",
2657
- formatDurationMs(w.span.durationMs)
2658
- ] })
2659
- ] }, w.span.spanId);
2660
- })
2661
- ] })
2662
- ] }) : /* @__PURE__ */ jsxRuntime.jsx(ink.Text, { dimColor: true, children: "Select a trace or span to view details." })
2663
- ] })
2664
- }
2665
- )
2666
- ] })),
2667
- showStats && /* @__PURE__ */ jsxRuntime.jsx(ink.Box, { marginTop: 1, borderStyle: "round", borderColor: "gray", paddingX: 1, children: /* @__PURE__ */ jsxRuntime.jsxs(ink.Text, { dimColor: true, children: [
2668
- "Spans: ",
2669
- stats.total,
2670
- " | Span errors: ",
2671
- stats.errors,
2672
- " | Logs:",
2673
- " ",
2674
- logStats.total,
2675
- " | Log errors: ",
2676
- logStats.errors,
2677
- " | Avg:",
2678
- " ",
2679
- formatDurationMs(stats.avg),
2680
- " | P95: ",
2681
- formatDurationMs(stats.p95)
2682
- ] }) })
2683
- ]
2684
- }
2685
- );
2686
- }
2687
- var globalStreamingProcessor = null;
2688
- function canAddSpanProcessor(provider) {
2689
- return typeof provider === "object" && provider !== null && "addSpanProcessor" in provider && typeof provider.addSpanProcessor === "function";
2690
- }
2691
- function renderTerminal(options = {}, stream) {
2692
- const title = options.title ?? "Autotel Trace Inspector";
2693
- const showStats = options.showStats !== false;
2694
- const maxSpans = options.maxSpans ?? 100;
2695
- const colors = options.colors ?? Boolean(process.stdout.isTTY);
2696
- const aiConfig = options.ai;
2697
- const stdinOption = process.stdin.isTTY ? process.stdin : void 0;
2698
- if (stream) {
2699
- try {
2700
- ink.render(
2701
- /* @__PURE__ */ jsxRuntime.jsx(
2702
- Dashboard,
2703
- {
2704
- title,
2705
- showStats,
2706
- maxSpans,
2707
- colors,
2708
- stream,
2709
- logStream: getTerminalLogStream(),
2710
- aiConfig
2711
- }
2712
- ),
2713
- { stdin: stdinOption }
2714
- );
2715
- } catch (error) {
2716
- console.error("[autotel-terminal] Failed to render dashboard:", error);
2717
- }
2718
- return;
2719
- }
2720
- let provider;
2721
- try {
2722
- provider = tracerProvider.getAutotelTracerProvider();
2723
- } catch (error) {
2724
- console.error(
2725
- "[autotel-terminal] Failed to get tracer provider. Call init() first or provide a stream.",
2726
- error
2727
- );
2728
- return;
2729
- }
2730
- if (!provider) {
2731
- console.error(
2732
- "[autotel-terminal] No tracer provider found. Call init() first or provide a stream."
2733
- );
2734
- return;
2735
- }
2736
- if (!canAddSpanProcessor(provider)) {
2737
- console.error(
2738
- "[autotel-terminal] TracerProvider does not support addSpanProcessor. Provide a stream manually."
2739
- );
2740
- return;
2741
- }
2742
- globalStreamingProcessor = new StreamingSpanProcessor(null);
2743
- const terminalStream = createTerminalSpanStream(globalStreamingProcessor);
2744
- provider.addSpanProcessor(globalStreamingProcessor);
2745
- try {
2746
- ink.render(
2747
- /* @__PURE__ */ jsxRuntime.jsx(
2748
- Dashboard,
2749
- {
2750
- title,
2751
- showStats,
2752
- maxSpans,
2753
- colors,
2754
- stream: terminalStream,
2755
- logStream: getTerminalLogStream()
2756
- }
2757
- ),
2758
- { stdin: stdinOption }
2759
- );
2760
- } catch (error) {
2761
- console.error("[autotel-terminal] Failed to render dashboard:", error);
2762
- }
2763
- }
2764
- var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
14
+ /** Format host:port, bracketing IPv6 literals (e.g. `[::1]:4319`). */
2765
15
  function formatAddress(host, port) {
2766
- return host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
2767
- }
16
+ return host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
17
+ }
18
+ /**
19
+ * Listen on `host:port`, and when `host` is a loopback literal, ALSO listen on
20
+ * the sibling loopback family (IPv4 ⟷ IPv6) so a client reaches the collector
21
+ * whether the OS resolves `localhost` to `127.0.0.1` or `::1`.
22
+ *
23
+ * Kills a silent footgun: a dev-server proxy targeting `http://localhost:PORT`
24
+ * on macOS resolves `localhost` to `::1`, but a collector bound only to
25
+ * `127.0.0.1` never receives the request — spans vanish with no error. If the
26
+ * sibling family cannot bind, it is surfaced as a warning, never fatal.
27
+ */
2768
28
  function listenLoopbackDualStack(args) {
2769
- const { primary, port, host, attachSecondary } = args;
2770
- let sibling;
2771
- const ready = new Promise(
2772
- (resolve) => {
2773
- const addresses = [];
2774
- const warnings = [];
2775
- const primaryHost = host === "localhost" ? "127.0.0.1" : host;
2776
- primary.listen(port, primaryHost, () => {
2777
- const addr = primary.address();
2778
- const resolvedPort = addr && typeof addr === "object" ? addr.port : port;
2779
- addresses.push(formatAddress(primaryHost, resolvedPort));
2780
- if (!LOOPBACK.has(host)) {
2781
- resolve({ addresses, warnings });
2782
- return;
2783
- }
2784
- const siblingHost = primaryHost === "::1" ? "127.0.0.1" : "::1";
2785
- const s = http.createServer();
2786
- attachSecondary(s);
2787
- const onError = (e) => {
2788
- s.close();
2789
- warnings.push(
2790
- `could not also bind ${formatAddress(siblingHost, resolvedPort)} (${e.message}); clients using the ${siblingHost === "::1" ? "IPv6" : "IPv4"} form of "localhost" may not connect.`
2791
- );
2792
- resolve({ addresses, warnings });
2793
- };
2794
- s.once("error", onError);
2795
- s.listen(resolvedPort, siblingHost, () => {
2796
- s.off("error", onError);
2797
- sibling = s;
2798
- addresses.push(formatAddress(siblingHost, resolvedPort));
2799
- resolve({ addresses, warnings });
2800
- });
2801
- });
2802
- }
2803
- );
2804
- return {
2805
- ready,
2806
- closeSibling: () => new Promise((res) => {
2807
- if (!sibling) return res();
2808
- sibling.close(() => res());
2809
- })
2810
- };
2811
- }
2812
-
2813
- // src/cli-stream.ts
29
+ const { primary, port, host, attachSecondary } = args;
30
+ let sibling;
31
+ return {
32
+ ready: new Promise((resolve) => {
33
+ const addresses = [];
34
+ const warnings = [];
35
+ const primaryHost = host === "localhost" ? "127.0.0.1" : host;
36
+ primary.listen(port, primaryHost, () => {
37
+ const addr = primary.address();
38
+ const resolvedPort = addr && typeof addr === "object" ? addr.port : port;
39
+ addresses.push(formatAddress(primaryHost, resolvedPort));
40
+ if (!LOOPBACK.has(host)) {
41
+ resolve({
42
+ addresses,
43
+ warnings
44
+ });
45
+ return;
46
+ }
47
+ const siblingHost = primaryHost === "::1" ? "127.0.0.1" : "::1";
48
+ const s = (0, node_http.createServer)();
49
+ attachSecondary(s);
50
+ const onError = (e) => {
51
+ s.close();
52
+ warnings.push(`could not also bind ${formatAddress(siblingHost, resolvedPort)} (${e.message}); clients using the ${siblingHost === "::1" ? "IPv6" : "IPv4"} form of "localhost" may not connect.`);
53
+ resolve({
54
+ addresses,
55
+ warnings
56
+ });
57
+ };
58
+ s.once("error", onError);
59
+ s.listen(resolvedPort, siblingHost, () => {
60
+ s.off("error", onError);
61
+ sibling = s;
62
+ addresses.push(formatAddress(siblingHost, resolvedPort));
63
+ resolve({
64
+ addresses,
65
+ warnings
66
+ });
67
+ });
68
+ });
69
+ }),
70
+ closeSibling: () => new Promise((res) => {
71
+ if (!sibling) return res();
72
+ sibling.close(() => res());
73
+ })
74
+ };
75
+ }
76
+
77
+ //#endregion
78
+ //#region src/cli-stream.ts
79
+ /**
80
+ * In-memory stream implementation for standalone CLI ingestion.
81
+ */
2814
82
  var CliTerminalSpanStream = class {
2815
- #subscribers = /* @__PURE__ */ new Set();
2816
- onSpanEnd(callback) {
2817
- this.#subscribers.add(callback);
2818
- return () => {
2819
- this.#subscribers.delete(callback);
2820
- };
2821
- }
2822
- push(event) {
2823
- for (const subscriber of this.#subscribers) {
2824
- subscriber(event);
2825
- }
2826
- }
83
+ #subscribers = /* @__PURE__ */ new Set();
84
+ onSpanEnd(callback) {
85
+ this.#subscribers.add(callback);
86
+ return () => {
87
+ this.#subscribers.delete(callback);
88
+ };
89
+ }
90
+ push(event) {
91
+ for (const subscriber of this.#subscribers) subscriber(event);
92
+ }
2827
93
  };
2828
94
 
2829
- // src/otlp-http-json.ts
2830
- var MAX_BODY_BYTES = 10 * 1024 * 1024;
95
+ //#endregion
96
+ //#region src/otlp-http-json.ts
97
+ const MAX_BODY_BYTES = 10 * 1024 * 1024;
2831
98
  function anyValueToPrimitive(value) {
2832
- if (!value) return void 0;
2833
- if (value.stringValue !== void 0) return value.stringValue;
2834
- if (value.boolValue !== void 0) return value.boolValue;
2835
- if (value.intValue !== void 0) {
2836
- const num = Number(value.intValue);
2837
- return Number.isNaN(num) ? value.intValue : num;
2838
- }
2839
- if (value.doubleValue !== void 0) return value.doubleValue;
2840
- if (value.bytesValue !== void 0) return value.bytesValue;
2841
- return void 0;
99
+ if (!value) return void 0;
100
+ if (value.stringValue !== void 0) return value.stringValue;
101
+ if (value.boolValue !== void 0) return value.boolValue;
102
+ if (value.intValue !== void 0) {
103
+ const num = Number(value.intValue);
104
+ return Number.isNaN(num) ? value.intValue : num;
105
+ }
106
+ if (value.doubleValue !== void 0) return value.doubleValue;
107
+ if (value.bytesValue !== void 0) return value.bytesValue;
2842
108
  }
2843
109
  function attrsToRecord(attributes) {
2844
- if (!attributes || attributes.length === 0) return {};
2845
- const out = {};
2846
- for (const attribute of attributes) {
2847
- out[attribute.key] = anyValueToPrimitive(attribute.value);
2848
- }
2849
- return out;
110
+ if (!attributes || attributes.length === 0) return {};
111
+ const out = {};
112
+ for (const attribute of attributes) out[attribute.key] = anyValueToPrimitive(attribute.value);
113
+ return out;
2850
114
  }
2851
115
  function normalizeHexId(id, expectedHexLength) {
2852
- if (!id) return "".padStart(expectedHexLength, "0");
2853
- const trimmed = id.trim();
2854
- if (/^[a-fA-F0-9]+$/.test(trimmed)) {
2855
- return trimmed.toLowerCase().padStart(expectedHexLength, "0").slice(-expectedHexLength);
2856
- }
2857
- try {
2858
- const decoded = Buffer.from(trimmed, "base64").toString("hex");
2859
- if (decoded.length > 0) {
2860
- return decoded.toLowerCase().padStart(expectedHexLength, "0").slice(-expectedHexLength);
2861
- }
2862
- } catch {
2863
- }
2864
- return "".padStart(expectedHexLength, "0");
116
+ if (!id) return "".padStart(expectedHexLength, "0");
117
+ const trimmed = id.trim();
118
+ if (/^[a-fA-F0-9]+$/.test(trimmed)) return trimmed.toLowerCase().padStart(expectedHexLength, "0").slice(-expectedHexLength);
119
+ try {
120
+ const decoded = Buffer.from(trimmed, "base64").toString("hex");
121
+ if (decoded.length > 0) return decoded.toLowerCase().padStart(expectedHexLength, "0").slice(-expectedHexLength);
122
+ } catch {}
123
+ return "".padStart(expectedHexLength, "0");
2865
124
  }
2866
125
  function toMs(unixNano) {
2867
- if (!unixNano) return Date.now();
2868
- const parsed = Number(unixNano);
2869
- if (Number.isNaN(parsed)) return Date.now();
2870
- return parsed / 1e6;
126
+ if (!unixNano) return Date.now();
127
+ const parsed = Number(unixNano);
128
+ if (Number.isNaN(parsed)) return Date.now();
129
+ return parsed / 1e6;
2871
130
  }
2872
- function mapStatus2(code) {
2873
- const normalized = typeof code === "string" ? code.toUpperCase() : code;
2874
- if (normalized === 1 || normalized === "STATUS_CODE_OK" || normalized === "OK")
2875
- return "OK";
2876
- if (normalized === 2 || normalized === "STATUS_CODE_ERROR" || normalized === "ERROR") {
2877
- return "ERROR";
2878
- }
2879
- return "UNSET";
131
+ function mapStatus(code) {
132
+ const normalized = typeof code === "string" ? code.toUpperCase() : code;
133
+ if (normalized === 1 || normalized === "STATUS_CODE_OK" || normalized === "OK") return "OK";
134
+ if (normalized === 2 || normalized === "STATUS_CODE_ERROR" || normalized === "ERROR") return "ERROR";
135
+ return "UNSET";
2880
136
  }
2881
- function mapKind2(kind) {
2882
- if (typeof kind === "string") return kind.toUpperCase();
2883
- switch (kind) {
2884
- case 1: {
2885
- return "INTERNAL";
2886
- }
2887
- case 2: {
2888
- return "SERVER";
2889
- }
2890
- case 3: {
2891
- return "CLIENT";
2892
- }
2893
- case 4: {
2894
- return "PRODUCER";
2895
- }
2896
- case 5: {
2897
- return "CONSUMER";
2898
- }
2899
- default: {
2900
- return "INTERNAL";
2901
- }
2902
- }
137
+ function mapKind(kind) {
138
+ if (typeof kind === "string") return kind.toUpperCase();
139
+ switch (kind) {
140
+ case 1: return "INTERNAL";
141
+ case 2: return "SERVER";
142
+ case 3: return "CLIENT";
143
+ case 4: return "PRODUCER";
144
+ case 5: return "CONSUMER";
145
+ default: return "INTERNAL";
146
+ }
2903
147
  }
2904
148
  function* extractSpans(payload) {
2905
- if (!payload || typeof payload !== "object") return;
2906
- const resourceSpans = payload.resourceSpans;
2907
- if (!Array.isArray(resourceSpans)) return;
2908
- for (const resourceSpan of resourceSpans) {
2909
- if (!resourceSpan || typeof resourceSpan !== "object") continue;
2910
- const resource = resourceSpan.resource;
2911
- const resourceAttrs = attrsToRecord(resource?.attributes);
2912
- const scopeSpans = resourceSpan.scopeSpans;
2913
- if (!Array.isArray(scopeSpans)) continue;
2914
- for (const scopeSpan of scopeSpans) {
2915
- if (!scopeSpan || typeof scopeSpan !== "object") continue;
2916
- const spans = scopeSpan.spans;
2917
- if (!Array.isArray(spans)) continue;
2918
- for (const span of spans) {
2919
- if (span && typeof span === "object") {
2920
- yield { span, resourceAttrs };
2921
- }
2922
- }
2923
- }
2924
- }
149
+ if (!payload || typeof payload !== "object") return;
150
+ const resourceSpans = payload.resourceSpans;
151
+ if (!Array.isArray(resourceSpans)) return;
152
+ for (const resourceSpan of resourceSpans) {
153
+ if (!resourceSpan || typeof resourceSpan !== "object") continue;
154
+ const resource = resourceSpan.resource;
155
+ const resourceAttrs = attrsToRecord(resource?.attributes);
156
+ const scopeSpans = resourceSpan.scopeSpans;
157
+ if (!Array.isArray(scopeSpans)) continue;
158
+ for (const scopeSpan of scopeSpans) {
159
+ if (!scopeSpan || typeof scopeSpan !== "object") continue;
160
+ const spans = scopeSpan.spans;
161
+ if (!Array.isArray(spans)) continue;
162
+ for (const span of spans) if (span && typeof span === "object") yield {
163
+ span,
164
+ resourceAttrs
165
+ };
166
+ }
167
+ }
2925
168
  }
2926
169
  function otlpSpanToTerminalEvent(span, resourceAttrs = {}) {
2927
- const startTime = toMs(span.startTimeUnixNano);
2928
- const endTime = toMs(span.endTimeUnixNano);
2929
- const spanAttrs = attrsToRecord(span.attributes);
2930
- const mergedAttrs = {};
2931
- for (const [k, v] of Object.entries(resourceAttrs)) {
2932
- mergedAttrs[k] = v;
2933
- }
2934
- for (const [k, v] of Object.entries(spanAttrs)) {
2935
- mergedAttrs[k] = v;
2936
- }
2937
- const parsedEvents = span.events?.length ? span.events.map((e) => ({
2938
- name: e.name || "",
2939
- timeMs: toMs(e.timeUnixNano),
2940
- attributes: attrsToRecord(e.attributes)
2941
- })) : void 0;
2942
- const parsedLinks = span.links?.length ? span.links.map((l) => ({
2943
- traceId: normalizeHexId(l.traceId, 32),
2944
- spanId: normalizeHexId(l.spanId, 16),
2945
- attributes: attrsToRecord(l.attributes)
2946
- })) : void 0;
2947
- return {
2948
- name: span.name || "unnamed",
2949
- spanId: normalizeHexId(span.spanId, 16),
2950
- traceId: normalizeHexId(span.traceId, 32),
2951
- parentSpanId: span.parentSpanId ? normalizeHexId(span.parentSpanId, 16) : void 0,
2952
- startTime,
2953
- endTime,
2954
- durationMs: Math.max(0, endTime - startTime),
2955
- status: mapStatus2(span.status?.code),
2956
- kind: mapKind2(span.kind),
2957
- attributes: mergedAttrs,
2958
- ...parsedEvents ? { events: parsedEvents } : {},
2959
- ...parsedLinks ? { links: parsedLinks } : {}
2960
- };
170
+ const startTime = toMs(span.startTimeUnixNano);
171
+ const endTime = toMs(span.endTimeUnixNano);
172
+ const spanAttrs = attrsToRecord(span.attributes);
173
+ const mergedAttrs = {};
174
+ for (const [k, v] of Object.entries(resourceAttrs)) mergedAttrs[k] = v;
175
+ for (const [k, v] of Object.entries(spanAttrs)) mergedAttrs[k] = v;
176
+ const parsedEvents = span.events?.length ? span.events.map((e) => ({
177
+ name: e.name || "",
178
+ timeMs: toMs(e.timeUnixNano),
179
+ attributes: attrsToRecord(e.attributes)
180
+ })) : void 0;
181
+ const parsedLinks = span.links?.length ? span.links.map((l) => ({
182
+ traceId: normalizeHexId(l.traceId, 32),
183
+ spanId: normalizeHexId(l.spanId, 16),
184
+ attributes: attrsToRecord(l.attributes)
185
+ })) : void 0;
186
+ return {
187
+ name: span.name || "unnamed",
188
+ spanId: normalizeHexId(span.spanId, 16),
189
+ traceId: normalizeHexId(span.traceId, 32),
190
+ parentSpanId: span.parentSpanId ? normalizeHexId(span.parentSpanId, 16) : void 0,
191
+ startTime,
192
+ endTime,
193
+ durationMs: Math.max(0, endTime - startTime),
194
+ status: mapStatus(span.status?.code),
195
+ kind: mapKind(span.kind),
196
+ attributes: mergedAttrs,
197
+ ...parsedEvents ? { events: parsedEvents } : {},
198
+ ...parsedLinks ? { links: parsedLinks } : {}
199
+ };
2961
200
  }
2962
201
  async function readJsonBody(req) {
2963
- const chunks = [];
2964
- let totalLength = 0;
2965
- for await (const chunk of req) {
2966
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
2967
- totalLength += buf.length;
2968
- if (totalLength > MAX_BODY_BYTES) {
2969
- throw new Error(`Body exceeds ${MAX_BODY_BYTES} byte limit`);
2970
- }
2971
- chunks.push(buf);
2972
- }
2973
- const raw = Buffer.concat(chunks).toString("utf8");
2974
- if (!raw) return {};
2975
- return JSON.parse(raw);
202
+ const chunks = [];
203
+ let totalLength = 0;
204
+ for await (const chunk of req) {
205
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
206
+ totalLength += buf.length;
207
+ if (totalLength > MAX_BODY_BYTES) throw new Error(`Body exceeds ${MAX_BODY_BYTES} byte limit`);
208
+ chunks.push(buf);
209
+ }
210
+ const raw = Buffer.concat(chunks).toString("utf8");
211
+ if (!raw) return {};
212
+ return JSON.parse(raw);
2976
213
  }
2977
214
  function sendJson(res, status, data) {
2978
- res.statusCode = status;
2979
- res.setHeader("content-type", "application/json");
2980
- res.end(JSON.stringify(data));
215
+ res.statusCode = status;
216
+ res.setHeader("content-type", "application/json");
217
+ res.end(JSON.stringify(data));
2981
218
  }
2982
219
  function parseOtlpEvents(payload) {
2983
- const events = [];
2984
- for (const { span, resourceAttrs } of extractSpans(payload)) {
2985
- events.push(otlpSpanToTerminalEvent(span, resourceAttrs));
2986
- }
2987
- return events;
220
+ const events = [];
221
+ for (const { span, resourceAttrs } of extractSpans(payload)) events.push(otlpSpanToTerminalEvent(span, resourceAttrs));
222
+ return events;
2988
223
  }
2989
224
  function mapSeverityToLevel(severityNumber, severityText) {
2990
- if (severityText) {
2991
- const lower = severityText.toLowerCase();
2992
- if (lower.startsWith("debug") || lower === "trace") return "debug";
2993
- if (lower.startsWith("info")) return "info";
2994
- if (lower.startsWith("warn")) return "warn";
2995
- if (lower.startsWith("error") || lower.startsWith("fatal")) return "error";
2996
- }
2997
- if (severityNumber !== void 0) {
2998
- if (severityNumber <= 4) return "debug";
2999
- if (severityNumber <= 8) return "debug";
3000
- if (severityNumber <= 12) return "info";
3001
- if (severityNumber <= 16) return "warn";
3002
- return "error";
3003
- }
3004
- return "info";
225
+ if (severityText) {
226
+ const lower = severityText.toLowerCase();
227
+ if (lower.startsWith("debug") || lower === "trace") return "debug";
228
+ if (lower.startsWith("info")) return "info";
229
+ if (lower.startsWith("warn")) return "warn";
230
+ if (lower.startsWith("error") || lower.startsWith("fatal")) return "error";
231
+ }
232
+ if (severityNumber !== void 0) {
233
+ if (severityNumber <= 4) return "debug";
234
+ if (severityNumber <= 8) return "debug";
235
+ if (severityNumber <= 12) return "info";
236
+ if (severityNumber <= 16) return "warn";
237
+ return "error";
238
+ }
239
+ return "info";
3005
240
  }
3006
241
  function bodyToMessage(body) {
3007
- if (!body) return "";
3008
- const value = anyValueToPrimitive(body);
3009
- return value === void 0 ? "" : String(value);
242
+ if (!body) return "";
243
+ const value = anyValueToPrimitive(body);
244
+ return value === void 0 ? "" : String(value);
3010
245
  }
3011
246
  function* extractLogRecords(payload) {
3012
- if (!payload || typeof payload !== "object") return;
3013
- const resourceLogs = payload.resourceLogs;
3014
- if (!Array.isArray(resourceLogs)) return;
3015
- for (const resourceLog of resourceLogs) {
3016
- if (!resourceLog || typeof resourceLog !== "object") continue;
3017
- const scopeLogs = resourceLog.scopeLogs;
3018
- if (!Array.isArray(scopeLogs)) continue;
3019
- for (const scopeLog of scopeLogs) {
3020
- if (!scopeLog || typeof scopeLog !== "object") continue;
3021
- const logRecords = scopeLog.logRecords;
3022
- if (!Array.isArray(logRecords)) continue;
3023
- for (const record of logRecords) {
3024
- if (record && typeof record === "object") {
3025
- yield record;
3026
- }
3027
- }
3028
- }
3029
- }
247
+ if (!payload || typeof payload !== "object") return;
248
+ const resourceLogs = payload.resourceLogs;
249
+ if (!Array.isArray(resourceLogs)) return;
250
+ for (const resourceLog of resourceLogs) {
251
+ if (!resourceLog || typeof resourceLog !== "object") continue;
252
+ const scopeLogs = resourceLog.scopeLogs;
253
+ if (!Array.isArray(scopeLogs)) continue;
254
+ for (const scopeLog of scopeLogs) {
255
+ if (!scopeLog || typeof scopeLog !== "object") continue;
256
+ const logRecords = scopeLog.logRecords;
257
+ if (!Array.isArray(logRecords)) continue;
258
+ for (const record of logRecords) if (record && typeof record === "object") yield record;
259
+ }
260
+ }
3030
261
  }
3031
262
  function parseOtlpLogEvents(payload) {
3032
- const events = [];
3033
- for (const record of extractLogRecords(payload)) {
3034
- const time = toMs(record.timeUnixNano || record.observedTimeUnixNano);
3035
- events.push({
3036
- time,
3037
- level: mapSeverityToLevel(record.severityNumber, record.severityText),
3038
- message: bodyToMessage(record.body),
3039
- traceId: record.traceId ? normalizeHexId(record.traceId, 32) : void 0,
3040
- spanId: record.spanId ? normalizeHexId(record.spanId, 16) : void 0,
3041
- attributes: attrsToRecord(record.attributes)
3042
- });
3043
- }
3044
- return events;
263
+ const events = [];
264
+ for (const record of extractLogRecords(payload)) {
265
+ const time = toMs(record.timeUnixNano || record.observedTimeUnixNano);
266
+ events.push({
267
+ time,
268
+ level: mapSeverityToLevel(record.severityNumber, record.severityText),
269
+ message: bodyToMessage(record.body),
270
+ traceId: record.traceId ? normalizeHexId(record.traceId, 32) : void 0,
271
+ spanId: record.spanId ? normalizeHexId(record.spanId, 16) : void 0,
272
+ attributes: attrsToRecord(record.attributes)
273
+ });
274
+ }
275
+ return events;
3045
276
  }
3046
277
  function countOtlpMetrics(payload) {
3047
- if (!payload || typeof payload !== "object") return 0;
3048
- let count = 0;
3049
- const resourceMetrics = payload.resourceMetrics;
3050
- if (!Array.isArray(resourceMetrics)) return 0;
3051
- for (const resourceMetric of resourceMetrics) {
3052
- if (!resourceMetric || typeof resourceMetric !== "object") continue;
3053
- const scopeMetrics = resourceMetric.scopeMetrics;
3054
- if (!Array.isArray(scopeMetrics)) continue;
3055
- for (const scopeMetric of scopeMetrics) {
3056
- if (!scopeMetric || typeof scopeMetric !== "object") continue;
3057
- const metrics = scopeMetric.metrics;
3058
- if (Array.isArray(metrics)) {
3059
- count += metrics.length;
3060
- }
3061
- }
3062
- }
3063
- return count;
3064
- }
3065
-
3066
- // src/cli.ts
278
+ if (!payload || typeof payload !== "object") return 0;
279
+ let count = 0;
280
+ const resourceMetrics = payload.resourceMetrics;
281
+ if (!Array.isArray(resourceMetrics)) return 0;
282
+ for (const resourceMetric of resourceMetrics) {
283
+ if (!resourceMetric || typeof resourceMetric !== "object") continue;
284
+ const scopeMetrics = resourceMetric.scopeMetrics;
285
+ if (!Array.isArray(scopeMetrics)) continue;
286
+ for (const scopeMetric of scopeMetrics) {
287
+ if (!scopeMetric || typeof scopeMetric !== "object") continue;
288
+ const metrics = scopeMetric.metrics;
289
+ if (Array.isArray(metrics)) count += metrics.length;
290
+ }
291
+ }
292
+ return count;
293
+ }
294
+
295
+ //#endregion
296
+ //#region src/cli.ts
3067
297
  function printHelp() {
3068
- process.stdout.write(
3069
- String.raw`autotel-terminal - Standalone OTLP receiver with terminal dashboard
298
+ process.stdout.write(String.raw`autotel-terminal - Standalone OTLP receiver with terminal dashboard
3070
299
 
3071
300
  Usage: autotel-terminal [options]
3072
301
 
@@ -3096,166 +325,143 @@ Examples:
3096
325
  npx autotel-terminal
3097
326
  npx autotel-terminal --ai-provider ollama --ai-model granite4
3098
327
  AI_API_KEY=sk-... npx autotel-terminal --ai-provider openai --ai-model gpt-4o
3099
- ` + "\n"
3100
- );
328
+ ` + "\n");
3101
329
  }
3102
330
  function printVersion() {
3103
- try {
3104
- const dir = undefined ?? new URL(".", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))).pathname;
3105
- const pkgPath = path__default.default.resolve(dir, "..", "package.json");
3106
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
3107
- process.stdout.write(`${pkg.version}
3108
- `);
3109
- } catch {
3110
- process.stdout.write("unknown\n");
3111
- }
331
+ try {
332
+ const dir = __dirname ?? new URL(".", require("url").pathToFileURL(__filename).href).pathname;
333
+ const pkgPath = node_path.default.resolve(dir, "..", "package.json");
334
+ const pkg = JSON.parse((0, node_fs.readFileSync)(pkgPath, "utf8"));
335
+ process.stdout.write(`${pkg.version}\n`);
336
+ } catch {
337
+ process.stdout.write("unknown\n");
338
+ }
3112
339
  }
3113
340
  function parseArgs(argv) {
3114
- const options = {
3115
- port: Number(process.env.AUTOTEL_TERMINAL_PORT || 4319),
3116
- host: process.env.AUTOTEL_TERMINAL_HOST || "127.0.0.1",
3117
- title: process.env.AUTOTEL_TERMINAL_TITLE,
3118
- ai: {}
3119
- };
3120
- for (let i = 0; i < argv.length; i++) {
3121
- const arg = argv[i];
3122
- const next = argv[i + 1];
3123
- if (arg === "--help" || arg === "-h") {
3124
- printHelp();
3125
- return null;
3126
- }
3127
- if (arg === "--version" || arg === "-v") {
3128
- printVersion();
3129
- return null;
3130
- }
3131
- if ((arg === "--port" || arg === "-p") && next) {
3132
- options.port = Number(next);
3133
- i++;
3134
- continue;
3135
- }
3136
- if ((arg === "--host" || arg === "-H") && next) {
3137
- options.host = next;
3138
- i++;
3139
- continue;
3140
- }
3141
- if ((arg === "--title" || arg === "-t") && next) {
3142
- options.title = next;
3143
- i++;
3144
- continue;
3145
- }
3146
- if (arg === "--ai-provider" && next) {
3147
- options.ai.provider = next;
3148
- i++;
3149
- continue;
3150
- }
3151
- if (arg === "--ai-model" && next) {
3152
- options.ai.model = next;
3153
- i++;
3154
- continue;
3155
- }
3156
- if (arg === "--ai-api-key" && next) {
3157
- options.ai.apiKey = next;
3158
- i++;
3159
- continue;
3160
- }
3161
- if (arg === "--ai-base-url" && next) {
3162
- options.ai.baseUrl = next;
3163
- i++;
3164
- }
3165
- }
3166
- return options;
3167
- }
3168
- var OTLP_ROUTES = /* @__PURE__ */ new Set(["/v1/traces", "/v1/logs", "/v1/metrics"]);
341
+ const options = {
342
+ port: Number(process.env.AUTOTEL_TERMINAL_PORT || 4319),
343
+ host: process.env.AUTOTEL_TERMINAL_HOST || "127.0.0.1",
344
+ title: process.env.AUTOTEL_TERMINAL_TITLE,
345
+ ai: {}
346
+ };
347
+ for (let i = 0; i < argv.length; i++) {
348
+ const arg = argv[i];
349
+ const next = argv[i + 1];
350
+ if (arg === "--help" || arg === "-h") {
351
+ printHelp();
352
+ return null;
353
+ }
354
+ if (arg === "--version" || arg === "-v") {
355
+ printVersion();
356
+ return null;
357
+ }
358
+ if ((arg === "--port" || arg === "-p") && next) {
359
+ options.port = Number(next);
360
+ i++;
361
+ continue;
362
+ }
363
+ if ((arg === "--host" || arg === "-H") && next) {
364
+ options.host = next;
365
+ i++;
366
+ continue;
367
+ }
368
+ if ((arg === "--title" || arg === "-t") && next) {
369
+ options.title = next;
370
+ i++;
371
+ continue;
372
+ }
373
+ if (arg === "--ai-provider" && next) {
374
+ options.ai.provider = next;
375
+ i++;
376
+ continue;
377
+ }
378
+ if (arg === "--ai-model" && next) {
379
+ options.ai.model = next;
380
+ i++;
381
+ continue;
382
+ }
383
+ if (arg === "--ai-api-key" && next) {
384
+ options.ai.apiKey = next;
385
+ i++;
386
+ continue;
387
+ }
388
+ if (arg === "--ai-base-url" && next) {
389
+ options.ai.baseUrl = next;
390
+ i++;
391
+ }
392
+ }
393
+ return options;
394
+ }
395
+ const OTLP_ROUTES = new Set([
396
+ "/v1/traces",
397
+ "/v1/logs",
398
+ "/v1/metrics"
399
+ ]);
3169
400
  async function main() {
3170
- const options = parseArgs(process.argv.slice(2));
3171
- if (!options) {
3172
- process.exit(0);
3173
- }
3174
- const spanStream = new CliTerminalSpanStream();
3175
- const logStream = getTerminalLogStream();
3176
- renderTerminal(
3177
- {
3178
- title: options.title || `Autotel Terminal (${options.host}:${options.port})`,
3179
- ai: options.ai
3180
- },
3181
- spanStream
3182
- );
3183
- const requestHandler = async (req, res) => {
3184
- if (req.method === "GET" && req.url === "/healthz") {
3185
- sendJson(res, 200, { ok: true });
3186
- return;
3187
- }
3188
- if (req.method !== "POST" || !OTLP_ROUTES.has(req.url ?? "")) {
3189
- sendJson(res, 404, { error: "Not found" });
3190
- return;
3191
- }
3192
- try {
3193
- const payload = await readJsonBody(req);
3194
- if (req.url === "/v1/traces") {
3195
- const events = parseOtlpEvents(payload);
3196
- for (const event of events) {
3197
- spanStream.push(event);
3198
- }
3199
- sendJson(res, 200, { acceptedSpans: events.length });
3200
- return;
3201
- }
3202
- if (req.url === "/v1/logs") {
3203
- const events = parseOtlpLogEvents(payload);
3204
- for (const event of events) {
3205
- logStream.emit(event);
3206
- }
3207
- sendJson(res, 200, { acceptedLogs: events.length });
3208
- return;
3209
- }
3210
- if (req.url === "/v1/metrics") {
3211
- const count = countOtlpMetrics(payload);
3212
- sendJson(res, 200, { acceptedMetrics: count });
3213
- return;
3214
- }
3215
- } catch (error) {
3216
- sendJson(res, 400, {
3217
- error: "Invalid OTLP JSON payload",
3218
- message: error instanceof Error ? error.message : String(error)
3219
- });
3220
- }
3221
- };
3222
- const server = http.createServer(requestHandler);
3223
- const listeners = listenLoopbackDualStack({
3224
- primary: server,
3225
- port: options.port,
3226
- host: options.host,
3227
- attachSecondary: (s) => s.on("request", requestHandler)
3228
- });
3229
- const { addresses, warnings } = await listeners.ready;
3230
- process.stdout.write(
3231
- `[autotel-terminal] listening on ${addresses.join(" + ")}
3232
- `
3233
- );
3234
- process.stdout.write(
3235
- "[autotel-terminal] endpoints: /v1/traces, /v1/logs, /v1/metrics\n"
3236
- );
3237
- process.stdout.write(
3238
- "[autotel-terminal] set OTEL_EXPORTER_OTLP_PROTOCOL=http/json and OTEL_EXPORTER_OTLP_ENDPOINT to this host/port\n"
3239
- );
3240
- for (const w of warnings) {
3241
- process.stdout.write(`[autotel-terminal] \u26A0 ${w}
3242
- `);
3243
- }
3244
- const shutdown = () => {
3245
- Promise.all([
3246
- new Promise((r) => server.close(() => r())),
3247
- listeners.closeSibling()
3248
- ]).then(() => process.exit(0));
3249
- };
3250
- process.on("SIGINT", shutdown);
3251
- process.on("SIGTERM", shutdown);
401
+ const options = parseArgs(process.argv.slice(2));
402
+ if (!options) process.exit(0);
403
+ const spanStream = new CliTerminalSpanStream();
404
+ const logStream = require_src.getTerminalLogStream();
405
+ require_src.renderTerminal({
406
+ title: options.title || `Autotel Terminal (${options.host}:${options.port})`,
407
+ ai: options.ai
408
+ }, spanStream);
409
+ const requestHandler = async (req, res) => {
410
+ if (req.method === "GET" && req.url === "/healthz") {
411
+ sendJson(res, 200, { ok: true });
412
+ return;
413
+ }
414
+ if (req.method !== "POST" || !OTLP_ROUTES.has(req.url ?? "")) {
415
+ sendJson(res, 404, { error: "Not found" });
416
+ return;
417
+ }
418
+ try {
419
+ const payload = await readJsonBody(req);
420
+ if (req.url === "/v1/traces") {
421
+ const events = parseOtlpEvents(payload);
422
+ for (const event of events) spanStream.push(event);
423
+ sendJson(res, 200, { acceptedSpans: events.length });
424
+ return;
425
+ }
426
+ if (req.url === "/v1/logs") {
427
+ const events = parseOtlpLogEvents(payload);
428
+ for (const event of events) logStream.emit(event);
429
+ sendJson(res, 200, { acceptedLogs: events.length });
430
+ return;
431
+ }
432
+ if (req.url === "/v1/metrics") {
433
+ sendJson(res, 200, { acceptedMetrics: countOtlpMetrics(payload) });
434
+ return;
435
+ }
436
+ } catch (error) {
437
+ sendJson(res, 400, {
438
+ error: "Invalid OTLP JSON payload",
439
+ message: error instanceof Error ? error.message : String(error)
440
+ });
441
+ }
442
+ };
443
+ const server = (0, node_http.createServer)(requestHandler);
444
+ const listeners = listenLoopbackDualStack({
445
+ primary: server,
446
+ port: options.port,
447
+ host: options.host,
448
+ attachSecondary: (s) => s.on("request", requestHandler)
449
+ });
450
+ const { addresses, warnings } = await listeners.ready;
451
+ process.stdout.write(`[autotel-terminal] listening on ${addresses.join(" + ")}\n`);
452
+ process.stdout.write("[autotel-terminal] endpoints: /v1/traces, /v1/logs, /v1/metrics\n");
453
+ process.stdout.write("[autotel-terminal] set OTEL_EXPORTER_OTLP_PROTOCOL=http/json and OTEL_EXPORTER_OTLP_ENDPOINT to this host/port\n");
454
+ for (const w of warnings) process.stdout.write(`[autotel-terminal] ⚠ ${w}\n`);
455
+ const shutdown = () => {
456
+ Promise.all([new Promise((r) => server.close(() => r())), listeners.closeSibling()]).then(() => process.exit(0));
457
+ };
458
+ process.on("SIGINT", shutdown);
459
+ process.on("SIGTERM", shutdown);
3252
460
  }
3253
461
  main().catch((error) => {
3254
- process.stderr.write(
3255
- `[autotel-terminal] failed to start: ${error instanceof Error ? error.message : String(error)}
3256
- `
3257
- );
3258
- process.exit(1);
462
+ process.stderr.write(`[autotel-terminal] failed to start: ${error instanceof Error ? error.message : String(error)}\n`);
463
+ process.exit(1);
3259
464
  });
3260
- //# sourceMappingURL=cli.cjs.map
465
+
466
+ //#endregion
3261
467
  //# sourceMappingURL=cli.cjs.map