agentflow-core API
AgentFlow — Universal execution tracing for AI agent systems.
Example
import { createGraphBuilder, getStats } from 'agentflow-core';
const builder = createGraphBuilder({ agentId: 'my-agent' });
const rootId = builder.startNode({ type: 'agent', name: 'main' });
builder.endNode(rootId);
const graph = builder.build();
console.log(getStats(graph));
Interfaces
| Interface | Description |
|---|---|
| Adapter | Framework adapter interface. Adapters hook into agent runtime lifecycle events and translate them into graph builder calls. |
| AgentFlowConfig | Configuration for AgentFlow. |
| AgentProfile | Derived per-agent profile accumulated from execution and pattern events. |
| AlertPayload | Alert payload passed to notification channels. |
| Bottleneck | Duration statistics for a node across multiple execution graphs. |
| ConformanceHistoryEntry | A single conformance history entry. |
| ConformanceReport | Result of comparing a single graph against a process model. |
| DecisionTraceData | Optional typed data for decision trace events. Frameworks can emit these to provide richer decision data than graph inference. SOMA will use these fields if present, falling back to graph-structure inference. |
| Deviation | A specific deviation between a graph and a process model. |
| DistributedTrace | A stitched distributed trace spanning multiple execution graphs. |
| DriftOptions | Options for drift detection. |
| DriftReport | Drift detection report. |
| EfficiencyFlag | Wasteful pattern detection flag. |
| EfficiencyReport | Aggregate efficiency report across runs. |
| EventEmitter | Event emitter for routing AgentFlow events to writers and subscribers. |
| EventEmitterConfig | Configuration for the event emitter. |
| EventWriter | Extended Writer interface that can handle structured events. Backward-compatible — existing Writers are unaffected. |
| ExecutionEdge | A directed relationship between two execution nodes. |
| ExecutionEvent | A structured event emitted after an agent execution completes or fails. |
| ExecutionEventOptions | Options for creating an ExecutionEvent from a graph. |
| ExecutionGraph | The complete execution graph for one agent run. |
| ExecutionNode | A single step in the execution graph. |
| FailurePoint | The point at which an execution failed. |
| GraphBuilder | Mutable graph builder returned by createGraphBuilder. |
| GraphStats | Aggregate statistics for an execution graph. |
| GuardConfig | Configuration for runtime guard detection. |
| GuardExplanation | Explanation attached to every guard violation for transparency. |
| GuardViolation | A detected guard violation. |
| InsightEngine | LLM-powered semantic analysis engine for agent execution data. |
| InsightEngineConfig | Configuration for the insight engine. |
| InsightEvent | A structured event emitted when the insight engine generates an LLM-powered analysis. |
| InsightResult | Result returned by InsightEngine methods. |
| JsonEventWriterConfig | Configuration for the JSON event writer. |
| KnowledgeStore | Filesystem-based knowledge store that accumulates execution and pattern events. Implements EventWriter so it can be used directly with createEventEmitter. |
| KnowledgeStoreConfig | Configuration for the knowledge store. |
| MutableExecutionNode | Mutable version of ExecutionNode used during graph construction. |
| NodeCost | Per-node cost attribution. |
| NormalizedDecision | A single decision made by an agent during execution — agent-agnostic. |
| OsProcess | - |
| OutcomeAssertion | Outcome assertion for post-action verification. |
| PatternEvent | A structured event emitted when process mining discovers a pattern. |
| PidFileResult | - |
| PolicySource | Read-only interface for querying accumulated knowledge. Used by guards to make adaptive decisions based on execution history. |
| PolicyThresholds | Thresholds for policy-derived guard violations. |
| ProcessAuditConfig | - |
| ProcessAuditResult | - |
| ProcessContext | Process mining context for an execution event. |
| ProcessModel | A process model discovered from multiple execution graphs. |
| ProcessTransition | A transition between two steps in a discovered process model. |
| RunConfig | - |
| RunEfficiency | Per-run efficiency summary. |
| RunReceipt | Structured run summary. |
| RunResult | - |
| SemanticContext | Optional semantic context attached to an execution event by adapters. |
| SomaEventWriterConfig | Configuration for the Soma event writer. |
| StartNodeOptions | Options for starting a new execution node. |
| StepSummary | Per-step summary in a run receipt. |
| SystemdUnitResult | - |
| TraceEvent | A raw event recorded during execution, before graph construction. |
| TraceStore | Trace storage interface for saving, loading, and querying execution graphs. |
| Variant | A group of execution graphs that share the same structural path. |
| VariantOptions | Options for variant analysis. |
| WatchConfig | Configuration for the watch command. |
| WorkerEntry | - |
| WorkersResult | - |
| Writer | Output adapter interface. Writers receive the completed execution graph and persist it to their target (console, file, etc.). |
Type Aliases
| Type Alias | Description |
|---|---|
| AgentFlowEventType | Event type discriminator for AgentFlow events. |
| AlertCondition | Alert condition parsed from --alert-on flags. |
| AnalysisFn | User-provided LLM function. AgentFlow constructs prompts and delegates the actual LLM call to this function. Any provider can be wrapped as an AnalysisFn. |
| ConformanceHistory | Conformance score history for an agent. |
| DeviationType | Category of deviation detected during conformance checking. |
| EdgeType | Relationship type between two nodes in the execution graph. |
| GraphStatus | Aggregate status of the entire execution graph. |
| NodeStatus | Lifecycle status of an execution node. |
| NodeType | The kind of step an execution node represents. |
| NotifyChannel | Notification channel parsed from --notify flags. |
| TraceEventType | Event types emitted during execution. These map to framework-level lifecycle events for adapter compatibility. |
Functions
| Function | Description |
|---|---|
| auditProcesses | Run a full process health audit. |
| buildAgentSummaryPrompt | Build a structured prompt for generating an agent health summary. |
| buildAnomalyExplanationPrompt | Build a structured prompt for explaining why an execution was anomalous. |
| buildFailureAnalysisPrompt | Build a structured prompt for LLM analysis of agent failures. |
| buildFixSuggestionPrompt | Build a structured prompt for generating actionable fix recommendations. |
| checkConformance | Compare a single execution graph against a discovered process model. |
| checkGuards | Check an execution graph for guard violations. |
| createEventEmitter | Create an event emitter for routing AgentFlow events to writers and subscribers. |
| createExecutionEvent | Create a structured ExecutionEvent from a completed execution graph. |
| createGraphBuilder | Create a new execution graph builder. |
| createInsightEngine | Create an LLM-powered semantic analysis engine. |
| createJsonEventWriter | Create a JSON event writer that persists events as individual files. |
| createKnowledgeStore | Create a filesystem-based knowledge store for accumulating execution intelligence. |
| createPatternEvent | Create a structured PatternEvent from process mining results. |
| createPolicySource | Create a PolicySource backed by a knowledge store. |
| createSomaEventWriter | Create a Soma event writer that persists events as Curator-compatible Markdown files. |
| createTraceStore | Create a JSON file-based trace store. |
| discoverAllProcessConfigs | Discover all process configurations from the given directories and systemd. |
| discoverProcess | Discover a process model from multiple execution graphs. |
| discoverProcessConfig | Scan directories for PID files (*.pid), worker registries (workers.json, *-workers.json), and infer a process name from the PID file name. |
| findVariants | Group execution graphs by their structural path and return variant clusters. |
| findWaitingOn | Find what a node is waiting on. Returns nodes connected via waited_on edges where the given nodeId is the from side. |
| formatAuditReport | Format an audit result as a human-readable terminal report. Uses Unicode box-drawing characters and status icons. |
| formatReceipt | Format a RunReceipt into a human-readable text block. |
| getBottlenecks | Identify performance bottlenecks by aggregating node durations across graphs. |
| getChildren | Get the direct children of a node. |
| getCriticalPath | Find the critical path: the longest-duration path from the root to any leaf node. Uses node duration (endTime - startTime) as the weight. Running nodes use Date.now() as a provisional endTime. |
| getDepth | Maximum nesting depth of the graph. The root node is depth 0. |
| getDuration | Total wall-clock duration of the graph in milliseconds. If the graph is still running, uses Date.now() as the provisional end. |
| getFailures | Find all nodes with a failure-category status: failed, hung, or timeout. |
| getHungNodes | Find all nodes that are still running (status 'running', no endTime). |
| getNode | Find a node by its ID. |
| getParent | Get the parent of a node. |
| getPathSignature | Produce a canonical string representation of a graph's execution path. |
| getStats | Compute aggregate statistics for the execution graph. |
| getSubtree | Get all descendants of a node (children, grandchildren, etc.) in breadth-first order. The given node itself is NOT included. |
| getTraceTree | - |
| graphToJson | Serialize an ExecutionGraph to a plain JSON-safe object. |
| groupByTraceId | - |
| loadGraph | Deserialize a JSON object (or JSON string) into a valid ExecutionGraph. |
| runTraced | Run a command with automatic AgentFlow tracing. |
| startLive | - |
| startWatch | - |
| stitchTrace | - |
| toAsciiTree | Render an ExecutionGraph as an ASCII tree showing parent-child hierarchy. |
| toReceipt | Walk an execution graph and produce a structured RunReceipt. |
| toTimeline | Render an ExecutionGraph as a horizontal timeline/waterfall. |
| withGuards | Create a guard-aware wrapper around a GraphBuilder. |