API Reference

This page lists public symbols exported from @dawn-ai/sdk, selected runtime packages, and the generated dawn:routes module. It is reference documentation — for concepts and examples, see the individual concept pages. Symbols are grouped by category and linked back to the page that explains them in depth.

@dawn-ai/sdk

Agent

Functions and types for declaring an LLM-driven agent route. See Agents.

agent(config)

ts
export function agent(config: AgentConfig): DawnAgent

Creates an agent route entry from a config object. The return value is the default export of a route's index.ts. Dawn discovers tool files found in the sibling tools/ directory and wires them into generated agent graphs.

ts
import { agent } from "@dawn-ai/sdk"
 
export default agent({
  model: "gpt-5-mini",
  systemPrompt: "You are a helpful assistant.",
})

See Agents.

AgentConfig

ts
export interface AgentConfig {
  readonly description?: string
  readonly model: KnownModelId
  readonly provider?: ModelProviderId
  readonly reasoning?: ReasoningConfig
  readonly retry?: RetryConfig
  readonly subagents?: readonly DawnAgent[]
  readonly tools?: ToolScope
  readonly systemPrompt: string
}

Configuration passed to agent(). description is optional metadata for agent and subagent selection. model must be a KnownModelId string. provider is optional. When omitted, Dawn infers a provider for known model families. Set it explicitly to one of the supported built-in provider ids for aliases, ambiguous model names, local models, or provider-router model ids. reasoning maps to OpenAI reasoning-effort options when the selected model supports them. retry controls automatic retries on transient failures. subagents lists child agent descriptors exposed through Dawn's subagent capability. tools scopes route-level tool exposure and approval policy with allow, deny, or approve. systemPrompt is sent as the system message on every invocation.

The built-in agent() route materializes to a LangChain chat model. Dawn infers providers for known model families and lazy-loads the matching LangChain integration package. Raw graph and chain routes can still instantiate any provider directly.

See Agents, Reasoning Effort, and Subagents.

ReasoningConfig

ts
export interface ReasoningConfig {
  readonly effort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh"
}

Optional reasoning-effort tuning for agent() routes. OpenAI reasoning models receive the matching reasoning-effort option; non-reasoning models ignore it.

See Reasoning Effort.

RetryConfig

ts
export interface RetryConfig {
  readonly maxAttempts?: number
  readonly baseDelay?: number  // milliseconds
}

Controls how the runtime retries a failed invocation. maxAttempts caps total attempts (default: 3). baseDelay sets the initial backoff in milliseconds before exponential growth.

See Retry.

DawnAgent

ts
export interface DawnAgent {
  readonly description?: string
  readonly model: string
  readonly provider?: ModelProviderId
  readonly reasoning?: ReasoningConfig
  readonly retry?: RetryConfig
  readonly subagents?: readonly DawnAgent[]
  readonly tools?: ToolScope
  readonly systemPrompt: string
}

Opaque branded type returned by agent(). Carry it as a route export; do not construct it manually. It preserves the public agent config fields plus Dawn's internal brand, including route-level tool policy. Use isDawnAgent() to check values at runtime.

See Agents and Subagents.

isDawnAgent(value)

ts
export function isDawnAgent(value: unknown): value is DawnAgent

Type guard that returns true when value was created by agent(). Checks the internal brand symbol — plain objects with matching keys return false.


Middleware

Functions and types for writing global request middleware. See Middleware.

defineMiddleware(fn)

ts
export function defineMiddleware(fn: DawnMiddleware): DawnMiddleware

Identity helper that types fn as DawnMiddleware so editors infer the argument and return types. Use it as the default export wrapper in src/middleware.ts.

ts
import { defineMiddleware, allow, reject } from "@dawn-ai/sdk"
 
export default defineMiddleware(async (req) => {
  if (!req.headers["x-api-key"]) return reject(401)
  return allow()
})

See Middleware.

allow(context?)

ts
export function allow(context?: Record<string, unknown>): ContinueResult

Returns a ContinueResult that lets the request proceed. Pass an optional context record to inject arbitrary values into every tool invocation for this request.

See Middleware.

reject(status, body?)

ts
export function reject(status: number, body?: unknown): RejectResult

Returns a RejectResult that stops execution and responds with the given HTTP status. When body is provided it is JSON-encoded into the response.

See Middleware.

DawnMiddleware

ts
export type DawnMiddleware = (
  req: MiddlewareRequest,
) => Promise<MiddlewareResult> | MiddlewareResult

The function signature for middleware. Either synchronous or async. Must return allow(...) or reject(...).

See Middleware.

MiddlewareRequest

ts
export interface MiddlewareRequest {
  readonly assistantId: string              // e.g. "/research#agent"
  readonly headers: Readonly<Record<string, string>>  // lowercase keys
  readonly method: string                   // HTTP method
  readonly params: Readonly<Record<string, string>>   // dynamic-segment values
  readonly routeId: string                  // e.g. "/research"
  readonly url: string                      // path + query
}

The request object passed to every middleware invocation. Header keys follow Node convention (lowercase). params contains dynamic-segment values extracted from the route path.

See Middleware.

MiddlewareResult

ts
export type MiddlewareResult = ContinueResult | RejectResult

The union type that middleware must return. Resolved to either ContinueResult (allow) or RejectResult (reject).

See Middleware.

ContinueResult

ts
export interface ContinueResult {
  readonly action: "continue"
  readonly context?: Record<string, unknown>
}

Returned by allow(). The optional context field carries arbitrary data into tool invocations for the current request.

See Middleware.

RejectResult

ts
export interface RejectResult {
  readonly action: "reject"
  readonly status: number
  readonly body?: unknown
}

Returned by reject(). status becomes the HTTP response status code. body is JSON-serialized when present.

See Middleware.


Memory

Functions and types for declaring a route's typed long-term memory. See Memory.

defineMemory(def)

ts
export function defineMemory<S extends z.ZodTypeAny>(def: {
  kind: "semantic" | "episodic" | "procedural" | "reflection"
  scope: readonly MemoryScopeDimension[]
  schema: S
  identity?: readonly string[]
}): DefinedMemory<S>

Declares a route's typed long-term memory. Place the call as the default export of a memory.ts file next to the route's index.ts — that file's presence activates the memory capability, contributes recall, and contributes remember unless memory writes are configured as "off". kind selects the memory category. scope lists the namespace dimensions the memory is partitioned by. schema is a zod schema validating each stored record. identity names the fields used for write reconciliation; it defaults to ["subject", "predicate"].

ts
import { defineMemory } from "@dawn-ai/sdk"
import { z } from "zod"
 
export default defineMemory({
  kind: "semantic",
  scope: ["workspace", "user"],
  schema: z.object({
    subject: z.string(),
    predicate: z.string(),
    object: z.string(),
  }),
})

See Memory and the memory config key.

DefinedMemory

ts
export interface DefinedMemory<S extends z.ZodTypeAny = z.ZodTypeAny> {
  readonly kind: "semantic" | "episodic" | "procedural" | "reflection"
  readonly scope: readonly MemoryScopeDimension[]
  readonly schema: S
  readonly identity?: readonly string[]
}

The descriptor returned by defineMemory(). Carry it as a route's memory.ts default export; do not construct it manually.

See Memory.

MemoryScopeDimension

ts
export type MemoryScopeDimension =
  | "workspace"
  | "route"
  | "tenant"
  | "user"
  | "agent"

The namespace dimensions a memory can be partitioned by, used in DefinedMemory.scope. workspace and route are derived automatically; tenant, user, and agent come from the config-level memory.resolveScope callback.

See Memory.


Route configuration

Types that shape route-level behaviour. See Routes.

RouteConfig

ts
export interface RouteConfig {
  readonly runtime?: "node" | "edge"
  readonly streaming?: boolean
  readonly tags?: readonly string[]
}

Optional metadata that a route's index.ts may export alongside its entry. runtime pins the route to a specific execution environment. streaming enables token-streaming responses. tags are arbitrary labels exposed by the Dev Server UI.

See Routes.

RouteKind

ts
export type RouteKind = "agent" | "chain" | "graph" | "workflow"

Discriminant for the four entry shapes Dawn supports. Determined at build time from the default export of a route's index.ts.

See Routes.


Route types

Open interfaces for module augmentation. Dawn's codegen populates them. See Routes.

RouteStateMap

ts
export interface RouteStateMap {}

Open interface that dawn typegen augments with per-route state shapes. Keyed by route path string (e.g. "/research"). Access via RouteState<P> from dawn:routes.

See Routes.

RouteToolMap

ts
export interface RouteToolMap {}

Open interface that dawn typegen augments with per-route tool type information. Keyed by route path string. Access via RouteTools<P> from dawn:routes.

See Agents, Tools.


Runtime

Types available inside a running route handler. See Tools.

RuntimeContext<Tools>

ts
export interface RuntimeContext<TTools extends ToolRegistry = ToolRegistry> {
  readonly signal: AbortSignal
  readonly tools: TTools
  readonly fs: WorkspaceFs
}

Injected into every tool invocation. signal is aborted when the client disconnects. tools is the registry of all tools bound to the current route, typed as TTools. fs is the workspace filesystem handle, available when the workspace capability is active.

See Tools.

RuntimeTool

ts
export type RuntimeTool<TInput = unknown, TOutput = unknown> = (
  input: TInput,
) => Promise<TOutput> | TOutput

The shape of a single tool function. A tool receives typed input and returns a value or a promise. Dawn infers TInput and TOutput from the function signature at build time.

See Tools.

ToolRegistry

ts
export type ToolRegistry = Record<string, RuntimeTool<never, unknown>>

A map of tool name to RuntimeTool. Used as the constraint on RuntimeContext's TTools type parameter. The generated dawn:routes module provides a concrete RouteTools<P> that satisfies this constraint.

See Tools.

DawnToolContext

ts
export interface DawnToolContext {
  readonly signal: AbortSignal
  readonly middleware?: Readonly<Record<string, unknown>>
  readonly fs: WorkspaceFs
}

The context argument Dawn passes to a route tool's function. signal is aborted when the client disconnects. middleware carries any context injected by allow(...) for the current request. fs is a sandboxed WorkspaceFs handle scoped to the route's workspace/ directory.

See Tools and Workspace Filesystem.

WorkspaceFs

ts
export interface WorkspaceFs {
  readFile(path: string, opts?: { readonly maxBytes?: number }): Promise<string>
  readBinaryFile(path: string, opts?: { readonly maxBytes?: number }): Promise<Uint8Array>
  writeFile(path: string, content: string): Promise<{ readonly bytesWritten: number }>
  listDir(path?: string): Promise<readonly string[]>
}

A sandboxed filesystem handle scoped to the route's workspace/ directory, available as ctx.fs on DawnToolContext. Relative paths resolve against the workspace root; paths inside workspace/ are always allowed, while paths outside consult the permissions store. readBinaryFile throws when the configured filesystem backend does not implement binary reads.

See Workspace Filesystem.


Models

String literal types for model identifiers. See Agents.

KnownModelId

ts
export type KnownModelId =
  | OpenAiModelId
  | GoogleModelId
  | AnthropicModelId
  | XaiModelId
  | (string & {})

The accepted type for AgentConfig.model. Includes named model IDs plus an escape hatch (string & {}) for models not yet in the union. The escape hatch preserves autocomplete for the named values; it does not imply every provider has an adapter in the built-in agent() path.

ModelProviderId

ts
export type ModelProviderId = BuiltInModelProviderId | (string & {})

The accepted type for AgentConfig.provider. Built-in values are openai, anthropic, google, mistral, groq, ollama, xai, and openrouter. The type includes a custom-string escape hatch for future and downstream typing, but built-in agent() materialization currently accepts only the built-in provider ids.

Use provider when model is an alias, an ambiguous local model name, or a provider-routed identifier. Set it to one of the supported built-in provider ids. Without an explicit provider, Dawn conservatively infers OpenAI gpt-*, o3*, and o4*; Anthropic claude-*; Google gemini-*; Mistral mistral-*, mixtral-*, and codestral-*; and xAI grok-*.

OpenAiModelId

ts
export type OpenAiModelId =
  | "gpt-5.5" | "gpt-5.5-pro" | "gpt-5.4" | "gpt-5.4-pro" | "gpt-5-mini"
  | "gpt-4.1" | "gpt-4.1-mini" | "gpt-4.1-nano"
  | "gpt-4o" | "gpt-4o-mini"
  | "o3" | "o3-mini" | "o4-mini"

String literals for supported OpenAI models.

GoogleModelId

ts
export type GoogleModelId =
  | "gemini-3.1-pro-preview"
  | "gemini-3-flash-preview"
  | "gemini-2.5-pro"
  | "gemini-2.5-flash"
  | "gemini-2.5-flash-lite"

String literals accepted by the KnownModelId type for autocomplete. The built-in agent() route infers the Google provider for gemini-* model IDs; raw graph and chain routes can still instantiate Google or any other provider directly.

AnthropicModelId

ts
export type AnthropicModelId =
  | "claude-fable-5"
  | "claude-opus-4-8"
  | "claude-sonnet-4-6"
  | "claude-haiku-4-5"
  | "claude-haiku-4-5-20251001"

String literals for supported Anthropic models. The built-in agent() route infers the Anthropic provider for claude-* model IDs.

XaiModelId

ts
export type XaiModelId = "grok-4.3"

String literals for supported xAI models. The built-in agent() route infers the xAI provider for grok-* model IDs.

inferProvider(model)

ts
export function inferProvider(model: string): BuiltInModelProviderId | undefined

Infers a built-in provider id from a model string for the known families, returning undefined when none match. Matches OpenAI (gpt-*, o3*, o4*), Anthropic (claude-*), Google (gemini-*), Mistral (mistral-*, mixtral-*, codestral-*), and xAI (grok-*). This is the same inference the built-in agent() path uses when AgentConfig.provider is omitted.

SUPPORTED_AGENT_PROVIDERS

ts
export const SUPPORTED_AGENT_PROVIDERS: readonly BuiltInModelProviderId[]
// ["openai", "anthropic", "google", "mistral", "groq", "ollama", "xai", "openrouter"]

The runtime array of built-in provider ids the agent() path can materialize. The corresponding type is BuiltInModelProviderId.

validateModelId(opts)

ts
export function validateModelId(opts: {
  readonly model: string
  readonly provider?: string
}): ModelIdValidation

Advisory check of a model id against the curated per-provider lists (CURATED_MODEL_IDS). When provider is omitted it is inferred via inferProvider. Returns { ok: true } for curated ids — and silently for uncurated or unresolvable providers — so consumers warn rather than hard-fail. On a miss it returns the resolved provider plus up to three nearest curated id suggestions.

ModelIdValidation

ts
export type ModelIdValidation =
  | { readonly ok: true }
  | {
      readonly ok: false
      readonly provider: string
      readonly suggestions: readonly string[]
    }

The result of validateModelId. The ok: false branch carries the resolved provider and the nearest curated id suggestions (closest first, max 3).

Model id constants

ts
export const CURATED_MODEL_IDS: Readonly<
  Partial<Record<BuiltInModelProviderId, readonly string[]>>
>
export const OPENAI_MODEL_IDS: readonly string[]
export const GOOGLE_MODEL_IDS: readonly string[]
export const ANTHROPIC_MODEL_IDS: readonly string[]
export const XAI_MODEL_IDS: readonly string[]

The runtime arrays backing the model-id literal types. Each per-provider constant (OPENAI_MODEL_IDS, GOOGLE_MODEL_IDS, ANTHROPIC_MODEL_IDS, XAI_MODEL_IDS) holds the same ids as its corresponding *ModelId type. CURATED_MODEL_IDS maps each curated provider id to its list and is consumed by validateModelId.


Backend adapter

Low-level interface for custom backend integrations.

BackendAdapter

ts
export interface BackendAdapter {
  readonly kind: RouteKind
  execute(
    entry: unknown,
    input: unknown,
    context: { readonly signal: AbortSignal },
  ): Promise<unknown>
  stream(
    entry: unknown,
    input: unknown,
    context: { readonly signal: AbortSignal },
  ): AsyncIterable<unknown>
}

Interface implemented by Dawn's built-in backends (LangChain, LangGraph). execute handles non-streaming invocations; stream handles token-streaming. Most projects never implement this directly — it is an extension point for custom runtimes.


Utilities

Prettify<T>

ts
export type Prettify<T> = { [K in keyof T]: T[K] } & {}

Resolves intersection and mapped types into a flat object shape. Makes IDE hover tooltips show the actual resolved type instead of unexpanded type algebra. Used internally by codegen; also available for project code.


@dawn-ai/core

Low-level config, discovery, capability, workspace, and typegen primitives used by the Dawn CLI and runtime integrations. Route code usually imports author-facing helpers from @dawn-ai/sdk; use @dawn-ai/core when building tooling, tests, or adapters.

ts
import {
  createWorkspaceFs,
  discoverRoutes,
  loadDawnConfig,
  renderDawnTypes,
  type DawnConfig,
} from "@dawn-ai/core"

See Configuration, Routes, Workspace Filesystem, Memory, and Tools.

Capability exports

ts
export {
  createAgentsMdMarker,
  createMemoryMarker,
  createMemoryMdMarker,
  createPlanningMarker,
  createSkillsMarker,
  createSubagentsMarker,
  createWorkspaceMarker,
  BUILT_IN_TOOL_NAMES,
}

Built-in capability markers detect route/app files and contribute prompt fragments, tools, or stream transformers. createWorkspaceMarker() activates when a workspace/ directory exists or a runtime workspaceRoot is supplied; createMemoryMarker() contributes recall, and contributes remember unless memory writes are configured as "off".

Types in this group include CapabilityMarker, CapabilityMarkerContext, CapabilityContribution, DawnToolDefinition, PromptFragment, StreamTransformer, MemoryContext, MemoryStoreLike, MemoryRecordLike, CapabilityRegistry, AppliedContribution, ApplyResult, and CapabilityError.

createCapabilityRegistry(markers) and applyCapabilities()

ts
export function createCapabilityRegistry(markers: readonly CapabilityMarker[]): CapabilityRegistry
export function applyCapabilities(...): Promise<ApplyResult>

Build and apply a marker registry for a route. Runtime integrations pass the built-in and custom CapabilityMarker list, then collect contributions before materializing an agent route.

gateToolOp() and wrapToolWithApproval()

ts
export function gateToolOp(...)
export function wrapToolWithApproval(...)

Apply tool-level permission checks before a tool executes. See Permissions.

createWorkspaceFs(options)

ts
export function createWorkspaceFs(options: CreateWorkspaceFsOptions): WorkspaceFs

Builds the WorkspaceFs handle used as ctx.fs. CreateWorkspaceFsOptions includes a workspaceRoot, a FilesystemBackend, optional permissions, an AbortSignal, and interruptCapable. The handle resolves paths relative to workspaceRoot, canonicalizes them with the backend's realPath, and uses the same permission gate as the agent-facing workspace tools.

See Workspace Filesystem and Execution Sandbox.

loadDawnConfig(options) and config(value)

ts
export function loadDawnConfig(options: LoadDawnConfigOptions): Promise<LoadedDawnConfig>
export function config(c: DawnConfig): DawnConfig

loadDawnConfig() loads dawn.config.ts for an app root. config() is a typed identity helper for authoring config files.

Types in this group include DawnConfig, LoadDawnConfigOptions, and LoadedDawnConfig.

discoverRoutes(options), findDawnApp(options), and route segments

ts
export function discoverRoutes(options?: DiscoverRoutesOptions): Promise<RouteManifest>
export function findDawnApp(options?: FindDawnAppOptions): Promise<DiscoveredDawnApp>
export function assertDawnRoutesDir(appRoot: string, routesDir?: string): Promise<void>
export function toRouteSegments(routeSegments: readonly string[]): RouteSegment[]
export function isPrivateSegment(segment: string): boolean
export function isRouteGroupSegment(segment: string): boolean

Discovery helpers find the Dawn app root, validate the routes directory, scan route files, and parse filesystem route segment names.

Types in this group include DiscoveredDawnApp, DiscoverRoutesOptions, FindDawnAppOptions, NormalizedRouteModule, RouteDefinition, RouteKind, RouteManifest, and RouteSegment.

State and typegen helpers

ts
export function resolveStateFields(...)
export function extractToolSchemasForRoute(...)
export function extractToolTypesForRoute(...)
export function renderDawnTypes(...)
export function renderRouteTypes(...)
export function renderStateTypes(...)
export function renderToolTypes(...)

resolveStateFields() resolves route state field reducers and defaults. The extraction helpers inspect route tools for JSON schemas and TypeScript signatures. The render helpers produce the generated dawn:routes declaration. Some audits call this group renderTypeDefinitions; the public exports are the four render functions above, not a single renderTypeDefinitions symbol.

Types in this group include ResolveStateFieldsOptions, RouteStateFields, ExtractToolSchemasOptions, ExtractToolTypesOptions, RouteToolSchemas, RouteToolTypes, ExtractedToolSchema, ExtractedToolType, JsonSchemaProperty, ResolvedStateField, and StateFieldReducer.

Tool scope

ts
export function resolveToolScope(
  tools: readonly ScopeInput[],
  scope: ToolScope | undefined,
  context: { readonly isSubagent: boolean; readonly routeId: string },
): ReadonlySet<string>
export function toolOrigin(...): ToolOrigin

Resolve which discovered tools are visible to a route and where each tool came from. Types in this group include ScopeInput and ToolOrigin.

Storage type re-export

ts
export type { ThreadsStore } from "@dawn-ai/sqlite-storage"

ThreadsStore is re-exported for config typing.


@dawn-ai/ag-ui

Pure, transport-agnostic AG-UI translation utilities. The CLI uses the same adapter when dawn dev or dawn start serves POST /agui/{routeId}; generated production entrypoints invoke the exported serveRuntime() function directly. The {routeId} URL segment is the URL-encoded Dawn assistant id, such as %2Fchat%23agent for /chat#agent.

ts
import {
  createCounterIdFactory,
  createDefaultIdFactory,
  fromRunAgentInput,
  toAguiEvents,
  type AguiOutboundEvent,
  type DawnAgentStreamChunk,
  type DawnInterruptEnvelope,
  type DawnMessage,
  type DawnResumeRequest,
  type DawnRunInput,
  type IdFactory,
  type RunContext,
  type ToAguiOptions,
} from "@dawn-ai/ag-ui"

See Dev Server.

ID factories

toAguiEvents uses createDefaultIdFactory() to generate prefixed UUID-based message, tool-call, and tool-result ids when it must synthesize them. createCounterIdFactory() produces deterministic counters for tests. Inject either factory, or a custom IdFactory, through options.idFactory:

ts
const events = toAguiEvents(chunks, context, {
  idFactory: createCounterIdFactory(),
})
ts
export type IdFactory = (kind: "message" | "toolCall" | "toolResult") => string
 
export interface ToAguiOptions {
  readonly idFactory?: IdFactory
}

toAguiEvents(chunks, context)

ts
export function toAguiEvents(
  chunks: AsyncIterable<DawnAgentStreamChunk>,
  context: RunContext,
  options?: ToAguiOptions,
): AsyncGenerator<AguiOutboundEvent>

Maps Dawn token, tool_call, tool_result, interrupt, and done chunks to canonical AG-UI lifecycle, text, and tool events. Upstream tool invocation ids are preserved. Interrupts produce a standard RUN_FINISHED interrupt outcome, successful runs produce a success outcome, and upstream failures produce one RUN_ERROR.

Planning updates, subagent capability events, and other unknown chunk types have no v1 mapping and are ignored.

fromRunAgentInput(input)

ts
export function fromRunAgentInput(input: RunAgentInput): DawnRunInput

Maps every AG-UI message structurally and preserves the original input as raw. A non-empty top-level RunAgentInput.resume array becomes DawnRunInput.resume with the same interruptId, status, and optional payload fields:

ts
export interface DawnRunInput {
  readonly messages: DawnMessage[]
  readonly resume?: Array<{
    readonly interruptId: string
    readonly status: "resolved" | "cancelled"
    readonly payload?: unknown
  }>
  readonly raw: RunAgentInput
}

The adapter leaves AG-UI tools, state, and context uninterpreted in v1; consumers can read them from raw.

SSE subpath: encodeAgUiSse(event, accept?)

ts
import { encodeAgUiSse } from "@dawn-ai/ag-ui/sse"
ts
export function encodeAgUiSse(event: BaseEvent, accept?: string): string

Encodes one AG-UI event as an SSE frame using @ag-ui/encoder. This transport helper is available only from @dawn-ai/ag-ui/sse; the root package remains transport-agnostic.


@dawn-ai/memory-pgvector

Postgres + pgvector backend for Dawn's typed long-term memory store. Use it through DawnConfig.memory.store when an app needs a shared production store, multiple app instances, or indexed vector retrieval.

ts
import {
  assertIdentifier,
  initSchema,
  pgvectorMemoryStore,
  vectorColumnDef,
  type PgvectorMemoryStore,
} from "@dawn-ai/memory-pgvector"

See Memory.

pgvectorMemoryStore(options)

ts
export function pgvectorMemoryStore(opts: {
  connectionString?: string
  pool?: Pool
  dimensions: number
  index?: { m?: number; efConstruction?: number; efSearch?: number }
  schema?: string
  tablePrefix?: string
  recall?: RecallRankingOptions
  vector?: VectorRankingOptions
}): PgvectorMemoryStore

Creates a MemoryStore backed by Postgres tables and pgvector indexes. Schema initialization is lazy and idempotent: the first store operation creates the extension, schema, tables, token indexes, and HNSW index if needed.

dimensions is validated during construction. Dimensions up to 2000 use vector(n); dimensions from 2001 through 4000 use halfvec(n); larger values throw a config error naming the 4000 halfvec index ceiling.

ts
import { config } from "@dawn-ai/core"
import { openaiEmbedder } from "@dawn-ai/langchain"
import { pgvectorMemoryStore } from "@dawn-ai/memory-pgvector"
 
export default config({
  memory: {
    store: pgvectorMemoryStore({
      connectionString: process.env.DATABASE_URL,
      dimensions: 1536,
    }),
    vector: { embedder: openaiEmbedder() },
  },
})

PgvectorMemoryStore

ts
export interface PgvectorMemoryStore extends MemoryStore {
  close(): Promise<void>
}

Implements put, get, search, update, supersede, delete, and listCandidates from @dawn-ai/memory. close() ends the owned pg.Pool; it is a no-op when the store was constructed with an injected pool.

Hybrid search runs when the query includes both queryEmbedding and embedderId. The store retrieves a keyword list and a pgvector nearest-neighbor list, then fuses them with the same shared hybrid ranking core used by SQLite.

vectorColumnDef(dimensions)

ts
export function vectorColumnDef(dimensions: number): { type: string; ops: string }

Returns the pgvector column definition and cosine operator class for a dimension count. Throws for non-positive, non-integer, or greater-than-4000 dimensions.

initSchema(client, options)

ts
export async function initSchema(
  client: PoolClient,
  opts: { prefix: string; schema: string; dimensions: number; m: number; efConstruction: number },
): Promise<void>

Low-level DDL helper used by the store. Most apps should not call it directly.

assertIdentifier(name, value)

ts
export function assertIdentifier(name: string, value: string): void

Rejects malformed schema and table-prefix identifiers before they are interpolated into DDL.


@dawn-ai/testing

Deterministic testing utilities for Dawn apps. The package replaces live model calls with aimock fixtures while running tools, prompts, capabilities, state, and workspace behavior normally.

ts
import {
  createAgentHarness,
  expectFinalMessage,
  expectNoToolErrors,
  expectToolCalled,
  script,
} from "@dawn-ai/testing"

See Testing your Dawn agent, Memory, and Evals.

Harnesses

ts
export function createAgentHarness(options: AgentHarnessOptions): Promise<AgentHarness>
export function createToolHarness(...): Promise<ToolHarness>
export function createWorkspaceHarness(options?: WorkspaceHarnessOptions): Promise<WorkspaceHarness>
export function createMiddlewareHarness(...): Promise<MiddlewareHarness>

createAgentHarness() is the primary route-level test harness. It starts aimock, runs typegen, resolves a route, and returns a harness whose run() method produces an AgentRunResult. Tool, workspace, and middleware harnesses provide narrower unit-test surfaces.

Types in this group include AgentHarness, AgentHarnessOptions, ToolHarness, ToolHarnessOptions, WorkspaceHarness, WorkspaceHarnessOptions, and MiddlewareHarness.

Aimock fixtures and recording

ts
export function script(): ScriptBuilder
export function loadFixtures(path: string): FixtureSet
export function writeFixtures(path: string, fixtures: FixtureSet | ScriptBuilder): void
export function record(options: RecordOptions): void
export function createAimock(...): Promise<Aimock>

script() builds deterministic fixture conversations. loadFixtures() and writeFixtures() manage committed fixture files. record() is a local authoring helper for capturing live model traffic into fixtures.

Types in this group include Aimock, AimockFixture, AimockResponse, AimockToolCall, FixtureSet, ScriptBuilder, and RecordOptions.

Matchers

ts
export {
  expectFinalMessage,
  expectInterrupt,
  expectNoInterrupt,
  expectNoToolErrors,
  expectOffloaded,
  expectPlan,
  expectState,
  expectStreamedTokens,
  expectSubagent,
  expectSystemPrompt,
  expectToolCalled,
  expectToolSequence,
}

Matchers assert final messages, tool calls, tool order, streamed tokens, offloaded outputs, state, subagent runs, plans, system prompts, and permission interrupts. expectNoToolErrors(run) verifies that tool results did not fail; permission interrupts are not counted as tool errors.

Supporting types include InterruptInfo, SubagentEvent, SubagentRun, and Todo.

Run-result utilities

ts
export function collectRunResult(...): Promise<AgentRunResult>
export function deriveToolResults(...): readonly ObservedToolResult[]

Normalize runtime output into AgentRunResult, ObservedToolCall, and ObservedToolResult structures for assertions and eval scoring.

Memory, protocol, and subprocess helpers

ts
export function seedMemory(...): Promise<MemoryStore>
export function createAgentProtocolInjector(...): Promise<AgentProtocolInjector>
export function createSubprocessApp(...): Promise<SubprocessApp>

seedMemory() populates a Dawn memory store for deterministic memory tests. The protocol injector and subprocess app helpers are lower-level orchestration surfaces for custom test runners.

Types in this group include AgentProtocolInjector, InjectResult, and SubprocessApp.

Example

ts
const h = await createAgentHarness({ appRoot, route: "/chat#agent" })
 
const run = await h.run({
  input: "Filter open items",
  fixtures: script()
    .user("Filter open items")
    .callsTool("applyFilter", { status: "open" })
    .replies("Found 2 open items."),
})
 
expectToolCalled(run, "applyFilter").withArgs({ status: "open" })
expectNoToolErrors(run)
expectFinalMessage(run).toContain("Found 2")

@dawn-ai/evals

Programmatic evaluation primitives for running Dawn agents over datasets, scoring each case, and gating aggregate quality.

ts
import {
  contains,
  defineEval,
  gate,
  memoryFresh,
  memoryIsolated,
  memoryRecalled,
  runEval,
  toolCalled,
} from "@dawn-ai/evals"

See Evaluating your Dawn agent and Testing your Dawn agent.

Eval definition and execution

ts
export function defineEval(def: EvalDefinition): EvalDefinition
export function resolveDataset(dataset: Dataset, baseDir: string): Promise<EvalCase[]>
export function runEval(def: EvalDefinition, options: RunEvalOptions): Promise<EvalReport>

defineEval() types an eval module. resolveDataset() supports inline cases, .json, .jsonl, and function datasets relative to a required base directory. runEval() drives a definition with a caller-provided runCase function and returns an aggregate report.

Types in this group include Dataset, EvalCase, EvalDefinition, RunEvalOptions, EvalReport, CaseResult, and ScoredReport.

Scores and gates

ts
export function normalizeScore(score: Score): NormalizedScore
export const gate: {
  mean(...)
  passRate(...)
  everyCase(...)
  perScorer(...)
  all(...)
  any(...)
}
export function resolveGate(...): GatePolicy

Scores can be numbers, booleans, or rich verdicts with a reason. Gates turn case and scorer aggregates into pass/fail decisions for CI.

Types in this group include Score, NormalizedScore, CaseScore, Scorer, ScorerAggregate, GatePolicy, and GateResult.

Built-in scorers

ts
export function exactMatch(options?): Scorer
export function contains(substring: string, options?): Scorer
export function regex(re: RegExp, options?): Scorer
export function jsonEquals(options?): Scorer
export function toolCalled(name: string, options?): Scorer
export function tokensUnder(budget: number, options?): Scorer
export function custom(fn, options?): Scorer
export function llmJudge(options: LlmJudgeOptions): Scorer

General scorers inspect the final message, parsed JSON, tool calls, token count, or arbitrary custom logic. llmJudge() asks a real model to grade quality and requires model credentials when it runs.

Memory scorers

ts
export function memoryRecalled(expectedIds: string[], options?): Scorer
export function memoryFresh(expectedValue: string, options?): Scorer
export function memoryIsolated(forbidden: string, options?): Scorer

memoryRecalled() checks recall tool output for expected memory ids. memoryFresh() checks that a newer value appears in the final response. memoryIsolated() checks that forbidden content did not leak through recall output or the final message.

Example

ts
import { contains, defineEval, gate, toolCalled } from "@dawn-ai/evals"
import { script } from "@dawn-ai/testing"
 
export default defineEval({
  name: "chat quality",
  dataset: [
    {
      input: "Filter open items",
      fixtures: script()
        .user("Filter open items")
        .callsTool("applyFilter", { status: "open" })
        .replies("Found 2 open items."),
    },
  ],
  scorers: [
    contains("Found", { threshold: 1 }),
    toolCalled("applyFilter", { threshold: 1 }),
  ],
  gate: gate.perScorer(),
})

dawn:routes (generated)

The dawn:routes module is emitted by dawn typegen (and implicitly by dawn build). It is never written by hand — the CLI writes .dawn/dawn.generated.d.ts, which declares the dawn:routes module for your app. Import from it to get per-route types narrowed to your project's actual routes and tools.

RouteTools<P>

ts
import type { RouteTools } from "dawn:routes"
 
// P is the route path string, e.g. "/research"
type Tools = RouteTools<"/research">
// resolves to the ToolRegistry for that route

Mapped type that resolves to the ToolRegistry for route P. The keys are the tool names found in that route's tools/ directory; the values are RuntimeTool instances with inferred input and output types. Pass as the TTools argument to RuntimeContext<TTools>.

See Tools.

RouteState<P>

ts
import type { RouteState } from "dawn:routes"
 
// P is the route path string, e.g. "/research"
type State = RouteState<"/research">
// resolves to the state shape for that route

Mapped type that resolves to the typed state shape for route P. Populated from the route's state.ts schema and any dynamic-segment fields extracted from the path. Use it to type workflow and graph handler arguments.

See Routes, State.


Where to read more

  1. Mental Model — how requests, routes, and tools fit together
  2. Routes — route kinds, pathname conventions, and RouteConfig
  3. Agentsagent(), tool auto-binding, model selection
  4. Tools — writing tools, RuntimeContext, type inference
  5. Memory, Planning, Skills, Subagents, and Reasoning Effort — route-level agent behavior
  6. Middleware — request gating, allow(), reject(), context flow
  7. CLIdawn dev, dawn build, dawn typegen, and other commands
  8. Dev Server — local development, hot reload, route playground

Related