Skip to main content
Status: design, awaiting independent security review. Key storage is in Per-workspace AI provider keys; analytics and alerts are in BYOK usage and observability.

Today

About 50 production call sites reach a model provider, almost all Gemini, and almost all build their own google(...), gateway(...) or createGoogleGenerativeAI(...) from the shared server key GOOGLE_GENERATIVE_AI_API_KEY. There is no shared model resolver. Existing pieces the router reuses:

Goals

  • One layer decides model, provider, credential, metering and run recording for every AI request, so BYOK works everywhere without per-feature code.
  • No behavior change by default: a workspace with no key and no routing rows gets today’s model, provider and metering.
  • The layer is framework-independent: request identity, the key resolver, credits and storage are injected by each app’s adapter, per the repository’s domain-library rule.

Design

New module packages/ai/src/routing/, exported as @tuturuuu/ai/routing.

Feature registry

AI_FEATURE_REGISTRY lists every feature key with its capability, default model, credit feature (an AI_FEATURES value), metering mode and whether BYOK may serve it: The metering field preserves each feature’s current behavior. Routing a feature through the layer never starts charging credits it does not charge today; changing a feature from unmetered is a separate product decision.

API

router.run does, in order:
  1. Resolve the route: the workspace’s feature row, else the registry default; the model must be in the catalog (private.ai_gateway_models), pass AI Studio model policy (private.workspace_ai_studio_policies: denied, then allowed) and the plan (resolvePlanModel).
  2. Begin the run (begin_ai_studio_run). On a BYOK route it takes the zero-credit path, checks the workspace daily BYOK caps and returns the run-scoped proof secret that keys.resolve needs (see proof of use).
  3. For each credential in the fallback order:
    • byok: keys.resolve(...); on a key, build a direct provider instance (createGoogleGenerativeAI, createOpenAI or createAnthropic with that key and the injected fetch); no credit reservation; the fee meter counts one request.
    • platform: today’s choice (google(bare) or gateway(id) with the platform key), with the feature’s metering (reservation, then settlement).
    • Wrap the model with withAiMemory where the feature uses memory.
  4. Execute. On an error, classify it (see error classes). Move to the next credential only when the class allows it and no output has reached the caller: once a stream has emitted a token, the error is returned, never retried on another credential.
  5. Settle usage, cost, latency, first-token latency, error class, credential_source and provider_key_id on the run.
router.credential does the same route, run and key steps, and returns the key and a settle function to transports that need a raw key: GoogleGenAI in the Meet Live Durable Object, authTokens.create for web and mobile Live ephemeral tokens (the browser still receives only the ephemeral token), and the Gemini TTS fetch. Ephemeral Live tokens. A token minted with a workspace key is a bearer credential for that key, so authTokens.create always sets:
  • uses: 1, so one token opens one session;
  • newSessionExpireTime 60 seconds after minting, and expireTime no later than the feature’s session limit;
  • liveConnectConstraints pinning the model and the session config (response modality, system instruction and tools) the server chose, so a client cannot redirect the token to another model or enable tools.
Each mint counts as a resolution on the session’s proof and is recorded with the session. Transport pinning. Every provider instance and raw fetch uses a fixed base URL constant in packages/ai/src/routing (https://generativelanguage.googleapis.com, https://api.openai.com, https://api.anthropic.com), never a value from configuration, the database or a request. Keys travel only in headers (x-goog-api-key, Authorization: Bearer, x-api-key), never as a ?key= query parameter, and a test asserts that no routed request URL contains a key.

Embeddings

Stored vectors must come from one model and dimension (gemini-embedding-2, 3072 dimensions). BYOK can serve embeddings only with the same model id on the workspace’s Google key; a route can never switch embeddings to another provider or model, because mixed vectors break search.

Per-feature model selection

  • fallback_order holds one or both of byok and platform, without repeats (a check constraint). The UI offers Workspace key, then platform credits (default), Workspace key only and Platform credits only.
  • Mira channels with keyMode: 'byok' force {byok}, matching their rule that a failing tenant key never falls back.
  • Only service-role definer RPCs read or write these tables, like the key tables. Every change writes a routing_changed key event.
  • Edit requires manage_ai_policy, the existing model-policy permission; view requires manage_workspace_secrets or use_ai_studio.
  • UI: a Per-feature models section in AI Studio → Governance → Model policy (/<wsId>/model-policy), beside the allow and deny lists, with one row per feature: model picker (only policy- and plan-allowed models), fallback order, and the provider whose key will be used. The keys tab links to it.

Fallback rules

A request that falls back to platform needs credits like any platform request; without them it fails with the usual credit error. A Live session changes credential only at connect or reconnect, after its gate recheck.

Health check and Test key

  • Passive health comes from the hourly usage rollups:
    • failing: an auth or quota error in the last 15 minutes and no success since;
    • degraded: at least 20 requests in the last hour with an error rate of 5 % or more, or 20 % or more rate-limited;
    • healthy: otherwise, when requests exist;
    • unused: no requests for 7 days.
  • Test key (POST …/ai-provider-keys/{provider}/test): the list-models call plus a one-token generation on the provider’s test model (test_model_id on private.ai_provider_key_providers, for example the provider’s cheapest text model). It reports success or an error class and the latency, writes a tested event, is limited to 6 tests per key per hour, and the UI states that it sends one small request billed by the provider.
  • Recovery probe: after a quota failure, a Cron Control job re-tests the key at most once an hour and 3 times a day, with bounded batches, idempotent progress and the job’s stop fence; success writes restored. An auth failure is never probed automatically; only an admin’s Test key or a new key restores it.

Call-site inventory and migration order

Migration is one call site per change, each with routing, fallback and billing tests; unmigrated sites keep working on the platform path. Out of scope: the Vertex year-plan route, the meeting eval tool, the roadmap changelog script, and ChatGPT subscriptions, which stay a per-user OAuth path recorded as credential_source = 'subscription'.

Security review