agentflow-core 0.1.2 → 0.1.4

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 ADDED
@@ -0,0 +1,544 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // src/cli.ts
5
+ var import_path = require("path");
6
+
7
+ // src/runner.ts
8
+ var import_node_child_process = require("child_process");
9
+ var import_node_fs = require("fs");
10
+ var import_node_path = require("path");
11
+
12
+ // src/graph-builder.ts
13
+ var import_crypto = require("crypto");
14
+ function deepFreeze(obj) {
15
+ if (obj === null || typeof obj !== "object") return obj;
16
+ if (obj instanceof Map) {
17
+ Object.freeze(obj);
18
+ for (const value of obj.values()) {
19
+ deepFreeze(value);
20
+ }
21
+ return obj;
22
+ }
23
+ Object.freeze(obj);
24
+ const record = obj;
25
+ for (const key of Object.keys(record)) {
26
+ const value = record[key];
27
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
28
+ deepFreeze(value);
29
+ }
30
+ }
31
+ return obj;
32
+ }
33
+ function createCounterIdGenerator() {
34
+ let counter = 0;
35
+ return () => {
36
+ counter++;
37
+ return `node_${String(counter).padStart(3, "0")}`;
38
+ };
39
+ }
40
+ function createGraphBuilder(config) {
41
+ const generateId = config?.idGenerator ?? createCounterIdGenerator();
42
+ const agentId = config?.agentId ?? "unknown";
43
+ const trigger = config?.trigger ?? "manual";
44
+ const spanId = (0, import_crypto.randomUUID)();
45
+ const traceId = config?.traceId ?? (typeof process !== "undefined" ? process.env?.AGENTFLOW_TRACE_ID : void 0) ?? (0, import_crypto.randomUUID)();
46
+ const parentSpanId = config?.parentSpanId ?? (typeof process !== "undefined" ? process.env?.AGENTFLOW_PARENT_SPAN_ID : void 0) ?? null;
47
+ const graphId = generateId();
48
+ const startTime = Date.now();
49
+ const nodes = /* @__PURE__ */ new Map();
50
+ const edges = [];
51
+ const events = [];
52
+ const parentStack = [];
53
+ let rootNodeId = null;
54
+ let built = false;
55
+ function assertNotBuilt() {
56
+ if (built) {
57
+ throw new Error("GraphBuilder: cannot mutate after build() has been called");
58
+ }
59
+ }
60
+ function getNode(nodeId) {
61
+ const node = nodes.get(nodeId);
62
+ if (!node) {
63
+ throw new Error(`GraphBuilder: node "${nodeId}" does not exist`);
64
+ }
65
+ return node;
66
+ }
67
+ function recordEvent(nodeId, eventType, data = {}) {
68
+ events.push({
69
+ timestamp: Date.now(),
70
+ eventType,
71
+ nodeId,
72
+ data
73
+ });
74
+ }
75
+ function buildGraph() {
76
+ if (rootNodeId === null) {
77
+ throw new Error("GraphBuilder: cannot build a graph with no nodes");
78
+ }
79
+ let graphStatus = "completed";
80
+ for (const node of nodes.values()) {
81
+ if (node.status === "failed" || node.status === "timeout" || node.status === "hung") {
82
+ graphStatus = "failed";
83
+ break;
84
+ }
85
+ if (node.status === "running") {
86
+ graphStatus = "running";
87
+ }
88
+ }
89
+ const endTime = graphStatus === "running" ? null : Date.now();
90
+ const frozenNodes = new Map(
91
+ [...nodes.entries()].map(([id, mNode]) => [
92
+ id,
93
+ {
94
+ id: mNode.id,
95
+ type: mNode.type,
96
+ name: mNode.name,
97
+ startTime: mNode.startTime,
98
+ endTime: mNode.endTime,
99
+ status: mNode.status,
100
+ parentId: mNode.parentId,
101
+ children: [...mNode.children],
102
+ metadata: { ...mNode.metadata },
103
+ state: { ...mNode.state }
104
+ }
105
+ ])
106
+ );
107
+ const graph = {
108
+ id: graphId,
109
+ rootNodeId,
110
+ nodes: frozenNodes,
111
+ edges: [...edges],
112
+ startTime,
113
+ endTime,
114
+ status: graphStatus,
115
+ trigger,
116
+ agentId,
117
+ events: [...events],
118
+ traceId,
119
+ spanId,
120
+ parentSpanId
121
+ };
122
+ return deepFreeze(graph);
123
+ }
124
+ const builder = {
125
+ get graphId() {
126
+ return graphId;
127
+ },
128
+ get traceContext() {
129
+ return { traceId, spanId };
130
+ },
131
+ startNode(opts) {
132
+ assertNotBuilt();
133
+ const id = generateId();
134
+ const parentId = opts.parentId ?? parentStack[parentStack.length - 1] ?? null;
135
+ if (parentId !== null && !nodes.has(parentId)) {
136
+ throw new Error(`GraphBuilder: parent node "${parentId}" does not exist`);
137
+ }
138
+ const node = {
139
+ id,
140
+ type: opts.type,
141
+ name: opts.name,
142
+ startTime: Date.now(),
143
+ endTime: null,
144
+ status: "running",
145
+ parentId,
146
+ children: [],
147
+ metadata: opts.metadata ? { ...opts.metadata } : {},
148
+ state: {}
149
+ };
150
+ nodes.set(id, node);
151
+ if (parentId !== null) {
152
+ const parent = nodes.get(parentId);
153
+ if (parent) {
154
+ parent.children.push(id);
155
+ }
156
+ edges.push({ from: parentId, to: id, type: "spawned" });
157
+ }
158
+ if (rootNodeId === null) {
159
+ rootNodeId = id;
160
+ }
161
+ recordEvent(id, "agent_start", { type: opts.type, name: opts.name });
162
+ return id;
163
+ },
164
+ endNode(nodeId, status = "completed") {
165
+ assertNotBuilt();
166
+ const node = getNode(nodeId);
167
+ if (node.endTime !== null) {
168
+ throw new Error(
169
+ `GraphBuilder: node "${nodeId}" has already ended (status: ${node.status})`
170
+ );
171
+ }
172
+ node.endTime = Date.now();
173
+ node.status = status;
174
+ recordEvent(nodeId, "agent_end", { status });
175
+ },
176
+ failNode(nodeId, error) {
177
+ assertNotBuilt();
178
+ const node = getNode(nodeId);
179
+ if (node.endTime !== null) {
180
+ throw new Error(
181
+ `GraphBuilder: node "${nodeId}" has already ended (status: ${node.status})`
182
+ );
183
+ }
184
+ const errorMessage = error instanceof Error ? error.message : error;
185
+ const errorStack = error instanceof Error ? error.stack : void 0;
186
+ node.endTime = Date.now();
187
+ node.status = "failed";
188
+ node.metadata.error = errorMessage;
189
+ if (errorStack) {
190
+ node.metadata.errorStack = errorStack;
191
+ }
192
+ recordEvent(nodeId, "tool_error", { error: errorMessage });
193
+ },
194
+ addEdge(from, to, type) {
195
+ assertNotBuilt();
196
+ getNode(from);
197
+ getNode(to);
198
+ edges.push({ from, to, type });
199
+ recordEvent(from, "custom", { to, type, action: "edge_add" });
200
+ },
201
+ pushEvent(event) {
202
+ assertNotBuilt();
203
+ getNode(event.nodeId);
204
+ events.push({
205
+ ...event,
206
+ timestamp: Date.now()
207
+ });
208
+ },
209
+ updateState(nodeId, state) {
210
+ assertNotBuilt();
211
+ const node = getNode(nodeId);
212
+ Object.assign(node.state, state);
213
+ recordEvent(nodeId, "custom", { action: "state_update", ...state });
214
+ },
215
+ withParent(parentId, fn) {
216
+ assertNotBuilt();
217
+ getNode(parentId);
218
+ parentStack.push(parentId);
219
+ try {
220
+ return fn();
221
+ } finally {
222
+ parentStack.pop();
223
+ }
224
+ },
225
+ getSnapshot() {
226
+ return buildGraph();
227
+ },
228
+ build() {
229
+ assertNotBuilt();
230
+ const graph = buildGraph();
231
+ built = true;
232
+ return graph;
233
+ }
234
+ };
235
+ return builder;
236
+ }
237
+
238
+ // src/loader.ts
239
+ function graphToJson(graph) {
240
+ const nodesObj = {};
241
+ for (const [id, node] of graph.nodes) {
242
+ nodesObj[id] = node;
243
+ }
244
+ return {
245
+ id: graph.id,
246
+ rootNodeId: graph.rootNodeId,
247
+ nodes: nodesObj,
248
+ edges: graph.edges,
249
+ startTime: graph.startTime,
250
+ endTime: graph.endTime,
251
+ status: graph.status,
252
+ trigger: graph.trigger,
253
+ agentId: graph.agentId,
254
+ events: graph.events,
255
+ traceId: graph.traceId,
256
+ spanId: graph.spanId,
257
+ parentSpanId: graph.parentSpanId
258
+ };
259
+ }
260
+
261
+ // src/runner.ts
262
+ function globToRegex(pattern) {
263
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
264
+ return new RegExp(`^${escaped}$`);
265
+ }
266
+ function snapshotDir(dir, patterns) {
267
+ const result = /* @__PURE__ */ new Map();
268
+ if (!(0, import_node_fs.existsSync)(dir)) return result;
269
+ for (const entry of (0, import_node_fs.readdirSync)(dir)) {
270
+ if (!patterns.some((re) => re.test(entry))) continue;
271
+ const full = (0, import_node_path.join)(dir, entry);
272
+ try {
273
+ const stat = (0, import_node_fs.statSync)(full);
274
+ if (stat.isFile()) {
275
+ result.set(full, stat.mtimeMs);
276
+ }
277
+ } catch {
278
+ }
279
+ }
280
+ return result;
281
+ }
282
+ function agentIdFromFilename(filePath) {
283
+ const base = (0, import_node_path.basename)(filePath, ".json");
284
+ const cleaned = base.replace(/-state$/, "");
285
+ return `alfred-${cleaned}`;
286
+ }
287
+ function deriveAgentId(command) {
288
+ return "orchestrator";
289
+ }
290
+ function fileTimestamp() {
291
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-").replace(/\.\d+Z$/, "");
292
+ }
293
+ async function runTraced(config) {
294
+ const {
295
+ command,
296
+ agentId = deriveAgentId(command),
297
+ trigger = "cli",
298
+ tracesDir = "./traces",
299
+ watchDirs = [],
300
+ watchPatterns = ["*.json"]
301
+ } = config;
302
+ if (command.length === 0) {
303
+ throw new Error("runTraced: command must not be empty");
304
+ }
305
+ const resolvedTracesDir = (0, import_node_path.resolve)(tracesDir);
306
+ const patterns = watchPatterns.map(globToRegex);
307
+ const orchestrator = createGraphBuilder({ agentId, trigger });
308
+ const { traceId, spanId } = orchestrator.traceContext;
309
+ const beforeSnapshots = /* @__PURE__ */ new Map();
310
+ for (const dir of watchDirs) {
311
+ beforeSnapshots.set(dir, snapshotDir(dir, patterns));
312
+ }
313
+ const rootId = orchestrator.startNode({ type: "agent", name: agentId });
314
+ const dispatchId = orchestrator.startNode({
315
+ type: "tool",
316
+ name: "dispatch-command",
317
+ parentId: rootId
318
+ });
319
+ orchestrator.updateState(dispatchId, { command: command.join(" ") });
320
+ const monitorId = orchestrator.startNode({
321
+ type: "tool",
322
+ name: "state-monitor",
323
+ parentId: rootId
324
+ });
325
+ orchestrator.updateState(monitorId, {
326
+ watchDirs,
327
+ watchPatterns
328
+ });
329
+ const startMs = Date.now();
330
+ const execCmd = command[0] ?? "";
331
+ const execArgs = command.slice(1);
332
+ process.env.AGENTFLOW_TRACE_ID = traceId;
333
+ process.env.AGENTFLOW_PARENT_SPAN_ID = spanId;
334
+ const result = (0, import_node_child_process.spawnSync)(execCmd, execArgs, { stdio: "inherit" });
335
+ delete process.env.AGENTFLOW_TRACE_ID;
336
+ delete process.env.AGENTFLOW_PARENT_SPAN_ID;
337
+ const exitCode = result.status ?? 1;
338
+ const duration = (Date.now() - startMs) / 1e3;
339
+ const stateChanges = [];
340
+ for (const dir of watchDirs) {
341
+ const before = beforeSnapshots.get(dir) ?? /* @__PURE__ */ new Map();
342
+ const after = snapshotDir(dir, patterns);
343
+ for (const [filePath, mtime] of after) {
344
+ const prevMtime = before.get(filePath);
345
+ if (prevMtime === void 0 || mtime > prevMtime) {
346
+ stateChanges.push(filePath);
347
+ }
348
+ }
349
+ }
350
+ orchestrator.updateState(monitorId, { stateChanges });
351
+ orchestrator.endNode(monitorId);
352
+ if (exitCode === 0) {
353
+ orchestrator.endNode(dispatchId);
354
+ } else {
355
+ orchestrator.failNode(dispatchId, `Command exited with code ${exitCode}`);
356
+ }
357
+ orchestrator.updateState(rootId, {
358
+ exitCode,
359
+ duration,
360
+ stateChanges
361
+ });
362
+ if (exitCode === 0) {
363
+ orchestrator.endNode(rootId);
364
+ } else {
365
+ orchestrator.failNode(rootId, `Command exited with code ${exitCode}`);
366
+ }
367
+ const orchestratorGraph = orchestrator.build();
368
+ const allGraphs = [orchestratorGraph];
369
+ for (const filePath of stateChanges) {
370
+ const childAgentId = agentIdFromFilename(filePath);
371
+ const childBuilder = createGraphBuilder({
372
+ agentId: childAgentId,
373
+ trigger: "state-change",
374
+ traceId,
375
+ parentSpanId: spanId
376
+ });
377
+ const childRootId = childBuilder.startNode({
378
+ type: "agent",
379
+ name: childAgentId
380
+ });
381
+ childBuilder.updateState(childRootId, {
382
+ stateFile: filePath,
383
+ detectedBy: "runner-state-monitor"
384
+ });
385
+ childBuilder.endNode(childRootId);
386
+ allGraphs.push(childBuilder.build());
387
+ }
388
+ if (!(0, import_node_fs.existsSync)(resolvedTracesDir)) {
389
+ (0, import_node_fs.mkdirSync)(resolvedTracesDir, { recursive: true });
390
+ }
391
+ const ts = fileTimestamp();
392
+ const tracePaths = [];
393
+ for (const graph of allGraphs) {
394
+ const filename = `${graph.agentId}-${ts}.json`;
395
+ const outPath = (0, import_node_path.join)(resolvedTracesDir, filename);
396
+ (0, import_node_fs.writeFileSync)(outPath, JSON.stringify(graphToJson(graph), null, 2), "utf-8");
397
+ tracePaths.push(outPath);
398
+ }
399
+ return {
400
+ exitCode,
401
+ traceId,
402
+ spanId,
403
+ tracePaths,
404
+ stateChanges,
405
+ duration
406
+ };
407
+ }
408
+
409
+ // src/cli.ts
410
+ function parseArgs(argv) {
411
+ const result = {
412
+ tracesDir: "./traces",
413
+ watchDirs: [],
414
+ watchPatterns: ["*.json"],
415
+ trigger: "cli",
416
+ command: []
417
+ };
418
+ const dashDashIdx = argv.indexOf("--");
419
+ const flagArgs = dashDashIdx === -1 ? argv : argv.slice(0, dashDashIdx);
420
+ const commandArgs = dashDashIdx === -1 ? [] : argv.slice(dashDashIdx + 1);
421
+ let i = 0;
422
+ while (i < flagArgs.length) {
423
+ const arg = flagArgs[i];
424
+ switch (arg) {
425
+ case "run":
426
+ i++;
427
+ break;
428
+ case "--traces-dir":
429
+ i++;
430
+ result.tracesDir = flagArgs[i] ?? result.tracesDir;
431
+ i++;
432
+ break;
433
+ case "--watch-dir":
434
+ i++;
435
+ if (flagArgs[i]) {
436
+ result.watchDirs.push(flagArgs[i]);
437
+ }
438
+ i++;
439
+ break;
440
+ case "--watch-pattern":
441
+ i++;
442
+ if (flagArgs[i]) {
443
+ if (result.watchPatterns.length === 1 && result.watchPatterns[0] === "*.json") {
444
+ result.watchPatterns = [];
445
+ }
446
+ result.watchPatterns.push(flagArgs[i]);
447
+ }
448
+ i++;
449
+ break;
450
+ case "--agent-id":
451
+ i++;
452
+ result.agentId = flagArgs[i];
453
+ i++;
454
+ break;
455
+ case "--trigger":
456
+ i++;
457
+ result.trigger = flagArgs[i] ?? result.trigger;
458
+ i++;
459
+ break;
460
+ default:
461
+ i++;
462
+ break;
463
+ }
464
+ }
465
+ result.command = commandArgs;
466
+ return result;
467
+ }
468
+ function printUsage() {
469
+ console.log(`
470
+ AgentFlow CLI \u2014 Wrap any command with automatic execution tracing.
471
+
472
+ Usage:
473
+ agentflow run [options] -- <command>
474
+
475
+ Options:
476
+ --traces-dir <path> Directory to save trace files (default: ./traces)
477
+ --watch-dir <path> Directory to watch for state changes (repeatable)
478
+ --watch-pattern <glob> File pattern to watch (default: *.json)
479
+ --agent-id <name> Agent ID for the orchestrator trace
480
+ --trigger <name> Trigger label (default: cli)
481
+ --help Show this help message
482
+
483
+ Examples:
484
+ agentflow run -- python -m alfred process
485
+ agentflow run --watch-dir /home/trader/.alfred/data -- python -m alfred process
486
+ agentflow run --traces-dir ./my-traces --agent-id alfred -- node worker.js
487
+ `.trim());
488
+ }
489
+ async function main() {
490
+ const argv = process.argv.slice(2);
491
+ if (argv.length === 0 || argv.includes("--help") || argv.includes("-h")) {
492
+ printUsage();
493
+ process.exit(0);
494
+ }
495
+ const parsed = parseArgs(argv);
496
+ if (parsed.command.length === 0) {
497
+ console.error("Error: No command specified. Use -- to separate agentflow flags from the command.");
498
+ console.error("Example: agentflow run -- python -m alfred process");
499
+ process.exit(1);
500
+ }
501
+ const commandStr = parsed.command.join(" ");
502
+ const watchSummary = parsed.watchDirs.length > 0 ? parsed.watchDirs.map((d) => `${d} (${parsed.watchPatterns.join(", ")})`).join(", ") : "(none)";
503
+ console.log(`
504
+ \u{1F50D} AgentFlow: Tracing command: ${commandStr}`);
505
+ console.log(`\u{1F4C1} Traces: ${parsed.tracesDir}`);
506
+ console.log(`\u{1F441}\uFE0F Watching: ${watchSummary}`);
507
+ console.log("");
508
+ const config = {
509
+ command: parsed.command,
510
+ tracesDir: parsed.tracesDir,
511
+ watchDirs: parsed.watchDirs,
512
+ watchPatterns: parsed.watchPatterns,
513
+ trigger: parsed.trigger
514
+ };
515
+ if (parsed.agentId) {
516
+ config.agentId = parsed.agentId;
517
+ }
518
+ try {
519
+ const result = await runTraced(config);
520
+ console.log("");
521
+ console.log(`\u2705 Command completed (exit code ${result.exitCode}, ${result.duration.toFixed(1)}s)`);
522
+ if (result.tracePaths.length > 0) {
523
+ console.log("\u{1F4DD} Traces saved:");
524
+ const orchPath = result.tracePaths[0];
525
+ const orchName = (0, import_path.basename)(orchPath, ".json").split("-")[0] ?? "orchestrator";
526
+ console.log(` ${orchName.padEnd(14)} \u2192 ${orchPath}`);
527
+ for (let i = 1; i < result.tracePaths.length; i++) {
528
+ const tPath = result.tracePaths[i];
529
+ const name = (0, import_path.basename)(tPath, ".json").replace(/-\d{4}-.*$/, "");
530
+ const isLast = i === result.tracePaths.length - 1;
531
+ const prefix = isLast ? "\u2514\u2500" : "\u251C\u2500";
532
+ console.log(` ${prefix} ${name.padEnd(12)} \u2192 ${tPath} (state changed)`);
533
+ }
534
+ }
535
+ console.log(`\u{1F517} Trace ID: ${result.traceId}`);
536
+ console.log("");
537
+ process.exit(result.exitCode);
538
+ } catch (err) {
539
+ const message = err instanceof Error ? err.message : String(err);
540
+ console.error(`\u274C AgentFlow error: ${message}`);
541
+ process.exit(1);
542
+ }
543
+ }
544
+ main();
package/dist/cli.d.cts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ runTraced
4
+ } from "./chunk-TT5DLU73.js";
5
+
6
+ // src/cli.ts
7
+ import { basename } from "path";
8
+ function parseArgs(argv) {
9
+ const result = {
10
+ tracesDir: "./traces",
11
+ watchDirs: [],
12
+ watchPatterns: ["*.json"],
13
+ trigger: "cli",
14
+ command: []
15
+ };
16
+ const dashDashIdx = argv.indexOf("--");
17
+ const flagArgs = dashDashIdx === -1 ? argv : argv.slice(0, dashDashIdx);
18
+ const commandArgs = dashDashIdx === -1 ? [] : argv.slice(dashDashIdx + 1);
19
+ let i = 0;
20
+ while (i < flagArgs.length) {
21
+ const arg = flagArgs[i];
22
+ switch (arg) {
23
+ case "run":
24
+ i++;
25
+ break;
26
+ case "--traces-dir":
27
+ i++;
28
+ result.tracesDir = flagArgs[i] ?? result.tracesDir;
29
+ i++;
30
+ break;
31
+ case "--watch-dir":
32
+ i++;
33
+ if (flagArgs[i]) {
34
+ result.watchDirs.push(flagArgs[i]);
35
+ }
36
+ i++;
37
+ break;
38
+ case "--watch-pattern":
39
+ i++;
40
+ if (flagArgs[i]) {
41
+ if (result.watchPatterns.length === 1 && result.watchPatterns[0] === "*.json") {
42
+ result.watchPatterns = [];
43
+ }
44
+ result.watchPatterns.push(flagArgs[i]);
45
+ }
46
+ i++;
47
+ break;
48
+ case "--agent-id":
49
+ i++;
50
+ result.agentId = flagArgs[i];
51
+ i++;
52
+ break;
53
+ case "--trigger":
54
+ i++;
55
+ result.trigger = flagArgs[i] ?? result.trigger;
56
+ i++;
57
+ break;
58
+ default:
59
+ i++;
60
+ break;
61
+ }
62
+ }
63
+ result.command = commandArgs;
64
+ return result;
65
+ }
66
+ function printUsage() {
67
+ console.log(`
68
+ AgentFlow CLI \u2014 Wrap any command with automatic execution tracing.
69
+
70
+ Usage:
71
+ agentflow run [options] -- <command>
72
+
73
+ Options:
74
+ --traces-dir <path> Directory to save trace files (default: ./traces)
75
+ --watch-dir <path> Directory to watch for state changes (repeatable)
76
+ --watch-pattern <glob> File pattern to watch (default: *.json)
77
+ --agent-id <name> Agent ID for the orchestrator trace
78
+ --trigger <name> Trigger label (default: cli)
79
+ --help Show this help message
80
+
81
+ Examples:
82
+ agentflow run -- python -m alfred process
83
+ agentflow run --watch-dir /home/trader/.alfred/data -- python -m alfred process
84
+ agentflow run --traces-dir ./my-traces --agent-id alfred -- node worker.js
85
+ `.trim());
86
+ }
87
+ async function main() {
88
+ const argv = process.argv.slice(2);
89
+ if (argv.length === 0 || argv.includes("--help") || argv.includes("-h")) {
90
+ printUsage();
91
+ process.exit(0);
92
+ }
93
+ const parsed = parseArgs(argv);
94
+ if (parsed.command.length === 0) {
95
+ console.error("Error: No command specified. Use -- to separate agentflow flags from the command.");
96
+ console.error("Example: agentflow run -- python -m alfred process");
97
+ process.exit(1);
98
+ }
99
+ const commandStr = parsed.command.join(" ");
100
+ const watchSummary = parsed.watchDirs.length > 0 ? parsed.watchDirs.map((d) => `${d} (${parsed.watchPatterns.join(", ")})`).join(", ") : "(none)";
101
+ console.log(`
102
+ \u{1F50D} AgentFlow: Tracing command: ${commandStr}`);
103
+ console.log(`\u{1F4C1} Traces: ${parsed.tracesDir}`);
104
+ console.log(`\u{1F441}\uFE0F Watching: ${watchSummary}`);
105
+ console.log("");
106
+ const config = {
107
+ command: parsed.command,
108
+ tracesDir: parsed.tracesDir,
109
+ watchDirs: parsed.watchDirs,
110
+ watchPatterns: parsed.watchPatterns,
111
+ trigger: parsed.trigger
112
+ };
113
+ if (parsed.agentId) {
114
+ config.agentId = parsed.agentId;
115
+ }
116
+ try {
117
+ const result = await runTraced(config);
118
+ console.log("");
119
+ console.log(`\u2705 Command completed (exit code ${result.exitCode}, ${result.duration.toFixed(1)}s)`);
120
+ if (result.tracePaths.length > 0) {
121
+ console.log("\u{1F4DD} Traces saved:");
122
+ const orchPath = result.tracePaths[0];
123
+ const orchName = basename(orchPath, ".json").split("-")[0] ?? "orchestrator";
124
+ console.log(` ${orchName.padEnd(14)} \u2192 ${orchPath}`);
125
+ for (let i = 1; i < result.tracePaths.length; i++) {
126
+ const tPath = result.tracePaths[i];
127
+ const name = basename(tPath, ".json").replace(/-\d{4}-.*$/, "");
128
+ const isLast = i === result.tracePaths.length - 1;
129
+ const prefix = isLast ? "\u2514\u2500" : "\u251C\u2500";
130
+ console.log(` ${prefix} ${name.padEnd(12)} \u2192 ${tPath} (state changed)`);
131
+ }
132
+ }
133
+ console.log(`\u{1F517} Trace ID: ${result.traceId}`);
134
+ console.log("");
135
+ process.exit(result.exitCode);
136
+ } catch (err) {
137
+ const message = err instanceof Error ? err.message : String(err);
138
+ console.error(`\u274C AgentFlow error: ${message}`);
139
+ process.exit(1);
140
+ }
141
+ }
142
+ main();