Skip to main content

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

InterfaceDescription
AdapterFramework adapter interface. Adapters hook into agent runtime lifecycle events and translate them into graph builder calls.
AgentFlowConfigConfiguration for AgentFlow.
AgentProfileDerived per-agent profile accumulated from execution and pattern events.
AlertPayloadAlert payload passed to notification channels.
BottleneckDuration statistics for a node across multiple execution graphs.
ConformanceHistoryEntryA single conformance history entry.
ConformanceReportResult of comparing a single graph against a process model.
DecisionTraceDataOptional 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.
DeviationA specific deviation between a graph and a process model.
DistributedTraceA stitched distributed trace spanning multiple execution graphs.
DriftOptionsOptions for drift detection.
DriftReportDrift detection report.
EfficiencyFlagWasteful pattern detection flag.
EfficiencyReportAggregate efficiency report across runs.
EventEmitterEvent emitter for routing AgentFlow events to writers and subscribers.
EventEmitterConfigConfiguration for the event emitter.
EventWriterExtended Writer interface that can handle structured events. Backward-compatible — existing Writers are unaffected.
ExecutionEdgeA directed relationship between two execution nodes.
ExecutionEventA structured event emitted after an agent execution completes or fails.
ExecutionEventOptionsOptions for creating an ExecutionEvent from a graph.
ExecutionGraphThe complete execution graph for one agent run.
ExecutionNodeA single step in the execution graph.
FailurePointThe point at which an execution failed.
GraphBuilderMutable graph builder returned by createGraphBuilder.
GraphStatsAggregate statistics for an execution graph.
GuardConfigConfiguration for runtime guard detection.
GuardExplanationExplanation attached to every guard violation for transparency.
GuardViolationA detected guard violation.
InsightEngineLLM-powered semantic analysis engine for agent execution data.
InsightEngineConfigConfiguration for the insight engine.
InsightEventA structured event emitted when the insight engine generates an LLM-powered analysis.
InsightResultResult returned by InsightEngine methods.
JsonEventWriterConfigConfiguration for the JSON event writer.
KnowledgeStoreFilesystem-based knowledge store that accumulates execution and pattern events. Implements EventWriter so it can be used directly with createEventEmitter.
KnowledgeStoreConfigConfiguration for the knowledge store.
MutableExecutionNodeMutable version of ExecutionNode used during graph construction.
NodeCostPer-node cost attribution.
NormalizedDecisionA single decision made by an agent during execution — agent-agnostic.
OsProcess-
OutcomeAssertionOutcome assertion for post-action verification.
PatternEventA structured event emitted when process mining discovers a pattern.
PidFileResult-
PolicySourceRead-only interface for querying accumulated knowledge. Used by guards to make adaptive decisions based on execution history.
PolicyThresholdsThresholds for policy-derived guard violations.
ProcessAuditConfig-
ProcessAuditResult-
ProcessContextProcess mining context for an execution event.
ProcessModelA process model discovered from multiple execution graphs.
ProcessTransitionA transition between two steps in a discovered process model.
RunConfig-
RunEfficiencyPer-run efficiency summary.
RunReceiptStructured run summary.
RunResult-
SemanticContextOptional semantic context attached to an execution event by adapters.
SomaEventWriterConfigConfiguration for the Soma event writer.
StartNodeOptionsOptions for starting a new execution node.
StepSummaryPer-step summary in a run receipt.
SystemdUnitResult-
TraceEventA raw event recorded during execution, before graph construction.
TraceStoreTrace storage interface for saving, loading, and querying execution graphs.
VariantA group of execution graphs that share the same structural path.
VariantOptionsOptions for variant analysis.
WatchConfigConfiguration for the watch command.
WorkerEntry-
WorkersResult-
WriterOutput adapter interface. Writers receive the completed execution graph and persist it to their target (console, file, etc.).

Type Aliases

Type AliasDescription
AgentFlowEventTypeEvent type discriminator for AgentFlow events.
AlertConditionAlert condition parsed from --alert-on flags.
AnalysisFnUser-provided LLM function. AgentFlow constructs prompts and delegates the actual LLM call to this function. Any provider can be wrapped as an AnalysisFn.
ConformanceHistoryConformance score history for an agent.
DeviationTypeCategory of deviation detected during conformance checking.
EdgeTypeRelationship type between two nodes in the execution graph.
GraphStatusAggregate status of the entire execution graph.
NodeStatusLifecycle status of an execution node.
NodeTypeThe kind of step an execution node represents.
NotifyChannelNotification channel parsed from --notify flags.
TraceEventTypeEvent types emitted during execution. These map to framework-level lifecycle events for adapter compatibility.

Functions

FunctionDescription
auditProcessesRun a full process health audit.
buildAgentSummaryPromptBuild a structured prompt for generating an agent health summary.
buildAnomalyExplanationPromptBuild a structured prompt for explaining why an execution was anomalous.
buildFailureAnalysisPromptBuild a structured prompt for LLM analysis of agent failures.
buildFixSuggestionPromptBuild a structured prompt for generating actionable fix recommendations.
checkConformanceCompare a single execution graph against a discovered process model.
checkGuardsCheck an execution graph for guard violations.
createEventEmitterCreate an event emitter for routing AgentFlow events to writers and subscribers.
createExecutionEventCreate a structured ExecutionEvent from a completed execution graph.
createGraphBuilderCreate a new execution graph builder.
createInsightEngineCreate an LLM-powered semantic analysis engine.
createJsonEventWriterCreate a JSON event writer that persists events as individual files.
createKnowledgeStoreCreate a filesystem-based knowledge store for accumulating execution intelligence.
createPatternEventCreate a structured PatternEvent from process mining results.
createPolicySourceCreate a PolicySource backed by a knowledge store.
createSomaEventWriterCreate a Soma event writer that persists events as Curator-compatible Markdown files.
createTraceStoreCreate a JSON file-based trace store.
discoverAllProcessConfigsDiscover all process configurations from the given directories and systemd.
discoverProcessDiscover a process model from multiple execution graphs.
discoverProcessConfigScan directories for PID files (*.pid), worker registries (workers.json, *-workers.json), and infer a process name from the PID file name.
findVariantsGroup execution graphs by their structural path and return variant clusters.
findWaitingOnFind what a node is waiting on. Returns nodes connected via waited_on edges where the given nodeId is the from side.
formatAuditReportFormat an audit result as a human-readable terminal report. Uses Unicode box-drawing characters and status icons.
formatReceiptFormat a RunReceipt into a human-readable text block.
getBottlenecksIdentify performance bottlenecks by aggregating node durations across graphs.
getChildrenGet the direct children of a node.
getCriticalPathFind 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.
getDepthMaximum nesting depth of the graph. The root node is depth 0.
getDurationTotal wall-clock duration of the graph in milliseconds. If the graph is still running, uses Date.now() as the provisional end.
getFailuresFind all nodes with a failure-category status: failed, hung, or timeout.
getHungNodesFind all nodes that are still running (status 'running', no endTime).
getNodeFind a node by its ID.
getParentGet the parent of a node.
getPathSignatureProduce a canonical string representation of a graph's execution path.
getStatsCompute aggregate statistics for the execution graph.
getSubtreeGet all descendants of a node (children, grandchildren, etc.) in breadth-first order. The given node itself is NOT included.
getTraceTree-
graphToJsonSerialize an ExecutionGraph to a plain JSON-safe object.
groupByTraceId-
loadGraphDeserialize a JSON object (or JSON string) into a valid ExecutionGraph.
runTracedRun a command with automatic AgentFlow tracing.
startLive-
startWatch-
stitchTrace-
toAsciiTreeRender an ExecutionGraph as an ASCII tree showing parent-child hierarchy.
toReceiptWalk an execution graph and produce a structured RunReceipt.
toTimelineRender an ExecutionGraph as a horizontal timeline/waterfall.
withGuardsCreate a guard-aware wrapper around a GraphBuilder.