Skip to content
Warlock.js v4.7.0

API reference

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";
ExportShapeSee
ai.agent(config)(config: AgentConfig) => AgentContract<T>Run agent
ai.tool(config)(config: ToolConfig) => ToolContract<TIn, TOut>Define tools
ai.systemPrompt(input?)() / (string) / (block[]) => SystemPromptWrite system prompts
ai.persona(text)(text: string) => PersonaContractWrite system prompts
ai.instruction(text)(text: string) => InstructionContractWrite system prompts
ai.workflow(config)<TIn, TOut, TState>(config) => WorkflowInstanceRun workflow
ai.step(config)<TIn, TState>(config) => StepDefinitionRun workflow
ai.supervisor(config)<TOutput>(config) => SupervisorContractRun supervisor
ai.team(config)<TOutput, TState, TMembers>(config) => SupervisorContract (manager + members + gate sugar)Run supervisor
ai.orchestrator(config)<TOutput, TState>(config) => OrchestratorContractRun orchestrator
ai.planner(config)<TOutput>(config) => PlannerContractPlanner
ai.spawnSubAgent(spec)<TOutput>(spec) => Promise<AgentResult<T>>Spawn sub-agent
ai.image(params)(params: ImageParams) => Promise<ImageResult> — text-to-image output verb (GeneratedImage[])OpenAI / Google
ai.speech(params)(params: SpeechParams) => Promise<SpeechResult> — text-to-speech output verb (GeneratedAudio)OpenAI
ai.transcribe(params)(params: TranscribeParams) => Promise<TranscriptionResult> — speech-to-text input verbOpenAI
ai.audioFromFile(path, opts?)(path, { mediaType? }) => Promise<AudioInput> — read + package an audio file (non-AI plumbing for ai.transcribe)OpenAI
ai.audioFromBuffer(bytes, mediaType, filename?)(...) => AudioInput — package raw audio bytes (no I/O, no AI)OpenAI
ai.memory(config)(config) => MemoryContractMemory
ai.skills(config)(config: SkillsConfig) => SkillsContract (progressive-disclosure skills library)Memory
ai.rag(config)(config: RagConfig) => Rag (chunk → embed → retrieve → cite)Memory
ai.rag.keywordReranker(opts?) / ai.rag.llmReranker(opts)built-in rerankers for the reranker slotMemory
ai.router(config)(config) => AgentContract (generated routing agent)Run supervisor
ai.fanOut(unit, n, opts?)spread one unit into N keyed intentsRun supervisor
ai.batch(exec, items, opts?)run an executable over a dataset, bounded concurrencyRun agent
ai.fallbackModel(models, opts?)ordered model list with failoverRun agent
ai.promptsPromptsManagerContract — the process-wide name@version prompt registry (resolve / merge / validate / diff / export by name)Prompt registry
ai.prompt(options?)thin facade over ai.prompts; the options form returns an isolated legacy PromptRegistryContractPrompt registry
ai.dataset(options)<TOutput>(options: DatasetOptions) => DatasetContract (filterable / shardable eval cases)Run agent
ai.vcr(model, options)(model: ModelContract, options: VcrOptions) => VcrModel (record / replay decorator)Run agent
ai.eval.{exact,contains,predicate,judge}built-in agent.eval() scorersRun agent
ai.eval.{toJUnit,toJSON,fromJSON}CI reporters / round-trip serialization over a finished EvalReportRun agent
ai.mockRouter(decisions, opts?)canned routing decisions for testsRun supervisor
ai.config(partial)(partial: Partial<AIConfig>) => AIConfigPersist AI data
ai.checkpoint.{memory,pg,redis}()orchestrator session checkpoint storesRun orchestrator
ai.snapshot.{memory,pg,redis}()workflow / supervisor / orchestrator snapshot storesPersist AI data
ai.systemPrompt.fromFile(path)seed a system prompt from a fileRun agent
ai.human.approval(opts)(opts: HumanApprovalOptions) => AgentMiddleware — the tool.before approval gateAttach middleware
ai.human.resume(id, decision, opts)<TOutput>(...) => Promise<ResumeResult> — out-of-process durable resumeAttach middleware
ai.human.interrupt.{memory,pg,redis}()durable InterruptStore factoriesAttach middleware
ai.guardrail(opts)(opts: GuardOptions) => AgentMiddleware — content-intelligence guardrail suiteAttach middleware
ai.guardrail.{pii,topic,injection,moderation}(opts?)built-in detector factories for the input / output / tool arraysAttach middleware
ai.middleware.budget(opts)budget cap middlewareAttach middleware
ai.middleware.guardrail(opts)pre/post check middleware (the legacy guardrail seed)Attach middleware
ai.middleware.semanticCache(opts)two-tier cache middlewareAttach middleware
ai.middleware.compose(...sources)flatten middleware sourcesAttach middleware
ai.middleware.forTool(name, mw)scope tool hooks to a tool nameAttach middleware
ExportWhat it is
AgentContract<T>The shape returned by ai.agent. Has .execute(), .stream(), .resume(), .on(), .off(), .name, .isAnonymous, .description.
AgentConfigConfig 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.
AgentSnapshot / AgentSnapshotStatus / AgentResumeOptions<T>The persisted agent state, its status, and resume() options ({ force?, ... }).
AgentExecuteOptionsPer-call options for execute / stream.
AgentResult<T>Result envelope — { type, data?, text?, report, usage, error? }.
AgentReportTrace 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".
CapturedMessageOne normalized conversation turn — { role, content, toolCalls?, toolCallId? }. Populates AgentReport.messages when captureMessages is enabled.
AgentEventHandlersTyped event handler map for on (factory / per-call).
AgentEventMapMap of event name → payload, keyed by agent.* event.
StreamingToolGuardConfigConfig for streamingToolGuard.
MessageHistory message — { role, content, ... }.
AttachmentImage attachment — string or tagged object.
ExportWhat it is
WorkflowInstance<TIn, TOut, TState, TContext>Returned by ai.workflow. .execute(), .resume(), .asTool(), .signature.
WorkflowDefinition<TIn, TOut, TState, TContext>Config for ai.workflow.
StepDefinition<TIn, TState, TContext>Returned by ai.step.
WorkflowContext<TIn, TState, TContext>The ctx argument step bodies receive.
WorkflowResult<TOut>Result envelope.
WorkflowReportTrace tree — { runId, signature, status, timings, steps }.
StepSnapshotOne step’s recorded outcome — { output, status, attempts, attemptHistory, timings, steps? }.
WorkflowRunOptionsPer-call options for execute / resume.
WorkflowSnapshotPersisted shape — see Persist AI data.
ExportWhat it is
SupervisorContract<TOutput>Returned by ai.supervisor. .execute(), .stream(), .resume(), .asTool(), .signature.
SupervisorConfig<TOutput>Config for ai.supervisor.
SupervisorContext<TOutput>ctx argument intent bodies and routers receive.
SupervisorResult<TOutput>Result envelope.
SupervisorReportTrace tree — iterations, intent dispatches.
SupervisorSnapshotPersisted shape.
ENDSentinel value to terminate routing.

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>.

ExportWhat it is
TeamConfig<TOutput, TState, TMembers>Config for ai.teamname, 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.
TeamMemberValueA role member — `AgentContract
ExportWhat it is
OrchestratorContract<TOutput, TState>Returned by ai.orchestrator. .execute(), .stream(), .resume(), .command(), .asTool(), .on(), .off(), .name, .signature, .version.
OrchestratorConfig<TOutput, TState, TIntents>Config for ai.orchestrator — supervisor surface + session lifecycle.
OrchestratorResult<TOutput>Per-turn envelope — { type, data?, sessionId, turnIndex, compaction?, report, usage, error? }.
OrchestratorReportSession-scoped turn report — turns[], turnIndex, signature, status (incl. "awaiting-input").
OrchestratorExecuteOptions<TState>Per-call options — sessionId (required), history (required), state?, context?, signal?, on?, force?.
OrchestratorResumeOptionsOptions for resume()context?, signal?, on?, force?.
OrchestratorCommandsTyped command map for command(); ships compact, open for module augmentation.
OrchestratorAsToolOptions<TToolInput>asTool() options — adds `sessionScope: “fresh"
OrchestratorEvent / OrchestratorEventMap / OrchestratorEventHandlersThe orchestrator.* event surface (3-tier).
CompactionResult{ summary, replacesFromIndex, replacesToIndex }.
SummarizeConfig / SummarizeCallbacksummarize policy shapes.
OrchestratorMemoryConfigThe orchestrator’s memory object form.
ExportWhat it is
PlannerContract<TOutput>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 }).
PlannerSnapshot / PlannerSnapshotStatus / PlannerResumeOptions<TOutput>The persisted planner state, its status, and resume() options.
PlannerCapability{ name, description, executable } — a unit the plan may reference.
PlannerResult<TOutput>Envelope — { type: "planner", data?, report, usage, error? }.
PlannerReport{ type, signature, plan?, executedSteps[], children[] }.
PlannerStep / PlannerPlan / PlannerStepSnapshotPlan + per-step records.
PlannerExecuteOptions<TOutput>Per-call — runId?, placeholders?, output?, signal?, sessionId?.
SpawnSubAgentSpec<TOutput>Spec for ai.spawnSubAgent{ name, model, task, systemPrompt?, tools?, maxTrips?, budget?, output?, ... }.
ExportWhat it is
MemoryContractReturned by ai.memory. .remember(), .recall(), .clear(), .name.
MemoryConfigConfig — working?, semantic?, defaultTier?, k?, threshold?.
SemanticMemoryConfig{ embedder, store?, namespace? }.
MemoryItem{ text, tier?, id?, metadata? }.
MemoryTier`“working"
RecalledMemory{ id, text, tier, score, metadata? }.
RecallOptions{ k?, tier?, threshold? }.

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.

ExportWhat it is
SkillsContractReturned by ai.skills. The mechanism the agent skills option drives.
SkillsConfigConfig — sources, inject?, scope?, review?, store?.
SkillRecord{ name, description, version, body, tags?, type, metadata? } — `type: “authored"
SkillCatalogEntryCheap catalog entry — `Pick<SkillRecord, “name"
SkillSource / SkillInjectMode / SkillReviewGate / SkillAnalyticsEventSource descriptors, injection policy, review gate, analytics hook.
LoadSkillInput{ name, version? } — validated input of the loadSkill tool.
SkillsStoreContractPluggable store backing a store source. MockSkillsStore / proceduralSkillStore() ship as implementations.
loadSkillTool(deps)Factory that builds the per-run loadSkill ToolContract<LoadSkillInput, LoadSkillResult> (progressive-disclosure body loader with a per-run load budget). ai.skills wires this for you.
LoadSkillResult / LoadSkillToolDepsResult fed back to the model — { body, name, version } | { error } — and the deps the tool closes over (load, maxLoadsPerRun, onLoaded?).
saveSkillTool(deps) / SaveSkillToolDepsFactory for the Phase-2 saveSkill tool (writes an inert type: "candidate"); auto-registered only when a review gate is set.
SaveSkillInput / SaveSkillResultsaveSkill input { name, description, body, tags? } and result { saved: true; name; status: "candidate" } | { error }.
runReviewGate(candidate, gate, emit?)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.
ReviewOutcome{ promoted: true; record; reason? } | { promoted: false; reason? }.

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.

ExportWhat it is
RagReturned by ai.rag. .index(), .retrieve(), .clear(), .asTool(), .name.
RagConfigConfig — embedder (required), store?, name?, namespace?, chunk?, reranker?, retrieve?.
RagAsToolOptionsasTool() options — name?, description?, retrieve?.
RagDocumentA source document handed to index().
Chunk / ChunkOptions / ChunkTypeThe chunker surface; ai.rag ships fixed / sentence / markdown / recursive splitters via chunk.
RetrievedChunkA single retrieval hit — { text, score, citation }.
Citation{ sourceId, chunkIndex, span, score, metadata? } — provenance for grounding.
RetrieveOptions{ topK?, threshold?, candidates?, tags? }.
RetrieveResult{ query, chunks: RetrievedChunk[] }.
RagRerankerReranker contract. ai.rag.keywordReranker(opts?) / ai.rag.llmReranker(opts) ship as built-ins; KeywordRerankerOptions / LlmRerankerOptions are their option shapes.
VectorStoreVector-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 + pgvector VectorStore{ 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 / PgVectorStoreInstanceThe 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.
RagLoaderResult / RagLoaderMetadata / RagLoaderType / RagLoaderOptionsShared loader output, derived metadata (source, loader, title), type tag, and base options.
LoadTextOptions / LoadHtmlOptions / LoadWebOptions / LoadPdfOptions / TextInputPer-loader option shapes + the loadText input type.
PDF_PARSE_INSTALL_INSTRUCTIONSThe 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.
ExportWhat it is
BatchResult<TResult>{ type: "batch", data[], items[], usage, report }.
BatchItemResult<TResult>{ index, status, result?, error?, attempts }.
BatchOptions<TResult>{ concurrency?, retry?, onItem?, signal?, sessionId?, name? }.
BatchReportPer-item rollup — { total, succeeded, failed, cancelled }.
EvalReport<T> / EvalCase / EvalScore / EvalScorer / EvalJudge / EvalOptions / EvalCaseResultagent.eval() surface.
DatasetContract<TOutput>Returned by ai.dataset. Immutable, .filter() / .shard()-able cases that feed agent.eval({ cases }). .name, .cases.
DatasetEntry<TOutput> / DatasetOptions<TOutput>A dataset row (a superset of EvalCase plus tags?); factory options (name, cases?, fromFile? JSONL).
EvalRegressionRegression verdict attached when agent.eval gets a baseline{ regressed[], removed, added, passed }.
ai.eval.toJUnit(report)JUnit-XML artifact for CI ingestion.
ai.eval.toJSON(report) / ai.eval.fromJSON(serialized)Round-trippable EvalReport snapshot — today’s report becomes tomorrow’s baseline.
registerAiMatchers()Vitest matchers toRouteTo / toConverge / toPassStep / toOutputShape.
matchRouteTo / matchConverge / matchPassStep / matchOutputShapeLibrary-agnostic verdict functions; MatcherVerdict, AiMatchers types.
ExportWhat it is
CheckpointStore / CheckpointRecordOrchestrator session-state store + row shape. ai.checkpoint.{memory,pg,redis}().
SnapshotStore<TSnapshot>Workflow / supervisor / orchestrator run-snapshot store. ai.snapshot.{memory,pg,redis}(). load / save / delete / list? / schema.
PgClientLike / RedisClientLikeMinimal pg / redis client surfaces the stores depend on (you pass the client in).
PgCheckpointOptions / RedisCheckpointOptionsai.checkpoint.pg / .redis options.
PgSnapshotStoreOptions / RedisSnapshotStoreOptionsai.snapshot.pg / .redis options.
FallbackModelContractReturned by ai.fallbackModel(models, opts?).
ExportWhat it is
ToolContract<TIn, TOut>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, ... }.
ToolCallOne recorded tool call — { name, input, output, error?, tripIndex, duration, startedAt, endedAt }.
ToolMode`“feedback"

ai.streamObject streams token deltas, progressively-parsed partial snapshots, and a final strictly-validated object. See Stream structured output.

ExportWhat it is
ai.streamObject(params)<T>(params: StreamObjectParams<T>) => AsyncIterable<ObjectStreamEvent<T>> — the structured-output streaming verb.
collectStreamObject(stream)Drain a streamObject stream down to just its terminal done event.
StreamObjectParams<T>Config — { model, messages, schema, options? }; schema validates the final object.
ObjectStreamEvent<T>{ type: "text-delta"; delta } | { type: "partial"; value: unknown } | { type: "done"; valid: true; value: T; usage } | { type: "done"; valid: false; error: AIError; usage }.
parsePartialJson(text)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.

ExportWhat it is
ai.image(params)Text-to-image verb. data.images is GeneratedImage[].
ImageParams / ImageData / ImageResult / ImageReportVerb config ({ model, prompt, count?, size?, quality?, aspectRatio?, negativePrompt?, ... }), data, envelope, and report node.
ImageModelContractReturned by sdk.image({ name }). Peer of EmbedderContract on the adapter.
GeneratedImage{ type: "base64"; base64; mediaType; revisedPrompt? } | { type: "url"; url; mediaType?; revisedPrompt? }.
ImageModelPricing{ input?, output?, perImage?, perImageBySize? } — token-metered (gpt-image) or per-image (DALL·E / Imagen).
computeImageCostCost helper folding image spend into the shared Usage.cost.
ai.speech(params)Text-to-speech verb. data.audio is GeneratedAudio.
SpeechParams / SpeechData / SpeechResult / SpeechReportVerb config ({ model, text, voice?, format?, speed?, instructions?, ... }), data, envelope, and report node (report.characters).
SpeechModelContractReturned by sdk.speech({ name, voice? }).
GeneratedAudio{ type: "base64"; base64; mediaType } — discriminated, leaving room for a future url variant.
SpeechModelPricing{ input?, output?, perMillionCharacters? } — per-token (gpt-4o-mini-tts) or per-character (tts-1).
ai.transcribe(params)Speech-to-text verb. data.text + optional data.segments.
TranscribeParams / TranscriptionData / TranscriptionResult / TranscriptionReportVerb config ({ model, audio, language?, prompt?, format?, ... }), data, envelope, and report node (report.durationSeconds).
TranscriptionModelContractReturned by sdk.transcribe({ name }).
TranscriptionSegment{ text; start?; end? } — timestamped segment (whisper verbose_json).
TranscriptionModelPricing{ input?, output?, perMinute? } — per-token (gpt-4o-transcribe) or per-minute (whisper-1).
ai.audioFromFile(path, opts?)Read a file → AudioInput; infers media type (.ogg / .opus / .m4a recognized), override with { mediaType }.
ai.audioFromBuffer(bytes, mediaType, filename?)Package raw bytes → AudioInput. No I/O, no AI.
AudioInput{ base64; mediaType; filename? } — provider-neutral, serializable audio payload for ai.transcribe.
MockImageModel / MockSpeechModel / MockTranscriptionModelDeterministic 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.

ExportWhat it is
SystemPromptImmutable 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.
SystemPrompt.validate(options?)Sugar over ai.prompts.validate(this, options) — deterministic missing-placeholder check + optional Nova-safe judge.
SystemPromptMeta{ name?, version?, description?, composedFrom?, required? }.
SystemPromptContractInterface implemented by SystemPrompt.
SystemPromptBlockContractDiscriminated union — `PersonaContract
PersonaContract{ type: "persona", text, resolve }.
InstructionContract{ type: "instruction", text, resolve }.

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.

ExportWhat it is
ai.promptsThe default PromptsManagerContract. .register(), .create(), .get(), .has(), .list(), .versions(), .resolve(), .define(), .tag(), .validate(), .diff(), .export(), .import().
prompts(options?)Factory for an isolated manager — options { judgeCache? }.
PromptsManagerContractThe manager interface above.
PromptsManagerEntryOne registered entry — { name, version, addedAt, contract, tags? }.
PromptTemplateVersionA define entry — `{ version, template: string
PromptsValidateOptionsvalidate options — { placeholders?, declare?, judge?, judgeCache? }.
PromptValidationResultvalidate outcome — { ok, missing, score?, issues? } (ok is the deterministic verdict; the judge never flips it).
PromptValidateTargetWhat validate accepts — a name, a SystemPromptContract, or a raw string.
PromptDiff / PromptDiffBlockdiff(name, from, to) outcome — { added, removed, changed, identical }.
ExportedRegistry / ExportedPrompt / ExportedPromptVersionThe portable export() / import() snapshot shapes.

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(...).

ExportWhat it is
EmbedderContractSibling of ModelContract on SDKAdapterContract. .embed(), .embedMany(), .dimensions.
EmbeddingResult{ vector: number[], usage: Usage, dimensions: number }.
EmbeddingBatchResult{ vectors: number[][], usage: Usage, dimensions: number }.
ExportWhat it is
SDKAdapterContractInterface every provider adapter implements — model(), embedder?().
ModelContractReturned by sdk.model({...}). Owns complete, stream, capabilities, pricing.
ModelCapabilities{ structuredOutput?, vision?, reasoning?, promptCaching?, audio?, ... } — feature flags the agent reads before forwarding options.
ModelCallOptionsPer-call options forwarded to the model — temperature, maxTokens, plus reasoning?: { effort?, maxTokens? } and cacheControl?: { breakpoints? }.
ReasoningEffort`“low"
ModelResponseShape returned by model.complete.
ModelPricing{ input, output, cachedInput?, cachedOutput?, reasoning? } — USD per 1M tokens, per channel.
Usage{ input, output, total, cachedTokens?, cacheWriteTokens?, reasoningTokens?, cost? }.
CostBreakdown{ input, output, cachedInput?, cachedOutput? } — USD.
ExportWhat it is
AgentMiddlewareShape — { name, execute?, trip?, tool?, log? }.
MiddlewareExecuteContextctx for execute hooks.
MiddlewareTripContextctx for trip hooks.
MiddlewareToolContextctx for tool hooks.

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.)

ExportWhat it is
ai.guardrail(options)Build the composed guardrail AgentMiddleware. GuardrailFactory typed.
ai.guardrail.pii(opts?)PII detector (regex + dictionary, zero runtime dep).
ai.guardrail.topic(opts)Topic filter (allow / deny string `
ai.guardrail.injection(opts?)Jailbreak / prompt-injection marker detector.
ai.guardrail.moderation(opts?)Optional OpenAI-backed moderation (lazy openai peer).
GuardOptionsFactory options — input / output / tool detector arrays plus escalation.
GuardrailVerdictDiscriminated union — allow / redact / block / flag, one shape per action.
GuardrailAction`“allow"
GuardrailPhase`“input"
GuardrailMatchOne detector match — { rule, span?, label? }.
GuardrailDetector / GuardrailDetectorContext / GuardrailEscalation / GuardrailBlockEventDetector contract, per-check context, escalation hook, emitted block event.
PiiDetectorOptions / PiiCategory / TopicFilterOptions / InjectionDetectorOptions / OpenAiModerationOptionsPer-detector option shapes.
guardThe standalone factory ai.guardrail wraps; FlagRecord is its flagged-match record.

ai.human.* adds interrupt / resume tool approval — a tool.before gate plus durable interrupt stores and out-of-process resume.

ExportWhat it is
ai.human.approval(options)The tool.before approval-gate AgentMiddleware. humanApproval standalone.
ai.human.resume(id, decision, options)Out-of-process durable resume — replays a decision against a persisted interrupt.
ai.human.interrupt.{memory,pg,redis}()Durable InterruptStore factories (memory ships real; pg / redis are lazy optional peers).
HumanApprovalOptions / ApprovalHandler / ApprovalRequest / ApprovalRequestContextGate config, handler, and the request a reviewer sees.
ApprovalDecision / ApprovalDecisionTypeA reviewer’s decision — approve / reject / edit.
InterruptStore / InterruptPolicy / PendingInterrupt / PendingInterruptStatusDurable-store contract, gating policy, and the persisted interrupt row.
ResumeOptions / ResumeResultresume() options and outcome.
PolicyContext / PolicyVerdict / evaluatePolicyPolicy seam used to decide whether a call needs approval.
PgInterruptOptions / RedisInterruptOptionsinterrupt.pg / .redis options.

ai.vcr decorates any ModelContract to record and replay model calls — deterministic, offline tests with no live provider hit.

ExportWhat it is
VcrModelThe decorated model returned by ai.vcr. Adds .save() and a readonly .cassette.
VcrOptions{ path, mode?, hashOptions? }.
VcrMode`“record"
CassetteOn-disk format — { version, model, provider, entries }.
CassetteEntryOne recorded request → response pair (response / chunks / error).
hashRequest / DEFAULT_HASH_OPTIONSRequest-hashing helper + the default hashed ModelCallOptions fields.

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.

ExportWhat 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.
ObserverThe structural observer contract a tool implements.
FlowObserveOptionA 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.

ExportWhat it is
ai.serve(executable, options?)Turn a ServableExecutable into a (req, res) => void node: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.
ServeOptions<TInput>serve options — authToken? (Bearer gate), toInput? (map body → input, default body.input), toOptions? (map body → per-call stream options, default passes sessionId / history).
ServableExecutable<TInput>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_DONEThe 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.

ClassCodeCategory
AIError(base)varies
AgentExecutionErrorAGENT_EXEC_FAILEDvaries
AgentDriftErrorAGENT_DRIFTdrift
SchemaValidationErrorSCHEMA_VALIDATION_FAILEDschema
ToolExecutionErrorTOOL_EXEC_FAILEDtool
WorkflowError(base)varies
StepFailedErrorSTEP_FAILEDprovider
WorkflowDriftErrorWORKFLOW_DRIFTdrift
WorkflowCancelledErrorWORKFLOW_CANCELLEDcancelled
MaxStepsExceededErrorWORKFLOW_MAX_STEPSmax-steps
RoutingErrorWORKFLOW_INVALID_GOTOrouting
ProviderErrorPROVIDER_ERRORprovider
ProviderRateLimitErrorPROVIDER_RATE_LIMITrate-limit
QuotaExceededErrorPROVIDER_QUOTA_EXCEEDEDquota
ProviderTimeoutErrorPROVIDER_TIMEOUTtimeout
ContextLengthExceededErrorCONTEXT_LENGTH_EXCEEDEDcontext-length
ContentFilterErrorCONTENT_FILTERcontent-filter
InvalidRequestErrorPROVIDER_INVALID_REQUESTvalidation
ProviderAuthErrorPROVIDER_AUTHauth
BudgetExceededErrorBUDGET_EXCEEDEDbudget
GuardrailViolationErrorGUARDRAIL_VIOLATIONguardrail
SupervisorDriftErrorSUPERVISOR_DRIFTdrift
MaxIterationsErrorSUPERVISOR_MAX_ITERATIONSmax-iterations
OrchestratorFailedErrorORCHESTRATOR_FAILEDvaries
OrchestratorDriftErrorORCHESTRATOR_DRIFTdrift
OrchestratorConfigErrorORCHESTRATOR_CONFIGvalidation
OrchestratorCancelledErrorORCHESTRATOR_CANCELLEDcancelled
PlannerFailedErrorPLANNER_FAILEDvaries
PlannerPlanInvalidErrorPLANNER_PLAN_INVALIDschema
PlannerDriftErrorPLANNER_DRIFTdrift
PlannerCancelledErrorPLANNER_CANCELLEDcancelled
PromptNotFoundErrorPROVIDER_INVALID_REQUESTvalidation
PromptValidationErrorSCHEMA_VALIDATION_FAILEDvalidation
VcrCassetteMissErrorVCR_CASSETTE_MISSunknown
ApprovalRejectedErrorAPPROVAL_REJECTEDunknown
InterruptSuspendedErrorINTERRUPT_SUSPENDEDunknown
OutboundPolicyErrorOUTBOUND_POLICY_BLOCKEDunknown
ExportWhat it is
AIConfig{ defaultStore?, defaultCheckpointStore?, defaultSnapshotStore? } — process-wide config. defaultStore is the cache driver (semanticCache + memory vector store); defaultSnapshotStore / defaultCheckpointStore are the snapshot / checkpoint stores.
ai.config(partial)Merge into the process-wide config.

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.

ExportWhat it is
OutboundPolicy / ResolvedOutboundPolicyOutbound-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.
redactHeaders / DEFAULT_SENSITIVE_KEYS / SENSITIVE_HEADERS / RedactOptions / RedactedErrorHeader scrubbing + the built-in sensitive-key/header sets + option / result types.
ExportWhat it is
BaseReportCommon report shape — runId, rootRunId, parentRunId?, reportSchemaVersion, version?, sessionId?.
LLMTripOne round-trip — { index, finishReason, usage, startedAt, endedAt, duration, ... }.
FinishReason`“stop"
ExportWhat it is
MockSDKTest double for any SDKAdapterContract. Use in tests instead of hitting real providers.
MockModelBacking model with scripted responses.
mockAgentWires MockSDK → mock model → agent() in one call — a scripted agent without the boilerplate.
mockRouterDeterministic supervisor router double — script the per-iteration routing decisions (or a predicate over RouteContext).
registerAiMatchersRegister the Vitest matchers (matchConverge, matchOutputShape, matchPassStep, matchRouteTo).