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.
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) — 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.
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? }. 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.
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.
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().
ToolConfig<TIn, TOut>
Config for ai.tool.
ToolContext<TArtifacts>
Second argument to execute — { artifacts, signal, ... }.
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(...).
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.
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), 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. Read it 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.