llm-governance-gateway
v0.22.0
Published
Governed structured-output LLM pipeline: rate limit → spend caps (per-user + global circuit breaker) → cache → provider-chain failover → Zod validation → usage logging → LLM-judge, with a deterministic mock provider for CI.
Maintainers
Readme
llm-governance-gateway
The governance layer LLM proxies promised as a TypeScript library you can read.
Every call runs through one governed pipeline:
rate limit → spend caps (per-user + global circuit breaker) → cache
→ schema-validated provider failover → usage log → LLM-judgeNo sidecar proxy to deploy. No hosted control plane. Five runtime dependencies (the Vercel AI SDK, three provider adapters, Zod); everything else is an optional peer. It runs in your process, enforces caps against your database, and the whole pipeline from caps, cache, failover, to judge, runs deterministically in CI with zero API keys.
Providers: Anthropic, Google, OpenAI, OpenRouter, Venice, Together.ai, Hugging Face, plus self-hosted endpoints (Ollama, vLLM, LM Studio, or any OpenAI-compatible server) and enterprise clouds (Bedrock, Azure, Vertex AI, watsonx.ai) via BYO-SDK provider factories, all mixable in one failover chain.
Why
Spend controls in this space are usually observed (dashboards that tell you after the money is gone) or enforced by infrastructure you must operate and trust (proxies, gateways, hosted control planes). This library takes the third path: governance as code in your own runtime, checked before every call, type-safe from Zod schema to spend cap.
- Spend caps that actually hold. Per-user daily caps plus an app-wide daily circuit breaker, checked against your usage store before every call. Unset ≠ uncapped: defaults are conservative, and only an explicit
0opts out. - Schema-validation-aware failover. primary → fallback → backup providers, with 429/5xx-aware retries (widen with
GatewayConfig.isRetryable, e.g. to network errors),Retry-Afterhonoring, and equal-jitter backoff. When a model returns schema-invalid output, the validation error is fed back for one repair attempt, then the chain falls to the next provider. A different model often satisfies the schema where the first couldn't (vercel/ai#9950, #9002). Chain links accept bring-your-own AI SDK models (Azure, Bedrock, custom base URLs). - Deterministic CI. Mock mode replaces providers with registered responders so your AI-dependent test suite runs offline with zero keys.
- Prompt library pattern. Store-as-override, code-as-fallback: admins can edit prompts at runtime; a broken edit (missing
{{placeholder}}) falls back to the code default instead of silently sending a malformed prompt. - Judge in the request path — sampled and budget-aware. Model-graded rubric scoring runs inline (not offline, not async-later): define criteria, sample a fraction of calls, and optionally gate low-scoring responses. The judge skips itself when its estimated cost would cross the global spend cap — a governance check never blows the budget — and gated responses still persist their scores for audit. Plus a free caller-computed rubric and full usage accounting (tokens, cost, latency, trace IDs) with an optional at-rest encryption hook.
- Task-based routing. Name your call sites (
"enrich","dedup_judge","editorial"), assign each a default model in code, and let an admin store override models per task at runtime — with TTL caching and graceful degradation to code defaults when the store is down. - Live model discovery.
listAllProviderModels()queries each vendor's models API for every provider with an API key configured; keyless or erroring providers fall back to static lists so admin UIs stay usable offline. - Prompt test runs.
runPromptTest()executes an edited (even unsaved) prompt body with sample variables against any model, bypassing the cache but not usage logging. The test spend shows up in the cost dashboard underadmin:prompt-test.
Contents
- Why
- How it compares
- Quickstart
- API key setup
- Testing without API keys
- Production storage
- Trialling caps before enforcing them
- Multi-tenancy (optional)
- Failover chains and tiers
- Timeouts and deadlines
- Task-based routing
- Model discovery
- Prompt test runs
- Local / self-hosted endpoints
- Enterprise clouds (Bedrock, Azure, Vertex, watsonx)
- ZDR-aware routing (zero data retention)
- Native Anthropic features (opt-in)
- Governed embeddings
- Per-link temperature
- Judge in the request path
- Batch processing (50% token cost)
- Streaming
- Editable prompts and the cache
- Model-id conventions, and the one place they differ
- The slug names the model
- Attribution beyond userId
- Governed runs (agent loops)
- Policy report
- Observability export (OTel, Langfuse, metrics)
- HTTP service (multi-app deployments)
- Guardrail hooks (pre/post)
- Design notes
- Status
- License
How it compares
| Tool | What it is | Where this library differs | | --- | --- | --- | | LiteLLM | Python proxy and SDK, 100+ providers, budgets and keys managed in the proxy's own database | TypeScript, in-process, governance-first. Seven providers built in plus bring-your-own SDK factories, not a universal adapter. Caps and the ledger live in your database. | | Portkey, Helicone | Gateways you route traffic through (hosted, or self-hosted on their terms); governance and observability live in their control plane | No extra network hop and no control plane to operate. Judge, guardrails and caps run before the provider call, in the same process as your app. Export to Langfuse or OTel if you want dashboards. | | Vercel AI SDK | The provider abstraction and structured-output layer this library is built on | Adds what the SDK leaves to you: enforced spend caps, a usage ledger, schema-validation-aware failover (vercel/ai#9950), a sampled judge, and a deterministic mock provider for CI. |
If you need a hundred providers or a hosted dashboard, use one of the first two. If you need governance you can read, test offline, and keep in your own process and database, this is the one.
Quickstart
Starting fresh? This section is enough. Already have your own retry loop, usage table and model constants? Read Adopting the gateway instead — the SPI boundary (which stores ship and which you write), a phased path where each step is independently revertible, and four traps that have each already bitten a real adopter.
import { z } from "zod";
import { Gateway, MemoryUsageStore } from "llm-governance-gateway";
const gw = new Gateway({
usage: new MemoryUsageStore(),
promptDefaults: [
{
slug: "summarize",
body: "Summarize in one sentence:\n\n{{text}}",
variables: ["text"],
},
],
providers: { apiKeys: { anthropic: process.env.ANTHROPIC_API_KEY! } },
caps: { userDailyCents: 200, globalDailyCents: 5000 },
});
const { object } = await gw.runStructured({
slug: "summarize",
schema: z.object({ summary: z.string() }),
input: { text: "..." },
variables: (i) => ({ text: i.text }),
cacheParts: ["..."], // or cache: false for PII-bearing calls
userId: "user-123",
});API key setup
npx llm-gateway init # guided key entry → .env.local (chmod 600)
npx llm-gateway doctor # validate every configured key against the provider's live models APIKeys resolve in order: ProviderConfig.apiKeys (programmatic) → shell env → .env.local / .env (loaded by the CLI and smoke script via loadEnvFiles(); call it yourself in dev servers if you want file-based keys there too). This is deliberately not a secrets manager because production keys belong in your deploy platform's secret store.
One honest limit: doctor validates keys against each provider's models API. Providers with scoped keys (Venice separates inference from admin keys, for example) can pass doctor yet 401 on generation — a generation-level smoke test is the stronger check.
Testing without API keys
const gw = new Gateway({ usage, promptDefaults, mock: true });
gw.registerMockResponder("summarize", () => ({ summary: "stub" }));Production storage
Reference UsageStore implementations ship for Drizzle ORM (optional peer dependency):
// SQLite / libSQL / Turso (also better-sqlite3, D1, sql.js)
import { DrizzleSqliteUsageStore, ensureTables } from "llm-governance-gateway/drizzle-sqlite";
const store = new DrizzleSqliteUsageStore(db);
await ensureTables(db); // dev quick-start; use drizzle-kit migrations in prod
// PostgreSQL (node-postgres, postgres.js, neon, vercel)
import { DrizzlePgUsageStore } from "llm-governance-gateway/drizzle-pg";Both export their table definitions (aiUsageLog, spendCapEvents, aiJudgeScores) — re-export them from your schema file so drizzle-kit generate produces migrations. Both are integration-tested against a real engine: SQLite through sql.js, Postgres through PGlite and, in CI, a Postgres server over node-postgres (set PG_TEST_URL to run that target locally). Or implement UsageStore yourself over any database (four methods — see src/types.ts).
Pass Redis-backed cache/rate limiting for multi-instance deployments:
import { Redis } from "@upstash/redis";
import { RedisCacheStore, RedisRateLimiter } from "llm-governance-gateway";
const redis = Redis.fromEnv();
const gw = new Gateway({
usage: myDrizzleUsageStore,
cache: new RedisCacheStore(redis),
rateLimiter: new RedisRateLimiter(redis, 20, 60),
});RedisLike is a four-method interface (get/set/incr/expire) — @upstash/redis satisfies it directly; ioredis needs a thin wrapper. The package has no hard Redis dependency.
Trialling caps before enforcing them
Routing real traffic through the gateway before you trust your thresholds against real spend:
caps: { userDailyCents: 200, globalDailyCents: 5000, mode: "observe" }"observe" evaluates every cap and writes the breach to spend_cap_events, but never throws. Default "enforce" blocks, as always.
This is not the same as setting the caps to 0. A zero cap skips the spend sum and the cap event entirely — there is nothing to look at afterwards, which is the opposite of what you wanted when you set out to measure. Observe mode does the whole computation and writes the audit row; only the throw is suppressed.
Two details that matter when you read the data back:
SpendCapEvent.enforceddistinguishes "we blocked this" from "we would have".wouldBlockistruein both modes, so without this flag the rows written before and after you flip the switch are indistinguishable.NULLon rows written before 0.11.0.- Observe evaluates every cap rather than stopping at the first breach, so one call can record a global, an org and a per-user breach. Enforce still short-circuits at the first.
Two things observe deliberately does not relax: the judge's budget-aware self-skip (an observe mode that silently costs more than enforce would be a bad surprise — raise globalDailyCents during a trial if you want full judge coverage), and batch({ maxCostCents }), which is a ceiling you passed for one specific call rather than a threshold on trial.
Multi-tenancy (optional)
orgId scopes a call to one tenant. It is entirely optional — omit it everywhere and the gateway behaves exactly as it did before tenancy existed, down to the cache-key bytes. Single-tenant apps can skip this section.
// One instance serving one tenant:
const gw = new Gateway({ usage, orgId: "acme" });
// One instance serving many — per-call wins over the config default:
await gw.runStructured({ ...opts, orgId: "acme" });What orgId scopes, once present:
| Surface | Scoped behavior |
|---|---|
| Cache keys | aicache:org:<org>:<slug>:<hash> — one tenant can never read another's cached completion |
| Global circuit breaker | Evaluated against that org's spend only; one tenant can't trip another's breaker |
| caps.orgDailyCents | Optional per-org daily cap, on top of per-user caps |
| PromptStore, ModelConfigStore, TaskOverrideStore | Receive orgId so prompts, chains and task routing can differ per tenant |
| UsageStore | Rows and cap events carry orgId; getSpendToday scopes the sum |
Why it's non-breaking. The store SPIs take orgId as an optional trailing parameter, and in TypeScript a function of fewer parameters is assignable to a type declaring more — so an existing getChain: async () => [...] still compiles and still passes. Unscoped cache keys keep their original aicache:<slug>:<hash> form, so upgrading doesn't cold-start your cache. The org_id column is nullable and added in place by ensureSchema, with no backfill.
The one thing that isn't opt-out is the column existing: on the Drizzle adapters ensureSchema adds a nullable org_id to ai_usage_log and spend_cap_events whether or not you use tenancy.
Failover chains and tiers
Provide a ModelConfigStore (e.g. an admin-editable table) to control routing at runtime:
const gw = new Gateway({
usage,
modelConfig: {
getOverride: async () => null, // hard-pin escape hatch
getChain: async () => [
{ provider: "anthropic", model: "claude-sonnet-4-6" },
{ provider: "openai", model: "gpt-4.1" },
],
},
});
// tier: "fast" re-routes every chain link to its provider's cheapest model
await gw.runStructured({ ...opts, tier: "fast" });tier applies to chain links, not to task. A task resolves through its
own defaults entry (or the override store) and its models are built verbatim,
so passing tier beside task does not change which model the task picks.
It is still passed to ModelConfigStore.getOverride(orgId, tier), though, and
that matters more than it looks. A store can use it to let an explicit tier
beat an admin pin — returning null when a tier is set, so a caller's
capability request falls through to the task instead of being silently
downgraded. If your store does that, tier next to task is load-bearing.
Dropping it as redundant makes the store return the pin, the pin outranks the
task, and every named call site stops using its task default for as long as a
pin row exists — with no error, and only when a pin is set.
Configure your own default. A call with no chain, no task and no override falls through to a last-resort default baked into the library. That fallback exists so the quickstart works, not as a recommendation — inheriting it means this library, rather than your deployment, picked your model and your vendor. Reaching it warns loudly once, naming the assumption. Set your own:
providers: { defaultProvider: "openai", defaultModel: "gpt-4.1" },
// or AI_DEFAULT_PROVIDER / AI_DEFAULT_MODEL in the environment
providers: { requireExplicitDefault: true }, // upgrade the warning to a throwConfig or env overrides silence the warning entirely. requireExplicitDefault is off by default so existing callers are unaffected.
Timeouts and deadlines
Every outbound provider call is bounded. The framing is ledger correctness, not latency: the usage row is written after generation returns, so anything that kills a call mid-flight loses the audit trail for money already spent.
const gw = new Gateway({
usage,
timeouts: {
attemptMs: 30_000, // bound on ONE provider attempt. Default 60s.
deadlineMs: 25_000, // bound on the WHOLE call. Default: unbounded.
streamFirstChunkMs: 60_000, // time to a stream's first emission. 0 disables.
streamStallMs: 60_000, // time since a stream's last emission. 0 disables.
},
});
// Per call, and a caller signal for request teardown / client disconnect:
await gw.runStructured({ ...opts, attemptMs: 10_000, deadlineMs: 20_000, signal });Precedence is the same as every other knob: per call → config → built-in default.
attemptMs vs deadlineMs. An attempt timeout means this link is slow — the chain advances to the next provider. A blown deadline means the whole operation is over — no further links, no retries, terminal. Keeping them distinguishable is why the gateway composes abort signals by hand instead of using AbortSignal.any([AbortSignal.timeout(ms), signal]); that composite reports a bare DOMException and can silently never fire.
Set deadlineMs on any platform with its own function deadline. A three-link chain with retries can otherwise run for minutes, and a platform kill takes the usage row with it. Unbounded is the default only because it preserves pre-existing behavior.
Streaming uses chunk-relative clocks, not a total-duration cap: a long stream that is actively producing tokens is healthy, and killing it at N seconds would be a regression. Silence is what is never healthy. Note these clocks measure parsed partial objects, not raw provider chunks — a model that has emitted {"ans has produced no partial yet, which is why the default window is a generous 60s.
On the native Anthropic path, attemptMs is the only knob. The gateway passes its own AbortSignal but deliberately never sets the Anthropic SDK's timeout — two competing clocks make it ambiguous which one aborted a call. A timeout you set when constructing your own client still exists, but the gateway's signal races it and the shorter one wins, so raise attemptMs rather than the client's timeout for long-running native calls (extended thinking, large prompt-cached contexts, server-side web search).
Aborted attempts are ledgered. Every timeout path writes a zero-token usage row before it throws, so a provider call that spent money but never returned still leaves an audit trail. Three error classes carry the diagnosis: AttemptTimeoutError, DeadlineExceededError, and StreamStallError (with phase: "first-chunk" | "stall"). A caller-initiated abort rethrows your own reason unwrapped — the gateway never disguises your cancellation as its own timeout.
Task-based routing
Model ids use a scheme prefix; bare ids are Anthropic: "claude-opus-4-8", "openai:gpt-4.1", "google:gemini-2.5-pro", "openrouter:meta-llama/llama-3.3-70b", "venice:mistral-31-24b".
const gw = new Gateway({
usage,
tasks: {
defaults: {
enrich: "claude-haiku-4-5-20251001", // high volume, low reasoning
editorial: "claude-opus-4-8", // long-form quality
translate: "google:gemini-2.0-flash",
},
store: myAdminOverrideStore, // optional: { getOverrides(): Promise<Record<string,TaskModelSpec>> }
},
});
await gw.runStructured({ ...opts, task: "enrich" });Precedence: modelConfig.getOverride() → task → chain → static default.
Per-task failover chains. A task's model can be a single id or an ordered chain the gateway walks on retryable errors and attempt timeouts:
defaults: {
enrich: "claude-haiku-4-5-20251001", // single model
editorial: [ // primary → fallback → backup2
"claude-opus-4-8",
"openai:gpt-4.1",
"google:gemini-2.5-pro",
],
},The array form is the primary/fallback/backup role chain, with roles expressed as positions — so there's no separate role vocabulary to learn. The single-id form is unchanged and a store returning it stays assignable.
Model discovery
import { listAllProviderModels } from "llm-governance-gateway";
// Every provider with a key: live model list from the vendor's models API.
const models = await listAllProviderModels(gw.registry);
// [{ provider: "anthropic", models: [...], source: "api", configured: true }, ...]Prompt test runs
const res = await gw.runPromptTest({
slug: "summarize",
body: "Summarize as haiku:\n\n{{text}}", // unsaved editor draft
variables: { text: "sample input" },
model: "openai:gpt-4.1-mini", // or task: "enrich", or omit for default
userId: "admin-id",
});
// res.text, res.costCents, res.durationMs — spend logged as route "admin:prompt-test"Local / self-hosted endpoints
Ollama, vLLM, and LM Studio work zero-config via localhost presets; any OpenAI-compatible server works via the endpoint registry:
const gw = new Gateway({
usage,
providers: { endpoints: { gpubox: { baseURL: "http://gpu:8000/v1", apiKeyEnv: "VLLM_KEY" } } },
modelConfig: {
getOverride: async () => null,
getChain: async () => [
{ endpoint: "gpubox", model: "qwen2.5-72b" }, // local first
{ provider: "anthropic", model: "claude-sonnet-4-6" }, // cloud fallback
],
},
});
// Task ids too: defaults: { summarize: "ollama:llama3.3" }Endpoint tokens are logged but cost $0 and never count against spend caps — caps are about real money. A flaky local vLLM gets the same schema-validated failover as a cloud API, so local-first/cloud-fallback chains work out of the box.
Enterprise clouds (Bedrock, Azure, Vertex, watsonx)
Bring your own cloud SDK — the gateway takes a factory, keeping this package at zero cloud dependencies and leaving SigV4/Entra/ADC/IAM auth to the SDKs built for it:
import { createAmazonBedrock } from "@ai-sdk/amazon-bedrock"; // your dependency
const bedrock = createAmazonBedrock({ region: "us-east-1" });
const gw = new Gateway({
usage,
providers: {
factories: { bedrock: { model: (id) => bedrock(id) } },
pricing: { "anthropic.claude-sonnet-4-6-v1:0": { in: 0.3, out: 1.5 } }, // region rates: yours to supply
retention: { bedrock: { zdr: true, note: "in-region, no retention per AWS terms" } },
},
modelConfig: {
getOverride: async () => null,
getChain: async () => [
{ factory: "bedrock", model: "anthropic.claude-sonnet-4-6-v1:0" },
{ provider: "anthropic", model: "claude-sonnet-4-6" }, // direct-API fallback
],
},
});
// Task ids too: "bedrock:anthropic.claude-...". Recipes for all four clouds
// (including a watsonx IAM token-refresh helper): examples/enterprise-recipes.mdFactory models cost real money: unknown pricing warns and estimates conservatively — never silent $0 — and factories are NOT ZDR until you assert your contract terms.
ZDR-aware routing (zero data retention)
Route by where data is retained, not just what it costs:
const gw = new Gateway({
usage,
providers: {
retention: {
anthropic: { zdr: true, note: "org ZDR addendum signed 2026-05" },
"openai:gpt-4.1-enterprise": { zdr: true }, // model-specific beats provider-level
},
},
tasks: {
defaults: { intake_summary: "claude-haiku-4-5-20251001" },
constraints: { intake_summary: { requireZdr: true } },
},
});
await gw.runStructured({ ...opts, requireZdr: true }); // or via the task constraintFailover chains skip non-eligible links and error only when none remain; the usage log records zdrEnforced so audits can prove the constraint held. Two things stated plainly: retention status is caller-asserted — ZDR is a contractual property of your account (Anthropic ZDR addendum, OpenAI enterprise tiers, in-region Bedrock), and this library will not pretend to detect it; missing entries are treated as NOT ZDR (fail closed). Self-hosted endpoints default to ZDR — override if yours is shared infrastructure. Check your own contracts: Anthropic Trust Center, OpenAI enterprise privacy, provider DPAs generally.
Native Anthropic features (opt-in)
Adaptive extended thinking, prompt-caching cache_control, and server-side web search need Anthropic's native API. Bring your own client — the package takes no dependency on @anthropic-ai/sdk:
import Anthropic from "@anthropic-ai/sdk";
const gw = new Gateway({
usage,
anthropic: { client: new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }) },
});
await gw.runStructured({
...opts,
system: "You are a meticulous analyst.",
anthropic: {
thinking: true, // adaptive; or { budgetTokens: 8000 }
cacheSystem: true, // ephemeral cache_control on the system block
webSearch: { maxUses: 4 }, // server-side web search, billed per request
},
});Only Anthropic links use the native client — other chain providers stay on the AI SDK, and failover still works across the boundary (native link fails → AI SDK fallback link runs). Thinking is gated per model (sending it to Haiku would 400). Cache-write/cache-read tokens and web-search counts are captured in the usage log and included in cost estimates.
The same options work on runText for web-search-grounded text generation — no schema, no emit tool, the model's text blocks are the answer:
const res = await gw.runText({
slug: "discovery",
input: { town: "Springfield" },
variables: (i) => ({ town: i.town }),
cache: false,
anthropic: { webSearch: { maxUses: 4 } },
});
// res.text is the grounded answer; res.webSearches says how many searches it usedOne caveat stated plainly: an unsupported-temperature 4xx on a native link is deliberately non-retryable, and a grounded call that fails over to a non-Anthropic link produces an ungrounded answer from the fallback model. If grounding is a hard requirement, keep the chain Anthropic-only for that call.
Governed embeddings
Embedding spend at document-pipeline volume is real money — it goes through the same front door (rate limit, caps, ZDR, ledger):
const { embeddings } = await gw.embed(texts, {
model: "openai:text-embedding-3-small", // default; pricing built in
dimensions: 1536,
userId, route: "docs/pipeline",
});
// Mock mode: deterministic seeded unit vectors (identical input → identical
// vector). BYO any AI SDK EmbeddingModel via opts.embeddingModel.Providers. OpenAI and Voyage are first-class (EMBEDDING_PROVIDER_IDS); Voyage speaks the same OpenAI-compatible embeddings shape, so it needs a base URL and a VOYAGE_API_KEY, not a new dependency:
await gw.embed(texts, { model: "voyage:voyage-3" }); // priced and attributed to voyageAnything else — a self-hosted encoder, a provider the gateway doesn't model — still goes through the embeddingModel BYO seam, which stays an escape hatch rather than the only option.
Embedding calls take the same bounds as generation (signal, attemptMs, deadlineMs) and the same orgId scoping.
Per-link temperature
Model temperature tolerance differs per chain link — claude-sonnet-5 rejects any non-default temperature (a 4xx, which is deliberately not retryable, so it fails the call rather than falling through). Override per link: null = never send, a number pins it, unset inherits the call level:
getChain: async () => [
{ provider: "anthropic", model: "claude-sonnet-5", temperature: null },
{ provider: "openai", model: "gpt-4o", temperature: 0.3 },
],Judge in the request path
const res = await gw.runStructured({
...opts,
judge: {
criteria: {
grounded: "Every claim is supported by the provided context",
brevity: "No filler or repetition",
},
sampleRate: 0.1, // judge 10% of calls — bounded eval spend
model: "claude-haiku-4-5-20251001", // cheap judge model
mode: "gate", threshold: 3, // optional: throw JudgeGateError below 3/5
},
});Scores land in your UsageStore (saveJudgeScore) linked to the call's usage row; judge spend is logged under route: "judge:<route>" so eval cost is visible, not hidden. In mock mode, register judge:<slug> responders to test gating deterministically.
The judge tier. The judge runs in the request path on every sampled call, so which model it uses is a governance decision an operator makes deliberately — not something it should inherit from whichever provider happens to be the default. It is a first-class tier alongside fast/power, and an admin can pin it at runtime:
providers: { tiers: { anthropic: { fast: "...", power: "...", judge: "claude-haiku-4-5-20251001" } } },
modelConfig: { getJudgeModel: async (orgId) => "openai:gpt-4o-mini" }, // admin pin, per tenantResolution: per-call judge.model → getJudgeModel() → gateway judge.model → provider judge tier → provider fast tier. There is no built-in judge model for any provider; an unset judge tier falls back to fast, which is the pre-tier behavior.
The judge can never fail your request. It runs on its own small budget, and a judge that times out, errors, or exhausts its budget is skipped — the response it was scoring still returns. A governance check must never be the thing that breaks the request it was watching.
Batch processing (50% token cost)
Anthropic Message Batches with two-phase spend accounting — see the design doc:
import Anthropic from "@anthropic-ai/sdk";
import { anthropicBatchClient, MemoryBatchJobStore } from "llm-governance-gateway";
const gw = new Gateway({
usage,
batch: { client: anthropicBatchClient(new Anthropic({ apiKey })), store: jobStore },
});
const sub = await gw.submitBatch(ItemSchema, {
slug: "menu_extract",
model: "claude-haiku-4-5-20251001",
items: pages.map((p) => ({ id: p.id, variables: { html: p.html } })),
maxCostCents: 500, // optional hard ceiling — the ESTIMATE is not the guarantee
});
// sub.cached — items served from cache, never submitted
// Reservation logged at submit: a submitted batch is committed money.
// Later (cron): if ((await gw.pollBatch(sub.batchId)).ready) …
const { results, costCents } = await gw.reconcileBatch(sub.batchId, ItemSchema);
// per-item: { ok:true, object } | { ok:false, reason: "schema"|"errored"|"expired"|"canceled" }Reconcile logs per-item discounted actuals, releases the reservation with a compensating row (net spend = actuals), and is idempotent by job state. Schema-invalid items are flagged, never silently re-run at sync prices.
Streaming
streamStructured runs the same governance front door (rate limit → caps → cache), then streams partial objects:
const res = await gw.streamStructured({ ...opts });
for await (const partial of res.partialObjectStream) render(partial);
const final = await res.object; // resolves after usage logging + cache write
res.failovers; // links abandoned before this one — read after `object` settlesMid-stream failover. When a link stalls or fails retryably, the gateway abandons it and restarts on the next link in the chain. Each abandoned attempt is ledgered as its own zero-token row, and onStreamFailover fires with reason ("stall" | "retryable") and hadPartialOutput.
The degradation contract, stated plainly: the next link restarts the object from scratch. A consumer rendering partials will see the object rebuild, not continue — the partial sequence is not monotonic across a failover. No information is lost (every partial is a complete snapshot), but a UI that assumes fields only ever accumulate will flicker. hadPartialOutput is the flag that tells you it happened; if that matters to your UI, buffer until object settles instead of rendering partials.
Restarting rather than resuming is deliberate: no provider offers mid-object continuation, and stitching two partial JSON objects together produces a document neither model would have written.
Remaining constraints, stated plainly: no repair retry, no judge, no native-Anthropic options on the streaming path. Cache hits return a single-emission stream.
Streaming text with tools: streamText
For a chat turn: text deltas, tool calling, same front door (rate limit, spend cap, guardrails, ledger). No cache and no judge. The caller builds the system prompt and messages; the slug names the call.
import { stepCountIs } from "ai";
const res = await gw.streamText({
slug: "scout-chat-user",
system,
messages, // must end with a user message
tools, // the AI SDK executes them
stopWhen: stepCountIs(4),
userId,
route: "scout-chat",
signal: req.signal,
});
for await (const delta of res.textStream) send(delta);
const out = await res.result; // after the ledger row: text, toolCalls, toolResults, usage, degradedThe failure contract is different from streamStructured's. Restarting text would repeat words the user already read, so:
- Before the point of no return (the first text delta or the first executed tool call), a stall or retryable error fails over to the next link.
- After it, the turn never restarts. The gateway appends a notice (
DEFAULT_DEGRADED_NOTICE, or yourdegradedNotice), ends the stream normally, resolvesresultwithdegraded: true, and ledgers the turn at an estimated cost. - A caller abort ends the stream with no notice;
resultrejects with your reason and the spend is still ledgered. - The stall clock pauses while a tool runs, so a slow tool is not a stall.
Native Anthropic streaming. Pass anthropic: { webSearch, thinking, cacheSystem } and Anthropic links stream through GatewayConfig.anthropic's client (messages.create({ stream: true })), with the same failure contract and with web searches and cache tokens on the ledger row. Text messages only, and not combinable with tools. For a long non-interactive completion, runText({ anthropic: { stream: true } }) uses the streaming transport and returns the joined text, which avoids the Anthropic SDK's 10-minute ceiling on non-streaming requests.
The same turn without a stream: generateText
For an agent nobody is watching: a worker, a queue consumer, a sub-agent. It
takes what streamText takes and resolves with the result.
const out = await gw.generateText({ slug: "triage-agent", system, messages, tools, stopWhen: stepCountIs(12), run });
out.text; out.toolCalls; out.toolResults; out.usage; out.traceId;
out.runStopped; // the run's budget cut the loop
out.toolDenials; // tool calls the policy or a hook refusedIt is the same governed loop as streamText, not a second one, so a run's
budget, a tool policy and the guardrail hooks behave identically and write the
same ledger rows. Two things differ, because no one has read any partial text:
- A link that fails after producing text, but before a tool has run, is failed
over like any other.
failovers[].hadPartialOutputistruefor it, and its row carries what it spent. - A turn that fails after a tool has run rejects with the error. It is not
failed over, since that would run the tool a second time, and there is no
notice to append. What it spent is ledgered first, on a row marked
degraded.
It reads the provider's streaming endpoint to do this, so streamFirstChunkMs
and streamStallMs still bound a silent provider. A provider that cannot
stream tool calls will not work with it.
Editable prompts and the cache
If prompts are edited at runtime — a prompt library, an admin UI, anything that
writes to your PromptStore — turn this on:
const gw = new Gateway({ ...cfg, invalidateCacheOnPromptChange: true });Without it, publishing a prompt changes nothing for any input already cached until the TTL expires (24h by default). The cache is read before the prompt is loaded, and the prompt is not part of the key, so the admin sees a successful edit while production keeps serving output generated by the previous version. Nothing reports a problem. That is the worst failure shape an admin tool can have, and it is why this exists.
With it on, the key carries a fingerprint of the resolved prompt — body,
modelHint, providerOverride and temperature — so an edit makes prior
entries unreachable rather than stale. Repointing a prompt at a different model
invalidates too, since that changes the answer just as surely as editing the
text.
The cost, which is why it is opt-in rather than the default: the prompt has
to be loaded before the cache can be consulted, so every cache hit gains a
getPrompt round-trip. Deployments running static promptDefaults with no
prompt store gain nothing here and should leave it off.
Two notes:
- Keys are unchanged when off, so upgrading does not cold-start an existing cache. Turning it on invalidates every existing entry once, by design.
- It fingerprints rather than versioning. A version number is only correct while every writer remembers to bump it, and one that forgets reintroduces exactly this bug — silently. A hash cannot go stale, and needs nothing of your store.
Model-id conventions, and the one place they differ
Most places take a scheme-prefixed id — tasks.defaults,
ChainLinkConfig.model, judge.model: "openai:gpt-4.1", bare means Anthropic.
Pricing is keyed on the bare id, because that is what a chain link carries and what the cost lookup uses:
providers: { pricing: { "gpt-4.1": { in: 0.2, out: 0.8 } } } // bare
gw.registry.addPricing("openai:gpt-4.1", { in: 0.2, out: 0.8 }); // also fine — normalisedBoth forms work: a prefixed key is normalised to the bare id on the way in. It did not use to be, and the failure was invisible — the key registered, nothing ever read it, and every call for that model was silently priced at the fallback estimate instead of the real rate. An adopter shipped that to production and found it by reading the source.
Usage rows keep the split: entry.provider is "openai" and entry.model is
"gpt-4.1", never rejoined. Reconstruct the prefixed id from both if your own
cost table uses that convention.
Check at startup, not in production:
gw.registry.assertPricingComplete(["gpt-4.1", "claude-sonnet-4-6", "google:gemini-2.5-pro"]);Throws listing everything unpriced. missingPricing() is the non-throwing form.
Run it at boot or in a test — a model with no pricing still generates fine, it
just costs you accurate spend data, which is the one thing this library exists to
give you. Unpriced models also warn once each (not once per call, which was
noise on a hot path).
There is deliberately no strict mode inside the cost calculation itself. Estimation runs inline in the usage-row payload, so throwing there would cost the ledger row for a call that already spent money — trading a wrong cost for no record at all.
The slug names the model
If your prompt library already stores a model next to each prompt, let that row decide. Turn it on once:
const gw = new Gateway({ ...cfg, slugPinWins: true, zdr: { slugs: ["intake-summary"] } });With slugPinWins, a slug whose row pins a model is routed by that pin, ahead
of the admin pin, the task and the chain. Code never names a model on a call;
an admin changes a call's model by editing the slug's row.
// A PromptStore row (or a PromptDefault in code)
{
slug: "scout-chat",
body: "...",
modelHint: "claude-sonnet-4-6", // the slug's model
tierModels: { fast: "claude-haiku-4-5-20251001", // rare: a user-facing
power: "claude-sonnet-4-6" }, // fast/power switch
fallbackModels: ["openai:gpt-4.1"], // tried next, in order
}- Which model:
tierModels[tier]when the row hastierModelsand the call passed atier; otherwisemodelHint; otherwise the power model. - On failure: the row's
fallbackModelsin order, then the configured chain. The admin pin and the task are skipped once a slug is pinned. - A slug that pins nothing resolves exactly as before.
- Every method:
runStructured,runText,streamStructured,streamText,generateText, andsubmitBatchwhen it is given nomodel.streamTextandgenerateTexttake your assembled prompt and still read the slug's row for its model. - The ledger says who decided. Model rows carry
routedBy:"slug","slug-fallback","admin-pin","task-override","task-default","chain"or"default"."chain"on a pinned slug means its own models all failed.
zdr.slugs is separate and works with or without slugPinWins. A slug listed
there is ZDR-required on every call, whatever the call or its task says. The
lock is in code on purpose: it is a security decision, and a prompt row is
something an admin can edit. On a locked slug the pin is filtered like
everything else, and if none of the slug's own models is ZDR-eligible the call
throws ZdrViolationError instead of quietly running on the chain.
Off by default, and off means resolution is unchanged. The reference Drizzle
adapters gain one nullable column for routedBy:
ALTER TABLE ai_usage_log ADD COLUMN routed_by TEXT;Design and the calls made in building it: docs/design/model-naming.md.
Attribution beyond userId
userId, orgId, app, route and promptSlug are the dimensions the gateway itself reasons about — caps, cache scoping, routing. If your cost model has one the gateway has no opinion on, pass it as metadata:
await gw.runStructured({ ...opts, metadata: { agentRunId, requestId } });It lands on every usage row the call writes and is handed to your UsageStore as-is. The reference Drizzle adapters persist it (SQLite JSON, Postgres jsonb).
The gateway never reads it — not in the cache key, not in routing, not in caps. Two calls differing only in metadata still share a cache entry, so an attribution field can't silently become a cache-busting bug.
It reaches the rows that are easy to forget, which are usually the ones that matter: cache hits (whose share grows exactly as your hit rate improves), the judge's own row, and the zero-token row written when an attempt times out.
One caveat: metadata is not covered by the encrypt hook, which applies to inputText/outputText only. Keep PII out of it, or encrypt it yourself before passing.
Governed runs (agent loops)
The daily caps bound a user per day. An agent loop can spend a day's budget in a minute. A run groups the calls of one agent turn, gives them a dollar budget across all of them, and bounds how many there may be:
const run = gw.startRun({ budgetCents: 100, maxSteps: 20 });
const plan = await gw.runStructured({ ...planOpts, run });
const chat = await gw.streamText({ slug: "agent", messages, tools, run });
await gw.embed(chunks, { run });
run.spentCents; // counted from the ledger rows the gateway wrote
run.remainingCents(); // undefined when nothing in the chain has a budgetEach governed call that carries the run is one step. What you get:
- Lineage in the ledger. Every row a step writes (final, cache hit,
guardrail block, failed link, judge) carries
runId,stepIndexandparentRunId. "What did this run cost" is oneWHERE run_id = ?. - A hard budget across calls. Checked before every call, in the same front
door as the daily caps. Once the run has spent
budgetCentsthe next call throwsRunLimitErrorbefore any provider is contacted, and a spend-cap event records it with the run id.caps.mode: "observe"records without throwing, like every other cap. - A step ceiling. The call past
maxStepsthrowsRunLimitErrorand leaves a zero-token row (provider: "run"). Always enforced, observe mode included: it is a loop guard, not a threshold on trial. - Nesting.
gw.startRun({ parent: run })makes a child for a sub-agent. Its spend also counts against the parent, and it is refused when the parent runs out. A sub-agent cannot spend what its parent has not got. - Runs that span processes.
run.snapshot()is JSON;gw.resumeRun(snapshot)continues it.
Inside a tool loop. One streamText call is one step of the run, however
many tool-loop steps the AI SDK takes inside it. The run still governs the
loop:
const res = await gw.streamText({ slug, messages, tools, stopWhen: stepCountIs(20), run });
const out = await res.result;
out.runStopped; // { limit: "budget", runId } when the run ran out mid-loop- When you pass
stopWhen, a budget condition joins it. After each inner step it prices the turn so far and stops the loop once the run, or an ancestor, is at its budget. The text and tool results produced so far come back as usual,result.runStoppedsays the loop was cut, a spend-cap event records it, and the run's next call is refused. Observe mode records and lets the loop run on. - Each completed tool step is ledgered as soon as it finishes, tagged
metadata.innerStep. The closing row carries only what is left, plusmetadata.innerSteps. Tokens, cost and tool-call counts are each ledgered once, so sums over the turn's rows equalresult.usage. A turn killed mid-loop therefore keeps the audit trail of what it had already spent. - A call with no run is unchanged: one row per turn.
Tools. Tools are where an agent's money and risk concentrate, and a proxy cannot see an in-process tool call at all. Give each tool a policy and a call to it is capped, priced and ledgered:
const gw = new Gateway({
usage,
toolPolicy: {
web_search: { costCents: 1, maxCalls: 10 }, // per run
run_sql: { maxCalls: 3 },
},
guardrails: {
tool: ({ tool, input }) =>
tool === "run_sql" && isWrite(input) ? { action: "block", reason: "read-only agent" } : { action: "allow" },
},
});
gw.preflightTools(tools); // throw at startup if a tool has no policy- Caps are counted per run (per call when there is no run):
maxCalls,maxCents, and for a priced tool whether the run's budget can afford it. guardrails.toolruns before each tool call and may allow it, rewrite its arguments, or block it.- A row per tool call:
provider: "tool", the tool's name asmodel, the policy price, the arguments and the result. The price is ordinary ledger spend, so it counts against the run's budget and the daily caps. - A denied call does not fail the turn. The model is told the tool was
not run and the loop goes on.
result.toolDenialslists what was denied.
Tool governance is on only when toolPolicy or guardrails.tool is set;
otherwise tools run as before and write no rows.
Three limits, stated plainly. Both budget checks run between steps, so a run
can overshoot by at most one step (one model call inside a loop). The in-loop
stop needs a stopWhen from you: with none the AI SDK runs a single step and
there is no loop to stop. And batch and runPromptTest take no run. Design,
and what comes next (per-tool caps, a non-streaming loop):
docs/design/run-governance.md.
Migration, all nullable; ensureTables() (SQLite quick-start) adds them:
ALTER TABLE ai_usage_log ADD COLUMN run_id TEXT;
ALTER TABLE ai_usage_log ADD COLUMN step_index INTEGER;
ALTER TABLE ai_usage_log ADD COLUMN parent_run_id TEXT;
ALTER TABLE spend_cap_events ADD COLUMN run_id TEXT;
CREATE INDEX idx_ai_usage_run ON ai_usage_log (run_id, step_index);Policy report
What is this deployment configured to enforce? One command answers it, in a form you can hand to a security reviewer or attach to a customer's questionnaire:
npx llm-gateway policy ./dist/gateway.js > POLICY.mdThe module exports your Gateway as gateway, as the default export, or under
--export <name>; a function that returns one works too. --json prints the
data instead of markdown, and --org <id> resolves chains for one tenant. A
TypeScript module needs a loader, for example
node --import tsx node_modules/llm-governance-gateway/dist/cli.js policy ./src/gateway.ts.
The report covers the daily spend limits and their mode, which guardrail hooks exist and whether they fail open, the model chain behind each task with every model's ZDR and pricing status, the tool policy, where the ledger and cache live and whether snapshots are encrypted, and the timeouts. It opens with findings: the settings a reviewer should look at, stated as facts.
## Findings
- Spend limits are in observe mode: a breach is recorded and the call is not refused.
- Task "contract_review" requires ZDR: 1 of the 2 models in its chain is not ZDR-asserted and is skipped (openai:gpt-4.1).
- openrouter:acme/new-model has no pricing: its cost is estimated from the fallback rate, so spend limits can undercount it.It reads configuration and the two stores that decide routing. It calls no
provider, and it prints no API key and no endpoint URL, only names. The same
configuration renders the same text, so committing POLICY.md and diffing it
in CI shows a policy change in review. From code:
import { renderPolicyMarkdown } from "llm-governance-gateway";
const policy = await gw.describePolicy(); // plain data; policy.findings is a string[]
if (policy.findings.length > 0) console.warn(renderPolicyMarkdown(policy));What it cannot see: per-call options (requireZdr, a judge, a run's budget)
are set where the call is made, and a store can change a chain after the report
ran. It reports what is configured, not what happened; the ledger is the record
of that.
Observability export (OTel, Langfuse, metrics)
The gateway is a governance library, not an observability platform — so it exports instead of competing. Three hooks fire after each durable write, fire-and-forget: a throwing or slow exporter can never break or block a governed call.
import { toOtelAttributes } from "llm-governance-gateway";
const gw = new Gateway({
usage,
observability: {
onUsage: (entry) => span?.setAttributes(toOtelAttributes(entry)),
onSpendCapEvent: (e) => meter.counter("llm_cap_blocks").add(1, { route: e.route ?? "" }),
onJudgeScore: (s) => langfuse.score({ traceId: String(s.usageLogId), value: s.overallScore }),
},
});toOtelAttributes maps usage entries onto the OTel GenAI semantic conventions (gen_ai.*) plus llm_gateway.* extensions for cost, cache hits, web searches, and ZDR enforcement. No OTel or Langfuse dependency is taken; the hooks receive plain objects. One privacy note: when an encrypt hook is configured, inputText/outputText reach your exporter already encrypted, so the at-rest guarantee extends to telemetry.
HTTP service (multi-app deployments)
Mount the pipeline as a service so apps in any language share one enforcement point. Hono (optional peer dep) runs on Cloudflare Workers, Node, Bun, and Deno:
import { createGatewayApp } from "llm-governance-gateway/http";
const app = createGatewayApp({
gateway: gw,
auth: { [env.APP_A_TOKEN]: "app-a", [env.APP_B_TOKEN]: "app-b" }, // token → appId tag
adminTokens: [env.ADMIN_TOKEN], // gates POST /prompt-test
});
export default app; // Cloudflare Workers
// Node: import { serve } from "@hono/node-server"; serve(app);Endpoints: POST /run (structured generation — send your Zod schema as JSON Schema via z.toJSONSchema()), GET /models, GET /tasks, POST /prompt-test, GET /health. Errors map to 429 (rate limit), 402 (spend cap — global-breaker responses say "at capacity", not "over your limit"), 400 (caller errors), 401/403.
POST /run supports both prompt modes: variables renders the server-side prompt library entry for slug; promptBody sends a client-rendered template instead.
Guardrail hooks (pre/post)
Policy enforced on every governed call (runStructured, runText,
streamStructured, and per item in batch), in the request path, with the
verdict written to the ledger. Two seams, both plain TypeScript functions:
import { Gateway, GuardrailError } from "llm-governance-gateway";
const gw = new Gateway({
usage,
guardrails: {
// After the prompt is rendered, before any provider spend.
pre: ({ prompt }) =>
/\b\d{3}-\d{2}-\d{4}\b/.test(prompt)
? { action: "block", reason: "SSN in prompt" }
: { action: "allow" },
// After generation and schema validation, before the cache write and the judge.
post: ({ output }) =>
containsCrisisLanguage(output)
? { action: "transform", output: redact(output), reason: "crisis redaction" }
: { action: "allow" },
// Default false: a hook that THROWS blocks the call. true lets it through
// and records that the gate was open. The choice is ledgered either way.
failOpen: false,
},
});
try {
await gw.runStructured({ ... });
} catch (err) {
if (err instanceof GuardrailError) {
err.hook; // "pre" | "post"
err.reason; // what the hook said
err.detail; // whatever the hook attached (JSON)
err.output; // for a post block: the object the provider returned
}
}A verdict is allow, transform (replace the prompt or the output and
continue) or block. Every verdict lands in UsageEntry.guardrails on the
call's usage row: a pre block writes a zero-token row (provider:
"guardrail"), a post block writes the row with the tokens that were spent,
then throws. An audit that cannot see blocked calls is not an audit. A
transformed output is what gets cached and what the judge scores; a transform
that breaks the caller's schema is treated as a block. Hooks run in mock mode
too, so CI can test policy without keys.
Cache hits run the hooks too. The pre hook runs on the rendered prompt before the cache is read, so a policy you add today applies to a prompt that was cached last week, and a per-caller policy cannot be bypassed by a shared cache entry. The post hook runs on the cached value; a transform is returned but not written back, a block writes the cache row with the verdict and throws. A plain hit with no hooks configured costs exactly what it did before.
Per path. runText: a post transform must return a string. streamStructured:
a post block can only stop the final object, since the partials were already
visible to the consumer; object rejects with GuardrailError, the iterator
fails, and a block never fails over to the next link. A transformed final object
is published as the last partial so a consumer rendering partials converges on
it. submitBatch: the pre hook runs per item; blocked items are excluded,
listed in result.blocked, and each leaves a zero-token row (trace id
batch:guardrail:<slug>:<item id>), while allow and transform verdicts ride the
reservation row tagged with detail.batchItemId. reconcileBatch: the post
hook runs per item; a block marks the item { ok: false, reason: "guardrail" }
and the item's usage row carries the verdict. The job store holds no per-item
prompt or input in this version, so a reconcile-time hook sees prompt: "" and
input: undefined.
TrustGate: confidence and human-in-the-loop routing as a post hook
trustGatePostGuardrail builds a post hook from the math of a production
decision-integrity platform: ground each extracted field in the source text,
check business rules, blend a confidence score (generator confidence 0.20,
schema 0.15, grounding 0.30, rules 0.15, judge 0.20) and route to a human when
it falls under a per-document-type threshold adjusted for risk and stake.
import { trustGatePostGuardrail } from "llm-governance-gateway";
guardrails: {
post: trustGatePostGuardrail<Invoice>({
sourceText: (ctx) => (ctx.input as { doc: string }).doc,
rules: [{ id: "status", field: "status", allowedValues: ["open", "paid"] }],
documentType: "invoice",
riskLevel: "MEDIUM",
estimatedValue: (ctx) => ctx.output.totalCents / 100,
thresholds: { invoice: { baseThreshold: 0.85 } },
onRoute: "block", // "allow" while calibrating: ledger the decision, let it through
}),
}A routed decision becomes a block whose detail carries the full decision
(threshold and why, confidence components, which fields failed grounding,
which rules failed), so the handler that queues it for a human has everything
it needs. The pieces are exported on their own too (groundFields,
checkBusinessRules, computeConfidence, routeToHitl).
Two things to know before trusting it. The default grounder is lexical: a
case-insensitive substring match with numeric normalization and a structured-
metadata fallback. It catches fabricated values and misses paraphrase, and it
will accept "1" because "1042" is in the source. Pass grounder to swap in an
embedding or NLI check. And the port's HITL defaults are not the original's:
the Python code lowered the threshold for high risk and high value, which
sends fewer high-stakes items to a human; this package raises it instead.
ORIGINAL_ADJUSTMENTS has the old numbers if you need parity.
Design notes
- Fail-open rate limiting, fail-closed spend caps. A Redis blip should not 500 every AI call — the limiter fails open with an alert, while the store-backed spend cap (independent of Redis) still bounds cost.
- Global breaker before per-user caps. Per-identity caps can't see N users × cap on a viral day.
- Cache is opt-out per call, and
cache: falseskips both read and write — required for PII-bearing calls. - In-memory defaults are for dev/single-process only. On serverless they reset every cold start, which silently disables enforcement.
Status
Extracted from a production system (three independent in-house implementations converged on this design). Pre-1.0, so the API may still shift — though in practice the store interfaces (UsageStore, PromptStore, ModelConfigStore, TaskOverrideStore, RateLimiter, CacheStore) have only ever gained capability through optional parameters, and existing implementations keep compiling. 1.0.0 is gated on a downstream integration proving that holds, not on a date. See CHANGELOG.md.
Next up (ROADMAP, full reasoning in docs/strategy/roadmap-2026-2027.md): governed agent runs with per-run budgets and tool caps, then 1.0, then a sibling control-plane package (store adapters and headless admin operations first, UI last if ever), specified in docs/design/admin-control-plane-package.md. It supersedes the earlier admin-UI sketch.
License
MIT
