Skip to content
Back to home

§ DOCUMENTATION

SDK Reference

Complete API reference for the Execlave SDKs.

§ 00

Choose your SDK

Same feature surface across both runtimes. Pick one — examples adapt automatically.

§ 01

Installation

npm install @execlave/sdk

Zero runtime dependencies. Supports Node.js 18+ and modern bundlers for browser-side usage. TypeScript types included.

§ 02

Initialization

import { Execlave } from '@execlave/sdk'; const exe = new Execlave({  apiKey: process.env.EXECLAVE_API_KEY!,      // required  baseUrl: 'https://api.execlave.com',              // default  environment: 'production',                      // default  asyncMode: true,                                // default: buffer traces  batchSize: 100,                                 // max traces per flush  flushIntervalMs: 10_000,                        // 10s flush interval  debug: false,                                   // verbose logging  enableControlChannel: true,                     // kill-switch polling  pollIntervalMs: 15_000,                         // poll interval  enableInjectionScan: true,                      // tags traces with injection score (does NOT block)  enforcementOnOutage: 'fail_open',               // fail_open | fail_closed  onEnforcementBypassed: (e) => alert(e),         // fires whenever an action ran UNGOVERNED  policyCacheTtlMs: 60_000,                       // policy decision cache TTL});
§ Important

Create a single Execlave instance and share it across your app. The SDK manages connection pooling, batching, and background flushing internally.

§ 03

Methods

registerAgent

exe.registerAgent(config: AgentConfig): Promise<Agent>

Register a new agent or update an existing one. Idempotent — safe to call on every app startup.

§ Parameters

agentIdstringUnique identifier for the agent
namestringDisplay name
type?stringchatbot | copilot | autonomous | workflow | data_processing
platform?stringcustom | openai | anthropic | langchain
environment?'development' | 'staging' | 'production'Defaults to development. Pin to production when running in prod.
description?stringAgent description
ownerEmail?stringSurfaced in the dashboard and on policy violation alerts.
allowedDataSources?string[]Governance allowlist of data sources the agent may read (e.g. ["s3://bucket-x", "postgres://orders"]). Enforced by data-access policies.
allowedActions?string[]Governance allowlist of tool/action names this agent may invoke. Anything not on the list is blocked by default.
requiresHumanApprovalFor?string[]Action names that always go to the human-approval queue regardless of policy outcome (e.g. ["wire_transfer", "delete_customer"]).
tags?string[]Tags for filtering
metadata?Record<string, unknown>Free-form metadata stored on the agent record (cost-center IDs, owning team, ticket links).
autonomyLevel?AutonomyLevelobserve | advise | act_with_approval | autonomous. Declares how much the agent may do unsupervised; drift detection can downgrade it later, and promotion to autonomous can be gated on a red-team score.

§ Returns

Promise<Agent>
await exe.registerAgent({  agentId: 'support-bot',  name: 'Customer Support Bot',  type: 'chatbot',  platform: 'openai',  environment: 'production',  ownerEmail: 'support-team@example.com',  allowedDataSources: ['postgres://customers'],  allowedActions: ['search_kb', 'create_ticket'],  requiresHumanApprovalFor: ['issue_refund'],  tags: ['support', 'tier-1'],  metadata: { costCenter: 'CS-101' },});

enforcePolicy

exe.enforcePolicy(opts): Promise<EnforcementDecision>

Synchronous pre-execution policy check. Call this BEFORE every LLM invocation. Throws PolicyBlockedError on a block-mode violation, AgentPausedError if the agent is kill-switched, and EnforcementUnavailableError only when enforcementOnOutage is 'fail_closed'. Tracing alone does NOT block — this method is the gate.

§ Parameters

agentIdstringAgent performing the call
inputstringUser input being sent to the LLM
environment?EnvironmentOverride the client environment for this check
metadata?Record<string, unknown>Optional metadata for custom validators
estimatedCost?numberEstimated call cost in USD (for budget policies)
tools?string[]Tool names the agent intends to use (for action_approval policies)

§ Returns

Promise<EnforcementDecision>. Throws PolicyBlockedError if blocked.
import { AgentPausedError, PolicyBlockedError } from '@execlave/sdk'; try {  await exe.enforcePolicy({ agentId: 'support-bot', input: userQuestion });  const answer = await llm.call(userQuestion);} catch (err) {  if (err instanceof PolicyBlockedError) {    // err.violations: list of { policyType, policyName, severity, message, enforcementMode }    return 'Your input was blocked by our content policies.';  }  if (err instanceof AgentPausedError) {    return 'Service temporarily unavailable.';  }  throw err;}

startTrace

exe.startTrace(opts: TraceOptions): Trace

Start a new trace to record an LLM interaction. Returns a chainable Trace object. Tracing is post-hoc — it does NOT block the LLM call. Pair with enforcePolicy() to actually block requests.

§ Parameters

agentIdstringAgent performing the trace
sessionId?stringGroup traces into conversations

§ Returns

Trace
const trace = exe.startTrace({ agentId: 'support-bot' });trace  .setInput('How do I reset my password?')  .setOutput('Go to Settings > Security...')  .setModel('gpt-4')  .setTokens(150, 320)  .setCost(0.0045)  .finish(); // Or finish with error:trace.finish('error', 'LLM call timed out');

wrap

exe.wrap<T>(fn, opts): (input: string) => Promise<T>

Wrap a function with automatic tracing. Input/output are captured, and the trace is finished on return or error.

§ Parameters

fnFunctionAsync function to wrap
opts.agentIdstringAgent performing the call

§ Returns

Wrapped function with same signature
const tracedAnswer = exe.wrap(  async (question: string) => {    const res = await openai.chat.completions.create({      model: 'gpt-4',      messages: [{ role: 'user', content: question }],    });    return res.choices[0].message.content;  },  { agentId: 'support-bot' }); // Usage — fully traced automaticallyconst answer = await tracedAnswer('How do I upgrade?');

enforceToolOutput

exe.enforceToolOutput(opts): Promise<EnforceResult>

Scan a tool's result BEFORE feeding it back to the model. This is what makes tool_output_scan preventive rather than detective — the framework adapters do not call it for you, so a result you never pass here cannot be blocked.

§ Parameters

agentIdstringAgent that invoked the tool
toolNamestringName of the tool that returned
outputunknownThe raw tool result to scan
input?unknownArguments the tool was called with

§ Returns

Promise<EnforceResult>
const raw = await webSearch(query);await exe.enforceToolOutput({ agentId: 'bot', toolName: 'web_search', output: raw });// Throws PolicyBlockedError if the result carries denied PII or injection.messages.push({ role: 'tool', content: raw });

verifyApproval

exe.verifyApproval(approvalId, actionContext): Promise<VerifyResult>

Verify that a granted approval actually covers the action about to run. The certificate is bound to the action context, so a mismatch or a replay is rejected rather than silently honoured.

§ Parameters

approvalIdstringFrom a 202 enforce response
actionContextRecord<string, unknown>The action being performed — must match what was approved

§ Returns

Promise<{ valid: boolean; reason?: string; certificate?: object }>
const v = await exe.verifyApproval(approvalId, { input, environment: 'production' });if (!v.valid) throw new Error(`approval not usable: ${v.reason}`);

checkAgentStatus

exe.checkAgentStatus(agentId?): Promise<string>

Current lifecycle status of an agent — most importantly whether it has been paused by the kill switch.

§ Returns

Promise<'active' | 'paused' | 'unknown'>
if ((await exe.checkAgentStatus('bot')) === 'paused') return;

ping

exe.ping(): Promise<boolean>

Liveness probe against the API. Useful at startup to fail fast on a misconfigured key or base URL.

§ Returns

Promise<boolean>
if (!(await exe.ping())) console.warn('Execlave unreachable');

flush

exe.flush(): Promise<void>

Force-send buffered traces without shutting down. Use in short-lived processes (a serverless invocation) where the flush interval may never fire.

§ Returns

Promise<void>
await exe.flush();

checkUsage

exe.checkUsage(): Promise<UsageStatus>

Current plan consumption. Lets you surface an approaching trace quota before ingestion starts failing.

§ Returns

Promise<UsageStatus>
const usage = await exe.checkUsage();

getAgentCredential

exe.getAgentCredential(agentId): Promise<AgentCredential>

Fetch the agent's exe_agt_ credential, which proves agent identity on trace ingest and agent-to-agent calls. Cached in-process.

§ Returns

Promise<AgentCredential>
const cred = await exe.getAgentCredential('bot');

authorizeAgentCall

exe.authorizeAgentCall(opts: AuthorizeCallOptions): Promise<AuthorizeResult>

Authorize one agent calling another (A2A). Requires FF_A2A_AUTH on the backend; records an a2a.authorize audit event.

§ Returns

Promise<AuthorizeResult>
const decision = await exe.authorizeAgentCall({ callerAgentId: 'a', targetAgentId: 'b' });

discoverAgents

exe.discoverAgents(capability?): Promise<DiscoveredAgent[]>

List agents in the organization, optionally filtered by a declared capability.

§ Returns

Promise<DiscoveredAgent[]>
const agents = await exe.discoverAgents('refunds');

reportAgentMetadata

exe.reportAgentMetadata(opts: ReportAgentMetadataOptions): Promise<unknown>

Report framework, model, and capability metadata for an agent. Feeds the agent passport and the inventory view.

§ Returns

Promise<unknown>
await exe.reportAgentMetadata({ agentId: 'bot', framework: 'langchain' });

toolDescriptor

exe.toolDescriptor(opts): ToolDescriptor

Build a hashed descriptor for one MCP tool. Synchronous — pair with reportToolBaseline to pin a supply-chain baseline.

§ Returns

{ server, tool, descriptorHash, description? }
const d = exe.toolDescriptor({ server: 'files', tool: 'read', descriptor: schema });

reportToolBaseline

exe.reportToolBaseline(opts: ReportToolBaselineOptions): Promise<unknown>

Pin the current MCP tool descriptors as the agent's baseline. Later drift is detected against it by tool_integrity policies.

§ Returns

Promise<unknown>
await exe.reportToolBaseline({ agentId: 'bot', tools: [d] });

shutdown

exe.shutdown(): Promise<void>

Flush all buffered traces and close connections. Call on process exit.

§ Returns

Promise<void>
process.on('SIGTERM', async () => {  await exe.shutdown();  process.exit(0);});
§ 04

Error types

AgentPausedError

Thrown when a trace is started for an agent that has been paused via the kill switch. Your app should catch this and return a graceful fallback to the user.

PolicyBlockedError

Thrown when a pre-execution policy check blocks the request. Contains the violated policy name and enforcement mode.

ErrorThrown when
EnforcementUnavailableErrorEnforcement could not be reached AND enforcementOnOutage is fail_closed. Under the default fail_open this is NOT thrown — the call returns allowed:true instead, which is what onEnforcementBypassed reports.
PolicyDeniedErrorA policy denied the action outright, as distinct from a block-mode violation.
ApprovalTimeoutErrorAn approval was required and no decision arrived before the timeout elapsed.
ApprovalVerificationErrorverifyApproval() could not confirm the approval covers this action.
CertificateMismatchErrorThe approval certificate does not bind to the action being performed — a swapped or replayed certificate.
ToolIntegrityErrorA presented MCP tool descriptor diverges from the pinned baseline.
ValidatorDeniedErrorA custom (BYOV) validator returned a deny decision.
PlanLimitExceededErrorA plan limit was hit AND planLimitBehavior is fail_closed. Under the default fail_open execution continues unmonitored and the bypass is reported instead.
QuotaExceededErrorTrace ingestion quota for the billing period is exhausted.
EnforcementHaltErrorAn adapter halted the run because enforcement could not be completed safely.
MetadataContractErrorSealed action metadata was altered between enforcement and execution.
ExeclaveAuthErrorThe API key or token was rejected.
ExeclaveErrorBase class for every error above — catch this to handle any SDK failure generically.

Python raises the same set under snake_case module paths (execlave.errors), with identical class names.

§ 05

Privacy & PII scrubbing

The TypeScript SDK can score every input for prompt-injection likelihood and tag the resulting trace with that score. This is metadata only — it does not block the LLM call. To actually block injection attempts, create an injection_scan policy in block mode and call exe.enforcePolicy() before your LLM invocation. Server-side PII scrubbing is performed by the processing service on ingestion.

const exe = new Execlave({  apiKey: process.env.EXECLAVE_API_KEY!,  enableInjectionScan: true,  // tags traces with injection score (does NOT block)}); // To block: create a block-mode injection_scan policy in the dashboard,// then gate every LLM call with enforcePolicy().await exe.enforcePolicy({ agentId: 'support-bot', input: userQuestion });
§ 06

OpenTelemetry integration

Switch the SDK into OTLP transport by setting mode: 'otlp' and pointing otlpEndpoint at the base URL of your OTLP collector (the SDK appends /v1/traces automatically). Use an OTLP-capable collector — do not point this at the Execlave REST API.

import { Execlave } from '@execlave/sdk'; const exe = new Execlave({  apiKey: process.env.EXECLAVE_API_KEY!,  mode: 'otlp',  // Base URL of your OTLP collector — exporter appends /v1/traces.  // e.g. http://localhost:4317 or your managed collector's base URL.  otlpEndpoint: process.env.OTLP_ENDPOINT!,}); // Traces emitted by the SDK are exported via OTLP instead of the// native REST ingest, so they flow through your existing collector// pipeline alongside the rest of your telemetry.
SDK Reference — Execlave Docs