Every public export of @warlock.js/ai, grouped by primitive. This page is the lookup table — for the “why” and “how to use it well” angle, follow the cross-links to the concept and basics pages.
All exports come from the same entry:
import { ai /* types, errors */ } from"@warlock.js/ai";
The shape returned by ai.agent. Has .execute(), .stream(), .resume(), .on(), .off(), .name, .isAnonymous, .description.
AgentConfig
Config object accepted by ai.agent. Includes captureMessages? — opt-in full-history capture onto AgentReport.messages (off by default; large + sensitive) — toolDispatch? ("concurrent" default, or "sequential"; see ToolDispatchMode), maxConcurrentTools? (default 4; cap on a trip’s tool calls running at once under concurrent dispatch) and durable? (below).
agent.resume(runId, opts?)
Durable mid-run crash-resume. Re-hydrates completed trips + tool calls + usage from the snapshot and continues from the next trip — never re-issuing a completed trip’s model call. Throws AgentDriftError on a structural mismatch unless { force: true }.
AgentConfig.durable
{ store?: SnapshotStore<AgentSnapshot>; deleteOnComplete? } — opt-in checkpointing after every settled trip. store falls back to ai.config({ defaultSnapshotStore }); when neither is set, writes skip and resume() throws.
The persisted agent state, its status, and resume() options ({ force?, ... }).
AgentExecuteOptions
Per-call options for execute / stream, including modelOptions (shallow-merged over the agent’s for that run) and continueOnOutputLimit.
AgentResult<T>
Result envelope — { type, data?, text?, blocks?, report, usage, error? }. blocks are the final trip’s raw provider blocks (see ProviderContentBlock).
ToolDispatchMode
"concurrent" | "sequential" — how the tool calls of one trip run. Concurrent (default) runs them in parallel, at most maxConcurrentTools (default 4) at a time; sequential awaits each call and appends its result before the next starts. Results reach the model in request order either way. Set on AgentConfig.toolDispatch or per call on AgentExecuteOptions.toolDispatch.
AgentReport
Trace tree — BaseReport plus model, trips, systemPrompt? (the resolved role: "system" message), and messages? (the full CapturedMessage[], present only when captureMessages is on). Tool dispatches live under children filtered by type === "tool".
CapturedMessage
One normalized conversation turn — { role, content, toolCalls?, toolCallId?, blocks?, compaction? }. Populates AgentReport.messages when captureMessages is enabled.
AgentEventHandlers
Typed event handler map for on (factory / per-call).
AgentEventMap
Map of event name → payload, keyed by agent.* event.
StreamingToolGuardConfig
Config for streamingToolGuard.
Message
History message — { role, content, toolCalls?, toolCallId?, blocks?, ... }. An assistant message’s blocks are replayed verbatim by the adapter whose format they belong to.
ProviderContentBlock
{ provider, type, data } — one raw provider content block (Anthropic thinking, redacted thinking, compaction, server tools…), kept on ModelResponse.blocks, Message.blocks, LLMTrip.blocks and AgentResult.blocks so the turn can be replayed exactly.
ai.team is transparent sugar over ai.supervisor — the manager becomes route/router, members become intents, and the gate becomes evaluate. It returns the unchanged SupervisorContract<TOutput>.
Export
What it is
TeamConfig<TOutput, TState, TMembers>
Config for ai.team — name, manager, members, gate, plus pass-throughs (goal, output, state, maxIterations, snapshotStore, on, observe).
TeamGate
"quality" (review-then-fix) `
TeamGateFn<TState>
Fully custom gate — same shape as SupervisorConfig.evaluate.
Options for resume() — context?, signal?, on?, force?.
OrchestratorCommands
Typed command map for command(); ships compact, open for module augmentation.
OrchestratorAsToolOptions<TToolInput>
asTool() options — sessionScope: "fresh" | "shared" plus (4.15.0) session, required for "shared": a literal session id, or a (ctx) => sessionId resolver reading the tool’s out-of-band ToolContext (never the model-visible payload). unsafeAllowModelSessionId restores the pre-4.15.0 payload-driven behavior.
Returned by ai.planner. Implements ExecutableContract. .execute(goal, opts?), .resume(runId, opts?), .name, .signature.
PlannerConfig<TOutput>
Config — model XOR planner, capabilities, maxSteps?, output?, durable? (below).
planner.resume(runId, opts?)
Durable crash-resume. Re-hydrates the plan + executed steps from the snapshot and continues; throws PlannerDriftError on a structural mismatch unless { force: true }.
PlannerConfig.durable
{ store?: SnapshotStore<PlannerSnapshot>; deleteOnComplete? } — opt-in checkpointing; store falls back to ai.config({ defaultSnapshotStore }).
ai.skills builds a runtime skills library — an always-injected metadata catalog plus an on-demand loadSkill tool (progressive disclosure), backed by directory / url / store sources.
Export
What it is
SkillsContract
Returned by ai.skills. The mechanism the agent skills option drives.
{ name, version? } — validated input of the loadSkill tool.
SkillsStoreContract
Pluggable store backing a store source. MockSkillsStore / proceduralSkillStore() ship as implementations.
loadSkillTool(deps)
Factory that builds the per-run loadSkillToolContract<LoadSkillInput, LoadSkillResult> (progressive-disclosure body loader with a per-run load budget). ai.skills wires this for you.
LoadSkillResult / LoadSkillToolDeps
Result fed back to the model — { body, name, version } | { error } — and the deps the tool closes over (load, maxLoadsPerRun, onLoaded?).
saveSkillTool(deps) / SaveSkillToolDeps
Factory for the Phase-2 saveSkill tool (writes an inert type: "candidate"); auto-registered only when a review gate is set.
Run a candidate skill through the default-DENY Phase-2 review gate; promotes on { approve: true }, else denies (fail-closed). Resolves a ReviewOutcome; never throws.
ai.rag is a native core verb — chunk → embed → vector store → retrieve → rerank → cite. It reuses the EmbedderContract and a @warlock.js/cache driver as the vector store, with zero new dependencies.
Export
What it is
Rag
Returned by ai.rag. .index(), .retrieve(), .clear(), .asTool(), .name.
Reranker contract. ai.rag.keywordReranker(opts?) / ai.rag.llmReranker(opts) ship as built-ins; KeywordRerankerOptions / LlmRerankerOptions are their option shapes.
VectorStore
Vector-store adapter. ai.rag.cacheVectorStore wraps a @warlock.js/cache driver; ai.rag.pgVectorStore is a native pgvector-backed store.
ai.rag.pgVectorStore(options)
Postgres + pgvectorVectorStore — { client | connectionString, dimensions, table?, ... }. Emits reference DDL via .schema() / .ensureSchema() for a migration.
ai.rag.vectorLiteral(vector)
Serialize a number[] to a pgvector literal ("[1,0.5,-2]"); throws on non-finite components.
PgVectorStoreOptions / PgVectorStoreInstance
The pgVectorStore option shape and the returned store (adds schema / ensureSchema).
ai.rag.loadText(input, opts?)
Turn a string (or strings) into RagDocument(s) — zero-dependency; the loader every other loader funnels into.
ai.rag.loadHtml(html, opts?)
Strip raw HTML → text RagDocument (regex + entity decode, no DOM parser); lifts <title> into metadata.
ai.rag.loadWeb(url, opts?)
Fetch + strip a URL → RagDocument. SSRF-safe — routes through guardedFetch / OutboundPolicy (scheme + host allowlist, post-DNS private-IP guard, byte cap), never a raw fetch.
ai.rag.loadPdf(bytes, opts?)
PDF bytes → RagDocument(s) (perPage?). Lazy optional peer — dynamic-imports pdf-parse on first use; throws curated install instructions when absent.
Per-loader option shapes + the loadText input type.
PDF_PARSE_INSTALL_INSTRUCTIONS
The curated install string loadPdf throws when the pdf-parse peer is missing (exported for tests / callers that match it).
bm25Rank(query, docs)
BM25 lexical ranking over a candidate set (k1 = 1.5, b = 0.75; zero-score docs dropped). Pure; no global index. See Hybrid retrieval.
reciprocalRankFusion(rankedLists, k?)
Fuse several ranked id lists into one consensus ranking via RRF (k default 60) — no score calibration needed.
hybridRank(params)
Convenience wrapper — runs bm25Rank over candidates and fuses it with your dense ranking via RRF.
multiQuery(model, query, opts?)
Ask a model for opts.n (default 3) alternative phrasings of a query; de-duped, original prepended (unless includeOriginal: false). Widens retrieval over vocabulary the original missed.
Returned by ai.tool. Has .name, .description, .invoke().
ExecutableTool<TIn, TOut>
Structural shape of an executable (agent / workflow / supervisor) dropped into tools: [] without .asTool() — { name, description?, inputSchema?, execute() }, no invoke.
AgentToolEntry<TIn, TOut>
An entry accepted in tools: [] — a ToolContract or a raw ExecutableTool the framework auto-adapts.
executableToTool(executable)
Adapt one raw ExecutableTool into a ToolContract (manifest derived from its name / description / inputSchema); throws AgentExecutionError when it has no name.
normalizeAgentTools(tools?)
Normalize an agent’s tools: [] to ToolContract[] — built tools pass through, raw executables auto-adapt.
isExecutableTool(entry)
Type guard — true when entry has execute() but no invoke().
A provider-defined tool (ProviderTool): definition is sent verbatim to the named provider and skipped with a warning elsewhere; execute runs client-run ones (Anthropic bash, …).
isProviderTool(value)
Type guard for ai.providerTool() results.
selectProviderTools(options, target)
Adapter helper — splits a call’s tools into function tools and the provider definitions the adapter accepts, warning once about the rest.
ProviderToolDefinition
{ provider, definition } — the entries of ModelCallOptions.providerTools.
ToolContext<TArtifacts>
Second argument to execute — { artifacts, signal, ... }.
createToolContext(options?)
Build a ToolContext ({ artifacts?, signal? }, empty bag by default) for invoking a tool outside the agent loop.
ToolSchemaMode
"full" (default) or "compact" — how tool input schemas are sent; the toolSchemas agent / execute option.
compactToolSchemas(tools, options?)
Copies of tools whose schemas serialize compact for every adapter; validation still uses the originals.
measureTools(tools, options?)
Input tokens a tool list adds to every call — { tokens, perTool, overhead, source: "native" | "estimate", mode }. Also ai.tools.measure with @warlock.js/ai-tools.
compactJsonSchema(schema, options?)
Strip annotation keywords (description, title, examples, default, …) and collapse const unions to enum; keepDescriptions keeps descriptions. extractJsonSchema(schema, { compact }) applies it.
describeToolSchema(tool, options?)
Per-provider schema check of one tool (openai-strict, anthropic, google) — { name, tokens, descriptionChars, schemaHash, targets, issues[], ok }. Also ai.tools.describe. See lint tool schemas.
describeToolSchemas(tools, options?)
The same for a list — { tools[], tokens, issueCount }. Also ai.tools.describeAll.
ToolConfig.lint / AIConfig.toolLint
false or DescribeToolSchemaOptions — silence or tune the development-time schema warning.
ToolCall
One recorded tool call — { name, input, output, error?, tripIndex, duration, startedAt, endedAt }.
Tolerant best-effort parser turning an incomplete streaming JSON prefix into a partial snapshot (undefined until parseable). Powers streamObject’s partial events.
The output/input-modality track — image, speech, and transcription verbs that share the uniform never-throws { data, error, usage, report } envelope with cost-truth and observe routing. Models come from an adapter’s image() / speech() / transcribe() factory. See OpenAI and Google.
Export
What it is
ai.image(params)
Text-to-image verb. data.images is GeneratedImage[].
Deterministic HTTP-free doubles; also wired via MockSDK({ imageResponses, speechResponses, transcriptionResponses, ... }).
Live rich-media add-on — @warlock.js/ai-live. A side-effect import "@warlock.js/ai-live" mounts two heavyweight modalities onto the shared ai.* facade: ai.video({ model, prompt }) — text-to-video (async submit→poll hidden behind the same uniform envelope, per-second cost-truth), and ai.realtime({ transport, model }) — a stateful duplex voice session over a pluggable RealtimeTransport (sendAudio / sendText / events() / close() → RealtimeReport). Exports include VideoModelContract, GeneratedVideo, VideoModelPricing, RealtimeSession, RealtimeEvent, RealtimeReport, plus MockVideoModel / MockRealtimeTransport. Shipped from its own package so the core stays dependency-light.
Immutable builder returned by ai.systemPrompt. .persona(t), .instruction(t), .merge(...), .meta(...), .validate(...), .resolve(placeholders).
SystemPrompt.merge(...)
Fold blocks (...blocks), a whole prompt (merge(contract) — persona replaces, instructions append, composedFrom provenance recorded), or a registered name (merge(name, { fromVersion })) into a new builder. Immutable.
SystemPrompt.meta(meta?)
No-arg reads the { name, version, description, required, composedFrom } snapshot (or undefined); the updater form returns a new builder — giving it a name auto-registers it in ai.prompts.
ai.prompts is the process-wide registry of named, versioned systemPrompt(...) builders keyed by name@version. A named prompt auto-registers; resolve / merge / validate / diff by name. prompts(options?) builds an isolated registry. See Prompt registry.
⚠ Breaking:ai.prompt is now a thin facade over ai.prompts. The isolated ai.prompt({ … }) options form (PromptRegistryContract with .register() / .add() / .resolve() / .validate() / .sync(), Langfuse sync) is unchanged; a bare ai.prompt() no longer mints a private registry — use ai.prompts or build one with prompts(...).
Interface every provider adapter implements — model(), embedder?().
ModelContract
Returned by sdk.model({...}). Owns complete, stream, capabilities, pricing.
ModelCapabilities
{ structuredOutput?, vision?, reasoning?, promptCaching?, audio?, ... } — feature flags the agent reads before forwarding options.
ModelCallOptions
Per-call options forwarded to the model — temperature, maxTokens, plus reasoning?: { effort?, maxTokens? }, cacheControl?: { breakpoints?, ttl? }, providerTools?: ProviderToolDefinition[], streamChunks?: StreamChunkOptions and providerOptions?: { [format]: {...} } (each adapter reads only its own key, e.g. anthropic).
ReasoningEffort
`“low”
ModelResponse
Shape returned by model.complete — { content, finishReason, usage, toolCalls?, blocks? }. First-party adapters set usage.cost when the model is priced.
ModelStreamChunk
One model.stream() chunk — delta, tool-call, done, plus the opt-in reasoning{ delta }, tool-args{ callId, name, delta } and usage{ usage } (running total).
StreamChunkOptions
ModelCallOptions.streamChunks — true or { reasoning?, toolArgs?, usage? }; opts a model.stream() call into the extra chunks (the agent sets it under agent.stream()). resolveStreamChunks(options) resolves it for adapters.
ModelPricing
{ input, output, cachedInput?, cacheWrite?, cacheWrite1h?, reasoning?, cachedOutput? } — USD per 1M tokens, per channel. cachedOutput is the deprecated alias of cacheWrite.
Usage.cost, the ModelPricing shape in USD: { input, output, cachedInput?, cacheWrite?, reasoning? }.
computeCost / attachCost / totalCost
Price a Usage against a ModelPricing (provider cache semantics included); set it on usage.cost in place; sum a breakdown into one USD number (undefined when unpriced).
estimateInputTokens / countInputTokens
Offline input-token estimate (characters ÷ charsPerToken, plus per-message / per-attachment allowances); native count via model.countTokens with the estimate as fallback, returning { tokens, source: "native" | "estimate" }.
ai.guardrail is the content-intelligence suite — a composed input / output / tool middleware built from detector factories. (The older ai.middleware.guardrail is the legacy pre/post-check seed; both ship.)
Export
What it is
ai.guardrail(options)
Build the composed guardrail AgentMiddleware. GuardrailFactory typed.
ai.guardrail.pii(opts?)
PII detector (regex + dictionary, zero runtime dep).
A generic, panoptic-agnostic observability seam. Observability tools (panoptic, OTel, …) implement Observer and register themselves; flows route their completed reports through the registry with no core import.
Export
What it is
registerObserver(observer)
Register an Observer into the process-wide registry.
getObservers()
The currently registered observers.
setObserveAll(value) / isObserveAll()
Toggle / read the “observe every flow by default” flag.
clearObservers()
Drop all registered observers (test teardown).
resolveObservers(option)
Resolve a flow’s FlowObserveOption against the registry.
onConfigApplied(listener)
Subscribe to ai.config(...) application so a tool can pick up its opaque config slot.
Observer
The structural observer contract a tool implements.
FlowObserveOption
A flow’s observe value — true / false / a flow-local Observer.
Turn any streaming primitive (agent / supervisor / orchestrator) into a node:http handler that streams its run to the client as Server-Sent Events. See Serve over SSE.
Export
What it is
ai.serve(executable, options?)
Turn a ServableExecutable into a (req, res) => voidnode:http handler. POST { input, sessionId?, history? }; responds text/event-stream — one frame per event, then a result frame, then [DONE]. Honors authToken (Bearer → 401) and nosniff / DENY security headers.
What serve can expose — anything whose stream(input, options?) returns a StreamLike. Agents, supervisors, and orchestrators satisfy it.
streamToSSE(stream)
Async generator that converts a StreamLike into SSE frame strings — one frame per event, then a result (or error) frame, then [DONE]. Transport-agnostic.
encodeSSE(frame)
Encode one SSE frame from { event?, data, id? }; multi-line data is split into multiple data: lines per the spec.
SSE_DONE
The terminal data: [DONE] frame a client watches for.
StreamLike<TEvent, TResult>
AsyncIterable<TEvent> & { result?: Promise<TResult> } — the shape every primitive’s stream() returns.
All extend AIError. Stable code strings listed in Handle errors.
Every ProviderError (and subclass) also carries status? (the HTTP status), billed (true, false or "unknown" — whether the failed call cost money) and retryable.
A shared trust-boundary foundation used by every server-side outbound request (attachment fetches, URL skill sources, RAG loaders) plus secret-scrubbing for logs / errors. See Outbound policy and Redact secrets.
Export
What it is
OutboundPolicy / ResolvedOutboundPolicy
Outbound-request controls — allowedSchemes? (default ["https"]), hostAllowlist?, denyPrivateIPsAfterDNS? (default true), maxBytes? (5 MiB), timeoutMs? (10s), maxRedirects? (default 5, 4.15.0), signal?, fetch?. The resolved form has every default filled.
resolveOutboundPolicy(policy?)
Fill a partial policy with the strict defaults (idempotent).
assertUrlAllowed(url, policy)
Validate scheme + host allowlist + post-DNS private-IP guard before any fetch. Returns the parsed URL; throws OutboundPolicyError.
guardedFetch(url, policy, init?)
assertUrlAllowed + timeout-merged fetch → raw Response. Every redirect hop is issued redirect: "manual" and re-validated via assertUrlAllowed before being followed, capped at maxRedirects, with authorization / cookie / proxy-authorization stripped on a cross-origin hop (4.15.0). Read the response with readTextCapped.
fetchTextWithPolicy(url, policy, init?)
guardedFetch + readTextCapped → { ok, status, statusText, text }.
readTextCapped(response, maxBytes)
Read a body as UTF-8 with a hard byte cap.
isPrivateOrReservedIp(ip)
true for private / loopback / link-local / unique-local / cloud-metadata addresses — the post-DNS SSRF predicate.
redact(value, options?)
Deep-copy with sensitive-keyed properties replaced by a placeholder (key-driven).
scrubSecrets(text)
Scrub known secret shapes (Bearer tokens, sk-…, xox…, ghp_…, AKIA…) from free-form text.
redactError(error, options?)
Serialize an error secret-free (RedactedError) — stack omitted unless includeStack: true; cause deep-redacted.