Skip to content
pleach

@pleach/gateway

@pleach/gateway — multi-tenant model routing, observability, and cost attribution layered over the family-locked matrix.

The gate in the hedge — every call walks through here, in family, on budget, attributable to one tenant. @pleach/gateway is the multi-tenant routing SKU layered over the @pleach/core model-family substrate. One client per tenant accepts a (family, callClass, model, prompt) call, picks a transport, walks the in-family cascade on transient failure, emits one cost event per successful call, and never silently widens across families.

In-family cascade behavior lives in Family-locked routing. The model resolution matrix defines the (family × callClass) cells. This page covers the layer on top: per-tenant scoping, operator allowlist, BYOK fingerprinting, and the per-call cost event.

The package is thin. Routing, the family matrix and BYOK transport resolution live in @pleach/core's model-family module. Gateway re-exports CallClass, ProviderFamily, and RoutingDecision so you import from one place.

Not a proxy

@pleach/gateway routes, refuses over-budget calls, attributes cost, and fails over, like a governed-proxy control plane (Portkey, Cloudflare AI Gateway). The difference is where it sits. A proxy sends your model calls through a vendor and holds the audit trail there. Gateway is an in-process client: it opens no socket of its own, consumes a GatewayTransport you supply, and writes cost events to a sink you own. An out-of-family or over-budget call is denied before it touches the wire. Both approaches enforce at runtime; they differ in altitude. See the comparison.

Install

npm install @pleach/gateway
pnpm add @pleach/gateway
yarn add @pleach/gateway
bun add @pleach/gateway
import {
  GatewayClient,
  asTenantId,
  fingerprintByokKey,
  GatewayFamilyDeniedError,
  GatewayFamilyExhaustedError,
  GatewayTransportMissingError,
  type CostEvent,
  type GatewayResponse,
  type GatewayTransport,
} from "@pleach/gateway";

GatewayClient

Use one client per tenant. tenantId is required; the constructor throws if it's missing or empty. Every cost event carries it, and allowedFamilies is scoped to the client.

const gateway = new GatewayClient({
  tenantId: asTenantId("acme-corp"),
  transports: new Map([
    ["anthropic", anthropicTransport],
    ["openai",    openaiTransport],
  ]),
  allowedFamilies: new Set(["anthropic", "openai"]),
  costEventEmitter: {
    emit(event) {
      eventLog.append(event);
    },
  },
});

const response = await gateway.route({
  family:    "anthropic",
  callClass: "synthesize",
  model:     "claude-sonnet-4-6",
  prompt:    "Summarize the meeting notes …",
});

asTenantId(raw) turns a string into the branded TenantId and throws on an empty value, so an unset env var fails at init instead of silently merging tenants.

Constructor options

OptionRequiredWhat it does
tenantIdyesBranded TenantId — every cost event the client emits carries it.
transportseffectivelyMap<family, GatewayTransport>. Omitted → every route() call throws GatewayTransportMissingError.
allowedFamiliesnoSet<ProviderFamily>. Calls with a family outside the set throw GatewayFamilyDeniedError before any transport invocation.
byokKeynoClient-scoped BYOK key. Header-only; never persisted. Per-call route({ byokKey }) overrides it.
costEventEmitternoSink for CostEvent. Defaults to a no-op so tests and dry-runs don't NPE; production must wire a real sink.
tracernoOTel tracer for llm.invocation spans (any @opentelemetry/api Tracer). Omitted → trace.getTracer("@pleach/gateway") from the optional @opentelemetry/api peer, a no-op when it isn't installed. null disables spans. See OpenTelemetry.

route()

Returns a GatewayResponse with modelInvoked, usage token counts, a cost block, the routingDecision, the cascadeWalks history (empty when the first rung succeeded), and a familyExhausted boolean.

close()

Marks the client closed; later route() calls reject. Transports are yours, so close() doesn't close them.

The transport seam

GatewayClient ships no HTTP clients. You supply a Map<family, GatewayTransport> at construction.

interface GatewayTransport {
  readonly kind:
    | "openrouter"
    | "native-anthropic"
    | "native-openai"
    | "native-google"
    | "bedrock"
    | "azure"
    | "vertex";
  invoke(req: GatewayTransportRequest): Promise<GatewayTransportResponse>;
}

Wrap your existing provider client (OpenRouter HTTP, the Anthropic SDK, an in-house Bedrock adapter) in a GatewayTransport. A transport receives callClass on each request, so it can choose per (family, callClass). Region-aware routing ships separately in Region routing. The chat-completion transport below receives the resolved provider, family and model, with no callClass.

The chat-completion transport seam

Experimental. GatewayChatTransport and createOpenAiCompatibleTransport are not frozen. The package README (not on npm yet) is the source of truth; if a shape here disagrees, the README wins.

GatewayChatTransport is a separate seam from GatewayTransport. GatewayTransport serves GatewayClient.route() and carries no cost. GatewayChatTransport serves GatewayRuntime.routeChatCompletion(): messages in, content + usage out.

interface GatewayChatTransport {
  route(request: GatewayChatTransportRequest): Promise<GatewayChatTransportResult>;
}

The request carries the resolved provider, family, model, messages, tenantId, and optional region and abortSignal. The result carries content, usage (promptTokens + completionTokens), and optional modelInvoked and costUsd.

RouteChatCompletionInput.callClass is optional and defaults to "converse". Any value outside core's ALL_CALL_CLASSES throws TypeError. It's attribution only: it lands on the llm.invocation span and the provenance row, and doesn't choose a model or provider.

When the provenance row can't be stored

routeChatCompletion waits for the provenance write. With provenanceWriteFailure: "fail" (the default on createGatewayRuntime), a LedgerWriteError from provenanceLedger rejects the call with that error. So does a write still pending after provenanceWriteTimeoutMs (default 30000), with reason write-timeout. The provider has already served and billed the call, but its result isn't returned.

Any other rejection is logged with console.error and the call returns. provenanceWriteFailure: "report" logs every failure and returns the call.

costUsd is optional. A transport that computed a cost may surface it; after a failover only the successful transport's cost counts. Otherwise costUsd is omitted and costOmitted is "unpriced", so take cost from your own rate card.

createOpenAiCompatibleTransport is the first concrete GatewayChatTransport. Point baseURL at any endpoint speaking the OpenAI Chat Completions dialect (OpenAI, OpenRouter, Together, Groq, a self-hosted vLLM) and supply an auth header callback. It has no encoder or decoder overrides; for a non-OpenAI wire format, use the lower-level HTTP transport.

The cloud-IAM transports — Bedrock, Azure OpenAI, Vertex — implement the same GatewayChatTransport contract over an IAM-credential adapter in later cuts. See @pleach/transport-bedrock, @pleach/transport-azure-openai, and @pleach/transport-vertex for the per-cloud placement.

Per-call cost event

Every successful route() emits one event to the configured sink, unbatched. A sink can batch internally. Field-level detail is in Cost events.

interface CostEvent {
  readonly type:             "domain.gateway.cost.recorded";
  readonly tenantId:         TenantId;
  readonly family:           ProviderFamily;
  readonly callClass:        CallClass;
  readonly modelInvoked:     string;
  readonly costUsd:          number;
  readonly promptTokens:     number;
  readonly completionTokens: number;
  readonly byokActive:       boolean;
  readonly byokKeyHash?:     string;
  readonly routingDecision:  RoutingDecision;
  readonly timestamp:        string;
}

The full routingDecision rides in the payload, so a downstream consumer such as @pleach/compliance can attest the call without querying the audit ledger. The decision also carries the pre-markup raw_provider_cost_usd and markup_pct separately from the marked costUsd.

In the decision, selected_model is the model the call was dispatched on. family and transport describe the requested route, so after a cross-family fallback they can disagree with selected_model. requested_model appears only when the call ran on a different model. Each fallback_chain entry has a reason of class_downgrade, same_model_retry, user_initiated or model_fallback, so an exhaustive switch needs a model_fallback arm. Steps a client cascade reports to a recording server are asserted by the client, not measured by the server, so don't bill on them.

response.cost.usd is raw_provider_cost × (1 + markupPct), with the 20% flat markup taken from MODEL_FAMILY_MATRIX.

BYOK is header-only

A BYOK key passed to the constructor or to route() goes to the transport in the request and nowhere else. The gateway keeps a one-way fingerprint for cache reuse, audit attribution on the routing decision, and the byokKeyHash field on the cost event. See BYOK.

import { fingerprintByokKey, isSameByokKey } from "@pleach/gateway";

fingerprintByokKey("sk-ant-api03-abc…");
// → "8f3a2b1c4d5e6f78"

isSameByokKey(a, b);
// → true iff fingerprintByokKey(a) === fingerprintByokKey(b)

The fingerprint is opaque and can't be reversed. brandedFingerprintByokKey returns it under a branded ByokKeyFingerprint type.

You're responsible for never logging the raw key.

Family-strict cascade on 503

On a transient transport failure (502, 503, 504, 429, timeout, abort), GatewayClient walks the in-family rungs with pickNextInFamily, in the runtime's order (synthesize → reasoning → utility → converse), skipping rungs already tried. Each attempt adds a CascadeWalk entry to the response.

When every rung fails, the gateway throws GatewayFamilyExhaustedError with the attempted-model list. It does not widen across families: cross-family is your explicit decision (see the cross-family fallback policy).

try {
  const response = await gateway.route({ family: "anthropic", … });
} catch (err) {
  if (err instanceof GatewayFamilyExhaustedError) {
    // err.family            — "anthropic"
    // err.attemptedModels   — ["claude-sonnet-4-6", "claude-haiku-4-5", …]
    // Consumer chooses: widen to "openai", surface to user, or fail.
  }
}

Hard exhaustion throws. The familyExhausted: true flag on the response is reserved. The cascade is bounded at 16 steps, so a misbehaving transport can't loop forever.

allowedFamilies governance

When allowedFamilies is set, route() checks the requested family before any transport call and throws GatewayFamilyDeniedError on denial. Denied calls never touch the wire, never count against rate budgets, and never emit a cost event.

const gateway = new GatewayClient({
  tenantId:        asTenantId("acme-corp"),
  transports:      transportMap,
  allowedFamilies: new Set(["anthropic", "openai"]),
});

await gateway.route({ family: "deepseek", … });
// → throws GatewayFamilyDeniedError
//   err.family            — "deepseek"
//   err.allowedFamilies   — Set { "anthropic", "openai" }

Use it for per-tenant family policy, to block a family during a rollback, or to gate a preview family. The check is on the family, not the model id string, so a client can't reach a family outside its allowlist.

Errors

route() rejects with one of three error classes. The constructor's TypeError for an invalid tenantId is the fourth.

ErrorWhenThrown before transport?
GatewayFamilyDeniedErrorfamily is not in allowedFamilies.Yes — governance check is first.
GatewayTransportMissingErrorNo transport configured for the resolved family.Yes — configuration check is second.
GatewayFamilyExhaustedErrorCascade walked every in-family rung and all failed.No — at least one rung was attempted.

The first two are configuration failures. GatewayFamilyExhaustedError carries the attempted-model list so you can decide what to widen to.

Tenant scoping

tenantId is stamped on every CostEvent. It matches the substrate's tenant facet and the multi-tenant deployment pattern: same field, same partition key. Gateway cost numbers come from the transport's reported usage; the gateway never queries the core audit ledger. Both surfaces partition the same way because both stamp the same opaque tenantId.

Use a GatewayClient per end customer (SaaS) or per cost center (internal). For per-tenant API keys separate from BYOK, manage rotation yourself.

What ships

  • GatewayClient with route() and close().
  • Per-call domain.gateway.cost.recorded event emission with full RoutingDecision payload.
  • BYOK fingerprinting (fingerprintByokKey, isSameByokKey, brandedFingerprintByokKey).
  • Family-strict cascade-on-503 via pickNextInFamily.
  • Operator allowedFamilies allowlist governance.
  • Three typed error classes.
  • Re-exports of CallClass, ProviderFamily, and RoutingDecision from @pleach/core.
  • One OTel llm.invocation span per routed call from route() and per transport-served routeChatCompletion() call, on core's attribute vocabulary (OpenTelemetry).
  • createGatewayRuntime() with routeChatCompletion(). It validates tenantId / family / messages and the allowedProviders hook, resolves the family default provider, and dispatches to the transport wired in GatewayRuntimeConfig.transports (e.g. createOpenAiCompatibleTransport), returning content + usage. costUsd passes through when the transport supplies one; otherwise it's omitted and costOmitted is "unpriced", so take cost from your own rate card. With no transport wired it returns a stub-shape response so you can build against the contract. routeEmbedding(), getProviderHealth(), and getTrafficStats() aren't available yet and throw.

What you provide

  • Transports. createOpenAiCompatibleTransport (from @pleach/gateway/transport) is the only concrete GatewayChatTransport. For a native provider API, Bedrock, Azure or Vertex, implement GatewayChatTransport yourself.
  • Transport choice. The cascade is family-strict and walk-order-strict. To choose per (family, callClass), do it inside your transport. Cross-provider failover and region routing are opt-in wrappers on experimental subpaths, outside the default route() path.

Tenant resolution

@pleach/gateway/auth ships the TenantResolver contract plus createInMemoryTenantResolver for tests. Four adapters resolve a tenantId from a request, each on its own subpath:

AdapterSubpathResolves from
createJwtTenantResolver@pleach/gateway/auth/adapters/jwta verified JWT claim (jwksUri or publicKey)
createClerkTenantResolver@pleach/gateway/auth/adapters/clerka Clerk organization/session
createOktaTenantResolver@pleach/gateway/auth/adapters/oktaan Okta token introspection
createApiKeyTenantResolver@pleach/gateway/auth/adapters/apiKeyan API-key Map or async lookup
import { createJwtTenantResolver } from "@pleach/gateway/auth/adapters/jwt"

const resolver = createJwtTenantResolver({
  jwksUri: "https://issuer.example.com/.well-known/jwks.json",
  tenantClaim: "org_id",
})
const { tenantId } = await resolver.resolve({ headers })

Failover

Experimental (status: experimental). The @pleach/gateway/failover signatures are not frozen; the package README wins on disagreement.

@pleach/gateway/failover wraps a provider chain you supply in a retry loop. It's vendor-neutral and imports no provider SDKs.

  • createFailoverPolicy({ chain, maxAttempts?, backoff? }) — a chain cursor. maxAttempts defaults to and clamps at chain.length; backoff defaults to defaultLinearBackoff.
  • createFailoverMiddleware({ policy, onExhausted?, sleep?, isTransient? }) — wraps a call in runWithFailover(fn). Throws FailoverExhaustedError and emits a structural FailoverExhausted event when the chain runs out.
import {
  createFailoverPolicy,
  createFailoverMiddleware,
} from "@pleach/gateway/failover"

const mw = createFailoverMiddleware({
  policy: createFailoverPolicy({ chain: ["primary", "secondary"] }),
})
const res = await mw.runWithFailover(() => callProvider())

Region routing

Experimental (status: experimental). Vendor-neutral. You implement a RegionResolver against any backing store.

@pleach/gateway/region augments a RoutingDecision with a region and enforces region allowlists:

  • createRegionRouter({ resolver }) — augments a route with its resolved region.
  • createStaticRegionResolver({ region }) — reference single-region resolver.
  • createRegionAwareCascade(...) — filters cascade candidates to a region allowlist.
  • createRegionDrPolicy({ primary, secondaries, mode? }) — primary→secondary DR ordering; mode defaults to "active-passive". Rejects with RegionNotPermittedError when no permitted region remains.

Identity providers

Experimental (status: experimental). The base subpath is vendor-neutral. Concrete adapters live on per-vendor subpaths.

@pleach/gateway/identity resolves short-lived federated credentials per tenant, so multi-cloud deployments needn't copy long-lived API keys into the gateway process. The base subpath ships the contract plus a credential cache:

  • IdentityProvider — the resolution seam. Resolves credentials for an IdentityContext.
  • IdentityContext — carries tenantId, targetFamily, and an optional region.
  • ResolvedCredentials — kind: "static" (a stored key) or kind: "federated" (a bearer token with expiresAt).
  • createTokenCache(...) — a cache that evicts on expiresAt.

Reference adapters resolve against a vendor client you inject:

SubpathFactoryBacking flow
@pleach/gateway/identity/providers/iamcreateIamIdentityProviderAWS STS AssumeRole
@pleach/gateway/identity/providers/azurecreateAzureManagedIdentityProviderAzure Managed Identity
@pleach/gateway/identity/providers/gcpcreateGcpWorkloadIdentityProviderGCP Workload Identity Federation

Each factory takes a client matching the vendor SDK shape (STSClient.send, TokenCredential.getToken, GoogleAuth.getAccessToken). See the government use case.

  • @pleach/core — the family-locked matrix, pickNextInFamily, MODEL_FAMILY_MATRIX, and the re-exported types.
  • @pleach/compliance — consumes domain.gateway.cost.recorded events for attestation provenance.
  • @pleach/observe — wires the gateway's cost events into OpenTelemetry / Datadog / Honeycomb spans.

For the full SKU map see Which SKU do I need?.

Where to go next