agentflow-core 0.1.4 → 0.2.1
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/chunk-FJVQYJFB.js +1105 -0
- package/dist/cli.cjs +670 -12
- package/dist/cli.js +57 -14
- package/dist/index.cjs +519 -63
- package/dist/index.d.cts +19 -1
- package/dist/index.d.ts +19 -1
- package/dist/index.js +18 -205
- package/package.json +1 -1
- package/dist/chunk-TT5DLU73.js +0 -435
package/dist/cli.cjs
CHANGED
|
@@ -236,6 +236,35 @@ function createGraphBuilder(config) {
|
|
|
236
236
|
}
|
|
237
237
|
|
|
238
238
|
// src/loader.ts
|
|
239
|
+
function toNodesMap(raw) {
|
|
240
|
+
if (raw instanceof Map) return raw;
|
|
241
|
+
if (Array.isArray(raw)) {
|
|
242
|
+
return new Map(raw);
|
|
243
|
+
}
|
|
244
|
+
if (raw !== null && typeof raw === "object") {
|
|
245
|
+
return new Map(Object.entries(raw));
|
|
246
|
+
}
|
|
247
|
+
return /* @__PURE__ */ new Map();
|
|
248
|
+
}
|
|
249
|
+
function loadGraph(input) {
|
|
250
|
+
const raw = typeof input === "string" ? JSON.parse(input) : input;
|
|
251
|
+
const nodes = toNodesMap(raw.nodes);
|
|
252
|
+
return {
|
|
253
|
+
id: raw.id ?? "",
|
|
254
|
+
rootNodeId: raw.rootNodeId ?? raw.rootId ?? "",
|
|
255
|
+
nodes,
|
|
256
|
+
edges: raw.edges ?? [],
|
|
257
|
+
startTime: raw.startTime ?? 0,
|
|
258
|
+
endTime: raw.endTime ?? null,
|
|
259
|
+
status: raw.status ?? "completed",
|
|
260
|
+
trigger: raw.trigger ?? "unknown",
|
|
261
|
+
agentId: raw.agentId ?? "unknown",
|
|
262
|
+
events: raw.events ?? [],
|
|
263
|
+
traceId: raw.traceId,
|
|
264
|
+
spanId: raw.spanId,
|
|
265
|
+
parentSpanId: raw.parentSpanId
|
|
266
|
+
};
|
|
267
|
+
}
|
|
239
268
|
function graphToJson(graph) {
|
|
240
269
|
const nodesObj = {};
|
|
241
270
|
for (const [id, node] of graph.nodes) {
|
|
@@ -406,8 +435,614 @@ async function runTraced(config) {
|
|
|
406
435
|
};
|
|
407
436
|
}
|
|
408
437
|
|
|
409
|
-
// src/
|
|
438
|
+
// src/live.ts
|
|
439
|
+
var import_node_fs2 = require("fs");
|
|
440
|
+
var import_node_path2 = require("path");
|
|
441
|
+
|
|
442
|
+
// src/graph-query.ts
|
|
443
|
+
function getFailures(graph) {
|
|
444
|
+
const failureStatuses = /* @__PURE__ */ new Set(["failed", "hung", "timeout"]);
|
|
445
|
+
return [...graph.nodes.values()].filter((node) => failureStatuses.has(node.status));
|
|
446
|
+
}
|
|
447
|
+
function getHungNodes(graph) {
|
|
448
|
+
return [...graph.nodes.values()].filter(
|
|
449
|
+
(node) => node.status === "running" && node.endTime === null
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
function getDuration(graph) {
|
|
453
|
+
const end = graph.endTime ?? Date.now();
|
|
454
|
+
return end - graph.startTime;
|
|
455
|
+
}
|
|
456
|
+
function getDepth(graph) {
|
|
457
|
+
const root = graph.nodes.get(graph.rootNodeId);
|
|
458
|
+
if (!root) return -1;
|
|
459
|
+
function dfs(node, depth) {
|
|
460
|
+
if (node.children.length === 0) return depth;
|
|
461
|
+
let maxDepth = depth;
|
|
462
|
+
for (const childId of node.children) {
|
|
463
|
+
const child = graph.nodes.get(childId);
|
|
464
|
+
if (!child) continue;
|
|
465
|
+
const childDepth = dfs(child, depth + 1);
|
|
466
|
+
if (childDepth > maxDepth) maxDepth = childDepth;
|
|
467
|
+
}
|
|
468
|
+
return maxDepth;
|
|
469
|
+
}
|
|
470
|
+
return dfs(root, 0);
|
|
471
|
+
}
|
|
472
|
+
function getStats(graph) {
|
|
473
|
+
const byStatus = {
|
|
474
|
+
running: 0,
|
|
475
|
+
completed: 0,
|
|
476
|
+
failed: 0,
|
|
477
|
+
hung: 0,
|
|
478
|
+
timeout: 0
|
|
479
|
+
};
|
|
480
|
+
const byType = {
|
|
481
|
+
agent: 0,
|
|
482
|
+
tool: 0,
|
|
483
|
+
subagent: 0,
|
|
484
|
+
wait: 0,
|
|
485
|
+
decision: 0,
|
|
486
|
+
custom: 0
|
|
487
|
+
};
|
|
488
|
+
let failureCount = 0;
|
|
489
|
+
let hungCount = 0;
|
|
490
|
+
for (const node of graph.nodes.values()) {
|
|
491
|
+
byStatus[node.status]++;
|
|
492
|
+
byType[node.type]++;
|
|
493
|
+
if (node.status === "failed" || node.status === "timeout" || node.status === "hung") {
|
|
494
|
+
failureCount++;
|
|
495
|
+
}
|
|
496
|
+
if (node.status === "running" && node.endTime === null) {
|
|
497
|
+
hungCount++;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return {
|
|
501
|
+
totalNodes: graph.nodes.size,
|
|
502
|
+
byStatus,
|
|
503
|
+
byType,
|
|
504
|
+
depth: getDepth(graph),
|
|
505
|
+
duration: getDuration(graph),
|
|
506
|
+
failureCount,
|
|
507
|
+
hungCount
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// src/graph-stitch.ts
|
|
512
|
+
function groupByTraceId(graphs) {
|
|
513
|
+
const groups = /* @__PURE__ */ new Map();
|
|
514
|
+
for (const g of graphs) {
|
|
515
|
+
if (!g.traceId) continue;
|
|
516
|
+
const arr = groups.get(g.traceId) ?? [];
|
|
517
|
+
arr.push(g);
|
|
518
|
+
groups.set(g.traceId, arr);
|
|
519
|
+
}
|
|
520
|
+
return groups;
|
|
521
|
+
}
|
|
522
|
+
function stitchTrace(graphs) {
|
|
523
|
+
if (graphs.length === 0) throw new Error("No graphs to stitch");
|
|
524
|
+
const traceId = graphs[0].traceId ?? "";
|
|
525
|
+
const graphsBySpan = /* @__PURE__ */ new Map();
|
|
526
|
+
const childMap = /* @__PURE__ */ new Map();
|
|
527
|
+
let rootGraph = null;
|
|
528
|
+
for (const g of graphs) {
|
|
529
|
+
if (g.spanId) graphsBySpan.set(g.spanId, g);
|
|
530
|
+
if (!g.parentSpanId) {
|
|
531
|
+
if (!rootGraph || g.startTime < rootGraph.startTime) rootGraph = g;
|
|
532
|
+
}
|
|
533
|
+
if (g.parentSpanId) {
|
|
534
|
+
const siblings = childMap.get(g.parentSpanId) ?? [];
|
|
535
|
+
if (g.spanId) siblings.push(g.spanId);
|
|
536
|
+
childMap.set(g.parentSpanId, siblings);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
if (!rootGraph) rootGraph = graphs[0];
|
|
540
|
+
let status = "completed";
|
|
541
|
+
let endTime = 0;
|
|
542
|
+
let startTime = Infinity;
|
|
543
|
+
for (const g of graphs) {
|
|
544
|
+
startTime = Math.min(startTime, g.startTime);
|
|
545
|
+
if (g.status === "failed") status = "failed";
|
|
546
|
+
else if (g.status === "running" && status !== "failed") status = "running";
|
|
547
|
+
if (g.endTime === null) endTime = null;
|
|
548
|
+
else if (endTime !== null) endTime = Math.max(endTime, g.endTime);
|
|
549
|
+
}
|
|
550
|
+
const frozenChildMap = /* @__PURE__ */ new Map();
|
|
551
|
+
for (const [k, v] of childMap) frozenChildMap.set(k, Object.freeze([...v]));
|
|
552
|
+
return Object.freeze({
|
|
553
|
+
traceId,
|
|
554
|
+
graphs: graphsBySpan,
|
|
555
|
+
rootGraph,
|
|
556
|
+
childMap: frozenChildMap,
|
|
557
|
+
startTime,
|
|
558
|
+
endTime,
|
|
559
|
+
status
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
function getTraceTree(trace) {
|
|
563
|
+
const result = [];
|
|
564
|
+
function walk(spanId) {
|
|
565
|
+
const graph = trace.graphs.get(spanId);
|
|
566
|
+
if (graph) result.push(graph);
|
|
567
|
+
const children = trace.childMap.get(spanId) ?? [];
|
|
568
|
+
for (const childSpan of children) walk(childSpan);
|
|
569
|
+
}
|
|
570
|
+
if (trace.rootGraph.spanId) walk(trace.rootGraph.spanId);
|
|
571
|
+
else result.push(trace.rootGraph);
|
|
572
|
+
return result;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// src/live.ts
|
|
576
|
+
var C = {
|
|
577
|
+
reset: "\x1B[0m",
|
|
578
|
+
bold: "\x1B[1m",
|
|
579
|
+
dim: "\x1B[90m",
|
|
580
|
+
under: "\x1B[4m",
|
|
581
|
+
red: "\x1B[31m",
|
|
582
|
+
green: "\x1B[32m",
|
|
583
|
+
yellow: "\x1B[33m",
|
|
584
|
+
blue: "\x1B[34m",
|
|
585
|
+
magenta: "\x1B[35m",
|
|
586
|
+
cyan: "\x1B[36m",
|
|
587
|
+
white: "\x1B[37m"
|
|
588
|
+
};
|
|
410
589
|
function parseArgs(argv) {
|
|
590
|
+
const config = { tracesDir: ".", refreshMs: 3e3, recursive: false };
|
|
591
|
+
const args = argv.slice(0);
|
|
592
|
+
if (args[0] === "live") args.shift();
|
|
593
|
+
let i = 0;
|
|
594
|
+
while (i < args.length) {
|
|
595
|
+
const arg = args[i];
|
|
596
|
+
if (arg === "--help" || arg === "-h") {
|
|
597
|
+
printUsage();
|
|
598
|
+
process.exit(0);
|
|
599
|
+
} else if (arg === "--refresh" || arg === "-r") {
|
|
600
|
+
i++;
|
|
601
|
+
const v = parseInt(args[i] ?? "", 10);
|
|
602
|
+
if (!isNaN(v) && v > 0) config.refreshMs = v * 1e3;
|
|
603
|
+
i++;
|
|
604
|
+
} else if (arg === "--recursive" || arg === "-R") {
|
|
605
|
+
config.recursive = true;
|
|
606
|
+
i++;
|
|
607
|
+
} else if (arg === "--traces-dir" || arg === "-t") {
|
|
608
|
+
i++;
|
|
609
|
+
config.tracesDir = args[i] ?? config.tracesDir;
|
|
610
|
+
i++;
|
|
611
|
+
} else if (!arg.startsWith("-")) {
|
|
612
|
+
config.tracesDir = arg;
|
|
613
|
+
i++;
|
|
614
|
+
} else {
|
|
615
|
+
i++;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
config.tracesDir = (0, import_node_path2.resolve)(config.tracesDir);
|
|
619
|
+
return config;
|
|
620
|
+
}
|
|
621
|
+
function printUsage() {
|
|
622
|
+
console.log(`
|
|
623
|
+
AgentFlow Live Monitor \u2014 real-time terminal dashboard for agent systems.
|
|
624
|
+
|
|
625
|
+
Auto-detects agent traces, state files, job schedulers, and session logs
|
|
626
|
+
from any JSON/JSONL files in the watched directory.
|
|
627
|
+
|
|
628
|
+
Usage:
|
|
629
|
+
agentflow live [directory] [options]
|
|
630
|
+
|
|
631
|
+
Arguments:
|
|
632
|
+
directory Directory to watch (default: current directory)
|
|
633
|
+
|
|
634
|
+
Options:
|
|
635
|
+
-r, --refresh <secs> Refresh interval in seconds (default: 3)
|
|
636
|
+
-R, --recursive Scan subdirectories (1 level deep)
|
|
637
|
+
-h, --help Show this help message
|
|
638
|
+
|
|
639
|
+
Examples:
|
|
640
|
+
agentflow live ./data
|
|
641
|
+
agentflow live ./traces --refresh 5
|
|
642
|
+
agentflow live /var/lib/myagent -R
|
|
643
|
+
`.trim());
|
|
644
|
+
}
|
|
645
|
+
function scanFiles(dir, recursive) {
|
|
646
|
+
const results = [];
|
|
647
|
+
function scanDir(d) {
|
|
648
|
+
try {
|
|
649
|
+
for (const f of (0, import_node_fs2.readdirSync)(d)) {
|
|
650
|
+
if (f.startsWith(".")) continue;
|
|
651
|
+
const fp = (0, import_node_path2.join)(d, f);
|
|
652
|
+
let stat;
|
|
653
|
+
try {
|
|
654
|
+
stat = (0, import_node_fs2.statSync)(fp);
|
|
655
|
+
} catch {
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
if (stat.isDirectory() && recursive && d === dir) {
|
|
659
|
+
scanDir(fp);
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
662
|
+
if (!stat.isFile()) continue;
|
|
663
|
+
if (f.endsWith(".json")) {
|
|
664
|
+
results.push({ filename: f, path: fp, mtime: stat.mtime.getTime(), ext: ".json" });
|
|
665
|
+
} else if (f.endsWith(".jsonl")) {
|
|
666
|
+
results.push({ filename: f, path: fp, mtime: stat.mtime.getTime(), ext: ".jsonl" });
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
} catch {
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
scanDir(dir);
|
|
673
|
+
results.sort((a, b) => b.mtime - a.mtime);
|
|
674
|
+
return results;
|
|
675
|
+
}
|
|
676
|
+
function safeReadJson(fp) {
|
|
677
|
+
try {
|
|
678
|
+
return JSON.parse((0, import_node_fs2.readFileSync)(fp, "utf8"));
|
|
679
|
+
} catch {
|
|
680
|
+
return null;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
function nameFromFile(filename) {
|
|
684
|
+
return (0, import_node_path2.basename)(filename).replace(/\.(json|jsonl)$/, "").replace(/-state$/, "");
|
|
685
|
+
}
|
|
686
|
+
function normalizeStatus(val) {
|
|
687
|
+
if (typeof val !== "string") return "unknown";
|
|
688
|
+
const s = val.toLowerCase();
|
|
689
|
+
if (["ok", "success", "completed", "done", "passed", "healthy", "good"].includes(s)) return "ok";
|
|
690
|
+
if (["error", "failed", "failure", "crashed", "unhealthy", "bad", "timeout"].includes(s)) return "error";
|
|
691
|
+
if (["running", "active", "in_progress", "started", "pending", "processing"].includes(s)) return "running";
|
|
692
|
+
return "unknown";
|
|
693
|
+
}
|
|
694
|
+
function findStatus(obj) {
|
|
695
|
+
for (const key of ["status", "state", "lastRunStatus", "lastStatus", "health", "result"]) {
|
|
696
|
+
if (key in obj) {
|
|
697
|
+
const val = obj[key];
|
|
698
|
+
if (typeof val === "string") return normalizeStatus(val);
|
|
699
|
+
if (typeof val === "object" && val !== null && "status" in val) {
|
|
700
|
+
return normalizeStatus(val.status);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
return "unknown";
|
|
705
|
+
}
|
|
706
|
+
function findTimestamp(obj) {
|
|
707
|
+
for (const key of ["ts", "timestamp", "lastRunAtMs", "last_run", "lastExecution", "updated_at", "started_at", "endTime", "startTime"]) {
|
|
708
|
+
const val = obj[key];
|
|
709
|
+
if (typeof val === "number") return val > 1e12 ? val : val * 1e3;
|
|
710
|
+
if (typeof val === "string") {
|
|
711
|
+
const d = Date.parse(val);
|
|
712
|
+
if (!isNaN(d)) return d;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return 0;
|
|
716
|
+
}
|
|
717
|
+
function extractDetail(obj) {
|
|
718
|
+
const parts = [];
|
|
719
|
+
for (const key of ["summary", "message", "description", "lastError", "error", "name", "jobId", "id"]) {
|
|
720
|
+
const val = obj[key];
|
|
721
|
+
if (typeof val === "string" && val.length > 0 && val.length < 200) {
|
|
722
|
+
parts.push(val.slice(0, 80));
|
|
723
|
+
break;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
for (const key of ["totalExecutions", "runs", "count", "processed", "consecutiveErrors"]) {
|
|
727
|
+
const val = obj[key];
|
|
728
|
+
if (typeof val === "number") {
|
|
729
|
+
parts.push(`${key}: ${val}`);
|
|
730
|
+
break;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
return parts.join(" | ") || "";
|
|
734
|
+
}
|
|
735
|
+
function tryLoadTrace(fp, raw) {
|
|
736
|
+
if (typeof raw !== "object" || raw === null) return null;
|
|
737
|
+
const obj = raw;
|
|
738
|
+
if (!("nodes" in obj)) return null;
|
|
739
|
+
if (!("agentId" in obj) && !("rootNodeId" in obj) && !("rootId" in obj)) return null;
|
|
740
|
+
try {
|
|
741
|
+
return loadGraph(obj);
|
|
742
|
+
} catch {
|
|
743
|
+
return null;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
function processJsonFile(file) {
|
|
747
|
+
const raw = safeReadJson(file.path);
|
|
748
|
+
if (raw === null) return [];
|
|
749
|
+
const records = [];
|
|
750
|
+
const trace = tryLoadTrace(file.path, raw);
|
|
751
|
+
if (trace) {
|
|
752
|
+
try {
|
|
753
|
+
const fails = getFailures(trace);
|
|
754
|
+
const hung = getHungNodes(trace);
|
|
755
|
+
const stats = getStats(trace);
|
|
756
|
+
records.push({
|
|
757
|
+
id: trace.agentId,
|
|
758
|
+
source: "trace",
|
|
759
|
+
status: fails.length === 0 && hung.length === 0 ? "ok" : "error",
|
|
760
|
+
lastActive: file.mtime,
|
|
761
|
+
detail: `${stats.totalNodes} nodes [${trace.trigger}]`,
|
|
762
|
+
file: file.filename,
|
|
763
|
+
traceData: trace
|
|
764
|
+
});
|
|
765
|
+
} catch {
|
|
766
|
+
}
|
|
767
|
+
return records;
|
|
768
|
+
}
|
|
769
|
+
if (typeof raw !== "object") return records;
|
|
770
|
+
const arr = Array.isArray(raw) ? raw : Array.isArray(raw.jobs) ? raw.jobs : Array.isArray(raw.tasks) ? raw.tasks : Array.isArray(raw.items) ? raw.items : null;
|
|
771
|
+
if (arr && arr.length > 0 && typeof arr[0] === "object" && arr[0] !== null) {
|
|
772
|
+
for (const item of arr.slice(0, 50)) {
|
|
773
|
+
const name = item.name ?? item.id ?? item.jobId ?? item.agentId;
|
|
774
|
+
if (!name) continue;
|
|
775
|
+
const state = typeof item.state === "object" && item.state !== null ? item.state : item;
|
|
776
|
+
const status2 = findStatus(state);
|
|
777
|
+
const ts2 = findTimestamp(state) || file.mtime;
|
|
778
|
+
const detail2 = extractDetail(state);
|
|
779
|
+
records.push({ id: String(name), source: "jobs", status: status2, lastActive: ts2, detail: detail2, file: file.filename });
|
|
780
|
+
}
|
|
781
|
+
return records;
|
|
782
|
+
}
|
|
783
|
+
const obj = raw;
|
|
784
|
+
for (const containerKey of ["tools", "workers", "services", "agents", "daemons"]) {
|
|
785
|
+
const container = obj[containerKey];
|
|
786
|
+
if (typeof container === "object" && container !== null && !Array.isArray(container)) {
|
|
787
|
+
for (const [name, info] of Object.entries(container)) {
|
|
788
|
+
if (typeof info !== "object" || info === null) continue;
|
|
789
|
+
const w = info;
|
|
790
|
+
const status2 = findStatus(w);
|
|
791
|
+
const ts2 = findTimestamp(w) || findTimestamp(obj) || file.mtime;
|
|
792
|
+
const pid = w.pid;
|
|
793
|
+
const detail2 = pid ? `pid: ${pid}` : extractDetail(w);
|
|
794
|
+
records.push({ id: name, source: "workers", status: status2, lastActive: ts2, detail: detail2, file: file.filename });
|
|
795
|
+
}
|
|
796
|
+
return records;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
const status = findStatus(obj);
|
|
800
|
+
const ts = findTimestamp(obj) || file.mtime;
|
|
801
|
+
const detail = extractDetail(obj);
|
|
802
|
+
records.push({ id: nameFromFile(file.filename), source: "state", status, lastActive: ts, detail, file: file.filename });
|
|
803
|
+
return records;
|
|
804
|
+
}
|
|
805
|
+
function processJsonlFile(file) {
|
|
806
|
+
try {
|
|
807
|
+
const content = (0, import_node_fs2.readFileSync)(file.path, "utf8").trim();
|
|
808
|
+
if (!content) return [];
|
|
809
|
+
const lines = content.split("\n");
|
|
810
|
+
const lastLine = lines[lines.length - 1];
|
|
811
|
+
const obj = JSON.parse(lastLine);
|
|
812
|
+
const name = obj.jobId ?? obj.agentId ?? obj.name ?? obj.id ?? nameFromFile(file.filename);
|
|
813
|
+
const status = findStatus(obj);
|
|
814
|
+
const ts = findTimestamp(obj) || file.mtime;
|
|
815
|
+
const action = obj.action;
|
|
816
|
+
const detail = action ? `${action} (${lines.length} entries)` : `${lines.length} entries`;
|
|
817
|
+
return [{ id: String(name), source: "session", status, lastActive: ts, detail, file: file.filename }];
|
|
818
|
+
} catch {
|
|
819
|
+
return [];
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
var prevFileCount = 0;
|
|
823
|
+
var newExecCount = 0;
|
|
824
|
+
var sessionStart = Date.now();
|
|
825
|
+
function render(config) {
|
|
826
|
+
const files = scanFiles(config.tracesDir, config.recursive);
|
|
827
|
+
if (files.length > prevFileCount && prevFileCount > 0) {
|
|
828
|
+
newExecCount += files.length - prevFileCount;
|
|
829
|
+
}
|
|
830
|
+
prevFileCount = files.length;
|
|
831
|
+
const allRecords = [];
|
|
832
|
+
const allTraces = [];
|
|
833
|
+
for (const f of files.slice(0, 300)) {
|
|
834
|
+
const records = f.ext === ".jsonl" ? processJsonlFile(f) : processJsonFile(f);
|
|
835
|
+
for (const r of records) {
|
|
836
|
+
allRecords.push(r);
|
|
837
|
+
if (r.traceData) allTraces.push(r.traceData);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
const agents = {};
|
|
841
|
+
for (const r of allRecords) {
|
|
842
|
+
if (!agents[r.id]) {
|
|
843
|
+
agents[r.id] = { name: r.id, total: 0, ok: 0, fail: 0, running: 0, lastTs: 0, source: r.source, detail: "" };
|
|
844
|
+
}
|
|
845
|
+
const ag = agents[r.id];
|
|
846
|
+
ag.total++;
|
|
847
|
+
if (r.status === "ok") ag.ok++;
|
|
848
|
+
else if (r.status === "error") ag.fail++;
|
|
849
|
+
else if (r.status === "running") ag.running++;
|
|
850
|
+
if (r.lastActive > ag.lastTs) {
|
|
851
|
+
ag.lastTs = r.lastActive;
|
|
852
|
+
ag.detail = r.detail;
|
|
853
|
+
ag.source = r.source;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
const agentList = Object.values(agents).sort((a, b) => b.lastTs - a.lastTs);
|
|
857
|
+
const totExec = agentList.reduce((s, a) => s + a.total, 0);
|
|
858
|
+
const totFail = agentList.reduce((s, a) => s + a.fail, 0);
|
|
859
|
+
const totRunning = agentList.reduce((s, a) => s + a.running, 0);
|
|
860
|
+
const sysRate = totExec > 0 ? ((totExec - totFail) / totExec * 100).toFixed(1) : "100.0";
|
|
861
|
+
const now = Date.now();
|
|
862
|
+
const buckets = new Array(12).fill(0);
|
|
863
|
+
const failBuckets = new Array(12).fill(0);
|
|
864
|
+
for (const r of allRecords) {
|
|
865
|
+
const age = now - r.lastActive;
|
|
866
|
+
if (age > 36e5 || age < 0) continue;
|
|
867
|
+
const idx = 11 - Math.floor(age / 3e5);
|
|
868
|
+
if (idx >= 0 && idx < 12) {
|
|
869
|
+
buckets[idx]++;
|
|
870
|
+
if (r.status === "error") failBuckets[idx]++;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
const maxBucket = Math.max(...buckets, 1);
|
|
874
|
+
const sparkChars = " \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";
|
|
875
|
+
const spark = buckets.map((v, i) => {
|
|
876
|
+
const level = Math.round(v / maxBucket * 8);
|
|
877
|
+
return (failBuckets[i] > 0 ? C.red : C.green) + sparkChars[level] + C.reset;
|
|
878
|
+
}).join("");
|
|
879
|
+
const distributedTraces = [];
|
|
880
|
+
if (allTraces.length > 1) {
|
|
881
|
+
const traceGroups = groupByTraceId(allTraces);
|
|
882
|
+
for (const [_tid, graphs] of traceGroups) {
|
|
883
|
+
if (graphs.length > 1) {
|
|
884
|
+
try {
|
|
885
|
+
distributedTraces.push(stitchTrace(graphs));
|
|
886
|
+
} catch {
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
distributedTraces.sort((a, b) => b.startTime - a.startTime);
|
|
891
|
+
}
|
|
892
|
+
const upSec = Math.floor((Date.now() - sessionStart) / 1e3);
|
|
893
|
+
const upMin = Math.floor(upSec / 60);
|
|
894
|
+
const upStr = upMin > 0 ? `${upMin}m ${upSec % 60}s` : `${upSec}s`;
|
|
895
|
+
const time = (/* @__PURE__ */ new Date()).toLocaleTimeString();
|
|
896
|
+
const sourceTag = (s) => {
|
|
897
|
+
switch (s) {
|
|
898
|
+
case "trace":
|
|
899
|
+
return `${C.cyan}trace${C.reset}`;
|
|
900
|
+
case "jobs":
|
|
901
|
+
return `${C.blue}job${C.reset}`;
|
|
902
|
+
case "workers":
|
|
903
|
+
return `${C.magenta}worker${C.reset}`;
|
|
904
|
+
case "session":
|
|
905
|
+
return `${C.yellow}session${C.reset}`;
|
|
906
|
+
case "state":
|
|
907
|
+
return `${C.dim}state${C.reset}`;
|
|
908
|
+
}
|
|
909
|
+
};
|
|
910
|
+
process.stdout.write("\x1B[2J\x1B[H");
|
|
911
|
+
console.log(`${C.bold}${C.cyan}\u2554${"\u2550".repeat(70)}\u2557${C.reset}`);
|
|
912
|
+
console.log(`${C.bold}${C.cyan}\u2551${C.reset} ${C.bold}${C.white}AGENTFLOW LIVE${C.reset} ${C.green}\u25CF LIVE${C.reset} ${C.dim}${time}${C.reset} ${C.bold}${C.cyan}\u2551${C.reset}`);
|
|
913
|
+
const metaLine = `Refresh: ${config.refreshMs / 1e3}s \xB7 Up: ${upStr} \xB7 Files: ${files.length}`;
|
|
914
|
+
const pad1 = Math.max(0, 64 - metaLine.length);
|
|
915
|
+
console.log(`${C.bold}${C.cyan}\u2551${C.reset} ${C.dim}${metaLine}${C.reset}${" ".repeat(pad1)}${C.bold}${C.cyan}\u2551${C.reset}`);
|
|
916
|
+
console.log(`${C.bold}${C.cyan}\u255A${"\u2550".repeat(70)}\u255D${C.reset}`);
|
|
917
|
+
const sc = totFail === 0 ? C.green : C.yellow;
|
|
918
|
+
console.log("");
|
|
919
|
+
console.log(` ${C.bold}Agents${C.reset} ${sc}${agentList.length}${C.reset} ${C.bold}Records${C.reset} ${sc}${totExec}${C.reset} ${C.bold}Success${C.reset} ${sc}${sysRate}%${C.reset} ${C.bold}Running${C.reset} ${C.green}${totRunning}${C.reset} ${C.bold}Errors${C.reset} ${totFail > 0 ? C.red : C.dim}${totFail}${C.reset} ${C.bold}New${C.reset} ${C.yellow}+${newExecCount}${C.reset}`);
|
|
920
|
+
console.log("");
|
|
921
|
+
console.log(` ${C.bold}Activity (1h)${C.reset} ${spark} ${C.dim}\u2190 now${C.reset}`);
|
|
922
|
+
console.log("");
|
|
923
|
+
console.log(` ${C.bold}${C.under}Agent Type Status Last Active Detail${C.reset}`);
|
|
924
|
+
for (const ag of agentList.slice(0, 30)) {
|
|
925
|
+
const lastTime = ag.lastTs > 0 ? new Date(ag.lastTs).toLocaleTimeString() : "n/a";
|
|
926
|
+
const isRecent = Date.now() - ag.lastTs < 3e5;
|
|
927
|
+
let statusIcon;
|
|
928
|
+
let statusText;
|
|
929
|
+
if (ag.fail > 0 && ag.ok === 0 && ag.running === 0) {
|
|
930
|
+
statusIcon = `${C.red}\u25CF${C.reset}`;
|
|
931
|
+
statusText = `${C.red}error${C.reset}`;
|
|
932
|
+
} else if (ag.running > 0) {
|
|
933
|
+
statusIcon = `${C.green}\u25CF${C.reset}`;
|
|
934
|
+
statusText = `${C.green}running${C.reset}`;
|
|
935
|
+
} else if (ag.fail > 0) {
|
|
936
|
+
statusIcon = `${C.yellow}\u25CF${C.reset}`;
|
|
937
|
+
statusText = `${C.yellow}${ag.ok}ok/${ag.fail}err${C.reset}`;
|
|
938
|
+
} else if (ag.ok > 0) {
|
|
939
|
+
statusIcon = isRecent ? `${C.green}\u25CF${C.reset}` : `${C.dim}\u25CB${C.reset}`;
|
|
940
|
+
statusText = ag.total > 1 ? `${C.green}${ag.ok}/${ag.total}${C.reset}` : `${C.green}ok${C.reset}`;
|
|
941
|
+
} else {
|
|
942
|
+
statusIcon = `${C.dim}\u25CB${C.reset}`;
|
|
943
|
+
statusText = `${C.dim}idle${C.reset}`;
|
|
944
|
+
}
|
|
945
|
+
const name = ag.name.length > 23 ? ag.name.slice(0, 22) + "\u2026" : ag.name.padEnd(23);
|
|
946
|
+
const src = sourceTag(ag.source).padEnd(16);
|
|
947
|
+
const active = isRecent ? `${C.green}${lastTime}${C.reset}` : `${C.dim}${lastTime}${C.reset}`;
|
|
948
|
+
const detail = ag.detail.length > 30 ? ag.detail.slice(0, 29) + "\u2026" : ag.detail;
|
|
949
|
+
console.log(` ${statusIcon} ${name} ${src} ${statusText.padEnd(18)} ${active.padEnd(20)} ${C.dim}${detail}${C.reset}`);
|
|
950
|
+
}
|
|
951
|
+
if (distributedTraces.length > 0) {
|
|
952
|
+
console.log("");
|
|
953
|
+
console.log(` ${C.bold}${C.under}Distributed Traces${C.reset}`);
|
|
954
|
+
for (const dt of distributedTraces.slice(0, 3)) {
|
|
955
|
+
const traceTime = new Date(dt.startTime).toLocaleTimeString();
|
|
956
|
+
const statusIcon = dt.status === "completed" ? `${C.green}\u2713${C.reset}` : dt.status === "failed" ? `${C.red}\u2717${C.reset}` : `${C.yellow}\u23F3${C.reset}`;
|
|
957
|
+
const dur = dt.endTime ? `${dt.endTime - dt.startTime}ms` : "running";
|
|
958
|
+
const tid = dt.traceId.slice(0, 8);
|
|
959
|
+
console.log(` ${statusIcon} ${C.magenta}trace:${tid}${C.reset} ${C.dim}${traceTime} ${dur} (${dt.graphs.size} agents)${C.reset}`);
|
|
960
|
+
const tree = getTraceTree(dt);
|
|
961
|
+
for (let i = 0; i < Math.min(tree.length, 6); i++) {
|
|
962
|
+
const g = tree[i];
|
|
963
|
+
const depth = getDistDepth(dt, g.spanId);
|
|
964
|
+
const indent = " " + "\u2502 ".repeat(Math.max(0, depth - 1));
|
|
965
|
+
const isLast = i === tree.length - 1 || getDistDepth(dt, tree[i + 1]?.spanId) <= depth;
|
|
966
|
+
const conn = depth === 0 ? " " : isLast ? "\u2514\u2500 " : "\u251C\u2500 ";
|
|
967
|
+
const gs = g.status === "completed" ? `${C.green}\u2713${C.reset}` : g.status === "failed" ? `${C.red}\u2717${C.reset}` : `${C.yellow}\u23F3${C.reset}`;
|
|
968
|
+
const gd = g.endTime ? `${g.endTime - g.startTime}ms` : "running";
|
|
969
|
+
console.log(`${indent}${conn}${gs} ${C.bold}${g.agentId}${C.reset} ${C.dim}[${g.trigger}] ${gd}${C.reset}`);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
const recentRecords = allRecords.filter((r) => r.lastActive > 0).sort((a, b) => b.lastActive - a.lastActive).slice(0, 8);
|
|
974
|
+
if (recentRecords.length > 0) {
|
|
975
|
+
console.log("");
|
|
976
|
+
console.log(` ${C.bold}${C.under}Recent Activity${C.reset}`);
|
|
977
|
+
for (const r of recentRecords) {
|
|
978
|
+
const icon = r.status === "ok" ? `${C.green}\u2713${C.reset}` : r.status === "error" ? `${C.red}\u2717${C.reset}` : r.status === "running" ? `${C.green}\u25B6${C.reset}` : `${C.dim}\u25CB${C.reset}`;
|
|
979
|
+
const t = new Date(r.lastActive).toLocaleTimeString();
|
|
980
|
+
const agent = r.id.length > 26 ? r.id.slice(0, 25) + "\u2026" : r.id.padEnd(26);
|
|
981
|
+
const age = Math.floor((Date.now() - r.lastActive) / 1e3);
|
|
982
|
+
const ageStr = age < 60 ? age + "s ago" : age < 3600 ? Math.floor(age / 60) + "m ago" : Math.floor(age / 3600) + "h ago";
|
|
983
|
+
const detail = r.detail.length > 25 ? r.detail.slice(0, 24) + "\u2026" : r.detail;
|
|
984
|
+
console.log(` ${icon} ${agent} ${C.dim}${t} ${ageStr.padStart(8)}${C.reset} ${C.dim}${detail}${C.reset}`);
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
if (files.length === 0) {
|
|
988
|
+
console.log("");
|
|
989
|
+
console.log(` ${C.dim}No JSON/JSONL files found. Waiting for data in:${C.reset}`);
|
|
990
|
+
console.log(` ${C.dim}${config.tracesDir}${C.reset}`);
|
|
991
|
+
}
|
|
992
|
+
console.log("");
|
|
993
|
+
console.log(` ${C.dim}Watching: ${config.tracesDir}${C.reset}`);
|
|
994
|
+
console.log(` ${C.dim}Press Ctrl+C to exit${C.reset}`);
|
|
995
|
+
}
|
|
996
|
+
function getDistDepth(dt, spanId) {
|
|
997
|
+
if (!spanId) return 0;
|
|
998
|
+
const g = dt.graphs.get(spanId);
|
|
999
|
+
if (!g || !g.parentSpanId) return 0;
|
|
1000
|
+
return 1 + getDistDepth(dt, g.parentSpanId);
|
|
1001
|
+
}
|
|
1002
|
+
function startLive(argv) {
|
|
1003
|
+
const config = parseArgs(argv);
|
|
1004
|
+
if (!(0, import_node_fs2.existsSync)(config.tracesDir)) {
|
|
1005
|
+
console.error(`Directory does not exist: ${config.tracesDir}`);
|
|
1006
|
+
console.error("Specify a directory containing JSON/JSONL files: agentflow live <dir>");
|
|
1007
|
+
process.exit(1);
|
|
1008
|
+
}
|
|
1009
|
+
render(config);
|
|
1010
|
+
let debounce = null;
|
|
1011
|
+
try {
|
|
1012
|
+
(0, import_node_fs2.watch)(config.tracesDir, { recursive: config.recursive }, () => {
|
|
1013
|
+
if (debounce) clearTimeout(debounce);
|
|
1014
|
+
debounce = setTimeout(() => render(config), 500);
|
|
1015
|
+
});
|
|
1016
|
+
} catch {
|
|
1017
|
+
}
|
|
1018
|
+
setInterval(() => render(config), config.refreshMs);
|
|
1019
|
+
process.on("SIGINT", () => {
|
|
1020
|
+
console.log("\n" + C.dim + "Monitor stopped." + C.reset);
|
|
1021
|
+
process.exit(0);
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// src/cli.ts
|
|
1026
|
+
function printHelp() {
|
|
1027
|
+
console.log(`
|
|
1028
|
+
AgentFlow CLI \u2014 execution tracing and live monitoring for AI agent systems.
|
|
1029
|
+
|
|
1030
|
+
Usage:
|
|
1031
|
+
agentflow <command> [options]
|
|
1032
|
+
|
|
1033
|
+
Commands:
|
|
1034
|
+
run [options] -- <cmd> Wrap a command with automatic execution tracing
|
|
1035
|
+
live [dir] [options] Real-time terminal monitor (auto-detects any JSON/JSONL)
|
|
1036
|
+
|
|
1037
|
+
Run \`agentflow <command> --help\` for command-specific options.
|
|
1038
|
+
|
|
1039
|
+
Examples:
|
|
1040
|
+
agentflow run --traces-dir ./traces -- python -m myagent process
|
|
1041
|
+
agentflow live ./data
|
|
1042
|
+
agentflow live ./data -R --refresh 5
|
|
1043
|
+
`.trim());
|
|
1044
|
+
}
|
|
1045
|
+
function parseRunArgs(argv) {
|
|
411
1046
|
const result = {
|
|
412
1047
|
tracesDir: "./traces",
|
|
413
1048
|
watchDirs: [],
|
|
@@ -465,9 +1100,9 @@ function parseArgs(argv) {
|
|
|
465
1100
|
result.command = commandArgs;
|
|
466
1101
|
return result;
|
|
467
1102
|
}
|
|
468
|
-
function
|
|
1103
|
+
function printRunUsage() {
|
|
469
1104
|
console.log(`
|
|
470
|
-
AgentFlow
|
|
1105
|
+
AgentFlow Run \u2014 wrap any command with automatic execution tracing.
|
|
471
1106
|
|
|
472
1107
|
Usage:
|
|
473
1108
|
agentflow run [options] -- <command>
|
|
@@ -481,21 +1116,20 @@ Options:
|
|
|
481
1116
|
--help Show this help message
|
|
482
1117
|
|
|
483
1118
|
Examples:
|
|
484
|
-
agentflow run -- python -m
|
|
485
|
-
agentflow run --watch-dir
|
|
486
|
-
agentflow run --traces-dir ./my-traces --agent-id
|
|
1119
|
+
agentflow run -- python -m myagent process
|
|
1120
|
+
agentflow run --watch-dir ./data -- python worker.py
|
|
1121
|
+
agentflow run --traces-dir ./my-traces --agent-id recon -- node agent.js
|
|
487
1122
|
`.trim());
|
|
488
1123
|
}
|
|
489
|
-
async function
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
printUsage();
|
|
1124
|
+
async function runCommand(argv) {
|
|
1125
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
1126
|
+
printRunUsage();
|
|
493
1127
|
process.exit(0);
|
|
494
1128
|
}
|
|
495
|
-
const parsed =
|
|
1129
|
+
const parsed = parseRunArgs(argv);
|
|
496
1130
|
if (parsed.command.length === 0) {
|
|
497
1131
|
console.error("Error: No command specified. Use -- to separate agentflow flags from the command.");
|
|
498
|
-
console.error("Example: agentflow run -- python -m
|
|
1132
|
+
console.error("Example: agentflow run -- python -m myagent process");
|
|
499
1133
|
process.exit(1);
|
|
500
1134
|
}
|
|
501
1135
|
const commandStr = parsed.command.join(" ");
|
|
@@ -541,4 +1175,28 @@ async function main() {
|
|
|
541
1175
|
process.exit(1);
|
|
542
1176
|
}
|
|
543
1177
|
}
|
|
1178
|
+
async function main() {
|
|
1179
|
+
const argv = process.argv.slice(2);
|
|
1180
|
+
if (argv.length === 0 || argv[0] !== "run" && argv[0] !== "live" && (argv.includes("--help") || argv.includes("-h"))) {
|
|
1181
|
+
printHelp();
|
|
1182
|
+
process.exit(0);
|
|
1183
|
+
}
|
|
1184
|
+
const subcommand = argv[0];
|
|
1185
|
+
switch (subcommand) {
|
|
1186
|
+
case "run":
|
|
1187
|
+
await runCommand(argv);
|
|
1188
|
+
break;
|
|
1189
|
+
case "live":
|
|
1190
|
+
startLive(argv);
|
|
1191
|
+
break;
|
|
1192
|
+
default:
|
|
1193
|
+
if (!subcommand?.startsWith("-")) {
|
|
1194
|
+
startLive(["live", ...argv]);
|
|
1195
|
+
} else {
|
|
1196
|
+
printHelp();
|
|
1197
|
+
process.exit(1);
|
|
1198
|
+
}
|
|
1199
|
+
break;
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
544
1202
|
main();
|