Skip to content
pleach
Build

Providers

Wire an LLM provider into the runtime — Vercel AI SDK, Anthropic SDK, or your own — through the `AgentProvider` interface.

A provider is what the runtime invokes to talk to a model. @pleach/core ships two — AiSdkProvider (Vercel AI SDK) and AnthropicSdkProvider (Anthropic's official SDK) — plus one interface (AgentProvider) you implement to wrap any other SDK.

The underlying SDK packages are optional peer deps. The runtime imports them dynamically at provider construction, so you only install the ones you use. See Model resolution matrix for how (family × callClass) resolves to a concrete model id, and Tools for how ProviderToolDef is built.

This page is the reference for the routing cluster's transport layer. The three concepts that decide what fires through which provider — CallClass, Seam, family-lock — are framed in Family-lock → the routing cluster.

ProviderFamily is a closed union of nine: anthropic | openai | google | deepseek | moonshot | mistral | qwen | thinkingmachines | xai. Each family locks the tokenizer, prompt-cache key, tool-call dialect, and refusal pattern — see Family-lock. The transport is one of four: native | openrouter | byok-native | byok-openrouter, locked at session start and never silently mutated.

Same shape, different provider

The fastest swap path is AiSdkProvider + OpenRouter. The model identifier is a <family>/<model> string — change it, change providers. Everything else on the page stays identical.

// Anthropic
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
import { AiSdkProvider, SessionRuntime } from "@pleach/core";

const openrouter = createOpenRouter({ apiKey: process.env.OPENROUTER_API_KEY! });

const runtime = new SessionRuntime({
  provider: new AiSdkProvider({
    model: openrouter("anthropic/claude-sonnet-4-5"),
  }),
  storage: supabaseAdapter,
  userId:  "user_123",
});
// OpenAI — same file, change one string
const runtime = new SessionRuntime({
  provider: new AiSdkProvider({
    model: openrouter("openai/gpt-4o"),
  }),
  storage: supabaseAdapter,
  userId:  "user_123",
});
// Google Gemini — same file, change one string
const runtime = new SessionRuntime({
  provider: new AiSdkProvider({
    model: openrouter("google/gemini-2.5-flash"),
  }),
  storage: supabaseAdapter,
  userId:  "user_123",
});

One OPENROUTER_API_KEY, nine families (anthropic | openai | google | deepseek | moonshot | mistral | qwen | thinkingmachines | xai), identical request shape. The runtime's family-lock reads the <family>/ prefix and locks the tokenizer, prompt-cache key, and tool-call dialect for the session — no silent cross-family fallback. Want direct vendor SDKs instead? Drop the OpenRouter wrapper for @ai-sdk/anthropic, @ai-sdk/openai, @ai-sdk/google etc. — covered below.

import { AiSdkProvider, AnthropicSdkProvider } from "@pleach/core";
import type {
  AgentProvider,
  AgentExecutionConfig,
  ProviderMessage,
  ProviderToolDef,
  ProviderCapabilities,
  ProviderStreamEvent,
  TokenUsage,
} from "@pleach/core/providers";

AiSdkProvider (Vercel AI SDK)

Wraps streamText from ai@6.x. Right pick when you want unified provider switching, the AI SDK's tool dialect, and the ecosystem of community providers. The recommended default — pair with OpenRouter to reach any family from one key.

import { createOpenRouter } from "@openrouter/ai-sdk-provider";
import { AiSdkProvider, SessionRuntime } from "@pleach/core";

const openrouter = createOpenRouter({ apiKey: process.env.OPENROUTER_API_KEY! });

const runtime = new SessionRuntime({
  provider: new AiSdkProvider({
    model:    openrouter("anthropic/claude-sonnet-4-5"),
    maxSteps: 5,
  }),
  storage:  supabaseAdapter,
  userId:   "user_123",
});

Drop the OpenRouter wrapper for a direct provider package any time — @ai-sdk/anthropic, @ai-sdk/openai, @ai-sdk/google, etc.:

import { anthropic } from "@ai-sdk/anthropic";

const runtime = new SessionRuntime({
  provider: new AiSdkProvider({
    model: anthropic("claude-sonnet-4-5"),
    maxSteps: 5,
  }),
  storage: supabaseAdapter,
  userId:  "user_123",
});

Config

FieldTypeDefaultPurpose
modelAI SDK LanguageModelrequiredAny AI SDK model factory output
maxStepsnumber1Maps to AI SDK v6's stopWhen: stepCountIs(N)
tenantHeaderstring | false"x-tenant-id"Name of the tenant header; false sends none
tenantHeaderSentinelsstring[]–Extra "no tenant" placeholders that are never sent

Install the ai package plus a provider package — OpenRouter is the default; switch to @ai-sdk/anthropic / @ai-sdk/openai / @ai-sdk/google for direct vendor access:

npm install ai @openrouter/ai-sdk-provider   # or @ai-sdk/anthropic, @ai-sdk/openai, @ai-sdk/google, etc.

Usage on message.complete

With maxSteps above 1, one turn is several model calls (a step per tool round). AiSdkProvider reports the usage of all of them on message.complete: it reads the AI SDK's totalUsage, not usage, which in ai@6 covers only the final step. Two edge cases are handled so a turn is never under-billed:

  • If totalUsage carries neither an input nor an output count (the stream ended after a finished step without a finish part, for example an error or abort in a later step), the finished steps' usage is summed instead.
  • If the steps cannot be read either, the final step's usage is used.

A count the provider did not report stays absent rather than reading as 0. The stream-part and usage normalizers behind this are public in @pleach/core/ai-sdk.

@pleach/core/ai-sdk

The subpath that reads Vercel AI SDK shapes. It maps the SDK's fullStream parts onto a closed ModelStreamEvent union and its usage objects onto ModelUsage, so code that consumes a stream (a custom provider, a recorded-tape replayer, a billing hook) switches on core's own vocabulary instead of raw SDK parts.

It is a separate subpath, not part of the @pleach/core root, because its declarations reference types from the ai package. A root re-export would force every consumer's type check to have ai installed. Import it only where you already depend on ai.

import {
  loadAiSdk,
  normalizeStreamPart,
  normalizeResultUsage,
} from "@pleach/core/ai-sdk";

const loaded = await loadAiSdk();
if (!loaded.ok) throw new Error(loaded.error); // code: "MISSING_DEPENDENCY"

const result = loaded.ai.streamText({ model, messages });

for await (const part of result.fullStream) {
  const event = normalizeStreamPart(part);
  if (event.kind === "text-delta") process.stdout.write(event.text);
  if (event.kind === "step-finish") console.log(event.usage); // scope: "step"
}

const usage = await normalizeResultUsage(result); // scope: "all-steps"
ExportSignaturePurpose
loadAiSdk() => Promise<LoadAiSdkResult>Dynamic-imports ai. Never throws: a missing install returns { ok: false, code: "MISSING_DEPENDENCY", error, cause }; success returns { ok: true, ai }. The error string carries the install hint.
normalizeStreamPart(part: AiSdkStreamPart) => ModelStreamEventOne streamText().fullStream part to one event. A part type the installed SDK adds later maps to an ignored event rather than throwing.
normalizeLegacyStreamPart(part: unknown) => ModelStreamEvent | undefinedOlder spellings (args, result, textDelta, UI-chunk delta, tool-call-streaming-start, tool-*-available). undefined when the part is not one.
normalizeUnknownStreamPart(part: unknown) => ModelStreamEventPart of unknown provenance: legacy spellings first, then the typed union, else ignored.
isAiSdkStreamPartType(type: string) => type is AiSdkStreamPartTypeTrue for a part type the installed SDK admits.
normalizeUsage(usage: AiSdkUsage | undefined, scope: ModelUsageScope) => ModelUsageNormalize one usage object under an explicit scope.
normalizeStepUsage / normalizeTotalUsage(usage: AiSdkUsage | undefined) => ModelUsageShorthands for scope "step" and "all-steps".
normalizeLooseUsage(usage: unknown, scope: ModelUsageScope) => ModelUsageProvider-spec nested usage or the older flat promptTokens / completionTokens shape. A total is never synthesized from its parts.
normalizeResultUsage(result: AiSdkUsageResult) => Promise<ModelUsage | undefined>Usage for a whole call: totalUsage when it has an input or output count; the summed steps when totalUsage is present but empty; else usage, labelled "final-step". undefined when none is present.

ModelUsage carries scope ("step" | "all-steps" | "final-step") so whoever bills from it states which one they read, plus optional inputTokens, outputTokens, totalTokens, noCacheTokens, cacheReadTokens, cacheWriteTokens and reasoningTokens. noCacheTokens is the uncached share of inputTokens, alongside the cache read and write subsets. ModelStreamEvent is a closed union on kind (text-delta, reasoning-delta, tool-call, tool-result, step-finish, finish, error, abort, ignored, and others), so a switch over it can be checked for exhaustiveness. The union's ModelFinishReason is stop | length | content-filter | tool-calls | error | other.

Serving useChat from a Pleach turn

toUIMessageStreamResponse encodes a turn's stream events as the AI SDK UI message stream, so a page keeps useChat from @ai-sdk/react while Pleach runs the turn on your server. It imports nothing from ai at runtime.

import { toUIMessageStreamResponse } from "@pleach/core/ai-sdk";

export async function POST(req: Request) {
  const { sessionId, text, messageId } = await req.json();
  return toUIMessageStreamResponse(runtime.executeMessage(sessionId, text), {
    messageId,
    signal: req.signal,
  });
}

The response reaches the browser, so authenticate the route and check that the caller owns the session. By default only presentation events cross: text, reasoning, tool input and output, citations and a short allowlist of status events. Error text goes through onError, which returns a generic line unless you replace it.

OptionDefaultEffect
messageIdnoneId for the start chunk. The encoder never invents one.
onErrorgeneric textMaps a thrown value or a failed tool's error to client text.
dataEventsallowlist"all", a list of event kinds, or a function that returns the data or null.
emitToolDenialstrueA denied or timed-out approval settles its call as output-denied. false leaves it approval-requested.

A tool call that failed settles as output-error, never as a success. A denied call stays denied: no later output or error is emitted for it.

Approvals and validateUIMessages. The stream has no chunk that carries an approval decision, so useChat records only the approval id, and ai 6 rejects a settled part without one. Run settleToolApprovals(messages) over the messages before validateUIMessages or before sending them back. It records the decision each settled state implies and leaves every other part alone. toUIMessageChunks and UiMessageStreamEncoder give the same encoding without the Response wrapper.

AnthropicSdkProvider

Wraps @anthropic-ai/sdk directly. Right pick when you want native Anthropic features (prompt caching, extended thinking, tool-use beta flags) without going through a unified wrapper.

import { AnthropicSdkProvider, SessionRuntime } from "@pleach/core";

const runtime = new SessionRuntime({
  provider: new AnthropicSdkProvider({
    apiKey:    process.env.ANTHROPIC_API_KEY!,
    model:     "claude-sonnet-4-5",
    maxTokens: 4096,
  }),
  storage: supabaseAdapter,
  userId:  "user_123",
});

Config

FieldTypeDefaultPurpose
apiKeystringrequired unless client is setAnthropic API key
client@anthropic-ai/sdk client–A client you built, in place of apiKey and baseURL
modelstring"claude-sonnet-4-5-20250514"Model id
maxTokensnumber4096Output token cap per call
baseURLstring–Override for proxies / regional endpoints
betasstring[]–Beta names, sent as the anthropic-beta header. Only betas that don't change a call's price are accepted
cacheControlboolean | { system?, tools?, lastUser? }nonePlaces 5-minute prompt-cache breakpoints; true places all three
thinking{ budgetTokens: number }–Extended thinking. The budget is an integer of at least 1024, below the call's max_tokens
defaultHeadersRecord<string, string>–Extra headers on every request. Auth, anthropic-* and tenant-header names throw
tenantHeaderstring | false"x-tenant-id"Name of the tenant header; false sends none
tenantHeaderSentinelsstring[]–Extra "no tenant" placeholders that are never sent
npm install @anthropic-ai/sdk

Pass your own client

Pass client instead of apiKey when you build the SDK client yourself, for a proxy, Bedrock, Vertex or your own fetch. OpenAINativeProvider takes an openai client the same way. Pass exactly one credential source. A config with neither, or with both, throws ProviderConfigError when the provider is constructed. isProviderConfigError narrows the thrown value.

import Anthropic from "@anthropic-ai/sdk";
import { AnthropicSdkProvider } from "@pleach/core/providers";

const provider = new AnthropicSdkProvider({
  client: new Anthropic({ apiKey, baseURL: gatewayUrl }),
  model:  "claude-sonnet-4-5",
});

Every request through a passed client carries maxRetries: 0. The provider does its own retries, so the client's retry setting never sends a request the audit ledger doesn't see.

Each attempt's modelCall row records attemptOrigin: "host-client". The client may point at any endpoint, so the row keeps its token counts but stays unpriced (costOmitted: "unpriced"). Supply rates for the serving endpoint through servedProviderRates, or use an endpoint that reports its own charge, and the row is priced. List rates are never applied to a host client.

With thinking set, Anthropic's signed thinking blocks arrive as one provider.blocks event. They ride on the request that continues the same turn after a tool call, and are never persisted.

Token counts. Anthropic's own input_tokens excludes the tokens it read from or wrote to the prompt cache. AnthropicSdkProvider reports inputTokens as the total prompt: input_tokens + cache_read_input_tokens + cache_creation_input_tokens, and totalTokens follows. When input_tokens is missing, inputTokens and totalTokens are left out, not zero-filled. A consumer that adds cacheReadTokens or cacheWriteTokens to inputTokens now double-counts them. A call that read or wrote the cache is priced when the rate source carries cache rates. With none, the call is costOmitted: "unpriced".

The AgentProvider interface

Implement this to wrap any other SDK — OpenAI directly, a custom gateway, a local Ollama instance, anything that streams.

interface AgentProvider {
  execute(config: AgentExecutionConfig): AsyncIterable<ProviderStreamEvent>;
  abort(): void;
  readonly capabilities: ProviderCapabilities;
  readonly auditsEveryAttempt?: true; // see "One audit row per provider attempt"
}

AgentExecutionConfig

What the runtime hands you per call.

FieldTypePurpose
messagesProviderMessage[]Normalized conversation history
toolsProviderToolDef[]?Tools available this call
systemPromptstring?Composed system prompt (post-composeBudgetedPrompt)
modelstring?Specific model id when the matrix resolved one
temperaturenumber?Sampling temperature
maxTokensnumber?Output token cap
abortSignalAbortSignal?User pressed stop / turn aborted
providerConfigRecord<string, unknown>?Provider-specific pass-through (cache headers, beta flags)
auditModelCallAttemptAgentProviderAttemptAuditHook?Per-attempt audit hook; set only for a provider that declares auditsEveryAttempt
tenantIdstring?The call's tenant; read only by the provider's tenant header

ProviderMessage

The normalized message shape your provider converts to its native format.

interface ProviderMessage {
  id?: string;
  role: "user" | "assistant" | "system" | "tool";
  content: unknown;
  tool_calls?: Array<{ id: string; name: string; arguments: unknown }>;
  tool_call_id?: string;
  name?: string;
}

ProviderStreamEvent

A tagged union. The runtime adapts these into the public StreamEvent consumers see.

type ProviderStreamEvent =
  | { type: "message.start";    messageId: string; role: string }
  | { type: "message.delta";    delta: string }
  | { type: "message.complete"; messageId: string; usage?: TokenUsage }
  | { type: "thinking.delta";   delta: string }
  | { type: "thinking.complete" }
  | { type: "tool.started";     toolCallId: string; toolName: string; arguments?: unknown }
  | { type: "tool.completed";   toolCallId: string; toolName: string; result?: unknown }
  | { type: "tool.failed";      toolCallId: string; toolName: string; error: string }
  | { type: "provider.blocks";  blocks: readonly ProviderOpaqueBlock[] }
  | { type: "error";            error: string; code?: string }
  | { type: "done" };

Breaking for exhaustive switches. provider.blocks is a new member. A switch over evt.type that ends in a never check stops compiling until it handles or ignores the case. A consumer that doesn't continue a turn can drop the event.

provider.blocks carries provider-native blocks, such as Anthropic's signed thinking, to the request that continues the same turn. They sit on ProviderMessage.providerBlocks. The runtime attaches a block only to a provider whose replaysProviderBlocks names the tag the block carries. AnthropicSdkProvider declares "anthropic". Other providers never receive them, a fallback within the same turn included.

TokenUsage carries inputTokens, outputTokens, totalTokens, cacheReadTokens, cacheWriteTokens and cacheWrite1hTokens (the part of the writes with a 1-hour lifetime) — all optional, all surfaced on message.complete. inputTokens is the total prompt, cached tokens included; cacheReadTokens and cacheWriteTokens are subsets of it, so don't add them on top.

ProviderCapabilities

Feature detection so the runtime knows what to ask for.

interface ProviderCapabilities {
  streaming:         boolean;
  toolCalling:       boolean;
  thinking:          boolean;
  structuredOutput:  boolean;
  maxContextTokens:  number;
  parallelToolCalls: boolean;
}

capabilities is declared metadata. The runtime logs it when it attaches the provider, and checkAgentProviderConformance validates its shape. It doesn't gate anything: toolCalling: false doesn't stop tool dispatch, and thinking: false doesn't drop thinking events.

Minimal custom provider sketch

// lib/providers/myProvider.ts
import type { AgentProvider, AgentExecutionConfig, ProviderStreamEvent } from "@pleach/core";

export class MyProvider implements AgentProvider {
  readonly capabilities = {
    streaming:         true,
    toolCalling:       true,
    thinking:          false,
    structuredOutput:  false,
    maxContextTokens:  128_000,
    parallelToolCalls: false,
  };

  private controller: AbortController | null = null;

  async *execute(config: AgentExecutionConfig): AsyncIterable<ProviderStreamEvent> {
    this.controller = new AbortController();
    const signal = this.controller.signal;
    config.abortSignal?.addEventListener("abort", () => this.controller?.abort());

    const stream = await callMyApi(config, { signal });
    for await (const chunk of stream) {
      yield translateChunk(chunk);
    }
  }

  abort() {
    this.controller?.abort();
  }
}

Drop it onto the runtime:

const runtime = new SessionRuntime({
  provider: new MyProvider(),
  storage:  supabaseAdapter,
  userId:   "user_123",
});

One audit row per provider attempt

AiSdkProvider and AnthropicSdkProvider run their own retries. They set the SDK's maxRetries to 0 and retry up to 2 times themselves, the same budget the SDKs had. A retry happens only for a retryable error and only before the attempt streamed any content. The delay honours retry-after-ms / retry-after up to 60 s, else backs off exponentially. An abort cancels the backoff.

Each request is its own attempt, and each attempt writes its own modelCall audit row, including aborted and served-then-stopped attempts. Before, up to three billed requests shared one row.

A provider opts in by declaring auditsEveryAttempt: true. The runtime then sets config.auditModelCallAttempt, and the provider must call it around every request it sends, retries included:

async *execute(config: AgentExecutionConfig): AsyncIterable<ProviderStreamEvent> {
  const attempt = () => this.send(config); // one HTTP request
  const events = config.auditModelCallAttempt
    ? config.auditModelCallAttempt({ model: config.model }, attempt)
    : attempt();
  yield* events;
}

The hook passes events, order, errors and return() through unchanged. A provider that does not declare the marker keeps exactly one row per call, however many requests it sends. OpenAINativeProvider, AnthropicSdkProvider and AiSdkProvider all declare it. The hook type is AgentProviderAttemptAuditHook (@pleach/core/providers). The contract is experimental.

Check a declaring provider with checkAgentProviderAttemptConformance. Force N requests with a fake transport, then pass N:

import { checkAgentProviderAttemptConformance } from "@pleach/core/testing";

// a fake transport that answers 429 once, then 200
const report = await checkAgentProviderAttemptConformance(myProvider, {
  expectedRequests: 2,
});
// report.ok, report.rows, report.attemptIndices, report.problems

It fails a declaring provider that sends a request outside the hook, and a non-declaring provider asked for more than one request.

Round-end tool-call announcements

An adapter that reports every tool call at the end of the provider round that produced it, after all of that round's text, can say so. Two optional AgentAdapter members carry the answer:

  • announcesToolCallsAtRoundEnd is the adapter-wide flag.
  • toolCallsAnnouncedAtRoundEndFor(messageId) answers for the latest tool-loop decision call served for that message.

The decision node reads them after the call's stream ends. Only when they hold does the final-step carry drop its zero-offset and 200-character guards. An adapter that declares neither keeps both guards.

forgetToolCallsAnnouncedAtRoundEndFor(messageId) is optional too. The decision node calls it as each fire starts, so the per-call answer covers only a call served during that fire. A seam cache re-serve can't inherit the record of an earlier call on the same message. The standard adapter implements all three.

Mid-stream retries. When the standard adapter's client loop retries an attempt that died mid-stream, the dead attempt's text no longer carries into the answer. The loop pushes a content.reset with reason midStreamRetry and the length of the text that attempt forwarded. Only that tail is cleared. Earlier rounds' text and tool calls stay.

Tenant header

AiSdkProvider, AnthropicSdkProvider and OpenAINativeProvider send the call's tenant id on every request, retries included. It is on by default, under x-tenant-id. tenantHeader takes another HTTP header name, or false to send no tenant header at all.

import { AnthropicSdkProvider } from "@pleach/core/providers";

const apiKey = process.env.ANTHROPIC_API_KEY!;

const provider = new AnthropicSdkProvider({ apiKey });                          // x-tenant-id
const renamed = new AnthropicSdkProvider({ apiKey, tenantHeader: "x-org-id" }); // x-org-id
const silent = new AnthropicSdkProvider({ apiKey, tenantHeader: false });       // no header

Data egress

By default your tenant id goes to the model provider, and to any gateway or proxy in between, on every request. That serves per-tenant rate limits, spend attribution and gateway routing. Pass tenantHeader: false when that party must not see the id. Take the tenant from a verified credential (with createPleachRoute, derive it in resolveTenantId), never from a request body or a header the caller controls.

Which tenant. The runtime's tenant wins when it is a real id the header can carry. Else the call's StreamChatOptions.tenantId. Else none. The graph tool loop's own dispatch uses the runtime's tenant only.

What is never sent:

  • a missing, empty or whitespace-only tenant id;
  • the placeholders "default" and "(unattributed)", or any you list in tenantHeaderSentinels, in any letter case;
  • a value with a character outside [A-Za-z0-9._:/@-], or longer than 256 characters. It is dropped, not rewritten.

Your tenantHeaderSentinels apply when the provider sends, not when the tenant is resolved. A runtime tenant equal to one of them still wins over the call's tenant, and then no header is sent.

Refused names. A name that is not an RFC 7230 token, or that is reserved, throws when the provider is constructed. Reserved covers credential and protocol headers (authorization, x-api-key, content-type, ...), forwarding, client-identity, caching and trace headers, and any name starting with a provider, SDK, gateway or browser prefix (anthropic-, openai-, x-stainless-, x-vercel-, helicone-, x-forwarded-, sec-, ...). Names compare case-insensitively, with _ read as -.

Name clashes. On OpenAINativeProvider, a header the provider builds itself under the same name wins, and the tenant header is not added. On AiSdkProvider and AnthropicSdkProvider the tenant header is a call-level header, which overrides the SDK client's default headers, so don't set the same name on the client as well. defaultHeaders on AnthropicSdkProvider and OpenAINativeProvider can't use the tenant header's name, x-tenant-id unless you changed it. The provider throws when it is constructed.

The withTenantHeader fetch wrapper on the tenant facet covers your own outbound HTTP. tenantHeader covers the provider's requests.

Reasoning effort on the wire

The quickstart's default provider stream sends each call's resolved reasoning effort in the field its endpoint expects:

EndpointField sent
OpenRouterreasoning.effort
DeepSeekreasoning_effort
Gemini, through its OpenAI compatibility layerreasoning_effort, thinking models only. "none" only on gemini-2.5 flash
OpenAI reasoning modelsreasoning_effort
Anthropic models that support effortoutput_config.effort. "none" is not sent

A call with no resolved effort, or one the endpoint or model doesn't accept, sends no reasoning field. A custom stream reads the value from the optional reasoningEffort on StandardProviderStreamContext.

ProviderSeam.invoke() applies the seam's resolveCallReasoningEffort on every call, the policy invokeStream already applied. The seam resolves it once per invoke(), keyed on its call class and the resolved family and model id, and forwards the result as StreamChatOptions.reasoningEffort. A resolver that is absent, throws or returns undefined sends no field. So non-streaming callers carry their call class's effort too.

SeamInputMetadata.applyCallReasoningEffort is deprecated and no longer read. Which level each class asks for, and how it is snapped to the model's catalog row, is in runtime strategies.

Family-strict cascade with pickNextInFamily

Provider failure inside the graph cascade walks the locked family ladder rather than silently widening cross-family. The primitive is pickNextInFamily(family, currentModel, triedModels) — it returns the next rung in the same family, or null when every rung is exhausted.

// `pickNextInFamily` is host-supplied — the harness ships no model
// registry, so you author the in-family ladder walk and register it via
// the `contributeFamilyPivot` plugin hook (below). Its signature:
declare function pickNextInFamily(
  family: string,
  currentModel: string,
  triedModels: Set<string>,
): { modelId: string; callClass: string } | null;

const next = pickNextInFamily(
  "anthropic",
  "claude-opus-4-7",
  new Set(["claude-opus-4-7"]),
);
// → { modelId: "claude-sonnet-4-7", callClass: "synthesize", ... } | null

The cascade pivot walks pickNextInFamily in-family. When every rung exhausts, it emits [UXParity:family-exhausted], calls setFamilyExhaustedState({...}), and returns shouldContinue: false. Hosts surface a FamilyExhaustedToast (or wire contributeFamilyExhaustedSurface — see below) and the user explicitly picks another family.

Stay inside the family. null from pickNextInFamily is the explicit termination signal, so surface it.

Non-matrix-resolvable models (BYOK / unrecognized slugs) keep the served model inside the family === null branch. The legacy cross-family fallback runs only under the deprecated legacyNonMatrixFallback opt-in. See Family-locked routing.

Provider routing with ProviderCatalogContract

When your gateway fronts several upstream providers for one model, ProviderCatalogContract lets you tell the runtime which upstreams to prefer — and which to avoid — per call. Supply an implementation via config.providerCatalog.

interface ProviderCatalogContract {
  // Ordered upstream-provider slugs to prefer for modelId, or null for none.
  resolveProviderOrder(
    modelId: string,
    opts?: { readonly exclude?: readonly string[] },
  ): ReadonlyArray<string> | null | Promise<ReadonlyArray<string> | null>;

  // Optional warm-up so the first real call hits a warm cache.
  prefetch?(modelIds?: ReadonlyArray<string>): Promise<void>;
}

The seam attaches the returned order to the call as ProviderPreferences with allowFallbacks: true, so the gateway can still reach a non-preferred upstream when every preferred one is down. Three rules keep it from ever stalling a turn:

  • Fail-soft. A throw, null, an empty array, or a rejected promise means no preference — the call takes the default path.
  • Time-bounded. The lookup is bounded at ~2s; a slower one is abandoned, so a hung catalog loses its preference rather than blocking the stream.
  • opts.exclude de-prioritizes upstreams for one call. The synthesize-time reroute uses it to steer a re-invoke away from an upstream that just degraded — the same recovery move as the stalled-provider pivot, but at the upstream-selection layer.

The slugs are opaque — core never inspects their shape. Your adapter maps them onto the gateway's native routing vocabulary.

Slow-cold-start planner families

Some model families run a slow planner on a cold start — slow enough that they can't win the async-planner race, so waiting the full default budget on them is pure dead time. isSlowColdStartPlannerFamily (@pleach/core/modelfamily) flags them, and the runtime holds a flagged family to a tight 1200 ms planner gate, then moves on rather than dead-waiting. 1200 ms is the fallback: the gate for any other family is 8000 ms, and a planner caller that declares its own ceiling overrides either value. The default planner caller declares 8000 ms.

import { isSlowColdStartPlannerFamily } from "@pleach/core/modelfamily";

// The flagged families are currently "deepseek", "moonshot" and "qwen".
isSlowColdStartPlannerFamily("deepseek"); // true
isSlowColdStartPlannerFamily("anthropic"); // false

Membership keys on the model family, not on your domain — the same axis as the deprecated weak-schema tool budget, which the runtime no longer reads.

Reasoning-only completion recovery

A reasoning / chain-of-thought model (deepseek-v4, o1-class, gemini-thinking) can finish a stream cleanly having emitted reasoning but zero user-facing text and zero tool calls — or hang until the seam watchdog force-unwinds it. Treated naively both look like an outage: the turn cascades to another provider, doubling cost, and can ship an empty answer. The correct behavior is one same-model content-elicitation retry ("write your final answer directly") before declaring the model unavailable.

The seam layer owns this recovery so it fires on the graph path, gated by an opt-in DI on SessionRuntimeConfig. Unset, the seam is byte-identical to today — no recovery arm:

import type { ReasoningRecoveryStrategy } from "@pleach/core/types/strategies";

const reasoningRecovery: ReasoningRecoveryStrategy = {
  // Authoritative: is this a reasoning model eligible for recovery?
  classifier: (modelId) => modelId.startsWith("deepseek-v4"),
  // The re-ask. A STATIC string, or a FUNCTION of the empty turn's
  // own (bounded) reasoning for a CORRECTIVE directive — higher
  // recovery reliability than a cold generic re-ask.
  elicitationPrompt: (ctx) =>
    ctx.reasoningText
      ? `You reasoned:\n${ctx.reasoningText}\n\nNow write the final answer for the user directly.`
      : "Now write your final answer for the user directly. Do not include your reasoning.",
};

const runtime = new SessionRuntime({ /* … */, reasoningRecovery });

The strategy shape mirrors ProviderDegradationStatsResolver — the host owns every domain value (the model set, the elicitation string) so no reasoning-model list lives in core. The recovery fires at most once per invoke, on both the clean-empty return path and the watchdog-unwind throw path, and only cascades if the retry is also content-free. It emits [UXParity:reasoning-only-recovery:*].

The construction above is opt-in — an unset SessionRuntime gets no recovery arm. The packaged createPleachRoute surface flips that default: reasoning-only recovery is on there, so a reasoning model that finishes a stream having emitted only its chain-of-thought gets one same-model re-elicitation instead of cascading to a false family-exhausted. Pass your own strategy to override the classifier or elicitation, or recoverReasoningOnly: false to opt out.

@pleach/core/providers also publishes the shared failure taxonomy — FailureCategory (AUTH / BILLING / RATE_LIMIT / MODEL_UNAVAILABLE / TOOL_HALLUCINATION / …), FailureClassification, BillingDisposition, ModelUnavailableReason — plus classifyEmptyStream (the precondition classifier the seam recovery keys on). Cross-SKU consumers (gateway, replay, observe) share the vocabulary; the provider-specific string→category matchers stay host-injected.

Plugin contribution hooks for retry, continuation, and family pivot

Four optional HarnessPlugin contribution hooks lift the retry loop's domain knowledge out of the host. Each is opt-in; an unset hook returns null and the runtime falls back to its default behavior.

HookReturnsCollectorWhat it owns
contributeRetryPolicyRetryPolicyContributionruntime.plugins.collectRetryPolicy()Retry behavior on transient failures — discovery-only tool set, workflow-narration nudge patterns, nudge template
contributeContinuationPolicyContinuationPolicyruntime.plugins.collectContinuationPolicy()When a tool result needs continuation vs termination — fetch-tool name set, stuck-discovery namespace prefixes, sandbox-clause regex
contributeFamilyPivotFamilyPivotContributionruntime.plugins.collectFamilyPivot()Classify a model into a family, then pick the next in-family rung — deriveFamilyFromModelId + pickNextInFamily paired
contributeFamilyExhaustedSurfaceFamilyExhaustedSurfaceContributionruntime.plugins.collectFamilyExhaustedSurface()UI surface (toast, banner, modal) when the family ladder exhausts — receives family, triedModels, chatId, optional messageId

The four hooks split the responsibility cleanly: contributeRetryPolicy

  • contributeContinuationPolicy carry DATA (tool name sets, regex patterns, templates); contributeFamilyPivot carries OPERATIONS (the harness has no model registry — both classification and in-family pick are host-supplied); contributeFamilyExhaustedSurface carries UI strategy (the harness has no view layer). Sketch:
import type { HarnessPlugin } from "@pleach/core";
import type { ProviderFamily } from "@pleach/core/modelfamily";

// Host-supplied — your own model-registry helpers. The harness has no
// model registry, so you author these and hand them to the runtime
// through `contributeFamilyPivot`.
declare function deriveFamilyFromModelId(modelId: string): ProviderFamily | null;
declare function pickNextInFamily(
  family: ProviderFamily,
  current: string,
  tried: Set<string>,
): { modelId: string } | null;

const myPlugin: HarnessPlugin = {
  name: "my-host",

  contributeFamilyPivot() {
    return {
      deriveFamilyFromModelId,
      pickNextInFamily: (family, current, tried) =>
        pickNextInFamily(family, current, new Set(tried))?.modelId ?? null,
    };
  },

  contributeFamilyExhaustedSurface() {
    return {
      surfaceFamilyExhausted: ({ family, triedModels, chatId, messageId }) => {
        myToastBus.emit({
          kind: "family-exhausted",
          family,
          attempted: Array.from(triedModels),
          chatId,
          messageId,
        });
      },
    };
  },
};

BYOK credential resolution is a sibling path. SessionRuntimeConfig takes a byokResolver, a synchronous (family) => key | undefined. The runtime consults it when it gates direct-family model access, and never for openrouter, which isn't a family. OpenRouter keys come from byokKeys. Any host with its own secrets store implements the same shape.

Provider cascade with audit attribution

Compose a primary plus fallback by wrapping two providers in a third. The cascade records why it fell through so the audit row joins back to a cause, not just a model id.

class CascadeProvider implements AgentProvider {
  constructor(private primary: AgentProvider, private fallback: AgentProvider) {}
  readonly capabilities = this.primary.capabilities;

  async *execute(config: AgentExecutionConfig): AsyncIterable<ProviderStreamEvent> {
    try {
      yield* this.primary.execute(config);
    } catch (err) {
      yield { type: "error", error: String(err), code: "5001" };
      yield { type: "message.delta", delta: "[fallback engaged]" };
      yield* this.fallback.execute({
        ...config,
        providerConfig: { ...config.providerConfig, cascadeReason: "primary_5001" },
      });
    }
  }

  abort() { this.primary.abort(); this.fallback.abort(); }
}

Stalled provider pivot vs user abort

A provider that accepts the request but stalls — a long time-to-first-token, or a stream that opens and then starves — is a failure the cascade recovers from, not a reason to end the turn. When the watchdog unwinds a stalled rung, the runtime tears down that provider stream and pivots to the next healthy rung in the same family, exactly as it does for an outright HTTP failure. See Family-strict cascade with pickNextInFamily for the rung walk itself.

The teardown is classed SYSTEM_ABORT, not USER_ABORT. The distinction is load-bearing for audit metrics: a stalled stream cancels the same way a user pressing Stop cancels it, so without the system-abort tag every provider pivot would inflate the user-abort count. The runtime tags the teardown as a system pivot only when it, not the client, initiated it. A genuine client Stop stays USER_ABORT.

A stalled rung and a dead rung therefore land in the ledger the same shape — a providerCascade row per step (see audit attribution) — and both attribute to a cause, not just a model id. The turn only surfaces an error to the client once every in-family rung is exhausted, the family-exhausted terminal state described in Errors and recovery.

The watchdog ladder

"The watchdog" above is not one timer. The seam samples stream progress on a ~10-second tick and runs a ladder of independent triggers, ordered from record-only to abort:

  • Content-starvation audit. A stream that keeps emitting chunks (reasoning or tool-call deltas) but zero answer content for ~6 consecutive ticks gets a degradation audit record without an abort — the stream may still recover, and the record exists so sustained starvation is attributable even when it does.
  • Zero-delta stall escalation. A fully silent stream force-unwinds after a call-class-scoped tick count — sooner for synthesize and utility (~60s) than for reasoning and converse (~120s). A frozen tool-loop decision stream is dead; a reasoning model may legitimately pause longer.
  • Content-starvation force-unwind. A chunk-dribbling, content-free stream unwinds at a class-scoped ceiling (~180s default, tighter for utility). The default deliberately equals the runtime's own reasoning re-arm budget, so the unwind never preempts work the runtime still considers valid.
  • Tool-call-phase grace. A stream actively emitting tool-call deltas keeps the full ceiling regardless of class, so a healthy tool-argument generation is never cut mid-args.
  • Tool-call caps. The grace has two exceptions. A utility stream past 35 tool-call events with no answer content unwinds. So does a synthesize stream past 20 tool-call events with under 400 characters of content.
  • Synthesize wall-clock ceiling. A synthesize stream unwinds at about 100 s however much it is still emitting.

Every force-unwind lands on the same cooperative teardown described above — classed SYSTEM_ABORT, then the family-strict cascade walks the next rung. The tick counts are tuning constants of the TypeScript seam layer, not wire contract; treat the shape of the ladder as stable and the exact seconds as versioned.

BYOK provider from session-scoped credentials

A multi-tenant deployment carries the customer key on the session, not the process env. Resolve it at construction time from the same userId / organizationId you pass to the runtime.

async function providerForOrg(organizationId: string): Promise<AgentProvider> {
  const apiKey = await loadOrgKey(organizationId);   // your secrets store
  return new AnthropicSdkProvider({
    apiKey,
    model:     "claude-sonnet-4-5",
    maxTokens: 4096,
  });
}

const runtime = new SessionRuntime({
  provider: await providerForOrg("org-acme"),
  storage:  supabaseAdapter,
  userId:   "user-7",
});

Provider vs orchestratorConfig

SessionRuntimeConfig accepts both provider (the AgentProvider-shaped surface above) and orchestratorConfig (a richer config object used by the legacy orchestrator path). Use provider for new code — it's the public substrate API. orchestratorConfig exists so hosts mid-migration don't break; new consumers should ignore it.

The class behind orchestratorConfig was renamed: OrchestratorClient → TurnOrchestrator. OrchestratorClient remains exported from @pleach/core as a deprecated alias for the @pleach/core@1.x migration window and is removed at 2.0.0. Existing imports keep working; new code should reach for TurnOrchestrator (or, better, the provider surface above).

Where to go next