Instrument agent behavior with trace events and behavioral primitives. DEV mode (full fidelity) and PROD mode (sampled, signed) for observability without receipt overhead.
`trace()` wraps a function with timing, hashing, anomaly scoring, and optional replay snapshots. Unlike `wrap()`, it does NOT create receipts — use it for debugging and monitoring.
`emit()` records behavioral primitives to the semantic behavior graph: DecisionPoint, GoalDrift, SubAgentSpawn, and ToolInvocation. These power anomaly detection, drift analysis, and the replay debugger. Emit is fire-and-forget.
The SDK supports DEV (full fidelity, no crypto overhead) and PROD (sampled, anomaly-scored, signed) modes.
const inv = Invariance.init({
apiKey: 'dev_...', mode: 'DEV', devOutput: 'console',
onAnomaly: (event) => console.warn('Anomaly:', event.anomalyScore),
});
const { result, event } = await inv.trace({
agentId: 'research-agent',
action: { type: 'ToolInvocation', tool: 'web_search', input: { query: 'AI safety' } },
fn: () => searchWeb('AI safety'),
});
console.log(event.durationMs);
console.log(event.anomalyScore);
inv.emit('DecisionPoint', {
nodeId: event.nodeId,
candidates: ['search', 'summarize', 'report'],
chosen: 'search',
depth: 0,
});interface TraceEvent {
schemaVersion: string;
nodeId: string;
sessionId: string;
agentId: string;
actionType: BehavioralPrimitive;
input: unknown;
output?: unknown;
timestamp: number;
durationMs: number;
hash: string;
previousHash: string;
anomalyScore: number;
}type BehavioralPrimitive =
| 'DecisionPoint' | 'ToolInvocation'
| 'SubAgentSpawn' | 'GoalDrift'
| 'ConstraintCheck' | 'PlanRevision'
| 'A2ASend' | 'A2AReceive';| Option | Type | Default | Description |
|---|---|---|---|
| mode | 'DEV' | 'PROD' | 'PROD' | DEV captures everything; PROD samples and signs |
| sampleRate | number | 0.01 | Fraction of events to trace in PROD mode |
| anomalyThreshold | number | 0.7 | Minimum score to trigger onAnomaly callback |
| devOutput | 'ui' | 'console' | 'both' | 'console' | Where to output trace data in DEV mode |
| captureReplaySnapshots | boolean | false | Whether to capture full input/output snapshots for replay debugging |
| replayContext | { type: 'full' } | { type: 'last' } | { type: 'window', size: number } | { type: 'last' } | Controls how much context is included in replay snapshots. "full" captures entire history, "last" captures only the most recent event, "window" captures the last N events. |