The official JavaScript/TypeScript SDK for the Seclai API. Provides full typed coverage of all API endpoints, file uploads, SSE streaming, polling helpers, and automatic pagination.
Works in Node.js 18+, Deno, Bun, Cloudflare Workers, and any runtime with a fetch implementation.
npm install @seclai/sdk
import { Seclai } from "@seclai/sdk";
const client = new Seclai({ apiKey: process.env.SECLAI_API_KEY });
// List all sources
const sources = await client.listSources();
// Run an agent and stream the result
const result = await client.runStreamingAgentAndWait(
"agent_id",
{ input: "Summarize the latest uploads", metadata: {} },
{ timeoutMs: 120_000 },
);
console.log(result);
| Option | Environment variable | Default |
|---|---|---|
apiKey |
SECLAI_API_KEY |
— |
accessToken |
— | — |
profile |
SECLAI_PROFILE |
"default" |
configDir |
SECLAI_CONFIG_DIR |
~/.seclai |
autoRefresh |
— | true |
accountId |
— | — |
baseUrl |
SECLAI_API_URL |
https://api.seclai.com |
apiKeyHeader |
— | x-api-key |
defaultHeaders |
— | {} |
fetch |
— | globalThis.fetch |
Credentials are resolved via a chain (first match wins):
apiKey optionaccessToken option (string or () => string | Promise<string>)SECLAI_API_KEY environment variable~/.seclai/sso/cache/ (requires a prior seclai auth login)// API key
const client = new Seclai({ apiKey: "sk-..." });
// Static bearer token
const client = new Seclai({ accessToken: "eyJhbGciOi..." });
// Dynamic bearer token provider (called per request)
const client = new Seclai({
accessToken: async () => fetchTokenFromVault(),
});
// SSO profile (uses cached tokens, auto-refreshes)
const client = new Seclai({ profile: "my-profile" });
// Environment variable (no options needed)
// export SECLAI_API_KEY="sk-..."
const client = new Seclai();
SSO is the default fallback when no explicit credentials are provided. The SDK
includes built-in production SSO defaults, so seclai configure sso is not
required. You only need to log in once to populate the token cache:
npx @seclai/cli auth login # authenticate via browser — no prior setup needed
To customize SSO settings (e.g. for a staging environment), use seclai configure sso
or set environment variables:
| Variable | Description | Default |
|---|---|---|
SECLAI_SSO_DOMAIN |
Cognito domain | auth.seclai.com |
SECLAI_SSO_CLIENT_ID |
Cognito app client ID | 4bgf8v9qmc5puivbaqon9n5lmr |
SECLAI_SSO_REGION |
AWS region | us-west-2 |
Online API documentation (latest):
https://seclai.github.io/seclai-javascript/latest/
Release history is in CHANGELOG.md.
The API dates its backward-incompatible changes. Nothing changes for you until you opt in, either per client or by pinning the account:
const client = new Seclai({
apiKey: "...",
apiVersion: SeclaiApiVersion.V2026_07_27, // sent as the Seclai-Version header
});
const state = await client.getApiVersion(); // what this request resolved to
await client.updateApiVersion(SeclaiApiVersion.V2026_07_27); // pin the whole account
Leave apiVersion unset and the header is omitted, so the account's pinned
baseline applies and responses keep their current shapes. Upgrading this package
alone never changes the wire contract.
Known versions are on SeclaiApiVersion (V2026_07_01 through V2026_11_04,
plus Default and Latest), imported from @seclai/sdk. A version this release was
not built against throws at construction: a newer version can reshape
responses, and this client would decode them incorrectly rather than reject them.
The same check applies to a Seclai-Version set through defaultHeaders or the
per-request headers of request() / requestRaw(), in any letter case, and an
empty value is rejected. Upgrade the package to adopt a new version, or set
allowUnknownApiVersion if you have to move first and accept that risk.
The guard only covers the header. An account pinned server-side can still be
newer than this release — getApiVersion() reports the effective_version the
request resolved to, and comparing it against SeclaiApiVersion.Latest is how
you detect the gap.
What 2026-07-27 changes. Undeclared query parameters become a 422 instead
of being ignored, and every list endpoint that answered with a bare array or
under a per-resource key moves to the canonical {data, pagination} envelope.
The methods for those endpoints return their declared type on either shape, so
code written against the default still reads the result after you opt in. Four
of them return fewer rows once you do, covered below the table:
| Declared return | Methods | From 2026-07-27 |
|---|---|---|
| An array | listEvaluationCriteria(), getAgentCallers(), listInboundEmailRejections(), listGovernanceAiConversations(), listSolutionConversations(), listModels(), listMemoryBankTemplates(), getAgentsUsingMemoryBank(), listCloudDriveProviders(), listCloudDrives(), getAgentsUsingCloudDrive(), listCloudDriveRejections() |
Still the array of items; the page metadata is not returned |
data, bare array by default |
listEvaluationCriteriaPage(), listRunEvaluationResults() |
data, plus pagination |
data with flat total/page/limit |
listEvaluationResults(), listAgentEvaluationResults(), listEvaluationRuns(), listCompatibleRuns() |
Unchanged, plus pagination |
| A per-resource key | listAgentEmailOptOuts() and listBlockedEmailSenders() / setAutoBlockMode() (items), listAlertConfigs() (configs), listOrganizationAlertPreferences() (preferences), listEmailDomains() (domains), listKnowledgeBases() (knowledge_bases), listMemoryBanks() (memory_banks), getGenerationTiers() (tiers), listModelAlerts() (alerts), listExperiments() (experiments), listEmbeddingModels() and listRerankerModels() (models) |
The same key and any flat total/page/limit, plus data and pagination |
Where a type declares flat total, page or limit, the client fills them
from pagination after you opt in. listRunEvaluationResults() has no counters
on its default bare array, and gains them with pagination. Fields that sit
beside a list, such as auto_block_mode or the email-domain plan capabilities,
are present on both shapes.
Opting in also turns paging on for endpoints that returned everything by default, so the same call can return fewer rows:
listEvaluationCriteria() and listRunEvaluationResults() return every item
by default and one page (20 unless you pass limit) after you opt in. The
array from listEvaluationCriteria() carries no sign of that; use
listEvaluationCriteriaPage() to see pagination.listAlertConfigs() ignores page and limit by default and returns every
config; after you opt in it returns one page.setAutoBlockMode() reports the account's full total by default, and the
number of rows it returned after you opt in.Later versions. Each is cumulative. Some change a value you may be reading,
a request that used to succeed, or (from 2026-10-21) which fields can be
null:
2026-09-30 and 2026-10-16 change what a string you may be parsing
contains — a run's output, and a run's input when it has uploads.2026-10-05 changes a value you may branch on: an item held for review
reports content_status completed instead of failed, so code that looks
for governance holds among failed items stops finding them. Check
held_for_review instead.2026-10-13 and 2026-10-19 reject with a 400 source settings that were
accepted before.2026-10-21 changes evaluation numbers you may be reading: an error result
no longer counts as failed or toward the rates, and testDraftEvaluation()
returns null score and passed for one.2026-10-28 changes what an if_else or switch step's output contains.
Read the arm it took from the step's decision, which is set on every version.2026-11-02 refuses an agent write that references a metadata key no trigger
declares, where older versions declare the key for you.2026-11-04 rejects with a 400 evaluation settings that were accepted before.| Version | What it changes |
|---|---|
2026-08-03 |
createMemoryBank() and updateMemoryBank() reject a non-zero max_age_days with a 400, and a memory bank's max_age_days reads as null. On create, an omitted retention_days resolves per bank type instead of to 30 |
2026-08-21 |
createSource() rejects an embedding dimension its embedder does not support with a 400 — listEmbeddingModels() reports the supported ones |
2026-09-28 |
Agent-definition writes use the current file-list grammar: an omitted attachments keeps the stored list and [] means no files |
2026-09-30 |
Breaks code that parses output. A run's and a step's output, and a step's input, are the plain text; below this version an output that has files is a JSON manifest string ({schema, text, attachments}). Read files from attachments, which is populated on every version |
2026-10-03 |
A new LLM step written without attachments takes its parent's files, and a new retrieval step's matched media are its files |
2026-10-05 |
An item held for review by an Enforce governance policy reports content_status completed (with held_for_review: true) from listSourceContents() and getSourceContentStatus(). Below it the item reports failed with the hold as the error |
2026-10-13 |
createSource() and updateSource() reject a media_types value other than images or video, or any value on a source that is not a website or RSS feed, with a 400. Below it an unknown value is dropped |
2026-10-16 |
uploadAgentInput() accepts a file of any type and it is ready at once. Each step receives the file itself when its model reads that type, and its text otherwise; a run's input carries only a # filename heading per file. Below it only a fixed list of extensions is accepted and each file's extracted text is written into input, so poll getAgentInputUploadStatus() before running |
2026-10-18 |
A source's document_images defaults to true on every embedder. Below it it defaults to false on a text-only embedder |
2026-10-19 |
createSource() rejects polling_max_items on any source type but an RSS feed with a 400. Below it the value is stored |
2026-10-21 |
An evaluation result whose evaluator returned no verdict (error) is left out of failed and of pass_rate / failure_rate in getNonManualEvaluationSummary(), and getEvaluationCriteriaSummary() averages average_score over passed and failed results only. testDraftEvaluation() returns score and passed as null for an error result. Below it the summary counts error results in failed and the rates, average_score includes their stored scores, and the test draft returns score 0.5 and passed: false. The summary's error count is returned on every version |
2026-10-28 |
An if_else or switch step's output is the result of the arm it took, or its input when that arm is empty or it took none. Below it the output is a {"branch": ...} marker naming the arm, with no attachments. The step's decision names the arm on every version |
2026-11-02 |
updateAgentDefinition(), and updateAgent() when it sets sampling_config, refuse a definition or sampling rule that references a metadata key no trigger declares, with a 400 and a 422 respectively. Declare the key first with setMetadataKeys(). An agent_definition import through createAgent() or updateAgent() is not refused and still declares the keys it reads. Below it each such key is declared on the trigger as optional |
2026-11-04 |
createEvaluationResult() rejects retry_triggered: true and updateAgent() rejects evaluation_mode eval_and_retry with a 400: evaluations never retry a step. createEvaluationCriteria(), and updateEvaluationCriteria() when it changes step_id, reject a step_id that does not name a display_result or streaming_result step with a 400. Below it eval_and_retry is stored as sample_and_flag |
Latest moves with the SDK. SeclaiApiVersion.Latest is the newest version
the installed release knows, so upgrading the package can opt a client that
passes it into every version added since — 1.6.0 moved it from 2026-07-27 to
2026-10-03, across the 2026-09-30 output change, and 1.7.0 moves it to
2026-10-21, across the 2026-10-05 status change, the 2026-10-13 and
2026-10-19 source-setting rejections, the 2026-10-16 input change and the
2026-10-21 evaluation change, 1.8.0 moves it to 2026-10-28,
across the if_else / switch step-output change, and 1.9.0 moves it to
2026-11-04, across the 2026-11-02 undeclared-metadata-key refusal and the
2026-11-04 evaluation-setting rejections. Pass a
dated constant such as SeclaiApiVersion.V2026_07_27 to keep behaviour fixed
across upgrades.
Two type changes can stop existing code compiling. If you pass
SeclaiApiVersion.Latest, it now sends 2026-10-21; the table above lists
what each version changes.
testDraftEvaluation() can return null scores. When the evaluator
returns no verdict, status is error. From API version 2026-10-21, score
and passed are then null. An account created after 2026-10-21 ships gets
that version even without setting apiVersion. Check status before reading
them, in JavaScript too; under strictNullChecks the type enforces it:
const result = await client.testDraftEvaluation("agent_id", { step_output: "...", pass_threshold: 0.7 });
// 1.6 and earlier: console.log(result.score.toFixed(2), result.passed);
if (result.status === "error") {
console.log("No verdict:", result.explanation);
} else {
console.log(result.score.toFixed(2), result.passed); // number and boolean here
}
InsufficientCreditsResponse matches the 402 body. Read the code at
error.code, not detail.error. Code that cast a 402 body to this type threw
on every real 402 before, so this only fixes it.
Discover who the credential belongs to and which organizations it can act for.
Each organization's account_id is what you pass as the client's accountId
option (sent as the X-Account-Id header) to target that org context.
const me = await client.getMe();
console.log(me.account_id); // the user's personal account
for (const org of me.organizations) {
console.log(org.name, org.account_id);
}
// Act as an organization
const orgClient = new Seclai({ accountId: me.organizations[0].account_id });
// CRUD
const agents = await client.listAgents({ page: 1, limit: 20 });
const agent = await client.createAgent({ name: "My Agent", description: "..." });
const fetched = await client.getAgent("agent_id");
const updated = await client.updateAgent("agent_id", { name: "Renamed" });
await client.deleteAgent("agent_id");
// Run and credit limits. To remove one, send its set_max_* flag and omit the value.
await client.updateAgent("agent_id", { max_runs_per_hour: 60, max_credits_per_period: 500 });
await client.updateAgent("agent_id", { set_max_runs_per_hour: true });
// Pause / resume — a disabled agent stops firing from every trigger path
const callers = await client.getAgentCallers("agent_id"); // live agents calling this one
await client.disableAgent("agent_id"); // 409 if any caller above is still live
await client.enableAgent("agent_id");
// Definition (step workflow)
const def = await client.getAgentDefinition("agent_id");
await client.updateAgentDefinition("agent_id", { steps: [...], change_id: def.change_id });
// Export / import an agent
const exported = await client.exportAgent("agent_id");
// Validate the payload first to surface unresolved entity refs in this account
const preview = await client.previewImportAgent({ agent_definition: exported });
const unresolved = (preview.unresolved_refs ?? []) as Array<{ ref_id: string }>;
const entity_remap = Object.fromEntries(
unresolved.map((ref) => [ref.ref_id, /* picked target uuid */ ""]),
);
// Commit — `entity_remap` substitutes workflow refs before save
const imported = await client.createAgent({
name: "Imported",
trigger_type: "dynamic_input",
agent_definition: exported,
entity_remap,
});
// `imported.import_warnings` lists any items that couldn't be applied.
The agent gallery lists example agents to start from. Pass an entry's key as
agent_template to createAgent(). Bind each resource the template needs with
resource_bindings, or set create_missing_resources to have the API create the
ones you leave out; created_resources reports what it made.
const examples = await client.listAgentExamples({ query: "support", useCase: "customer_support", limit: 10 });
const example = examples.data[0];
console.log(example.key, example.title, examples.pagination.total);
for (const slot of example.resources) {
console.log(slot.slot, slot.kind, slot.creatable); // what resource_bindings can bind
}
const agent = await client.createAgent({
name: "Support triage",
agent_template: example.key,
resource_bindings: { [example.resources[0].slot]: "kb_id" },
create_missing_resources: true,
});
console.log(agent.created_resources); // { slot: resource_id } for each resource it created
// Start a run
const run = await client.runAgent("agent_id", { input: "Hello" });
// List & search runs
const runs = await client.listAgentRuns("agent_id", { status: "completed" });
const search = await client.searchAgentRuns({ agent_id: "...", status: ["completed"] });
// Fetch run details (optionally with step outputs)
const detail = await client.getAgentRun("run_id", { includeStepOutputs: true });
// Cancel or delete
await client.cancelAgentRun("run_id");
await client.deleteAgentRun("run_id");
The SDK provides two streaming patterns over the SSE /runs/stream endpoint:
Block until done — returns the run from the done event. If timeoutMs
elapses first, it throws SeclaiStreamingError, whose run holds the latest
snapshot: the result snapshot if one arrived, else the init snapshot. An
abort through signal rethrows the abort error.
By default, a stream that ends before done returns the latest snapshot when
its status is not pending, so the run returned may not have finished: check
status and result_reported_at. A stream that breaks throws the fetch error.
Pass throwOnIncomplete: true to throw SeclaiStreamingError, with the snapshot
in run, in both cases instead, and also when the server answers with plain
JSON for a run that has not finished. It is recommended, and becomes the default in
the next major version:
const result = await client.runStreamingAgentAndWait(
"agent_id",
{ input: "Hello", metadata: {} },
{ timeoutMs: 60_000, throwOnIncomplete: true },
);
Async iterator — yields every SSE event as { event, data }:
for await (const event of client.runStreamingAgent(
"agent_id",
{ input: "Hello" },
{ timeoutMs: 120_000 },
)) {
console.log(event.event, event.data);
if (event.event === "done") break;
}
When the server answers with plain JSON instead of an SSE stream,
runStreamingAgent yields only a done event, so read the answer from it.
A result event carries the run's answer in output once result_reported_at
is set. It comes before done, and for an agent that reports its result early it
can arrive while later steps still run. Pass returnOnResult: true to
runStreamingAgentAndWait to return that result snapshot without waiting for
done. Such a run may still be in progress: its status is not terminal and the
run can still fail, so check result_reported_at, not status:
const run = await client.runStreamingAgentAndWait("agent_id", { input: "Hello" }, { returnOnResult: true });
if (run.result_reported_at) console.log(run.output);
On a timeout, or with throwOnIncomplete on a cut stream, read the answer, if
one was reported, from the error's run:
import { SeclaiStreamingError } from "@seclai/sdk";
try {
const run = await client.runStreamingAgentAndWait("agent_id", { input: "Hello" }, { throwOnIncomplete: true });
console.log(run.output);
} catch (err) {
if (err instanceof SeclaiStreamingError && err.run?.result_reported_at) {
console.log("Answer, run not finished:", err.run.output);
} else {
throw err;
}
}
Pass include_reasoning: true to also receive stream_reasoning events carrying
the model's reasoning while it thinks. They are sent only for a
streaming_result step whose author enabled show_reasoning, and reasoning is
never part of output:
for await (const event of client.runStreamingAgent("agent_id", {
input: "Hello",
include_reasoning: true,
})) {
if (event.event === "stream_reasoning") console.log(event.data);
}
For environments where SSE is not practical, poll for a completed run:
const result = await client.runAgentAndPoll(
"agent_id",
{ input: "Hello" },
{ pollIntervalMs: 2_000, timeoutMs: 120_000 },
);
A run's answer can be ready before its last step finishes: once
result_reported_at is set on getAgentRun(), output holds the answer. Pass
returnOnResult: true to return as soon as a run has it set, the one
runAgent() returns included. With includeStepOutputs, when that run would end
the poll and signal is not aborted, it is fetched again at once, because the
runAgent() response carries no step outputs; after an abort it comes back
without step outputs. Such a run may still be in progress: its status
is not terminal and the run can still fail, so check result_reported_at, not
status. If timeoutMs elapses first, it throws SeclaiStreamingError with the
latest run it has (the runAgent() response if no poll ran) in run.
const run = await client.runAgentAndPoll("agent_id", { input: "Hello" }, { returnOnResult: true });
if (run.result_reported_at) console.log(run.output);
// Discover which files (if any) the agent expects before staging uploads
const refs = await client.getAgentAttachmentReferences("agent_id");
if (refs.requires_uploads) {
// refs.agent lists the exact_names / indexes_max / patterns a run batch must satisfy
}
const upload = await client.uploadAgentInput("agent_id", {
file: new Uint8Array([/* file bytes */]),
fileName: "input.pdf",
});
// From API version 2026-10-16 the upload is `ready` at once. Below it, poll
// until `status` is `ready` before running.
let status = await client.getAgentInputUploadStatus("agent_id", upload.id);
while (status.status !== "ready") {
if (status.status === "failed") throw new Error(`Upload failed: ${status.error}`);
await new Promise((resolve) => setTimeout(resolve, 1_000));
status = await client.getAgentInputUploadStatus("agent_id", upload.id);
}
const run = await client.runAgent("agent_id", { input_upload_id: upload.id, priority: false });
Only a dynamic_input agent takes uploads; any other agent rejects one with a
400.
// Download a file emitted by a step in an agent run. The attachment_id is the
// URL-safe-base64 storage_key surfaced in run output manifests / webhooks.
const resp = await client.downloadAgentRunAttachment("run_id", "attachment_id");
const blob = await resp.blob(); // raw Response — stream or save the bytes
Configure the inbound address and handling rules on an agent's EMAIL_RECEIVED
trigger. Omitted fields are left unchanged; null (or "" for alias) clears them.
const config = await client.setEmailTriggerConfig("agent_id", "trigger_id", {
alias: "support",
allowed_senders: ["example.com", "ops@partner.com"], // empty/null accepts any sender
ignore_auto_generated: true, // drop auto-replies/bulk mail to prevent loops
require_sender_auth: true, // require SPF or DMARC even on an open inbox
queue_on_quota: false, // park over-rate mail instead of failing it
});
console.log(config.email_addresses); // ["support.<accountID>@agent.seclai.com", ...]
Set run_on_attachment_mismatch: true to run an email whose attachments do not
fit what the agent accepts: files it cannot take are left out and the problems
are listed in the run's email_attachment_issues metadata. By default the run fails.
Configure an agent's SLACK_COMMAND trigger, which people run from Slack with
/seclai <alias> or the message shortcut. Omitted fields are left unchanged.
alias is generated from the agent's name when not set; the text after the alias,
or the message the shortcut was used on, is the run's input. input is
deprecated and ignored by the API.
const slack = await client.setSlackTriggerConfig("agent_id", "trigger_id", {
alias: "support", // people run `/seclai support`
scope: "selected_channels", // or "bot_channels"
channel_ids: ["C0123456789"],
activation: "everywhere", // or "channel_opt_in"
visibility: "private", // or "channel"
allow_dms: true,
turns_enabled: true, // let people keep the conversation going
max_turns: 5,
form: [{ key: "ticket", label: "Ticket ID", type: "short_text", required: true }],
});
console.log(slack.missing_scopes); // Slack scopes the connection lacks for optional features
Each form value reaches the run as {{metadata.<key>}}.
Declare the input attachments a trigger accepts. A run's files are each assigned
to one named slot before any step runs, and steps reference a slot as
{{agent.attachments.<name>}}. The call replaces the whole declaration, and is
refused with a 400 when the agent references a slot it leaves out. min defaults
to 0. The same slots can be set as accepted_attachments on createAgent() and
updateAgentDefinition().
const agent = await client.getAgent("agent_id");
const { accepted_attachments } = await client.setAcceptedAttachments("agent_id", agent.trigger_id!, {
accepted_attachments: [
{ name: "invoice", content_types: ["application/pdf"], min: 1, max: 1 },
{ name: "photos", content_types: ["image/*"], label: "Photos of the damage" },
],
});
console.log(accepted_attachments.map((slot) => `${slot.name}: ${slot.min}..${slot.max ?? "any"}`));
Declare the run metadata keys a trigger provides, which steps reference as
{{metadata.<key>}}. system and source keys are written by the platform;
custom keys are sent by the caller or set on the trigger, and only a custom
key can be required (default false): a caller-started run without it is
refused. A run is also refused with a 400 when its metadata sends a custom key
the trigger does not declare, on every API version, so declare custom keys with
setMetadataKeys() before sending them in a run's metadata. The call replaces
the whole declaration, and is refused with a 400 when the agent references a key
no trigger of its branch declares.
const agent = await client.getAgent("agent_id");
const current = await client.getMetadataKeys("agent_id", agent.trigger_id!);
console.log(current.declarable_keys.map((k) => `${k.key} (${k.origin})`));
const updated = await client.setMetadataKeys("agent_id", agent.trigger_id!, {
metadata_keys: [
{ key: "customer_id", origin: "custom", required: true },
{ key: "region", origin: "custom" },
],
});
console.log(updated.warnings); // agents whose `call_agent` mapping no longer fits
// Recipients who opted out of this account's agent emails
const optOuts = await client.listAgentEmailOptOuts({ agentId: "agent_id", limit: 50 });
await client.removeAgentEmailOptOut("optout_id"); // opt them back in
// Blocked inbound senders (owner/admin only)
const blocked = await client.listBlockedEmailSenders({ limit: 50, offset: 0 });
await client.blockEmailSender({ sender_email: "spam.example.com", match_type: "domain" });
await client.unblockEmailSender("blocked_id");
// Auto-block on a governance BLOCK: "disabled" | "input" | "input_and_output"
await client.setAutoBlockMode({ mode: "input_and_output" });
// Inbound emails discarded before running an agent
const rejections = await client.listInboundEmailRejections({ agentId: "agent_id" });
// Account-wide overload circuit breaker
const status = await client.getInboundEmailStatus(); // { paused, queued_backlog }
await client.cancelQueuedEmailRuns(); // fail all QUEUED (over-quota parked) runs
await client.resumeInboundEmail(); // one-shot override; re-arms if still overloaded
const steps = await client.generateAgentSteps("agent_id", { user_input: "Build a RAG pipeline" });
const config = await client.generateStepConfig("agent_id", { step_type: "llm", user_input: "..." });
// Conversation history
const history = await client.getAgentAiConversationHistory("agent_id");
await client.markAgentAiSuggestion("agent_id", "conversation_id", { accepted: true });
const criteria = await client.listEvaluationCriteria("agent_id", { page: 1, limit: 50 });
// page/limit only take effect with apiVersion "2026-07-27" or later; the legacy
// response is unpaginated. listEvaluationCriteriaPage() returns the same items
// plus a `pagination` object when opted in.
const created = await client.createEvaluationCriteria("agent_id", { name: "Accuracy", ... });
const detail = await client.getEvaluationCriteria("criteria_id");
await client.updateEvaluationCriteria("criteria_id", { ... });
await client.deleteEvaluationCriteria("criteria_id");
// Test a draft. Check status first: an "error" result has no verdict, and its
// score and passed can be null.
const draft = await client.testDraftEvaluation("agent_id", { step_output: "...", pass_threshold: 0.7 });
if (draft.status !== "error") console.log(draft.score, draft.passed);
// Results by criteria
const results = await client.listEvaluationResults("criteria_id", { flaggedOnly: true, timeFrom: "2026-10-01T00:00:00Z" });
const summary = await client.getEvaluationCriteriaSummary("criteria_id");
await client.createEvaluationResult("criteria_id", { ... });
// Results by run
const runResults = await client.listRunEvaluationResults("agent_id", "run_id");
const agentResults = await client.listAgentEvaluationResults("agent_id", { status: "failed", step: "step_id" });
const evalRuns = await client.listEvaluationRuns("agent_id", { timeFrom: "2026-10-01T00:00:00Z" });
// Non-manual evaluation summary, for one agent or the whole account
const nonManual = await client.getNonManualEvaluationSummary("agent_id", { days: 7 });
const accountWide = await client.getNonManualEvaluationSummary(undefined, { startDate: "2026-10-01", endDate: "2026-10-31" });
// Compatible runs for a criteria
const compatible = await client.listCompatibleRuns("criteria_id", { startedAfter: "2026-10-01T00:00:00Z" });
const kbs = await client.listKnowledgeBases();
const kb = await client.createKnowledgeBase({ name: "Docs KB" });
const fetched = await client.getKnowledgeBase("kb_id");
await client.updateKnowledgeBase("kb_id", { name: "Renamed KB" });
await client.deleteKnowledgeBase("kb_id");
See which item-metadata keys a knowledge base's content carries, for all time and the last 30 and 7 days:
const stats = await client.getKnowledgeBaseMetadataKeyStats("kb_id");
for (const w of stats.windows) {
console.log(w.window, w.total_items, w.keys.map((k) => `${k.key}: ${k.items}`));
}
const banks = await client.listMemoryBanks({ type: "conversation" });
const bank = await client.createMemoryBank({ name: "Chat Memory", type: "conversation" });
const fetched = await client.getMemoryBank("mb_id");
await client.updateMemoryBank("mb_id", { name: "Renamed" });
await client.deleteMemoryBank("mb_id");
// Stats & compaction
const stats = await client.getMemoryBankStats("mb_id", { startDate: "2026-10-01", endDate: "2026-10-31" });
await client.compactMemoryBank("mb_id");
// Test compaction
const test = await client.testMemoryBankCompaction("mb_id", { ... });
const standalone = await client.testCompactionPromptStandalone({ ... });
// Templates & agents
const templates = await client.listMemoryBankTemplates();
const agents = await client.getAgentsUsingMemoryBank("mb_id");
// AI assistant
const suggestion = await client.generateMemoryBankConfig({ user_input: "..." });
const history = await client.getMemoryBankAiLastConversation({ limit: 5 });
await client.acceptMemoryBankAiSuggestion("conv_id", { ... });
// Source management
await client.deleteMemoryBankSource("mb_id");
const sources = await client.listSources({ page: 1, limit: 20, order: "asc" });
const source = await client.createSource({ name: "My Source", ... });
const fetched = await client.getSource("source_id");
await client.updateSource("source_id", { name: "Renamed" });
await client.deleteSource("source_id");
A spend limit caps the credits a source may commit per billing period. When it is
reached, stop refuses new uploads and email, and delete removes entries in
spend_cap_delete_order to make room. Send null to remove the limit.
const capped = await client.updateSource("source_id", {
max_credits_per_period: 1000,
spend_cap_action: "delete",
spend_cap_delete_order: "oldest_published",
});
console.log(capped.spend_cap_reached);
await client.updateSource("source_id", { max_credits_per_period: null });
Indexing status of a source's content, keyed by the content_version_id the
upload methods return:
const failed = await client.listSourceContents("source_id", { status: "failed" });
const batch = await client.listSourceContents("source_id", {
contentVersionIds: ["cv_1", "cv_2"],
});
console.log(batch.pagination.total, failed.data.map((item) => item.error));
const one = await client.getSourceContentStatus("source_id", "cv_1");
console.log(one.content_status, one.held_for_review);
An item an Enforce governance policy blocked at import is held for review:
held_for_review is true until a reviewer releases it. Its content_status is
completed from API version 2026-10-05, and failed with the hold as the
error below it.
An email source stores mail from email_allowed_senders only, and lists what it
refused. Each entry names the sender and the reason, never the subject or body;
adding a refused sender to email_allowed_senders helps only when authenticated
is true. Listing rejections requires an account owner or administrator.
const inbox = await client.createSource({
name: "Newsletters",
source_type: "email",
email_allowed_senders: ["news@example.com", "example.org"],
});
console.log(inbox.email_address); // send mail here
const rejections = await client.listEmailSourceRejections(inbox.id, { page: 1, limit: 50 });
for (const r of rejections.data) console.log(r.from_address, r.reason, r.authenticated);
// Index the images inside documents, and an RSS feed's enclosures
await client.updateSource("source_id", { document_images: true, feed_attachments: ["enclosures"] });
A cloud_drive source takes cloud_drive_connection_id (from listCloudDrives())
on create, and cloud_drive_folder_path, cloud_drive_path_pattern,
cloud_drive_content_types and cloud_drive_max_file_mb to choose which files
it indexes.
const providers = await client.listCloudDriveProviders();
const drives = await client.listCloudDrives();
const drive = await client.getCloudDrive(drives[0].id);
await client.updateCloudDrive(drive.id, { name: "Contracts" });
// Which agents depend on it, and which files it skipped and why
const agents = await client.getAgentsUsingCloudDrive(drive.id);
const skipped = await client.listCloudDriveRejections(drive.id, { limit: 20 });
console.log(providers.length, agents.length, skipped.map((r) => r.reason));
const disconnected = await client.disconnectCloudDrive(drive.id); // keeps the connection
console.log(disconnected.connected);
await client.deleteCloudDrive(drive.id);
Upload a file to a source (max 200 MiB). The SDK infers MIME type from the file extension when mimeType is not provided.
import { readFile } from "node:fs/promises";
await client.uploadFileToSource("source_id", {
file: await readFile("document.pdf"),
fileName: "document.pdf",
title: "Q4 Report",
metadata: { department: "finance" },
});
Upload inline text:
await client.uploadInlineTextToSource("source_id", {
text: "Hello, world!",
title: "Greeting",
});
Replace a content version with a new file:
await client.uploadFileToContent("content_version_id", {
file: await readFile("updated.pdf"),
fileName: "updated.pdf",
mimeType: "application/pdf",
});
const exports = await client.listSourceExports("source_id");
const exp = await client.createSourceExport("source_id", { format: "json" });
const status = await client.getSourceExport("source_id", exp.id);
const estimate = await client.estimateSourceExport("source_id", {});
const response = await client.downloadSourceExport("source_id", exp.id);
await client.deleteSourceExport("source_id", exp.id);
await client.cancelSourceExport("source_id", exp.id);
const migration = await client.getSourceEmbeddingMigration("source_id");
await client.startSourceEmbeddingMigration("source_id", { target_model: "..." });
await client.cancelSourceEmbeddingMigration("source_id");
const detail = await client.getContentDetail("content_id", { start: 0, end: 1000 });
const embeddings = await client.listContentEmbeddings("content_id");
await client.deleteContent("content_id");
// Replace content with inline text
await client.replaceContentWithInlineText("content_id", { text: "Updated text", title: "Updated" });
// Upload a replacement file
await client.uploadFileToContent("content_id", {
file: await readFile("updated.pdf"),
fileName: "updated.pdf",
});
A content item's attachments are the files an agent step, an email, a feed, a
web page's media or a document's images added to it. Each says whether it is
indexed for search and, if indexing failed, why. An email item's
skipped_attachments (on getContentDetail()) lists the parts that were not
stored, with the reason.
const attachments = await client.listContentAttachments("content_id", { limit: 50 });
for (const att of attachments.data) {
console.log(att.id, att.content_type, att.indexed, att.indexing_error);
}
const att = await client.getContentAttachment("content_id", "attachment_id", { start: 0, end: 2000 });
console.log(att.text_content, att.file_withheld);
const vectors = await client.listContentAttachmentEmbeddings("content_id", "attachment_id");
// Raw Response; 403 while the file is withheld (see `file_withheld`).
const file = await client.downloadContentAttachment("content_id", "attachment_id");
const bytes = new Uint8Array(await file.arrayBuffer());
const solutions = await client.listSolutions({ search: "billing" });
const sol = await client.createSolution({ name: "My Solution" });
const fetched = await client.getSolution("solution_id");
await client.updateSolution("solution_id", { name: "Renamed" });
await client.deleteSolution("solution_id");
// Link / unlink resources
await client.linkAgentsToSolution("solution_id", { ids: ["agent_id"] });
await client.unlinkAgentsFromSolution("solution_id", { ids: ["agent_id"] });
await client.linkKnowledgeBasesToSolution("solution_id", { ids: ["kb_id"] });
await client.unlinkKnowledgeBasesFromSolution("solution_id", { ids: ["kb_id"] });
await client.linkSourceConnectionsToSolution("solution_id", { ids: ["source_id"] });
await client.unlinkSourceConnectionsFromSolution("solution_id", { ids: ["source_id"] });
// AI assistant
const plan = await client.generateSolutionAiPlan("solution_id", { user_input: "Set up a RAG pipeline" });
await client.acceptSolutionAiPlan("solution_id", "conversation_id", {});
await client.declineSolutionAiPlan("solution_id", "conversation_id");
// AI-generated knowledge base / source within the solution
await client.generateSolutionAiKnowledgeBase("solution_id", { user_input: "..." });
await client.generateSolutionAiSource("solution_id", { user_input: "..." });
// Conversations
const convs = await client.listSolutionConversations("solution_id");
await client.addSolutionConversationTurn("solution_id", { user_input: "..." });
await client.markSolutionConversationTurn("solution_id", "conversation_id", { ... });
const plan = await client.generateGovernanceAiPlan({ user_input: "Add a toxicity policy" });
const convs = await client.listGovernanceAiConversations({ limit: 10 });
await client.acceptGovernanceAiPlan("conversation_id");
await client.declineGovernanceAiPlan("conversation_id");
const alerts = await client.listAlerts({ status: "active", agentId: "agent_id", timeFrom: "2026-10-01T00:00:00Z" });
const alert = await client.getAlert("alert_id");
await client.changeAlertStatus("alert_id", { status: "resolved" });
await client.addAlertComment("alert_id", { text: "Investigating" });
// Subscriptions
await client.subscribeToAlert("alert_id");
await client.unsubscribeFromAlert("alert_id");
// Alert configs
const configs = await client.listAlertConfigs({ agentId: "agent_id" });
await client.createAlertConfig({ ... });
await client.getAlertConfig("config_id");
await client.updateAlertConfig("config_id", { ... });
await client.deleteAlertConfig("config_id");
// Organization preferences
const prefs = await client.listOrganizationAlertPreferences({ includeDefaults: true });
await client.updateOrganizationAlertPreference("org_id", "alert_type", { ... });
// List models, optionally filtered by capability
const providers = await client.listModels({ supportsToolUse: true });
const imageModels = await client.listModels({ supportsOutputMedia: "image" });
const pdfModels = await client.listModels({ supportsInputMedia: "pdf" });
const model = await client.getModel("model_id");
// Media-generation quality tiers (fast/balanced/thorough) and what each resolves to
const tiers = await client.getGenerationTiers();
// Embedding and reranker models, with their pricing
const embedders = await client.listEmbeddingModels({ supportsInputMedia: "image" });
const rerankers = await client.listRerankerModels();
console.log(embedders.models, embedders.default_model_type, rerankers.models);
const alerts = await client.listModelAlerts({ unreadOnly: true });
await client.markModelAlertRead("alert_id");
await client.markAllModelAlertsRead();
const unread = await client.getUnreadModelAlertCount();
const recs = await client.getModelRecommendations("model_id", { requireToolUse: true, minContextTokens: 100_000 });
// Model playground experiments
const experiment = await client.createExperiment({ model_ids: ["model_id"], prompt: "..." });
const experiments = await client.listExperiments();
const detail = await client.getExperiment("experiment_id");
await client.cancelExperiment("experiment_id");
await client.deleteExperiment("experiment_id"); // soft-delete, preserves audit history
const results = await client.search({ query: "quarterly report" });
const filtered = await client.search({ query: "my agent", entityType: "agent", limit: 5 });
Search the Seclai docs. Results are global (not account-scoped) and each carries a
doc_slug plus an optional anchor for building a
https://seclai.com/docs/<doc_slug>[#<anchor>] link.
// Fast title/summary match, no AI cost
const hits = await client.searchDocs({ query: "email triggers" });
// Semantic body match — adds a `highlight` with the best matching sentence
const semantic = await client.searchDocs({
query: "how do I stop auto-reply loops",
mode: "semantic",
limit: 5,
});
Send and receive agent email on your own domain instead of the shared
agent.seclai.com. These endpoints require a user-bound credential (an
account-only API key is refused with 403) and, for mutations, an account owner/admin.
// Current domains, their DNS records, and what your plan allows
const { domains, can_add_custom, has_custom } = await client.listEmailDomains();
// Add a vanity subdomain (<slug>.seclai.com) or your own custom domain
const vanity = await client.addEmailDomain({ kind: "vanity", value: "acme" });
const custom = await client.addEmailDomain({
kind: "custom",
value: "agent.mycompany.com",
delegated: true, // let Seclai manage a dedicated Route53 zone
});
// Publish custom.dns_records at your DNS provider, then check without waiting
// for the background sweep
const checked = await client.verifyEmailDomain(custom.id);
// Promote a verified domain, or fall back to the shared domain
await client.setPrimaryEmailDomain(custom.id);
await client.useSharedEmailDomain(); // keeps the domain configured & verified
// Confirm delivery end-to-end (always sends to the account owner only)
await client.sendEmailDomainTestEmail(custom.id);
// DMARC aggregate-report summary
const dmarc = await client.getDmarcSummary(custom.id, { days: 30, topSources: 10 });
// Removing a delegated domain returns a cleanup_note about the registrar NS record
const { cleanup_note } = await client.removeEmailDomain(custom.id);
// Generate plans for different resource types
const kb = await client.aiAssistantKnowledgeBase({ user_input: "Create a docs KB" });
const src = await client.aiAssistantSource({ user_input: "Add a web source" });
const sol = await client.aiAssistantSolution({ user_input: "Set up monitoring" });
const mb = await client.aiAssistantMemoryBank({ user_input: "Create a chat memory" });
// Accept or decline the generated plan
await client.acceptAiAssistantPlan("conversation_id", { confirm_deletions: true });
await client.declineAiAssistantPlan("conversation_id");
// Memory bank conversation history
const history = await client.getAiAssistantMemoryBankHistory();
await client.acceptAiMemoryBankSuggestion("conversation_id", { ... });
// Feedback
await client.submitAiFeedback({ ... });
Automatically iterate through all pages of a list method:
for await (const source of client.paginate(
(opts) => client.listSources(opts),
{ limit: 50 },
)) {
console.log(source.name);
}
All errors extend SeclaiError:
import {
SeclaiError,
SeclaiConfigurationError,
SeclaiAPIStatusError,
SeclaiAPIValidationError,
SeclaiStreamingError,
} from "@seclai/sdk";
try {
await client.getAgent("bad_id");
} catch (err) {
if (err instanceof SeclaiAPIValidationError) {
console.error("Validation:", err.validationError);
} else if (err instanceof SeclaiAPIStatusError) {
console.error(`HTTP ${err.statusCode}:`, err.responseText);
} else if (err instanceof SeclaiStreamingError) {
console.error("Stream failed for run:", err.runId);
}
}
All low-level methods support an AbortSignal for request cancellation:
const controller = new AbortController();
// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5_000);
const data = await client.request("GET", "/agents", {
signal: controller.signal,
});
For endpoints not yet covered by a convenience method, use request or requestRaw:
// JSON request/response
const data = await client.request("POST", "/custom/endpoint", {
json: { key: "value" },
query: { filter: "active" },
});
// Raw Response (e.g. binary downloads)
const response = await client.requestRaw("GET", "/files/download/123");
const blob = await response.blob();
npm install
npm run typecheck
npm run build
This also regenerates src/openapi.ts from openapi/seclai.openapi.json.
npm test
Generate HTML docs into build/docs/:
npm run docs