Skip to content
Warlock.js v4.4.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.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.memory(config)(config) => MemoryContractMemory
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.eval.{exact,contains,predicate,judge}built-in agent.eval() scorersRun 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.middleware.budget(opts)budget cap middlewareAttach middleware
ai.middleware.guardrail(opts)pre/post check middlewareAttach 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(), .on(), .off(), .name, .isAnonymous, .description.
AgentConfigConfig object accepted by ai.agent.
AgentExecuteOptionsPer-call options for execute / stream.
AgentResult<T>Result envelope — { type, data?, text?, report, usage, error? }.
AgentReportTrace tree — { status, startedAt, endedAt, duration, model, trips, toolCalls }.
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.
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?), .name, .signature.
PlannerConfig<TOutput>Config — model XOR planner, capabilities, maxSteps?, output?.
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? }.
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.
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().
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"
ExportWhat it is
SystemPromptImmutable builder returned by ai.systemPrompt. .persona(t), .instruction(t), .resolve(placeholders).
SystemPromptContractInterface implemented by SystemPrompt.
SystemPromptBlockContractDiscriminated union — `PersonaContract
PersonaContract{ type: "persona", text, resolve }.
InstructionContract{ type: "instruction", text, resolve }.
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.

All extend AIError. Stable code strings listed in Handle errors.

ClassCodeCategory
AIError(base)varies
AgentExecutionErrorAGENT_EXEC_FAILEDvaries
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
PlannerCancelledErrorPLANNER_CANCELLEDcancelled
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.
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.
MockEmbedderBacking embedder with scripted vectors.