Constructor, configuration, event streaming, decorators, tracing, and framework integrations for TypeScript and Node.js.
The main entry point and orchestration layer. Coordinates configuration, tracing, the event pipeline, queues, and transport.
new BlocklogClient(
config: BlocklogConfig,
dependencies?: ClientDependencies
)config · BlocklogConfigConfiguration object. See BlocklogConfig below.
dependencies · ClientDependencies, optionalDependency injection overrides for testing.
decisions: DecisionsClientCreate, get, list, search, update, and verify decision records.
traces: TracesClientRetrieve traces and trace timelines.
approvals: ApprovalClientHuman-in-the-loop approval workflows. Aliased as client.hitl.
incidents: IncidentsClientCreate, update, assign, resolve, and close incidents.
compliance: ComplianceClientGenerate audits, dashboards, and exportable evidence.
replay: ReplayClientReconstruct, verify, replay, and compare traces. Aliased as client.forensics.
traceManager: typeof TraceManagerStatic span-management class.
const client = new BlocklogClient({
apiKey: 'your-api-key',
endpoint: 'https://api.blocklogsecurity.com',
batchSize: 100,
flushInterval: 5000
});The configuration object passed to the BlocklogClient constructor.
interface BlocklogConfig {
apiKey: string;
endpoint?: string;
batchSize?: number;
flushInterval?: number;
timeout?: number;
retryCount?: number;
enableSigning?: boolean;
signingKey?: string;
signingAlg?: 'hmac-sha256' | 'ed25519';
enableCompression?: boolean;
debug?: boolean;
}apiKey · stringRequired. Your Blocklog API key.
endpoint · string, optionalOverride the default API base URL.
batchSize · number, optionalEvents per batch flush. Default is 100.
flushInterval · number, optionalMilliseconds between automatic flushes.
timeout · number, optionalPer-request timeout in milliseconds.
retryCount · number, optionalAutomatic retry attempts on failure.
enableSigning · boolean, optionalTurn on tamper-evident event signing.
signingKey · string, optionalKey used for signing when enableSigning is true.
signingAlg · 'hmac-sha256' | 'ed25519', optionalSigning algorithm. Defaults to hmac-sha256.
enableCompression · boolean, optionalCompress event payloads before sending.
debug · boolean, optionalLog outbound requests to console in development.
const client = new BlocklogClient({
apiKey: process.env.BLOCKLOG_API_KEY!,
enableSigning: true,
signingAlg: 'hmac-sha256',
debug: process.env.NODE_ENV !== 'production'
});Send a single event immediately with event(), or buffer it for batched delivery with enqueue().
event(eventType: string, payload: any, options?: EventOptions): Promise<IngestResponse>
enqueue(eventType: string, payload: any, options?: EventOptions): Promise<IngestResponse | null>eventType · stringEvent type identifier, e.g. "AGENT_RUN" or "TOOL_CALL".
payload · anyEvent payload data. Must be serializable.
options · EventOptions, optionalmetadata, trace_id, span_id, and timestamp overrides.
await client.event('AGENT_RUN', {
agent_id: 'credit-scoring-v2',
input: { applicant_id: 'app_8819', score: 742 },
output: { approved: true, limit: 500000 }
});Register a middleware hook that can transform, enrich, validate, or filter outbound events.
addHook(hook: MiddlewareHook): BlocklogClient
type MiddlewareHook = (event: EventEnvelope) => EventEnvelope | Promise<EventEnvelope> | nullhook · MiddlewareHookReceives an EventEnvelope and returns modified envelope, or null to drop.
client.addHook((event) => {
event.metadata = { ...event.metadata, environment: 'production' };
return event;
});Manage the client's buffered events and background resources.
flush(): Promise<IngestResponse>
shutdown(): Promise<void>
health(): Promise<HealthStatus>flush()Flushes the pipeline, buffer, and queues immediately.
shutdown()Flushes all buffers, persists the queue, and cleanly stops background timers.
health()Returns { healthy, queueDepth, pendingEvents, transportReady }.
await client.flush();
const health = await client.health();
console.log(health.healthy); // trueTrace an AI agent method automatically, emitting AGENT_START, AGENT_COMPLETE, and AGENT_ERROR events.
function traceAgent(options: AgentOptions | string)options · AgentOptions | stringAgent name string, or an options object: { name, version, tags, metadata }.
class CreditAgent {
@traceAgent('credit-decisioning')
async evaluateRisk(applicantId: string): Promise<DecisionResult> {
return { status: 'APPROVED' };
}
}Static class managing span lifecycle and context propagation across async operations via AsyncLocalStorage.
class TraceManager {
static startSpan(name: string, options?: SpanOptions): Span
static endSpan(span: Span | string, status?: string): void
static currentSpan(): Span | undefined
static parentSpan(): Span | undefined
static runWithSpan<T>(span: Span, fn: () => Promise<T>): Promise<T>
}const span = TraceManager.startSpan('evaluate-loan');
const result = await TraceManager.runWithSpan(span, async () => {
return await processLoan();
});
TraceManager.endSpan(span, 'success');Native instrumentation for LangChain and OpenAI Agents. Wires into callback systems to trace chains, tools, and LLM calls automatically.
Wraps LangChain's callback system to trace chains, tools, LLM calls, and agents automatically.
import { BlocklogClient, setGlobalClient, instrumentLangChain } from '@blocklog/sdk';
const client = new BlocklogClient({ apiKey: 'your-api-key' });
setGlobalClient(client);
const tracer = instrumentLangChain();import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
const agent = await createOpenAIFunctionsAgent(llm, tools, prompt);
const executor = new AgentExecutor({ agent, tools, verbose: true });
// Execution is automatically traced
const result = await executor.invoke({ input: 'Evaluate credit eligibility' });| Method | Description |
|---|---|
handleChainStart(chain, inputs, runId) | Mark a chain's start. chain is { name, metadata? }. |
handleChainEnd(outputs, runId) | Mark a chain's successful completion. |
handleToolStart(tool, input, runId) | Mark a tool call's start. |
handleToolEnd(output, runId) | Mark a tool call's completion. |
handleLLMStart(llm, prompts, runId) | Mark an LLM call's start. |
handleLLMEnd(output, runId) | Mark an LLM call's completion. |
Traces OpenAI chat completion calls, tool/function calls, and messages exchanged during an agent run.
import { BlocklogClient, setGlobalClient, instrumentOpenAIAgents } from '@blocklog/sdk';
const client = new BlocklogClient({ apiKey: 'your-api-key' });
setGlobalClient(client);
const hooks = instrumentOpenAIAgents();import { OpenAI } from 'openai';
const openai = new OpenAI({ apiKey: 'your-openai-key' });
// Chat completions, tool calls, and messages are automatically traced
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Process application' }]
});| Method | Description |
|---|---|
onAgentRunStart(agentId, input) | Mark the start of an agent run. |
onAgentRunEnd(agentId, output) | Mark an agent run's successful completion. |
onAgentRunError(agentId, error) | Mark an agent run's failure. |
onToolCall(toolName, args) | Record a tool call's name and arguments. |
onMessage(role, content) | Record a message exchanged during the run. |