Skip to Content
ZeroLeaksDocs
API reference

SDK reference

Methods, options and types of the @zeroleaks/sdk client.

The client exposes one namespace for each ZeroLeaks scan type and calls the versioned /api/v1 REST API. For walkthroughs of each scan type, see ZeroLeaks SDK.

import { ZeroLeaks } from "@zeroleaks/sdk";

const zeroleaks = new ZeroLeaks();

Client

new ZeroLeaks(options?) creates a client. createZeroLeaks(options?) is an equivalent factory.

interface ZeroLeaksOptions {
  apiKey?: string;
  baseUrl?: string;
  timeoutMs?: number;
  fetch?: typeof globalThis.fetch;
}
OptionDefault
apiKeyprocess.env.ZEROLEAKS_API_KEY
baseUrlhttps://zeroleaks.ai
timeoutMs30 seconds per HTTP request
fetchThe runtime's global fetch
const zeroleaks = new ZeroLeaks({
  apiKey: process.env.ZEROLEAKS_API_KEY,
  timeoutMs: 60_000,
});

The constructor throws a ZeroLeaksError with code MISSING_API_KEY when no API key is available and INVALID_API_KEY when the API key does not start with zl_live_. Every request sends an X-ZeroLeaks-SDK: typescript/<version> header.

Namespaces

NamespacePurpose
scansHistorical system-prompt scans (retired: get, list, wait, and cancel only; create and run throw PROMPT_SCANS_RETIRED)
runtimeScansAgent scans that execute through local application code
endpointConfigsDeployed HTTP agent configuration
endpointScansAgent scans against deployed HTTP agents
skillScansRepository, URL, and ZIP skill scans
reportsPrompt-scan report retrieval
healthUnauthenticated service health
capabilitiesModels, modes, surfaces, and API limits

agentConfigs and agentScans remain compatibility aliases for endpointConfigs and endpointScans.

Health and capabilities

await zeroleaks.health.check();
await zeroleaks.capabilities.get();

Neither method requires authentication. They send no API key, so they work with a revoked API key or one without access to the workspace. The constructor still needs a well-formed API key. To check the API before you have one, call GET /api/v1/health or GET /api/v1/capabilities directly.

capabilities.get() returns supported scan modes, target models, reasoning efforts, knowledge profiles, attack surfaces, adapters, and API limits.

Runtime scans

To set up a runtime scan, see Runtime scans.

MethodDescriptionReturns
runtimeScans.create(definition, options?)Start the hosted workflow without a local runnerCreateRuntimeScanResponse
runtimeScans.get(id, signal?)Read scan state and reportRuntimeScan
runtimeScans.list(options?)List runtime scansRuntimeScanListResponse
runtimeScans.run(target, options?)Create the scan, execute relay events, and return the report{ scan, report }
runtimeScans.cancel(id)Cancel the hosted workflow{ success: boolean }

create() takes a RuntimeTargetDefinition and RuntimeScanOptions. run() takes a RuntimeScanTarget and RuntimeRunOptions.

In the run() result, report is an AgentReport. get() and list() return scans with credential-shaped values in target and options scrubbed.

await zeroleaks.runtimeScans.run(target, {
  eventConcurrency: 4,
  workerStallTimeoutMs: 6 * 60_000,
  scan: { scanMode: "full" },
});

Target

interface RuntimeScanTarget {
  describe(): RuntimeTargetDefinition | Promise<RuntimeTargetDefinition>;
  invoke(invocation: RuntimeTargetInvocation):
    | RuntimeTargetResponse
    | string
    | Promise<RuntimeTargetResponse | string>;
  reset?(sessionId: string): void | Promise<void>;
}

Create a target with createRuntimeTarget(options), or keep the type of an existing target object with defineRuntimeTarget(target). Provider adapters are exported from @zeroleaks/sdk/ai-sdk and @zeroleaks/sdk/openai. See AI SDK and OpenAI.

Run options

interface RuntimeRunOptions extends WaitOptions<RuntimeScan> {
  eventConcurrency?: number;
  eventPollIntervalMs?: number;
  workerStallTimeoutMs?: number;
  onEvent?: (event: RuntimeScanEvent) => void | Promise<void>;
  scan?: RuntimeScanOptions;
}
OptionDefaultDescription
eventConcurrency8How many isolated target sessions the local runner may execute at once. Capped at 16. Events within one session remain ordered.
workerStallTimeoutMsSix minutesCancels a run when the hosted workflow stops making progress.

Scan options

interface RuntimeScanOptions {
  workspaceId?: string;
  scanMode?: "full" | "quick"; // defaults to full
  targetModel?: string;
  temperature?: number;
  reasoningEffort?: "low" | "medium" | "high";
  knowledgeProfile?: "baseline" | "production" | "research";
  attackSurfaces?: AttackSurface[];
  usePineconeKnowledge?: boolean;
  maxAdaptiveCandidates?: number;
}
scanModeBehavior
full (default)Covers every attack surface and ignores attackSurfaces. Uses the production knowledge profile unless you pass research, always uses adaptive knowledge, and raises maxAdaptiveCandidates to at least 10.
quickHonors attackSurfaces, knowledgeProfile, usePineconeKnowledge, and maxAdaptiveCandidates. Skips the production probe catalog.

Endpoint scans

To register an endpoint and scan it, see Endpoint scans.

Endpoint configurations

MethodReturns
endpointConfigs.create(input){ id: string }
endpointConfigs.list(workspaceId?)AgentConfigListResponse
endpointConfigs.update(configId, input){ success: boolean }
endpointConfigs.delete(configId){ success: boolean }
interface AgentConfigInput {
  name: string; // up to 200 characters
  endpointUrl: string;
  authMethod?: "none" | "bearer" | "api_key" | "custom_header";
  authValue?: string; // write-only
  authHeaderName?: string; // required for custom_header
  requestFormat?: AgentRequestFormat;
  description?: string;
  tools?: AgentTool[];
  plantedSecret?: string; // write-only canary, 8-200 characters with a digit or separator
  workspaceId?: string; // create only
}

AgentConfig, returned by list(), omits authValue and plantedSecret and reports authValueConfigured and plantedSecretConfigured instead.

update() is a partial update: send only the fields you want to change. Omitted fields keep their stored values, including authValue and plantedSecret. requestFormat is merged key by key, and requestFormat.headers is replaced as a whole when you send it. Set plantedSecret: "" to clear the canary. See Plant a canary.

plantedSecret and plantedSecretConfigured are typed in @zeroleaks/sdk 0.3.0 or later. Version 0.2.2 sends the configuration unchanged, so plantedSecret reaches the API but requires a type cast.

Scan methods

MethodReturns
endpointScans.create(configId)Scan and workflow identifiers
endpointScans.get(scanId, signal?)AgentScanResult
endpointScans.list(workspaceId?)AgentScanListResponse
endpointScans.wait(scanId, options?)AgentScanResult
endpointScans.run(configId, options?)Completed AgentScanResult
endpointScans.cancel(scanId){ success: boolean }

AgentScanResult is { scan, config, report }. report is null until the scan completes and then holds an AgentReport. Endpoint scans take no scan options and always run full coverage.

const result = await zeroleaks.endpointScans.run(configId, {
  onPoll: ({ scan }) => console.log(scan.currentPhase),
});

console.log(result.report?.overallScore);
console.log(result.report?.components);

Skill scans

skillScans scans skill repositories, URLs, local archives, and manifests. To run one, see Skill scans.

MethodDescriptionReturns
skillScans.create(input)Start a remote-source or synchronous scanCreateSkillScanResponse | Record<string, unknown>
skillScans.uploadArchive(file, options?)Upload a ZIP archiveCreateSkillScanResponse | Record<string, unknown>
skillScans.get(scanId, signal?)Get scan state and reportSkillScanResult
skillScans.list(limit?)List recent scansSkillScanListResponse
skillScans.wait(scanId, options?)Poll until terminalSkillScanResult
skillScans.run(input, options?)Create an asynchronous scan and wait for completionSkillScanResult

create() takes a CreateSkillScanRequest. uploadArchive() takes the same options without source, plus fileName. run() takes them without delivery.

OptionTypeSets
sourcestringSource to scan. Required.
sourceType"skill" | "mcp"Source type. "mcp" scans an MCP server.
mcpAuthorizationstringAuthorization header value for an MCP server
skillstringSkill to scan
delivery"async" | "sync"Delivery mode
webhookUrl, webhookSecretstringWebhook delivery
model, behaviorModelstringStatic and behavior models
maxFiles, maxBytesnumberFile limits
toolProfileSkillToolProfileTool profile
modeSkillScanModeScan mode
behaviorTrials, behaviorAdaptiveLimitnumberBehavior trial limits
includeAssetsbooleanAsset inclusion
timeoutMsnumberRequest timeout
const result = await zeroleaks.skillScans.run({
  source: "https://github.com/acme/agent-skill",
  mode: "full",
  toolProfile: "networked",
});

Reports

The reports namespace only returns reports from prompt scans, all of which predate the prompt-scan retirement.

MethodReturns
reports.get(reportId)ScanReport
reports.getByScan(scanId)ScanReport
reports.list(options?)ReportListResponse
const report = await zeroleaks.reports.getByScan(scanId);

console.log(report.overallScore);
console.log(report.overallVulnerability);
console.log(report.findings);
console.log(report.recommendations);

A ScanReport can include extraction and injection scores, findings, attack-family statistics, sandbox tool logs, exposed canaries, kill chains, prompt remediation, and knowledge-version metadata.

Agent reports

Runtime and endpoint scans return an AgentReport on the scan result from runtimeScans.get() or endpointScans.get(). See Reports for field details.

FieldDetails
overallScore, overallVulnerability, attacksRun, summary, recommendations, conversationLog, containmentOn every agent report
componentspromptSecurity, toolSafety, multiTurnResilience, dataLeakage
boundaryAssuranceIncludes secretsInContext, attackQuality, strategy, fingerprint, priorFingerprint, campaignStates, and searchTree
toolTrace, targetRuntime reports only

@zeroleaks/sdk 0.3.0 or later exports a type for each part of the report: AgentReportComponent, AgentFinding, BoundaryAssurance, BoundaryInvariant, SecretsInContextSummary, SecretLeak, DefenseFingerprint, and CampaignState.

Types

All public SDK types are exported from @zeroleaks/sdk.

Polling

interface WaitOptions<T> {
  pollIntervalMs?: number;
  timeoutMs?: number;
  signal?: AbortSignal;
  onPoll?: (value: T) => void | Promise<void>;
}

Attack surfaces

type AttackSurface =
  | "direct_chat"
  | "indirect_content"
  | "tool_calling"
  | "mcp"
  | "repo_ci"
  | "rag_vector"
  | "multi_turn";

Report unions

Exported by @zeroleaks/sdk 0.3.0 or later.

type SecretLeakClass =
  | "credential"
  | "planted_canary"
  | "authorization_rule"
  | "internal_endpoint"
  | "tool_schema"
  | "instruction_text";

type EvidenceStrength =
  | "semantic"
  | "indicator"
  | "observed_tool_call"
  | "deterministic_effect";

type FindingSeverity = "critical" | "high" | "medium" | "low" | "informational";

Errors

ErrorMeaning
ZeroLeaksErrorBase API, validation, authentication, or network error
ZeroLeaksTimeoutErrorRequest, polling, or runtime relay timed out
ZeroLeaksAbortErrorThe supplied abort signal was triggered
ZeroLeaksScanErrorA scan reached a non-success terminal state or the runtime target failed

Every error extends ZeroLeaksError, which includes status, code, details (the response body or scan result), and requestId. It also includes retryAfterMs when the response provides a Retry-After header. ZeroLeaksScanError adds scanId.

import { ZeroLeaksScanError } from "@zeroleaks/sdk";

try {
  await zeroleaks.runtimeScans.run(target);
} catch (error) {
  if (error instanceof ZeroLeaksScanError) {
    console.error(error.scanId, error.details);
  }
}

To handle errors, retries and rate limits, see Errors.

Error codes

codeSource
MISSING_API_KEY, INVALID_API_KEYClient constructor
MISSING_FETCHNo fetch implementation available
NETWORK_ERRORThe API could not be reached
TIMEOUT, ABORTEDZeroLeaksTimeoutError, ZeroLeaksAbortError
SCAN_FAILEDZeroLeaksScanError
INVALID_TARGET_RESPONSEA runtime target returned something without text; arrives as the details of a ZeroLeaksScanError
SUBSCRIPTION_LIMITAPI 403: no scan access on the current plan or workspace
SCAN_CONCURRENCY_LIMIT, SCAN_HOURLY_LIMITAPI 429: plan rate limit
PROMPT_SCANS_RETIREDAPI 410 from scans.create and scans.run: hosted prompt scans are retired. Do not retry.

On this page