agentflow-core 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-DGLK6IBP.js +402 -0
- package/dist/cli.cjs +542 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +142 -0
- package/dist/index.cjs +174 -0
- package/dist/index.d.cts +50 -1
- package/dist/index.d.ts +50 -1
- package/dist/index.js +5 -225
- package/package.json +6 -3
package/dist/index.cjs
CHANGED
|
@@ -34,6 +34,7 @@ __export(index_exports, {
|
|
|
34
34
|
getSubtree: () => getSubtree,
|
|
35
35
|
getTraceTree: () => getTraceTree,
|
|
36
36
|
groupByTraceId: () => groupByTraceId,
|
|
37
|
+
runTraced: () => runTraced,
|
|
37
38
|
stitchTrace: () => stitchTrace
|
|
38
39
|
});
|
|
39
40
|
module.exports = __toCommonJS(index_exports);
|
|
@@ -264,6 +265,178 @@ function createGraphBuilder(config) {
|
|
|
264
265
|
return builder;
|
|
265
266
|
}
|
|
266
267
|
|
|
268
|
+
// src/runner.ts
|
|
269
|
+
var import_node_child_process = require("child_process");
|
|
270
|
+
var import_node_fs = require("fs");
|
|
271
|
+
var import_node_path = require("path");
|
|
272
|
+
function globToRegex(pattern) {
|
|
273
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
274
|
+
return new RegExp(`^${escaped}$`);
|
|
275
|
+
}
|
|
276
|
+
function snapshotDir(dir, patterns) {
|
|
277
|
+
const result = /* @__PURE__ */ new Map();
|
|
278
|
+
if (!(0, import_node_fs.existsSync)(dir)) return result;
|
|
279
|
+
for (const entry of (0, import_node_fs.readdirSync)(dir)) {
|
|
280
|
+
if (!patterns.some((re) => re.test(entry))) continue;
|
|
281
|
+
const full = (0, import_node_path.join)(dir, entry);
|
|
282
|
+
try {
|
|
283
|
+
const stat = (0, import_node_fs.statSync)(full);
|
|
284
|
+
if (stat.isFile()) {
|
|
285
|
+
result.set(full, stat.mtimeMs);
|
|
286
|
+
}
|
|
287
|
+
} catch {
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return result;
|
|
291
|
+
}
|
|
292
|
+
function agentIdFromFilename(filePath) {
|
|
293
|
+
const base = (0, import_node_path.basename)(filePath, ".json");
|
|
294
|
+
const cleaned = base.replace(/-state$/, "");
|
|
295
|
+
return `alfred-${cleaned}`;
|
|
296
|
+
}
|
|
297
|
+
function deriveAgentId(command) {
|
|
298
|
+
return "orchestrator";
|
|
299
|
+
}
|
|
300
|
+
function fileTimestamp() {
|
|
301
|
+
return (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-").replace(/\.\d+Z$/, "");
|
|
302
|
+
}
|
|
303
|
+
function graphToJson(graph) {
|
|
304
|
+
const nodesObj = {};
|
|
305
|
+
for (const [id, node] of graph.nodes) {
|
|
306
|
+
nodesObj[id] = node;
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
id: graph.id,
|
|
310
|
+
rootNodeId: graph.rootNodeId,
|
|
311
|
+
nodes: nodesObj,
|
|
312
|
+
edges: graph.edges,
|
|
313
|
+
startTime: graph.startTime,
|
|
314
|
+
endTime: graph.endTime,
|
|
315
|
+
status: graph.status,
|
|
316
|
+
trigger: graph.trigger,
|
|
317
|
+
agentId: graph.agentId,
|
|
318
|
+
events: graph.events,
|
|
319
|
+
traceId: graph.traceId,
|
|
320
|
+
spanId: graph.spanId,
|
|
321
|
+
parentSpanId: graph.parentSpanId
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
async function runTraced(config) {
|
|
325
|
+
const {
|
|
326
|
+
command,
|
|
327
|
+
agentId = deriveAgentId(command),
|
|
328
|
+
trigger = "cli",
|
|
329
|
+
tracesDir = "./traces",
|
|
330
|
+
watchDirs = [],
|
|
331
|
+
watchPatterns = ["*.json"]
|
|
332
|
+
} = config;
|
|
333
|
+
if (command.length === 0) {
|
|
334
|
+
throw new Error("runTraced: command must not be empty");
|
|
335
|
+
}
|
|
336
|
+
const resolvedTracesDir = (0, import_node_path.resolve)(tracesDir);
|
|
337
|
+
const patterns = watchPatterns.map(globToRegex);
|
|
338
|
+
const orchestrator = createGraphBuilder({ agentId, trigger });
|
|
339
|
+
const { traceId, spanId } = orchestrator.traceContext;
|
|
340
|
+
const beforeSnapshots = /* @__PURE__ */ new Map();
|
|
341
|
+
for (const dir of watchDirs) {
|
|
342
|
+
beforeSnapshots.set(dir, snapshotDir(dir, patterns));
|
|
343
|
+
}
|
|
344
|
+
const rootId = orchestrator.startNode({ type: "agent", name: agentId });
|
|
345
|
+
const dispatchId = orchestrator.startNode({
|
|
346
|
+
type: "tool",
|
|
347
|
+
name: "dispatch-command",
|
|
348
|
+
parentId: rootId
|
|
349
|
+
});
|
|
350
|
+
orchestrator.updateState(dispatchId, { command: command.join(" ") });
|
|
351
|
+
const monitorId = orchestrator.startNode({
|
|
352
|
+
type: "tool",
|
|
353
|
+
name: "state-monitor",
|
|
354
|
+
parentId: rootId
|
|
355
|
+
});
|
|
356
|
+
orchestrator.updateState(monitorId, {
|
|
357
|
+
watchDirs,
|
|
358
|
+
watchPatterns
|
|
359
|
+
});
|
|
360
|
+
const startMs = Date.now();
|
|
361
|
+
const execCmd = command[0] ?? "";
|
|
362
|
+
const execArgs = command.slice(1);
|
|
363
|
+
process.env.AGENTFLOW_TRACE_ID = traceId;
|
|
364
|
+
process.env.AGENTFLOW_PARENT_SPAN_ID = spanId;
|
|
365
|
+
const result = (0, import_node_child_process.spawnSync)(execCmd, execArgs, { stdio: "inherit" });
|
|
366
|
+
delete process.env.AGENTFLOW_TRACE_ID;
|
|
367
|
+
delete process.env.AGENTFLOW_PARENT_SPAN_ID;
|
|
368
|
+
const exitCode = result.status ?? 1;
|
|
369
|
+
const duration = (Date.now() - startMs) / 1e3;
|
|
370
|
+
const stateChanges = [];
|
|
371
|
+
for (const dir of watchDirs) {
|
|
372
|
+
const before = beforeSnapshots.get(dir) ?? /* @__PURE__ */ new Map();
|
|
373
|
+
const after = snapshotDir(dir, patterns);
|
|
374
|
+
for (const [filePath, mtime] of after) {
|
|
375
|
+
const prevMtime = before.get(filePath);
|
|
376
|
+
if (prevMtime === void 0 || mtime > prevMtime) {
|
|
377
|
+
stateChanges.push(filePath);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
orchestrator.updateState(monitorId, { stateChanges });
|
|
382
|
+
orchestrator.endNode(monitorId);
|
|
383
|
+
if (exitCode === 0) {
|
|
384
|
+
orchestrator.endNode(dispatchId);
|
|
385
|
+
} else {
|
|
386
|
+
orchestrator.failNode(dispatchId, `Command exited with code ${exitCode}`);
|
|
387
|
+
}
|
|
388
|
+
orchestrator.updateState(rootId, {
|
|
389
|
+
exitCode,
|
|
390
|
+
duration,
|
|
391
|
+
stateChanges
|
|
392
|
+
});
|
|
393
|
+
if (exitCode === 0) {
|
|
394
|
+
orchestrator.endNode(rootId);
|
|
395
|
+
} else {
|
|
396
|
+
orchestrator.failNode(rootId, `Command exited with code ${exitCode}`);
|
|
397
|
+
}
|
|
398
|
+
const orchestratorGraph = orchestrator.build();
|
|
399
|
+
const allGraphs = [orchestratorGraph];
|
|
400
|
+
for (const filePath of stateChanges) {
|
|
401
|
+
const childAgentId = agentIdFromFilename(filePath);
|
|
402
|
+
const childBuilder = createGraphBuilder({
|
|
403
|
+
agentId: childAgentId,
|
|
404
|
+
trigger: "state-change",
|
|
405
|
+
traceId,
|
|
406
|
+
parentSpanId: spanId
|
|
407
|
+
});
|
|
408
|
+
const childRootId = childBuilder.startNode({
|
|
409
|
+
type: "agent",
|
|
410
|
+
name: childAgentId
|
|
411
|
+
});
|
|
412
|
+
childBuilder.updateState(childRootId, {
|
|
413
|
+
stateFile: filePath,
|
|
414
|
+
detectedBy: "runner-state-monitor"
|
|
415
|
+
});
|
|
416
|
+
childBuilder.endNode(childRootId);
|
|
417
|
+
allGraphs.push(childBuilder.build());
|
|
418
|
+
}
|
|
419
|
+
if (!(0, import_node_fs.existsSync)(resolvedTracesDir)) {
|
|
420
|
+
(0, import_node_fs.mkdirSync)(resolvedTracesDir, { recursive: true });
|
|
421
|
+
}
|
|
422
|
+
const ts = fileTimestamp();
|
|
423
|
+
const tracePaths = [];
|
|
424
|
+
for (const graph of allGraphs) {
|
|
425
|
+
const filename = `${graph.agentId}-${ts}.json`;
|
|
426
|
+
const outPath = (0, import_node_path.join)(resolvedTracesDir, filename);
|
|
427
|
+
(0, import_node_fs.writeFileSync)(outPath, JSON.stringify(graphToJson(graph), null, 2), "utf-8");
|
|
428
|
+
tracePaths.push(outPath);
|
|
429
|
+
}
|
|
430
|
+
return {
|
|
431
|
+
exitCode,
|
|
432
|
+
traceId,
|
|
433
|
+
spanId,
|
|
434
|
+
tracePaths,
|
|
435
|
+
stateChanges,
|
|
436
|
+
duration
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
267
440
|
// src/graph-stitch.ts
|
|
268
441
|
function groupByTraceId(graphs) {
|
|
269
442
|
const groups = /* @__PURE__ */ new Map();
|
|
@@ -482,5 +655,6 @@ function getStats(graph) {
|
|
|
482
655
|
getSubtree,
|
|
483
656
|
getTraceTree,
|
|
484
657
|
groupByTraceId,
|
|
658
|
+
runTraced,
|
|
485
659
|
stitchTrace
|
|
486
660
|
});
|
package/dist/index.d.cts
CHANGED
|
@@ -276,6 +276,55 @@ interface MutableExecutionNode {
|
|
|
276
276
|
*/
|
|
277
277
|
declare function createGraphBuilder(config?: AgentFlowConfig): GraphBuilder;
|
|
278
278
|
|
|
279
|
+
/**
|
|
280
|
+
* CLI runner that wraps any command with automatic AgentFlow tracing.
|
|
281
|
+
*
|
|
282
|
+
* No code changes needed in the target application — the runner sets
|
|
283
|
+
* AGENTFLOW_TRACE_ID and AGENTFLOW_PARENT_SPAN_ID env vars so any child
|
|
284
|
+
* process using AgentFlow auto-joins the distributed trace.
|
|
285
|
+
*
|
|
286
|
+
* @example
|
|
287
|
+
* ```ts
|
|
288
|
+
* const result = await runTraced({
|
|
289
|
+
* command: ['python', '-m', 'alfred', 'process'],
|
|
290
|
+
* watchDirs: ['/home/trader/.alfred/data'],
|
|
291
|
+
* });
|
|
292
|
+
* ```
|
|
293
|
+
* @module
|
|
294
|
+
*/
|
|
295
|
+
interface RunConfig {
|
|
296
|
+
/** Command to execute (e.g. ['python', '-m', 'alfred', 'process']). */
|
|
297
|
+
command: string[];
|
|
298
|
+
/** Agent ID for the orchestrator trace (default: derived from command). */
|
|
299
|
+
agentId?: string;
|
|
300
|
+
/** Trigger label (default: "cli"). */
|
|
301
|
+
trigger?: string;
|
|
302
|
+
/** Directory to save trace files (default: ./traces). */
|
|
303
|
+
tracesDir?: string;
|
|
304
|
+
/** Directories to watch for state file changes during execution. */
|
|
305
|
+
watchDirs?: string[];
|
|
306
|
+
/** File patterns to watch (default: ["*.json"]). */
|
|
307
|
+
watchPatterns?: string[];
|
|
308
|
+
}
|
|
309
|
+
interface RunResult {
|
|
310
|
+
exitCode: number;
|
|
311
|
+
traceId: string;
|
|
312
|
+
spanId: string;
|
|
313
|
+
tracePaths: string[];
|
|
314
|
+
stateChanges: string[];
|
|
315
|
+
duration: number;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Run a command with automatic AgentFlow tracing.
|
|
319
|
+
*
|
|
320
|
+
* 1. Creates an orchestrator (parent) trace.
|
|
321
|
+
* 2. Snapshots watched directories.
|
|
322
|
+
* 3. Spawns the command with trace env vars.
|
|
323
|
+
* 4. After exit, detects state file changes and creates child traces.
|
|
324
|
+
* 5. Saves all trace JSON files.
|
|
325
|
+
*/
|
|
326
|
+
declare function runTraced(config: RunConfig): Promise<RunResult>;
|
|
327
|
+
|
|
279
328
|
declare function groupByTraceId(graphs: ExecutionGraph[]): Map<string, ExecutionGraph[]>;
|
|
280
329
|
declare function stitchTrace(graphs: ExecutionGraph[]): DistributedTrace;
|
|
281
330
|
declare function getTraceTree(trace: DistributedTrace): ExecutionGraph[];
|
|
@@ -396,4 +445,4 @@ declare function getDepth(graph: ExecutionGraph): number;
|
|
|
396
445
|
*/
|
|
397
446
|
declare function getStats(graph: ExecutionGraph): GraphStats;
|
|
398
447
|
|
|
399
|
-
export { type Adapter, type AgentFlowConfig, type DistributedTrace, type EdgeType, type ExecutionEdge, type ExecutionGraph, type ExecutionNode, type GraphBuilder, type GraphStats, type GraphStatus, type MutableExecutionNode, type NodeStatus, type NodeType, type StartNodeOptions, type TraceEvent, type TraceEventType, type Writer, createGraphBuilder, findWaitingOn, getChildren, getCriticalPath, getDepth, getDuration, getFailures, getHungNodes, getNode, getParent, getStats, getSubtree, getTraceTree, groupByTraceId, stitchTrace };
|
|
448
|
+
export { type Adapter, type AgentFlowConfig, type DistributedTrace, type EdgeType, type ExecutionEdge, type ExecutionGraph, type ExecutionNode, type GraphBuilder, type GraphStats, type GraphStatus, type MutableExecutionNode, type NodeStatus, type NodeType, type RunConfig, type RunResult, type StartNodeOptions, type TraceEvent, type TraceEventType, type Writer, createGraphBuilder, findWaitingOn, getChildren, getCriticalPath, getDepth, getDuration, getFailures, getHungNodes, getNode, getParent, getStats, getSubtree, getTraceTree, groupByTraceId, runTraced, stitchTrace };
|
package/dist/index.d.ts
CHANGED
|
@@ -276,6 +276,55 @@ interface MutableExecutionNode {
|
|
|
276
276
|
*/
|
|
277
277
|
declare function createGraphBuilder(config?: AgentFlowConfig): GraphBuilder;
|
|
278
278
|
|
|
279
|
+
/**
|
|
280
|
+
* CLI runner that wraps any command with automatic AgentFlow tracing.
|
|
281
|
+
*
|
|
282
|
+
* No code changes needed in the target application — the runner sets
|
|
283
|
+
* AGENTFLOW_TRACE_ID and AGENTFLOW_PARENT_SPAN_ID env vars so any child
|
|
284
|
+
* process using AgentFlow auto-joins the distributed trace.
|
|
285
|
+
*
|
|
286
|
+
* @example
|
|
287
|
+
* ```ts
|
|
288
|
+
* const result = await runTraced({
|
|
289
|
+
* command: ['python', '-m', 'alfred', 'process'],
|
|
290
|
+
* watchDirs: ['/home/trader/.alfred/data'],
|
|
291
|
+
* });
|
|
292
|
+
* ```
|
|
293
|
+
* @module
|
|
294
|
+
*/
|
|
295
|
+
interface RunConfig {
|
|
296
|
+
/** Command to execute (e.g. ['python', '-m', 'alfred', 'process']). */
|
|
297
|
+
command: string[];
|
|
298
|
+
/** Agent ID for the orchestrator trace (default: derived from command). */
|
|
299
|
+
agentId?: string;
|
|
300
|
+
/** Trigger label (default: "cli"). */
|
|
301
|
+
trigger?: string;
|
|
302
|
+
/** Directory to save trace files (default: ./traces). */
|
|
303
|
+
tracesDir?: string;
|
|
304
|
+
/** Directories to watch for state file changes during execution. */
|
|
305
|
+
watchDirs?: string[];
|
|
306
|
+
/** File patterns to watch (default: ["*.json"]). */
|
|
307
|
+
watchPatterns?: string[];
|
|
308
|
+
}
|
|
309
|
+
interface RunResult {
|
|
310
|
+
exitCode: number;
|
|
311
|
+
traceId: string;
|
|
312
|
+
spanId: string;
|
|
313
|
+
tracePaths: string[];
|
|
314
|
+
stateChanges: string[];
|
|
315
|
+
duration: number;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Run a command with automatic AgentFlow tracing.
|
|
319
|
+
*
|
|
320
|
+
* 1. Creates an orchestrator (parent) trace.
|
|
321
|
+
* 2. Snapshots watched directories.
|
|
322
|
+
* 3. Spawns the command with trace env vars.
|
|
323
|
+
* 4. After exit, detects state file changes and creates child traces.
|
|
324
|
+
* 5. Saves all trace JSON files.
|
|
325
|
+
*/
|
|
326
|
+
declare function runTraced(config: RunConfig): Promise<RunResult>;
|
|
327
|
+
|
|
279
328
|
declare function groupByTraceId(graphs: ExecutionGraph[]): Map<string, ExecutionGraph[]>;
|
|
280
329
|
declare function stitchTrace(graphs: ExecutionGraph[]): DistributedTrace;
|
|
281
330
|
declare function getTraceTree(trace: DistributedTrace): ExecutionGraph[];
|
|
@@ -396,4 +445,4 @@ declare function getDepth(graph: ExecutionGraph): number;
|
|
|
396
445
|
*/
|
|
397
446
|
declare function getStats(graph: ExecutionGraph): GraphStats;
|
|
398
447
|
|
|
399
|
-
export { type Adapter, type AgentFlowConfig, type DistributedTrace, type EdgeType, type ExecutionEdge, type ExecutionGraph, type ExecutionNode, type GraphBuilder, type GraphStats, type GraphStatus, type MutableExecutionNode, type NodeStatus, type NodeType, type StartNodeOptions, type TraceEvent, type TraceEventType, type Writer, createGraphBuilder, findWaitingOn, getChildren, getCriticalPath, getDepth, getDuration, getFailures, getHungNodes, getNode, getParent, getStats, getSubtree, getTraceTree, groupByTraceId, stitchTrace };
|
|
448
|
+
export { type Adapter, type AgentFlowConfig, type DistributedTrace, type EdgeType, type ExecutionEdge, type ExecutionGraph, type ExecutionNode, type GraphBuilder, type GraphStats, type GraphStatus, type MutableExecutionNode, type NodeStatus, type NodeType, type RunConfig, type RunResult, type StartNodeOptions, type TraceEvent, type TraceEventType, type Writer, createGraphBuilder, findWaitingOn, getChildren, getCriticalPath, getDepth, getDuration, getFailures, getHungNodes, getNode, getParent, getStats, getSubtree, getTraceTree, groupByTraceId, runTraced, stitchTrace };
|
package/dist/index.js
CHANGED
|
@@ -1,228 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
if (obj instanceof Map) {
|
|
6
|
-
Object.freeze(obj);
|
|
7
|
-
for (const value of obj.values()) {
|
|
8
|
-
deepFreeze(value);
|
|
9
|
-
}
|
|
10
|
-
return obj;
|
|
11
|
-
}
|
|
12
|
-
Object.freeze(obj);
|
|
13
|
-
const record = obj;
|
|
14
|
-
for (const key of Object.keys(record)) {
|
|
15
|
-
const value = record[key];
|
|
16
|
-
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
17
|
-
deepFreeze(value);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return obj;
|
|
21
|
-
}
|
|
22
|
-
function createCounterIdGenerator() {
|
|
23
|
-
let counter = 0;
|
|
24
|
-
return () => {
|
|
25
|
-
counter++;
|
|
26
|
-
return `node_${String(counter).padStart(3, "0")}`;
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
function createGraphBuilder(config) {
|
|
30
|
-
const generateId = config?.idGenerator ?? createCounterIdGenerator();
|
|
31
|
-
const agentId = config?.agentId ?? "unknown";
|
|
32
|
-
const trigger = config?.trigger ?? "manual";
|
|
33
|
-
const spanId = randomUUID();
|
|
34
|
-
const traceId = config?.traceId ?? (typeof process !== "undefined" ? process.env?.AGENTFLOW_TRACE_ID : void 0) ?? randomUUID();
|
|
35
|
-
const parentSpanId = config?.parentSpanId ?? (typeof process !== "undefined" ? process.env?.AGENTFLOW_PARENT_SPAN_ID : void 0) ?? null;
|
|
36
|
-
const graphId = generateId();
|
|
37
|
-
const startTime = Date.now();
|
|
38
|
-
const nodes = /* @__PURE__ */ new Map();
|
|
39
|
-
const edges = [];
|
|
40
|
-
const events = [];
|
|
41
|
-
const parentStack = [];
|
|
42
|
-
let rootNodeId = null;
|
|
43
|
-
let built = false;
|
|
44
|
-
function assertNotBuilt() {
|
|
45
|
-
if (built) {
|
|
46
|
-
throw new Error("GraphBuilder: cannot mutate after build() has been called");
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
function getNode2(nodeId) {
|
|
50
|
-
const node = nodes.get(nodeId);
|
|
51
|
-
if (!node) {
|
|
52
|
-
throw new Error(`GraphBuilder: node "${nodeId}" does not exist`);
|
|
53
|
-
}
|
|
54
|
-
return node;
|
|
55
|
-
}
|
|
56
|
-
function recordEvent(nodeId, eventType, data = {}) {
|
|
57
|
-
events.push({
|
|
58
|
-
timestamp: Date.now(),
|
|
59
|
-
eventType,
|
|
60
|
-
nodeId,
|
|
61
|
-
data
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
function buildGraph() {
|
|
65
|
-
if (rootNodeId === null) {
|
|
66
|
-
throw new Error("GraphBuilder: cannot build a graph with no nodes");
|
|
67
|
-
}
|
|
68
|
-
let graphStatus = "completed";
|
|
69
|
-
for (const node of nodes.values()) {
|
|
70
|
-
if (node.status === "failed" || node.status === "timeout" || node.status === "hung") {
|
|
71
|
-
graphStatus = "failed";
|
|
72
|
-
break;
|
|
73
|
-
}
|
|
74
|
-
if (node.status === "running") {
|
|
75
|
-
graphStatus = "running";
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
const endTime = graphStatus === "running" ? null : Date.now();
|
|
79
|
-
const frozenNodes = new Map(
|
|
80
|
-
[...nodes.entries()].map(([id, mNode]) => [
|
|
81
|
-
id,
|
|
82
|
-
{
|
|
83
|
-
id: mNode.id,
|
|
84
|
-
type: mNode.type,
|
|
85
|
-
name: mNode.name,
|
|
86
|
-
startTime: mNode.startTime,
|
|
87
|
-
endTime: mNode.endTime,
|
|
88
|
-
status: mNode.status,
|
|
89
|
-
parentId: mNode.parentId,
|
|
90
|
-
children: [...mNode.children],
|
|
91
|
-
metadata: { ...mNode.metadata },
|
|
92
|
-
state: { ...mNode.state }
|
|
93
|
-
}
|
|
94
|
-
])
|
|
95
|
-
);
|
|
96
|
-
const graph = {
|
|
97
|
-
id: graphId,
|
|
98
|
-
rootNodeId,
|
|
99
|
-
nodes: frozenNodes,
|
|
100
|
-
edges: [...edges],
|
|
101
|
-
startTime,
|
|
102
|
-
endTime,
|
|
103
|
-
status: graphStatus,
|
|
104
|
-
trigger,
|
|
105
|
-
agentId,
|
|
106
|
-
events: [...events],
|
|
107
|
-
traceId,
|
|
108
|
-
spanId,
|
|
109
|
-
parentSpanId
|
|
110
|
-
};
|
|
111
|
-
return deepFreeze(graph);
|
|
112
|
-
}
|
|
113
|
-
const builder = {
|
|
114
|
-
get graphId() {
|
|
115
|
-
return graphId;
|
|
116
|
-
},
|
|
117
|
-
get traceContext() {
|
|
118
|
-
return { traceId, spanId };
|
|
119
|
-
},
|
|
120
|
-
startNode(opts) {
|
|
121
|
-
assertNotBuilt();
|
|
122
|
-
const id = generateId();
|
|
123
|
-
const parentId = opts.parentId ?? parentStack[parentStack.length - 1] ?? null;
|
|
124
|
-
if (parentId !== null && !nodes.has(parentId)) {
|
|
125
|
-
throw new Error(`GraphBuilder: parent node "${parentId}" does not exist`);
|
|
126
|
-
}
|
|
127
|
-
const node = {
|
|
128
|
-
id,
|
|
129
|
-
type: opts.type,
|
|
130
|
-
name: opts.name,
|
|
131
|
-
startTime: Date.now(),
|
|
132
|
-
endTime: null,
|
|
133
|
-
status: "running",
|
|
134
|
-
parentId,
|
|
135
|
-
children: [],
|
|
136
|
-
metadata: opts.metadata ? { ...opts.metadata } : {},
|
|
137
|
-
state: {}
|
|
138
|
-
};
|
|
139
|
-
nodes.set(id, node);
|
|
140
|
-
if (parentId !== null) {
|
|
141
|
-
const parent = nodes.get(parentId);
|
|
142
|
-
if (parent) {
|
|
143
|
-
parent.children.push(id);
|
|
144
|
-
}
|
|
145
|
-
edges.push({ from: parentId, to: id, type: "spawned" });
|
|
146
|
-
}
|
|
147
|
-
if (rootNodeId === null) {
|
|
148
|
-
rootNodeId = id;
|
|
149
|
-
}
|
|
150
|
-
recordEvent(id, "agent_start", { type: opts.type, name: opts.name });
|
|
151
|
-
return id;
|
|
152
|
-
},
|
|
153
|
-
endNode(nodeId, status = "completed") {
|
|
154
|
-
assertNotBuilt();
|
|
155
|
-
const node = getNode2(nodeId);
|
|
156
|
-
if (node.endTime !== null) {
|
|
157
|
-
throw new Error(
|
|
158
|
-
`GraphBuilder: node "${nodeId}" has already ended (status: ${node.status})`
|
|
159
|
-
);
|
|
160
|
-
}
|
|
161
|
-
node.endTime = Date.now();
|
|
162
|
-
node.status = status;
|
|
163
|
-
recordEvent(nodeId, "agent_end", { status });
|
|
164
|
-
},
|
|
165
|
-
failNode(nodeId, error) {
|
|
166
|
-
assertNotBuilt();
|
|
167
|
-
const node = getNode2(nodeId);
|
|
168
|
-
if (node.endTime !== null) {
|
|
169
|
-
throw new Error(
|
|
170
|
-
`GraphBuilder: node "${nodeId}" has already ended (status: ${node.status})`
|
|
171
|
-
);
|
|
172
|
-
}
|
|
173
|
-
const errorMessage = error instanceof Error ? error.message : error;
|
|
174
|
-
const errorStack = error instanceof Error ? error.stack : void 0;
|
|
175
|
-
node.endTime = Date.now();
|
|
176
|
-
node.status = "failed";
|
|
177
|
-
node.metadata.error = errorMessage;
|
|
178
|
-
if (errorStack) {
|
|
179
|
-
node.metadata.errorStack = errorStack;
|
|
180
|
-
}
|
|
181
|
-
recordEvent(nodeId, "tool_error", { error: errorMessage });
|
|
182
|
-
},
|
|
183
|
-
addEdge(from, to, type) {
|
|
184
|
-
assertNotBuilt();
|
|
185
|
-
getNode2(from);
|
|
186
|
-
getNode2(to);
|
|
187
|
-
edges.push({ from, to, type });
|
|
188
|
-
recordEvent(from, "custom", { to, type, action: "edge_add" });
|
|
189
|
-
},
|
|
190
|
-
pushEvent(event) {
|
|
191
|
-
assertNotBuilt();
|
|
192
|
-
getNode2(event.nodeId);
|
|
193
|
-
events.push({
|
|
194
|
-
...event,
|
|
195
|
-
timestamp: Date.now()
|
|
196
|
-
});
|
|
197
|
-
},
|
|
198
|
-
updateState(nodeId, state) {
|
|
199
|
-
assertNotBuilt();
|
|
200
|
-
const node = getNode2(nodeId);
|
|
201
|
-
Object.assign(node.state, state);
|
|
202
|
-
recordEvent(nodeId, "custom", { action: "state_update", ...state });
|
|
203
|
-
},
|
|
204
|
-
withParent(parentId, fn) {
|
|
205
|
-
assertNotBuilt();
|
|
206
|
-
getNode2(parentId);
|
|
207
|
-
parentStack.push(parentId);
|
|
208
|
-
try {
|
|
209
|
-
return fn();
|
|
210
|
-
} finally {
|
|
211
|
-
parentStack.pop();
|
|
212
|
-
}
|
|
213
|
-
},
|
|
214
|
-
getSnapshot() {
|
|
215
|
-
return buildGraph();
|
|
216
|
-
},
|
|
217
|
-
build() {
|
|
218
|
-
assertNotBuilt();
|
|
219
|
-
const graph = buildGraph();
|
|
220
|
-
built = true;
|
|
221
|
-
return graph;
|
|
222
|
-
}
|
|
223
|
-
};
|
|
224
|
-
return builder;
|
|
225
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
createGraphBuilder,
|
|
3
|
+
runTraced
|
|
4
|
+
} from "./chunk-DGLK6IBP.js";
|
|
226
5
|
|
|
227
6
|
// src/graph-stitch.ts
|
|
228
7
|
function groupByTraceId(graphs) {
|
|
@@ -441,5 +220,6 @@ export {
|
|
|
441
220
|
getSubtree,
|
|
442
221
|
getTraceTree,
|
|
443
222
|
groupByTraceId,
|
|
223
|
+
runTraced,
|
|
444
224
|
stitchTrace
|
|
445
225
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentflow-core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Universal execution tracing for AI agent systems",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"dist"
|
|
18
18
|
],
|
|
19
19
|
"scripts": {
|
|
20
|
-
"build": "tsup src/index.ts --format esm,cjs --dts --clean --tsconfig tsconfig.build.json"
|
|
20
|
+
"build": "tsup src/index.ts src/cli.ts --format esm,cjs --dts --clean --tsconfig tsconfig.build.json"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {},
|
|
23
23
|
"keywords": [
|
|
@@ -27,5 +27,8 @@
|
|
|
27
27
|
"execution-graph",
|
|
28
28
|
"observability"
|
|
29
29
|
],
|
|
30
|
-
"license": "MIT"
|
|
30
|
+
"license": "MIT",
|
|
31
|
+
"bin": {
|
|
32
|
+
"agentflow": "./dist/cli.js"
|
|
33
|
+
}
|
|
31
34
|
}
|