# @pleach/gateway (/docs/gateway)



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](/docs/family-lock).
The [model resolution matrix](/docs/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](/docs/model-resolution-matrix).
Gateway re-exports `CallClass`, `ProviderFamily`, and `RoutingDecision`
so you import from one place.

## Not a proxy [#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](/docs/comparison#governance-control-planes-and-ai-gateways-a-proxy-side-category).

**Package:** `@pleach/gateway` ([not on npm yet](</docs/install#not-on-npm-yet>)) · **Source:** [github.com/pleachhq/gateway](<https://www.getpleach.com/docs/gateway>)

## Install [#install]

<Tabs items="['npm', 'pnpm', 'yarn', 'bun']" groupId="pkg">
  <Tab value="npm">
    ```bash
    npm install @pleach/gateway
    ```
  </Tab>

  <Tab value="pnpm">
    ```bash
    pnpm add @pleach/gateway
    ```
  </Tab>

  <Tab value="yarn">
    ```bash
    yarn add @pleach/gateway
    ```
  </Tab>

  <Tab value="bun">
    ```bash
    bun add @pleach/gateway
    ```
  </Tab>
</Tabs>

```typescript
import {
  GatewayClient,
  asTenantId,
  fingerprintByokKey,
  GatewayFamilyDeniedError,
  GatewayFamilyExhaustedError,
  GatewayTransportMissingError,
  type CostEvent,
  type GatewayResponse,
  type GatewayTransport,
} from "@pleach/gateway";
```

## `GatewayClient` [#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.

```typescript
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 [#constructor-options]

| Option             | Required    | What it does                                                                                                                                                                                                                                                                                 |
| ------------------ | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tenantId`         | yes         | Branded `TenantId` — every cost event the client emits carries it.                                                                                                                                                                                                                           |
| `transports`       | effectively | `Map<family, GatewayTransport>`. Omitted → every `route()` call throws `GatewayTransportMissingError`.                                                                                                                                                                                       |
| `allowedFamilies`  | no          | `Set<ProviderFamily>`. Calls with a family outside the set throw `GatewayFamilyDeniedError` before any transport invocation.                                                                                                                                                                 |
| `byokKey`          | no          | Client-scoped BYOK key. Header-only; never persisted. Per-call `route({ byokKey })` overrides it.                                                                                                                                                                                            |
| `costEventEmitter` | no          | Sink for `CostEvent`. Defaults to a no-op so tests and dry-runs don't NPE; production must wire a real sink.                                                                                                                                                                                 |
| `tracer`           | no          | OTel 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](/docs/gateway/otel#llminvocation-spans). |

### `route()` [#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()` [#close]

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

## The transport seam [#the-transport-seam]

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

```typescript
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](#region-routing). The chat-completion transport below
receives the resolved provider, family and model, with no `callClass`.

## The chat-completion transport seam [#the-chat-completion-transport-seam]

<Callout type="warn">
  **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.
</Callout>

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

```typescript
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 [#when-the-provenance-row-cant-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`](/docs/transport-bedrock),
[`@pleach/transport-azure-openai`](/docs/transport-azure-openai), and
[`@pleach/transport-vertex`](/docs/transport-vertex) for the
per-cloud placement.

## Per-call cost event [#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](/docs/gateway/cost-events).

```typescript
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 [#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](/docs/gateway/byok).

```typescript
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 [#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](/docs/model-resolution-matrix#cross-family-fallback-policy)).

```typescript
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 [#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.

```typescript
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 [#errors]

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

| Error                          | When                                                | Thrown before transport?              |
| ------------------------------ | --------------------------------------------------- | ------------------------------------- |
| `GatewayFamilyDeniedError`     | `family` is not in `allowedFamilies`.               | Yes — governance check is first.      |
| `GatewayTransportMissingError` | No transport configured for the resolved family.    | Yes — configuration check is second.  |
| `GatewayFamilyExhaustedError`  | Cascade 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 [#tenant-scoping]

`tenantId` is stamped on every `CostEvent`. It matches the substrate's
[tenant facet](/docs/tenant-facet) and the
[multi-tenant deployment](/docs/multi-tenant) 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 [#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](/docs/gateway/otel#llminvocation-spans)).
* `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 [#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](#failover) and
  [region routing](#region-routing) are opt-in wrappers on
  experimental subpaths, outside the default `route()` path.

## Tenant resolution [#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:

| Adapter                      | Subpath                                | Resolves from                                   |
| ---------------------------- | -------------------------------------- | ----------------------------------------------- |
| `createJwtTenantResolver`    | `@pleach/gateway/auth/adapters/jwt`    | a verified JWT claim (`jwksUri` or `publicKey`) |
| `createClerkTenantResolver`  | `@pleach/gateway/auth/adapters/clerk`  | a Clerk organization/session                    |
| `createOktaTenantResolver`   | `@pleach/gateway/auth/adapters/okta`   | an Okta token introspection                     |
| `createApiKeyTenantResolver` | `@pleach/gateway/auth/adapters/apiKey` | an API-key `Map` or async lookup                |

```ts
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 [#failover]

<Callout type="warn">
  **Experimental** (`status: experimental`). The `@pleach/gateway/failover`
  signatures are not frozen; the package README wins on
  disagreement.
</Callout>

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

```ts
import {
  createFailoverPolicy,
  createFailoverMiddleware,
} from "@pleach/gateway/failover"

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

## Region routing [#region-routing]

<Callout type="warn">
  **Experimental** (`status: experimental`). Vendor-neutral. You
  implement a `RegionResolver` against any backing store.
</Callout>

`@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 [#identity-providers]

<Callout type="warn">
  **Experimental** (`status: experimental`). The base subpath is
  vendor-neutral. Concrete adapters live on per-vendor subpaths.
</Callout>

`@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:

| Subpath                                    | Factory                              | Backing flow                     |
| ------------------------------------------ | ------------------------------------ | -------------------------------- |
| `@pleach/gateway/identity/providers/iam`   | `createIamIdentityProvider`          | AWS STS AssumeRole               |
| `@pleach/gateway/identity/providers/azure` | `createAzureManagedIdentityProvider` | Azure Managed Identity           |
| `@pleach/gateway/identity/providers/gcp`   | `createGcpWorkloadIdentityProvider`  | GCP Workload Identity Federation |

Each factory takes a client matching the vendor SDK shape
(`STSClient.send`, `TokenCredential.getToken`,
`GoogleAuth.getAccessToken`). See the [government use case](/docs/use-cases/government).

## Related SKUs [#related-skus]

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

For the full SKU map see [Which SKU do I need?](/docs/which-sku).

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Family-locked routing" href="/docs/family-lock" description="What locks at session start and how `pickNextInFamily` walks the column." />

  <Card title="Model resolution matrix" href="/docs/model-resolution-matrix" description="The `(family × callClass)` matrix, the downgrade ladder, and the cross-family policy." />

  <Card title="Multi-tenant deployments" href="/docs/multi-tenant" description="Where `tenantId` lives in the substrate." />

  <Card title="@pleach/compliance" href="/docs/compliance" description="Reads gateway cost events for attestation provenance." />
</Cards>
