BlocklogAI Compliance
SDK Reference

TypeScript / Node.js SDK Reference

Constructor, configuration, event streaming, decorators, tracing, and framework integrations for TypeScript and Node.js.

Constructor

new BlocklogClient()

The main entry point and orchestration layer. Coordinates configuration, tracing, the event pipeline, queues, and transport.

signature.ts
typescript
new BlocklogClient(
  config: BlocklogConfig,
  dependencies?: ClientDependencies
)

Parameters

  • config · BlocklogConfig

    Configuration object. See BlocklogConfig below.

  • dependencies · ClientDependencies, optional

    Dependency injection overrides for testing.

Key Client Properties

  • decisions: DecisionsClient

    Create, get, list, search, update, and verify decision records.

  • traces: TracesClient

    Retrieve traces and trace timelines.

  • approvals: ApprovalClient

    Human-in-the-loop approval workflows. Aliased as client.hitl.

  • incidents: IncidentsClient

    Create, update, assign, resolve, and close incidents.

  • compliance: ComplianceClient

    Generate audits, dashboards, and exportable evidence.

  • replay: ReplayClient

    Reconstruct, verify, replay, and compare traces. Aliased as client.forensics.

  • traceManager: typeof TraceManager

    Static span-management class.

Example

example.ts
typescript
const client = new BlocklogClient({
  apiKey: 'your-api-key',
  endpoint: 'https://api.blocklogsecurity.com',
  batchSize: 100,
  flushInterval: 5000
});
Type

BlocklogConfig

The configuration object passed to the BlocklogClient constructor.

signature.ts
typescript
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;
}

Fields

  • apiKey · string

    Required. Your Blocklog API key.

  • endpoint · string, optional

    Override the default API base URL.

  • batchSize · number, optional

    Events per batch flush. Default is 100.

  • flushInterval · number, optional

    Milliseconds between automatic flushes.

  • timeout · number, optional

    Per-request timeout in milliseconds.

  • retryCount · number, optional

    Automatic retry attempts on failure.

  • enableSigning · boolean, optional

    Turn on tamper-evident event signing.

  • signingKey · string, optional

    Key used for signing when enableSigning is true.

  • signingAlg · 'hmac-sha256' | 'ed25519', optional

    Signing algorithm. Defaults to hmac-sha256.

  • enableCompression · boolean, optional

    Compress event payloads before sending.

  • debug · boolean, optional

    Log outbound requests to console in development.

Example

example.ts
typescript
const client = new BlocklogClient({
  apiKey: process.env.BLOCKLOG_API_KEY!,
  enableSigning: true,
  signingAlg: 'hmac-sha256',
  debug: process.env.NODE_ENV !== 'production'
});
Event Methods

client.event() / client.enqueue()

Send a single event immediately with event(), or buffer it for batched delivery with enqueue().

signature.ts
typescript
event(eventType: string, payload: any, options?: EventOptions): Promise<IngestResponse>
enqueue(eventType: string, payload: any, options?: EventOptions): Promise<IngestResponse | null>

Parameters

  • eventType · string

    Event type identifier, e.g. "AGENT_RUN" or "TOOL_CALL".

  • payload · any

    Event payload data. Must be serializable.

  • options · EventOptions, optional

    metadata, trace_id, span_id, and timestamp overrides.

Example

example.ts
typescript
await client.event('AGENT_RUN', {
  agent_id: 'credit-scoring-v2',
  input: { applicant_id: 'app_8819', score: 742 },
  output: { approved: true, limit: 500000 }
});
Middleware Method

client.addHook()

Register a middleware hook that can transform, enrich, validate, or filter outbound events.

signature.ts
typescript
addHook(hook: MiddlewareHook): BlocklogClient

type MiddlewareHook = (event: EventEnvelope) => EventEnvelope | Promise<EventEnvelope> | null

Parameters

  • hook · MiddlewareHook

    Receives an EventEnvelope and returns modified envelope, or null to drop.

Example

example.ts
typescript
client.addHook((event) => {
  event.metadata = { ...event.metadata, environment: 'production' };
  return event;
});
Lifecycle

client.flush() / shutdown() / health()

Manage the client's buffered events and background resources.

signature.ts
typescript
flush(): Promise<IngestResponse>
shutdown(): Promise<void>
health(): Promise<HealthStatus>

Lifecycle Methods

  • 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 }.

Example

example.ts
typescript
await client.flush();

const health = await client.health();
console.log(health.healthy); // true
Decorator

@traceAgent

Trace an AI agent method automatically, emitting AGENT_START, AGENT_COMPLETE, and AGENT_ERROR events.

signature.ts
typescript
function traceAgent(options: AgentOptions | string)

Parameters

  • options · AgentOptions | string

    Agent name string, or an options object: { name, version, tags, metadata }.

Example

example.ts
typescript
class CreditAgent {
  @traceAgent('credit-decisioning')
  async evaluateRisk(applicantId: string): Promise<DecisionResult> {
    return { status: 'APPROVED' };
  }
}
Tracing

TraceManager

Static class managing span lifecycle and context propagation across async operations via AsyncLocalStorage.

signature.ts
typescript
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>
}

Example

example.ts
typescript
const span = TraceManager.startSpan('evaluate-loan');
const result = await TraceManager.runWithSpan(span, async () => {
  return await processLoan();
});
TraceManager.endSpan(span, 'success');
Framework Instrumentation

Framework Integrations

Native instrumentation for LangChain and OpenAI Agents. Wires into callback systems to trace chains, tools, and LLM calls automatically.

Integration

LangChain

Wraps LangChain's callback system to trace chains, tools, LLM calls, and agents automatically.

Setup

setup.ts
typescript
import { BlocklogClient, setGlobalClient, instrumentLangChain } from '@blocklog/sdk';

const client = new BlocklogClient({ apiKey: 'your-api-key' });
setGlobalClient(client);

const tracer = instrumentLangChain();

Automatic Tracing

usage.ts
typescript
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' });

Manual Tracing Hooks

MethodDescription
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.
Integration

OpenAI Agents

Traces OpenAI chat completion calls, tool/function calls, and messages exchanged during an agent run.

Setup

setup.ts
typescript
import { BlocklogClient, setGlobalClient, instrumentOpenAIAgents } from '@blocklog/sdk';

const client = new BlocklogClient({ apiKey: 'your-api-key' });
setGlobalClient(client);

const hooks = instrumentOpenAIAgents();

Automatic Tracing

usage.ts
typescript
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' }]
});

Manual Tracing Hooks

MethodDescription
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.