Documentation

Install BYOKI and wire it to your session.

The API section on this page is generated from the package exports when the site is built. The narrative around it matches the example app in this repository.

Installation

The packages are ESM-only, versioned together, and licensed under MIT. They need Node 20 or newer. @byoki/react needs React 19. There is no CommonJS build.

After the packages are published:

pnpm
pnpm add @byoki/[email protected] @byoki/[email protected] @byoki/[email protected] @byoki/[email protected] @byoki/[email protected]
npm
npm install @byoki/[email protected] @byoki/[email protected] @byoki/[email protected] @byoki/[email protected] @byoki/[email protected]

Until then, download the tarballs from the downloads page. Those files are produced by pnpm pack during the demo app build.

Inside this repository:

repository
corepack pnpm install --frozen-lockfile
corepack pnpm build
corepack pnpm --filter @byoki/example build
corepack pnpm --filter @byoki/example dev

Quick start

Resolve the signed-in user in your own auth middleware. Pass that { tenantId, userId } into the router. Do not accept a user id from the browser as authorization.

server.ts
import { defineAIConnections } from "@byoki/core";
import { createAIConnectionsApp } from "@byoki/server";
import {
  MANUAL_CATALOG,
  PROVIDER_LINKS,
  createProviderAdapters,
} from "@byoki/providers";
import { PRICE_CATALOG, estimateCost } from "@byoki/pricing";

const ai = createAIConnectionsApp({
  config: defineAIConnections({
    appName: "Your app",
    capabilities: {
      chat: {
        description: "Answers questions for the signed-in user.",
        providers: ["openai", "anthropic", "gemini"],
        userCanChooseModel: true,
        required: true,
      },
    },
  }),
  adapters: createProviderAdapters(),
  catalog: MANUAL_CATALOG,
  links: PROVIDER_LINKS,
  estimateCost: (args) => estimateCost(PRICE_CATALOG, args),
});

// tenantId and userId come from your session. Do not take them from the browser.
await ai.router.forScope({ tenantId, userId }).invoke({
  capability: "chat",
  input: [{ role: "user", text: "Summarize this note." }],
});

A capability controls SDK routing and the settings screen. It does not limit what the provider account can do with that key. The host that stores the key can also use it outside this SDK.

Mock adapters

Set BYOKI_USE_MOCK=1 and pass mock adapters when you want the same routing without a paid call. The public demo does this by default.

mock adapters
import { createMockAdapter } from "@byoki/core";
import { MANUAL_CATALOG } from "@byoki/providers";

const adapters = {
  openai: createMockAdapter("openai", {
    models: MANUAL_CATALOG.filter((model) => model.provider === "openai"),
  }),
  anthropic: createMockAdapter("anthropic", {
    models: MANUAL_CATALOG.filter((model) => model.provider === "anthropic"),
  }),
  gemini: createMockAdapter("gemini", {
    models: MANUAL_CATALOG.filter((model) => model.provider === "gemini"),
  }),
};

Settings UI

settings-screen.tsx
"use client";

import { useMemo } from "react";
import { AIConnectionsSettings, createConnectionsClient } from "@byoki/react";

export function SettingsScreen({ csrfToken }: { csrfToken: string }) {
  const client = useMemo(
    () => createConnectionsClient({ baseUrl: "/api/ai", csrfToken }),
    [csrfToken],
  );
  return <AIConnectionsSettings client={client} />;
}

Pass csrfToken from the server session. Mutating requests send it as x-csrf-token.

Configuration

Put secrets in the host environment, not in the image and not in git. The demo app reads examples/next-app/.env.local in local development. Copy .env.example and fill it in.

VariableRequiredUsed byPurpose
SESSION_SECRETRequired to run the demo siteDemo session cookieHMAC secret for anonymous demo session cookies. Generate a long random string and keep it out of git.
BYOKI_MASTER_KEYRequired for the development file store@byoki/server file store and BYOKI_STORE=file32-byte key encoded as base64 or hex. Encrypts credentials in the development file store. It is not written into that file. The public demo's default memory store does not read it.
BYOKI_USE_MOCKDefaults to mock mode when unsetDemo site and starter kitSet to 1 to answer requests with the mock adapters and make no provider calls. Set to 0 to send the signed-in user's key to OpenAI, Anthropic, or Gemini. Leave this at 1 on the public demo.
BYOKI_STOREDefaults to memoryDemo sitememory keeps each visitor's key in the Node process until the session expires, the visitor ends the session, or the process restarts. file uses the encrypted development store at .data/store.json and should not be used for the public demo.
BYOKI_SESSION_TTL_SECONDSDefaults to 7200Demo siteLifetime of an anonymous demo session in seconds. Values are clamped to the range 300–86400. The cookie Max-Age uses the same value.
BYOKI_PUBLIC_HOSTOptionalDemo site redirectsComma-separated extra hostnames allowed when building redirects from X-Forwarded-Host. byoki.eastonnielson.dev, localhost, and 127.0.0.1 are always allowed. Other forwarded hosts are ignored.
BYOKI_PUBLIC_ORIGINDefaults to https://byoki.eastonnielson.devDemo site metadata and redirect allow listAbsolute origin of the deployed site, used for metadata. Its hostname is also allowed for proxy redirects.
OPENAI_API_KEYTest onlyOpt-in provider smoke testsRead only when BYOKI_LIVE=1 runs the provider package smoke tests. The demo site does not use this variable. Visitors supply their own keys.
ANTHROPIC_API_KEYTest onlyOpt-in provider smoke testsRead only when BYOKI_LIVE=1 runs the provider package smoke tests. The demo site does not use this variable.
GEMINI_API_KEYTest onlyOpt-in provider smoke testsRead only when BYOKI_LIVE=1 runs the provider package smoke tests. The demo site does not use this variable.
BYOKI_LIVETest onlyOpt-in provider smoke testsSet to 1 to run live OpenAI, Anthropic, and Gemini smoke tests. Leave it unset in CI and on the public demo.

Generate a master key

shell
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"

defineAIConnections checks the config with zod. It requires an app name and at least one capability. Providers are openai, anthropic, and gemini. Capabilities in this version are chat and vision.

API reference

Browser code imports @byoki/core/browser. Server code imports the other entry points. Signatures below are taken from the TypeScript source of each public export.

Host routes

Forward /api/ai/* to handlers.dispatch with the session scope. That includes POST /api/ai/invoke. The settings client does not send prompts. Non-JavaScript clients use the same routes; see docs/INTEGRATING.md.

MethodPathPurpose
GET/api/ai/connectionsAllowed providers, connection status, purposes, links, and selections. No secrets.
PUT/api/ai/connections/:providerCreate or replace a key for the signed-in user. Body: { apiKey }.
DELETE/api/ai/connections/:providerDelete the stored connection for this app.
POST/api/ai/connections/:provider/testTest a submitted or stored key. Rate limited. Failures return a fixed category message, not provider error text.
GET/api/ai/models?capability=chatAllowed compatible models. Add discover=1 to refresh from the provider.
PUT/api/ai/selections/:capabilitySave an allowed provider and model. Body: { provider, modelId }.
GET/api/ai/usage?from=...&to=...Observed ledger summary for the signed-in user.
POST/api/ai/invokeSend a chat or vision prompt. Omit stream for JSON. stream true uses text/event-stream.

Cookie sessions need the session cookie and a matching CSRF token. A native client uses Authorization: Bearer instead. Error bodies use { ok: false, error: { code, message } }.

Stable codes: INVALID_CONFIG PROVIDER_NOT_ALLOWED CAPABILITY_UNSUPPORTED MODEL_INCOMPATIBLE MODEL_UNAVAILABLE CREDENTIAL_MISSING INVALID_KEY RATE_LIMITED UPSTREAM_UNAVAILABLE BUDGET_BLOCKED PAYLOAD_TOO_LARGE UNAUTHENTICATED FORBIDDEN CSRF_FAILED.

@byoki/core

Capability routing, config validation, and provider interfaces for BYOKI. Version 0.2.0. Node >=20.

AIConnectionsConfigtype
export type AIConnectionsConfig = {
  appName: string;
  capabilities: Partial<Record<Capability, CapabilityPolicy>>;
  limits: {
    maxOutputTokens?: number;
    requestTimeoutMs: number;
    budget?: BudgetPolicy;
  };
};
AIConnectionsErrorclass
export class AIConnectionsError extends Error {
  readonly code: ErrorCode;
  readonly providerRequestId?: string;
  /** Visitor category when `code` alone cannot tell rate limits from quota. */
  readonly category?: UpstreamErrorCategory;

  constructor(
    code: ErrorCode,
    message: string,
    providerRequestId?: string,
    category?: UpstreamErrorCategory,
  ) {
    super(message);
    this.name = "AIConnectionsError";
    this.code = code;
    if (providerRequestId !== undefined) {
      this.providerRequestId = providerRequestId;
    }
    if (category !== undefined) {
      this.category = category;
    }
  }
}
AIConnectionsInputtype
export type AIConnectionsInput = z.input<typeof inputSchema>;
AIRoutertype
export type AIRouter = ReturnType<typeof createRouter>;
AVAILABILITY_CAVEATconst
const AVAILABILITY_CAVEAT = "A listed model is not guaranteed to be enabled for every account. If a call fails, choose another model."
BudgetPolicytype
export type BudgetPolicy = {
  warnAtUsd?: number;
  blockAtUsd?: number;
};
CAPABILITIESconst
const CAPABILITIES = ["chat", "vision", "image", "embedding", "audio"] as const
Capabilitytype
export type Capability = (typeof CAPABILITIES)[number];
CapabilityPolicytype
export type CapabilityPolicy = {
  description: string;
  providers: ProviderId[];
  userCanChooseModel: boolean;
  required: boolean;
  /** Models this app has tested for the capability. Shown first in settings. */
  recommendedModels?: RecommendedModel[];
  /** Used when the user has not chosen. Defaults to the first recommended model. */
  defaultModel?: RecommendedModel;
};
categorizeModelfunction

Capability tags for a model the user's key can access. Provider metadata wins. Name heuristics fill what the list endpoint leaves out. A model may have several tags. An unrecognized id has none.

function categorizeModel(provider: ProviderId, id: string, metadata: ModelListMetadata = {}): Capability[]
connectionTestCategoryfunction

Category shown for a failed connection test. Unknown when the adapter did not name a real category.

function connectionTestCategory(result: {
  ok: boolean;
  reason?: string;
  category?: string;
}): UpstreamErrorCategory | undefined
connectionTestMessagefunction

Message shown for a connection test. Ignores any reason that is not a fixed category string.

function connectionTestMessage(result: {
  ok: boolean;
  reason?: string;
  category?: string;
}): string | undefined
ContentParttype
export type ContentPart =
  | { type: "text"; text: string }
  | { type: "image"; mimeType: string; data: string };
CostEstimatetype
export type CostEstimate = {
  status: "known" | "unknown";
  currency: "USD";
  amount?: number;
  catalogVersion?: string;
};
createDirectClientfunction
function createDirectClient(deps: DirectClientDeps): DirectClient
createMockAdapterfunction
function createMockAdapter(id: ProviderId, options: MockAdapterOptions = {}): ProviderAdapter
createRouterfunction
function createRouter(deps: RouterDeps)
CredentialStoreinterface
export interface CredentialStore {
  put(scope: Scope, provider: ProviderId, plaintextKey: string): Promise<void>;
  get(scope: Scope, provider: ProviderId): Promise<string | null>;
  delete(scope: Scope, provider: ProviderId): Promise<void>;
  has(scope: Scope, provider: ProviderId): Promise<boolean>;
}
DEFAULT_INVOKE_TIMEOUT_MSconst
const DEFAULT_INVOKE_TIMEOUT_MS = 60_000
defineAIConnectionsfunction
function defineAIConnections(input: AIConnectionsInput): AIConnectionsConfig
detectProviderfunction

Prefix-only detection. `sk-ant-` is checked before `sk-` so Anthropic keys are not treated as OpenAI. An unrecognized key must not be sent anywhere.

function detectProvider(apiKey: string): ProviderId | null
DirectClienttype
export type DirectClient = {
  detectProvider(apiKey: string): ProviderId | null;
  models(filter?: { provider?: ProviderId; capability?: Capability }): ModelOption[];
  /**
   * Lists models with the user's key. Successful lists are cached for this client
   * instance. A network, CORS, or permission failure returns the developer catalog.
   */
  discoverModels(apiKey: string, options?: { capability?: Capability; refresh?: boolean }): Promise<ModelDiscovery>;
  testKey(apiKey: string): Promise<DirectKeyTest>;
  invoke(input: DirectInvokeInput): Promise<DirectInvokeResult>;
  invokeStream(input: DirectInvokeInput): AsyncIterable<DirectStreamEvent>;
};
DirectInvokeInputtype
export type DirectInvokeInput = {
  apiKey: string;
  /** Must match key-prefix detection when set. */
  provider?: ProviderId;
  modelId: string;
  capability?: Capability;
  input: InputMessage[];
  maxOutputTokens?: number;
  temperature?: number;
  timeoutMs?: number;
};
DirectInvokeResulttype
export type DirectInvokeResult = {
  outputText: string;
  provider: ProviderId;
  modelId: string;
  usage?: UsageUnits;
};
DirectKeyTesttype
export type DirectKeyTest =
  | { ok: true; provider: ProviderId }
  | { ok: false; provider: ProviderId | null; category: UpstreamCategory; message: string };
DirectStreamEventtype
export type DirectStreamEvent = { type: "delta"; text: string } | { type: "done"; result: DirectInvokeResult };
ERROR_CODESconst
const ERROR_CODES = [
  "INVALID_CONFIG",
  "PROVIDER_NOT_ALLOWED",
  "CAPABILITY_UNSUPPORTED",
  "MODEL_INCOMPATIBLE",
  "MODEL_UNAVAILABLE",
  "CREDENTIAL_MISSING",
  "INVALID_KEY",
  "RATE_LIMITED",
  "UPSTREAM_UNAVAILABLE",
  "BUDGET_BLOCKED",
  "PAYLOAD_TOO_LARGE",
  "UNAUTHENTICATED",
  "FORBIDDEN",
  "CSRF_FAILED",
] as const
ErrorCodetype
export type ErrorCode = (typeof ERROR_CODES)[number];
explainSelectionfunction
function explainSelection(config: AIConnectionsConfig, catalog: ModelOption[], adapters: Partial<Record<ProviderId, ProviderAdapter>>, selection: Selection): AIConnectionsError | null
findCatalogModelfunction
function findCatalogModel(catalog: ModelOption[], provider: ProviderId, modelId: string): ModelOption | undefined
InputMessagetype
export type InputMessage = {
  role: "user" | "assistant" | "system";
  text?: string;
  parts?: ContentPart[];
};
InvokeBodytype
export type InvokeBody = {
  capability: Capability;
  input: InputMessage[];
  stream?: boolean;
  temperature?: number;
};
InvokeStreamEventtype

Events from `invokeStream`. `done.result` matches a buffered `invoke` success.

export type InvokeStreamEvent =
  | { type: "delta"; text: string }
  | { type: "done"; result: InvokeSuccess };
InvokeSuccesstype
export type InvokeSuccess = {
  outputText: string;
  provider: ProviderId;
  modelId: string;
  providerRequestId?: string;
  usage?: UsageRecord["usage"];
  estimationStatus: "known" | "unknown";
  estimatedCost?: number;
  warning?: string;
};
isAIConnectionsErrorfunction
function isAIConnectionsError(error: unknown): error is AIConnectionsError
isCapabilityfunction
function isCapability(value: string): value is Capability
isFixedUpstreamMessagefunction
function isFixedUpstreamMessage(message: string): boolean
isModelIdfunction
function isModelId(value: string): boolean
isProviderIdfunction
function isProviderId(value: string): value is ProviderId
isRecommendedModelfunction
function isRecommendedModel(recommended: readonly RecommendedModel[] | undefined, provider: ProviderId, modelId: string): boolean
isTaskMismatchBodyfunction

True when a provider error body says this model cannot do the requested task. Parameter incompatibilities are not task mismatches. The provider text is not returned.

function isTaskMismatchBody(body: string): boolean
isUpstreamErrorCategoryfunction
function isUpstreamErrorCategory(value: unknown): value is UpstreamErrorCategory
KEY_TEST_TIMEOUT_MSconst
const KEY_TEST_TIMEOUT_MS = 15_000
keyFingerprintfunction

Non-cryptographic session cache identity. The raw key is not stored.

function keyFingerprint(apiKey: string): string
LedgerOutcometype
export type LedgerOutcome = "success" | "failure";
MAX_DIRECT_MESSAGESconst
const MAX_DIRECT_MESSAGES = 32
MAX_DIRECT_PARTSconst
const MAX_DIRECT_PARTS = 8
mergeDiscoveredModelsfunction

Prefer the developer display name and keep every capability either side reported.

function mergeDiscoveredModels(discovered: ModelOption[], catalog: ModelOption[]): ModelOption[]
messageForVisitorfunction

Visitor text for an error that may have been built from a provider response. Upstream codes are forced onto the fixed category strings.

function messageForVisitor(error: AIConnectionsError): string
MODEL_ID_PATTERNconst

Model ids accepted on the wire and in local storage names.

const MODEL_ID_PATTERN = /^[A-Za-z0-9._:-]+$/
MODEL_UNAVAILABLE_MESSAGEconst
const MODEL_UNAVAILABLE_MESSAGE = "That model is not available. Choose another model."
modelAckNamefunction

Local storage name for a one-time acknowledgment of a non-recommended model.

function modelAckName(provider: ProviderId, modelId: string): string
ModelDiscoverytype
export type ModelDiscovery = {
  models: ModelOption[];
  source: "discovered" | "catalog";
  /** True when the provider list failed and the developer catalog was used. */
  fallback: boolean;
};
ModelListMetadatatype
export type ModelListMetadata = {
  displayName?: string;
  /**
   * Provider-reported image input. `false` blocks the vision heuristic.
   * Omit it when the provider did not say.
   */
  imageInput?: boolean;
  /** Gemini `supportedGenerationMethods` and similar lists. */
  methods?: string[];
};
ModelOptiontype
export type ModelOption = {
  id: string;
  provider: ProviderId;
  capabilities: Capability[];
  displayName: string;
  catalogUpdatedAt: string;
  source: "catalog" | "discovered";
  availabilityCaveat: string;
};
NON_RECOMMENDED_MODEL_WARNINGconst

Shown before a non-recommended model is saved. The user must acknowledge it.

const NON_RECOMMENDED_MODEL_WARNING = "This model isn't recommended for this app. It may produce unexpected results, and you're responsible for its output."
normalizeInputfunction
function normalizeInput(input: InputMessage[]): ProviderRequest["input"]
partitionModelsfunction
function partitionModels<T extends { provider: ProviderId; id: string }>(models: T[], recommended: readonly RecommendedModel[] | undefined): { recommended: T[]; available: T[] }
PROVIDER_IDSconst
const PROVIDER_IDS = ["openai", "anthropic", "gemini"] as const
ProviderAdapterinterface
export interface ProviderAdapter {
  id: ProviderId;
  supportedCapabilities: readonly Capability[];
  testMaySpendQuota: boolean;
  testConnection(key: string): Promise<{
    ok: boolean;
    /** Fixed visitor text. Hosts must not replace this with provider response text. */
    reason?: string;
    category?: UpstreamErrorCategory;
  }>;
  listModels(key: string): Promise<ModelOption[]>;
  invoke(request: ProviderRequest, key: string): Promise<ProviderResult>;
  /**
   * Optional token stream. Hosts that do not implement this still work:
   * the router emits one delta from `invoke` and then a done event.
   * The iterable must throw before the first yield when the provider rejects
   * the call, and must not include the API key in any event.
   */
  invokeStream?(request: ProviderRequest, key: string): AsyncIterable<ProviderStreamEvent>;
}
ProviderIdtype
export type ProviderId = (typeof PROVIDER_IDS)[number];
ProviderRequesttype
export type ProviderRequest = {
  capability: Capability;
  modelId: string;
  input: Array<{ role: "user" | "assistant" | "system"; parts: ContentPart[] }>;
  maxOutputTokens?: number;
  /** Sent when set. Dropped and retried when the model rejects it. */
  temperature?: number;
  timeoutMs: number;
};
ProviderResulttype
export type ProviderResult = {
  status: "success";
  output: ContentPart[];
  providerRequestId?: string;
  latencyMs: number;
  usage?: UsageUnits;
  /** Usage fields this provider cannot supply for the request. */
  usageGaps: string[];
  metadata?: Record<string, unknown>;
};
ProviderStreamEventtype

One chunk from a provider streaming call. `done` carries the same fields as a buffered result.

export type ProviderStreamEvent =
  | { type: "delta"; text: string }
  | {
      type: "done";
      output: ContentPart[];
      providerRequestId?: string;
      latencyMs: number;
      usage?: UsageUnits;
      usageGaps: string[];
      metadata?: Record<string, unknown>;
    };
RecommendedModeltype
export type RecommendedModel = {
  provider: ProviderId;
  modelId: string;
};
RouterDepstype
export type RouterDeps = {
  config: AIConnectionsConfig;
  adapters: Partial<Record<ProviderId, ProviderAdapter>>;
  credentials: CredentialStore;
  selections: SelectionStore;
  ledger: UsageLedger;
  catalog: ModelOption[];
  estimateCost?: (args: {
    provider: ProviderId;
    modelId: string;
    usage: UsageRecord["usage"];
  }) => CostEstimate;
  now?: () => Date;
};
Scopetype
export type Scope = {
  tenantId: string;
  userId: string;
};
scrubVisitorTextfunction

Replace text that could carry a provider body or key echo. Safe, authored messages pass through.

function scrubVisitorText(message: string, fallback = UPSTREAM_ERROR_MESSAGES.unknown): string
Selectiontype
export type Selection = {
  capability: Capability;
  provider: ProviderId;
  modelId: string;
};
SelectionStoreinterface
export interface SelectionStore {
  get(scope: Scope, capability: Capability): Promise<Selection | null>;
  put(scope: Scope, selection: Selection): Promise<void>;
  list(scope: Scope): Promise<Selection[]>;
}
TASK_UNSUPPORTED_MESSAGEconst

Shown when a selected model cannot perform the requested call.

const TASK_UNSUPPORTED_MESSAGE = "This model can't do that task. Choose a model that supports it."
TRUST_NOTICESconst
const TRUST_NOTICES = {
  capabilityDoesNotLimitKey:
    "A capability only controls routing and this screen. It does not restrict what this API key can do at the provider.",
  hostOperatesKey:
    "This app's server receives your key and the content you submit, and it sends that content to the provider you select.",
  localDeletionDoesNotRevoke:
    "Removing a connection here deletes the key from this app. It does not revoke the key at the provider.",
  estimatedInThisApp:
    "Estimated in this app. Provider account totals can differ because this ledger only includes requests routed through this app.",
  budgetIsBestEffort:
    "Budget checks use observed spend in this app before a call. They cannot see the final token count, and concurrent requests can cross a threshold. This is not a guaranteed spending cap. Set limits in the provider account where they are offered.",
  testMaySpendQuota: "Testing this connection may use provider quota and can incur a charge.",
} as const
UPSTREAM_ERROR_CATEGORIESconst

Visitor-facing buckets for an upstream provider failure.

const UPSTREAM_ERROR_CATEGORIES = ["invalid_key", "rate_limited", "quota", "unavailable", "unknown"] as const
UPSTREAM_ERROR_MESSAGESconst

Fixed visitor copy for upstream failures. These strings are the only text a key test or provider error may show. They never include provider bodies, key material, request ids, or headers.

const UPSTREAM_ERROR_MESSAGES: Record<UpstreamErrorCategory, string> = {
  invalid_key: "The provider rejected this key. Check the key and try again.",
  rate_limited: "The provider rate limit was reached. Wait and try again.",
  quota: "The provider quota or billing limit was reached. Check the provider account.",
  unavailable: "The provider is unavailable or the request timed out. Try again later.",
  unknown: "The provider request failed. Try again.",
}
UpstreamErrorCategorytype
export type UpstreamErrorCategory = (typeof UPSTREAM_ERROR_CATEGORIES)[number];
UsageLedgerinterface
export interface UsageLedger {
  append(record: UsageRecord): Promise<void>;
  query(scope: Scope, range: { from: string; to: string }): Promise<UsageRecord[]>;
}
UsageRecordtype
export type UsageRecord = {
  id: string;
  time: string;
  tenantId: string;
  userId: string;
  capability: Capability;
  provider: ProviderId;
  modelId: string;
  outcome: LedgerOutcome;
  latencyMs: number;
  providerRequestId?: string;
  usage?: UsageUnits;
  priceCatalogVersion?: string;
  estimatedCost?: number;
  estimationStatus: "known" | "unknown";
  errorCode?: ErrorCode;
  streamed: boolean;
};
UsageUnitstype
export type UsageUnits = {
  inputTokens?: number;
  outputTokens?: number;
  cacheReadTokens?: number;
  cacheWriteTokens?: number;
  imageCount?: number;
};
AVAILABILITY_CAVEATconst
const AVAILABILITY_CAVEAT = "A listed model is not guaranteed to be enabled for every account. If a call fails, choose another model."
CAPABILITIESconst
const CAPABILITIES = ["chat", "vision", "image", "embedding", "audio"] as const
Capabilitytype
export type Capability = (typeof CAPABILITIES)[number];
categorizeModelfunction

Capability tags for a model the user's key can access. Provider metadata wins. Name heuristics fill what the list endpoint leaves out. A model may have several tags. An unrecognized id has none.

function categorizeModel(provider: ProviderId, id: string, metadata: ModelListMetadata = {}): Capability[]
connectionTestCategoryfunction

Category shown for a failed connection test. Unknown when the adapter did not name a real category.

function connectionTestCategory(result: {
  ok: boolean;
  reason?: string;
  category?: string;
}): UpstreamErrorCategory | undefined
connectionTestMessagefunction

Message shown for a connection test. Ignores any reason that is not a fixed category string.

function connectionTestMessage(result: {
  ok: boolean;
  reason?: string;
  category?: string;
}): string | undefined
CostEstimatetype
export type CostEstimate = {
  status: "known" | "unknown";
  currency: "USD";
  amount?: number;
  catalogVersion?: string;
};
createDirectClientfunction
function createDirectClient(deps: DirectClientDeps): DirectClient
detectProviderfunction

Prefix-only detection. `sk-ant-` is checked before `sk-` so Anthropic keys are not treated as OpenAI. An unrecognized key must not be sent anywhere.

function detectProvider(apiKey: string): ProviderId | null
DirectClienttype
export type DirectClient = {
  detectProvider(apiKey: string): ProviderId | null;
  models(filter?: { provider?: ProviderId; capability?: Capability }): ModelOption[];
  /**
   * Lists models with the user's key. Successful lists are cached for this client
   * instance. A network, CORS, or permission failure returns the developer catalog.
   */
  discoverModels(apiKey: string, options?: { capability?: Capability; refresh?: boolean }): Promise<ModelDiscovery>;
  testKey(apiKey: string): Promise<DirectKeyTest>;
  invoke(input: DirectInvokeInput): Promise<DirectInvokeResult>;
  invokeStream(input: DirectInvokeInput): AsyncIterable<DirectStreamEvent>;
};
DirectInvokeInputtype
export type DirectInvokeInput = {
  apiKey: string;
  /** Must match key-prefix detection when set. */
  provider?: ProviderId;
  modelId: string;
  capability?: Capability;
  input: InputMessage[];
  maxOutputTokens?: number;
  temperature?: number;
  timeoutMs?: number;
};
DirectInvokeResulttype
export type DirectInvokeResult = {
  outputText: string;
  provider: ProviderId;
  modelId: string;
  usage?: UsageUnits;
};
DirectKeyTesttype
export type DirectKeyTest =
  | { ok: true; provider: ProviderId }
  | { ok: false; provider: ProviderId | null; category: UpstreamCategory; message: string };
DirectStreamEventtype
export type DirectStreamEvent = { type: "delta"; text: string } | { type: "done"; result: DirectInvokeResult };
ERROR_CODESconst
const ERROR_CODES = [
  "INVALID_CONFIG",
  "PROVIDER_NOT_ALLOWED",
  "CAPABILITY_UNSUPPORTED",
  "MODEL_INCOMPATIBLE",
  "MODEL_UNAVAILABLE",
  "CREDENTIAL_MISSING",
  "INVALID_KEY",
  "RATE_LIMITED",
  "UPSTREAM_UNAVAILABLE",
  "BUDGET_BLOCKED",
  "PAYLOAD_TOO_LARGE",
  "UNAUTHENTICATED",
  "FORBIDDEN",
  "CSRF_FAILED",
] as const
ErrorCodetype
export type ErrorCode = (typeof ERROR_CODES)[number];
isFixedUpstreamMessagefunction
function isFixedUpstreamMessage(message: string): boolean
isModelIdfunction
function isModelId(value: string): boolean
isRecommendedModelfunction
function isRecommendedModel(recommended: readonly RecommendedModel[] | undefined, provider: ProviderId, modelId: string): boolean
MODEL_UNAVAILABLE_MESSAGEconst
const MODEL_UNAVAILABLE_MESSAGE = "That model is not available. Choose another model."
modelAckNamefunction

Local storage name for a one-time acknowledgment of a non-recommended model.

function modelAckName(provider: ProviderId, modelId: string): string
ModelDiscoverytype
export type ModelDiscovery = {
  models: ModelOption[];
  source: "discovered" | "catalog";
  /** True when the provider list failed and the developer catalog was used. */
  fallback: boolean;
};
ModelListMetadatatype
export type ModelListMetadata = {
  displayName?: string;
  /**
   * Provider-reported image input. `false` blocks the vision heuristic.
   * Omit it when the provider did not say.
   */
  imageInput?: boolean;
  /** Gemini `supportedGenerationMethods` and similar lists. */
  methods?: string[];
};
ModelOptiontype
export type ModelOption = {
  id: string;
  provider: ProviderId;
  capabilities: Capability[];
  displayName: string;
  catalogUpdatedAt: string;
  source: "catalog" | "discovered";
  availabilityCaveat: string;
};
NON_RECOMMENDED_MODEL_WARNINGconst

Shown before a non-recommended model is saved. The user must acknowledge it.

const NON_RECOMMENDED_MODEL_WARNING = "This model isn't recommended for this app. It may produce unexpected results, and you're responsible for its output."
partitionModelsfunction
function partitionModels<T extends { provider: ProviderId; id: string }>(models: T[], recommended: readonly RecommendedModel[] | undefined): { recommended: T[]; available: T[] }
PROVIDER_IDSconst
const PROVIDER_IDS = ["openai", "anthropic", "gemini"] as const
ProviderIdtype
export type ProviderId = (typeof PROVIDER_IDS)[number];
RecommendedModeltype
export type RecommendedModel = {
  provider: ProviderId;
  modelId: string;
};
scrubVisitorTextfunction

Replace text that could carry a provider body or key echo. Safe, authored messages pass through.

function scrubVisitorText(message: string, fallback = UPSTREAM_ERROR_MESSAGES.unknown): string
Selectiontype
export type Selection = {
  capability: Capability;
  provider: ProviderId;
  modelId: string;
};
TASK_UNSUPPORTED_MESSAGEconst

Shown when a selected model cannot perform the requested call.

const TASK_UNSUPPORTED_MESSAGE = "This model can't do that task. Choose a model that supports it."
TRUST_NOTICESconst
const TRUST_NOTICES = {
  capabilityDoesNotLimitKey:
    "A capability only controls routing and this screen. It does not restrict what this API key can do at the provider.",
  hostOperatesKey:
    "This app's server receives your key and the content you submit, and it sends that content to the provider you select.",
  localDeletionDoesNotRevoke:
    "Removing a connection here deletes the key from this app. It does not revoke the key at the provider.",
  estimatedInThisApp:
    "Estimated in this app. Provider account totals can differ because this ledger only includes requests routed through this app.",
  budgetIsBestEffort:
    "Budget checks use observed spend in this app before a call. They cannot see the final token count, and concurrent requests can cross a threshold. This is not a guaranteed spending cap. Set limits in the provider account where they are offered.",
  testMaySpendQuota: "Testing this connection may use provider quota and can incur a charge.",
} as const
UPSTREAM_ERROR_CATEGORIESconst

Visitor-facing buckets for an upstream provider failure.

const UPSTREAM_ERROR_CATEGORIES = ["invalid_key", "rate_limited", "quota", "unavailable", "unknown"] as const
UPSTREAM_ERROR_MESSAGESconst

Fixed visitor copy for upstream failures. These strings are the only text a key test or provider error may show. They never include provider bodies, key material, request ids, or headers.

const UPSTREAM_ERROR_MESSAGES: Record<UpstreamErrorCategory, string> = {
  invalid_key: "The provider rejected this key. Check the key and try again.",
  rate_limited: "The provider rate limit was reached. Wait and try again.",
  quota: "The provider quota or billing limit was reached. Check the provider account.",
  unavailable: "The provider is unavailable or the request timed out. Try again later.",
  unknown: "The provider request failed. Try again.",
}
UpstreamErrorCategorytype
export type UpstreamErrorCategory = (typeof UPSTREAM_ERROR_CATEGORIES)[number];
UsageUnitstype
export type UsageUnits = {
  inputTokens?: number;
  outputTokens?: number;
  cacheReadTokens?: number;
  cacheWriteTokens?: number;
  imageCount?: number;
};

@byoki/server

Authenticated connection handlers and the development credential store for BYOKI. Version 0.2.0. Node >=20.

AIConnectionsAppOptionstype
export type AIConnectionsAppOptions = {
  config: AIConnectionsConfig;
  adapters: Partial<Record<ProviderId, ProviderAdapter>>;
  catalog: ModelOption[];
  links: Record<ProviderId, ProviderLink>;
  estimateCost: (args: {
    provider: ProviderId;
    modelId: string;
    usage: UsageUnits | undefined;
  }) => CostEstimate;
  /** Required unless credentials, selections, and ledger are all provided. */
  masterKey?: string;
  dataFile?: string;
  credentials?: CredentialStore;
  selections?: SelectionStore;
  ledger?: UsageLedger;
  logger?: Logger;
};
assertProductionStorefunction
function assertProductionStore(store: ProductionCredentialStore): ProductionCredentialStore
AuthContexttype
export type AuthContext = {
  scope: Scope | null;
  csrfHeader: string | null;
  expectedCsrf: string | null;
  origin: string | null;
  host: string | null;
  /**
   * `cookie` (default) requires a matching `x-csrf-token` on mutations, and
   * rejects a cross-origin `Origin` when both Origin and Host are present.
   * `bearer` skips those checks. Set it only after the host has authenticated
   * an `Authorization: Bearer` credential. Do not set it for a cookie session:
   * browsers attach cookies on their own, so skipping CSRF would allow a
   * cross-site request to use the session.
   */
  transport?: AuthTransport;
};
AuthTransporttype
export type AuthTransport = "cookie" | "bearer";
createAIConnectionsAppfunction

Wires the router and settings handlers for one host process. Pass your own stores in production. Omit them in development to use the encrypted file store and BYOKI_MASTER_KEY.

function createAIConnectionsApp(options: AIConnectionsAppOptions)
createEncryptedFileStorefunction

Development store. Credentials are encrypted with AES-256-GCM. The master key comes from the host environment and is never written to the file. Production hosts should implement CredentialStore with their own secrets manager.

function createEncryptedFileStore(filePath: string, masterKey: Buffer)
createHandlersfunction
function createHandlers(deps: HandlerDeps)
createMemoryCredentialStorefunction
function createMemoryCredentialStore(): CredentialStore
createMemoryLedgerfunction
function createMemoryLedger(): UsageLedger & { all(): UsageRecord[] }
createMemorySelectionStorefunction
function createMemorySelectionStore(): SelectionStore
createNodeHttpServerfunction

Node HTTP server that forwards each request to a Fetch `dispatch`. Response bodies are written as they arrive, so `text/event-stream` is not buffered. Call `listen` on the returned server. This helper does not choose a port or a user.

function createNodeHttpServer(options: NodeHttpServerOptions): Server
createRateLimiterfunction
function createRateLimiter(limit: number, windowMs: number, now = () => Date.now()): RateLimiter
createRedactingLoggerfunction
function createRedactingLogger(write: (line: string) => void): Logger
decodeMasterKeyfunction
function decodeMasterKey(raw: string): Buffer
decryptStringfunction
function decryptString(payload: { iv: string; tag: string; ciphertext: string }, key: Buffer): string
EncryptedFileStoretype
export type EncryptedFileStore = ReturnType<typeof createEncryptedFileStore>;
encryptStringfunction
function encryptString(plaintext: string, key: Buffer): { iv: string; tag: string; ciphertext: string }
HandlerDepstype
export type HandlerDeps = {
  config: AIConnectionsConfig;
  credentials: CredentialStore;
  selections: SelectionStore;
  ledger: UsageLedger;
  adapters: Partial<Record<ProviderId, ProviderAdapter>>;
  catalog: ModelOption[];
  links: Record<ProviderId, ProviderLink>;
  rateLimit: RateLimiter;
  logger: Logger;
  maxBodyBytes?: number;
  /** Byte cap for `POST /invoke`. Defaults to 1 MiB. Key routes stay on `maxBodyBytes`. */
  maxInvokeBodyBytes?: number;
  /** Buffered prompt call. Omit to leave `POST /invoke` disabled. */
  invoke?: (scope: Scope, body: InvokeBody) => Promise<InvokeSuccess>;
  /** Token stream used when the invoke body sets `stream: true`. */
  invokeStream?: (scope: Scope, body: InvokeBody) => AsyncIterable<InvokeStreamEvent>;
};
Loggertype
export type Logger = {
  info(event: string, fields?: Record<string, unknown>): void;
  error(event: string, fields?: Record<string, unknown>): void;
};
NODE_HTTP_BODY_LIMITconst

Largest request body the Node listener will read before `dispatch`. Matches the invoke cap.

const NODE_HTTP_BODY_LIMIT = 1_048_576
NodeHttpServerOptionstype
export type NodeHttpServerOptions = {
  dispatch: (request: Request, auth: AuthContext) => Promise<Response>;
  /**
   * Map the incoming request to a scope. For a native client, validate
   * `Authorization: Bearer` here and return `transport: "bearer"`.
   * The bearer token is the app session, not the provider API key.
   */
  authenticate: (request: Request) => Promise<AuthContext> | AuthContext;
};
PayloadTooLargeErrorclass
export class PayloadTooLargeError extends Error {
  readonly status = 413;
  constructor() {
    super("Request body is too large.");
    this.name = "PayloadTooLargeError";
  }
}
ProductionCredentialStoretype

Production credential stores use a secrets manager or envelope encryption with keys managed outside the application process. Implement CredentialStore. Do not store plaintext keys in application databases or logs.

export type ProductionCredentialStore = CredentialStore & {
  readonly kind: "production";
};
ProviderLinktype
export type ProviderLink = {
  keys: string;
  usage: string;
  billing: string;
  reviewedAt: string;
};
readIncomingRequestfunction

Buffer a Node request into a Fetch `Request`, rejecting bodies over `NODE_HTTP_BODY_LIMIT`.

async function readIncomingRequest(req: IncomingMessage): Promise<Request>
redactfunction

Drop a string that contains a key, including a provider's masked echo (`sk-test-*******-000`). The whole value is replaced so the surrounding upstream sentence is not kept.

function redact(text: string, extraSecrets: string[] = []): string
writeFetchResponsefunction

Write a Fetch `Response` to Node, including a streaming body.

async function writeFetchResponse(res: ServerResponse, response: Response): Promise<void>

@byoki/providers

OpenAI, Anthropic, and Gemini adapters for BYOKI. Version 0.2.0. Node >=20.

CATALOG_UPDATED_ATconst
const CATALOG_UPDATED_AT = "2026-09-25T00:00:00.000Z"
createAnthropicAdapterfunction
function createAnthropicAdapter(fetchImpl: FetchLike = fetch): ProviderAdapter
createGeminiAdapterfunction
function createGeminiAdapter(fetchImpl: FetchLike = fetch): ProviderAdapter
createOnDeviceClientfunction

Browser, Electron, or another client. No server and no key storage.

function createOnDeviceClient(fetchImpl?: FetchLike): DirectClient
createOpenAIAdapterfunction
function createOpenAIAdapter(fetchImpl: FetchLike = fetch): ProviderAdapter
createProviderAdaptersfunction
function createProviderAdapters(fetchImpl?: FetchLike): Record<ProviderId, ProviderAdapter>
MANUAL_CATALOGconst
const MANUAL_CATALOG: ModelOption[] = [
  model("openai", "gpt-5.6-terra", "GPT-5.6 Terra", ["chat", "vision"]),
  model("openai", "gpt-5.6-luna", "GPT-5.6 Luna", ["chat", "vision"]),
  model("anthropic", "claude-sonnet-5", "Claude Sonnet 5", ["chat", "vision"]),
  model("anthropic", "claude-haiku-4-5", "Claude Haiku 4.5", ["chat", "vision"]),
  model("gemini", "gemini-3.5-flash", "Gemini 3.5 Flash", ["chat", "vision"]),
  model("gemini", "gemini-3.1-flash-lite", "Gemini 3.1 Flash-Lite", ["chat", "vision"]),
]
PROVIDER_LINKSconst
const PROVIDER_LINKS = {
  openai: {
    keys: "https://platform.openai.com/api-keys",
    usage: "https://platform.openai.com/usage",
    billing: "https://platform.openai.com/settings/organization/billing",
    reviewedAt: "2026-09-25",
  },
  anthropic: {
    keys: "https://platform.claude.com/settings/keys",
    usage: "https://platform.claude.com/usage",
    billing: "https://platform.claude.com/settings/billing",
    reviewedAt: "2026-09-25",
  },
  gemini: {
    keys: "https://aistudio.google.com/apikey",
    usage: "https://aistudio.google.com/usage",
    billing: "https://console.cloud.google.com/billing",
    reviewedAt: "2026-09-25",
  },
} as const

@byoki/pricing

Versioned price catalog and cost estimates for BYOKI. Version 0.2.0. Node >=20.

estimateCostfunction
function estimateCost(catalog: PriceEntry[], args: { provider: ProviderId; modelId: string; usage: UsageUnits | undefined }): CostEstimate
PRICE_CATALOGconst

Prices reviewed against public provider pages on 2026-09-25. Models without an entry estimate as unknown rather than zero. OpenAI figures are from the models guide. Anthropic Opus 5 and Fable 5.1 figures are from Anthropic's model catalog. Other models stay unpriced until a reviewed entry is added.

const PRICE_CATALOG: PriceEntry[] = [
  { provider: "openai", modelId: "gpt-5.6-sol", version: PRICE_CATALOG_VERSION, currency: "USD", inputPerMillion: 4, outputPerMillion: 20 },
  { provider: "openai", modelId: "gpt-5.6-terra", version: PRICE_CATALOG_VERSION, currency: "USD", inputPerMillion: 2, outputPerMillion: 12 },
  { provider: "openai", modelId: "gpt-5.6-luna", version: PRICE_CATALOG_VERSION, currency: "USD", inputPerMillion: 0.2, outputPerMillion: 1.2 },
  { provider: "anthropic", modelId: "claude-opus-5", version: PRICE_CATALOG_VERSION, currency: "USD", inputPerMillion: 5, outputPerMillion: 25 },
  { provider: "anthropic", modelId: "claude-fable-5-1", version: PRICE_CATALOG_VERSION, currency: "USD", inputPerMillion: 10, outputPerMillion: 50, cacheReadPerMillion: 0.25 },
]
PRICE_CATALOG_VERSIONconst
const PRICE_CATALOG_VERSION = "2026-09-25"
PriceEntrytype
export type PriceEntry = {
  provider: ProviderId;
  modelId: string;
  version: string;
  currency: "USD";
  inputPerMillion?: number;
  outputPerMillion?: number;
  cacheReadPerMillion?: number;
  cacheWritePerMillion?: number;
};

@byoki/react

Settings screen and typed host API client for BYOKI. Requires React 19. Version 0.2.0. Node >=20.

AIConnectionsSettingsfunction
function AIConnectionsSettings({
  client,
  refreshToken = 0,
}: {
  client: ConnectionsClient;
  /** Increment after a host request so usage reloads without resetting the form. */
  refreshToken?: number;
})
ConnectionsClienttype
export type ConnectionsClient = {
  getConnections(): Promise<ConnectionsView>;
  putKey(provider: ProviderId, apiKey: string): Promise<void>;
  deleteKey(provider: ProviderId): Promise<void>;
  testKey(
    provider: ProviderId,
    apiKey?: string,
  ): Promise<{ ok: boolean; reason?: string; category?: UpstreamErrorCategory; testMaySpendQuota: boolean }>;
  getModels(capability: Capability, discover?: boolean): Promise<{ models: ModelView[]; warnings: string[] }>;
  putSelection(capability: Capability, provider: ProviderId, modelId: string): Promise<void>;
  getUsage(from: string, to: string): Promise<UsageView>;
};
ConnectionsViewtype
export type ConnectionsView = {
  appName: string;
  notices: {
    capabilityDoesNotLimitKey: string;
    hostOperatesKey: string;
    localDeletionDoesNotRevoke: string;
    estimatedInThisApp: string;
    budgetIsBestEffort: string;
    testMaySpendQuota: string;
  };
  capabilities: Array<{
    id: Capability;
    description: string;
    required: boolean;
    userCanChooseModel: boolean;
    providers: ProviderId[];
    recommendedModels: Array<{ provider: ProviderId; modelId: string; displayName?: string }>;
    defaultModel: { provider: ProviderId; modelId: string; displayName?: string } | null;
    selection: Selection | null;
    selectionIssue: { code: string; message: string } | null;
  }>;
  providers: Array<{
    id: ProviderId;
    status: "connected" | "disconnected";
    keyUrl: string;
    usageUrl: string;
    billingUrl: string;
    linksReviewedAt: string;
    testMaySpendQuota: boolean;
  }>;
  limits: {
    maxOutputTokens?: number;
    requestTimeoutMs: number;
    budget?: { warnAtUsd?: number; blockAtUsd?: number };
  };
  observedSpendUsd: number;
  observedSpendHasUnknown: boolean;
};
createConnectionsClientfunction
function createConnectionsClient(options: { baseUrl: string; csrfToken: string }): ConnectionsClient
ModelViewtype
export type ModelView = {
  id: string;
  provider: ProviderId;
  capabilities: Capability[];
  displayName: string;
  catalogUpdatedAt: string;
  source: "catalog" | "discovered";
  availabilityCaveat: string;
};
UsageViewtype
export type UsageView = {
  label: string;
  from: string;
  to: string;
  requests: number;
  successes: number;
  failures: number;
  estimatedCost: number | null;
  estimationStatus: "known" | "unknown";
  observedKnownUsd: number;
  units: Array<{
    time: string;
    capability: Capability;
    provider: ProviderId;
    modelId: string;
    outcome: string;
    usage: { inputTokens?: number; outputTokens?: number } | null;
    estimationStatus: "known" | "unknown";
    estimatedCost: number | null;
    errorCode: string | null;
  }>;
  budgetNotice: string;
};

Security model

The host authenticates the user and then holds that user’s provider key. Anything running on that server can use the key outside this SDK. Users should also set spending limits in the provider account. A declared capability restricts SDK routing and the settings UI. It does not restrict the provider account.

What the SDK enforces

  • Keys are submitted over the host session. The reference UI does not write them to browser storage.
  • Read endpoints return connection status, not the key.
  • The development file store encrypts keys with AES-256-GCM. The master key comes from the environment.
  • Logs pass through a redactor that strips common key prefixes and fields named like secrets.
  • Records are scoped by tenant and user.
  • Provider calls use fixed HTTPS endpoints. This release does not accept a caller-supplied provider URL.
  • Connection tests and model discovery are rate limited.
  • Upstream failures are shown as a fixed message for the failure category. Provider response text, request ids, and headers are not returned.

What this public demo adds

  • Each visitor gets an anonymous session id. There is no shared password.
  • The default store is process memory. Keys are deleted when the session expires, the visitor ends the session, or the process restarts.
  • Mock mode is the default, including when BYOKI_USE_MOCK is unset, so the site can run with no provider credentials on the server.
  • Redirects only honor byoki.eastonnielson.dev, localhost, and hosts you list in BYOKI_PUBLIC_HOST or BYOKI_PUBLIC_ORIGIN. A stray forwarded host cannot send the browser elsewhere.
  • The invoke route returns a fixed message for provider failures and does not log the prompt or the key.

Local deletion removes the key from this app. It does not revoke the key at the provider. Budget checks are best-effort and are not a guaranteed spending cap.

Production guidance

Implement CredentialStore with a secrets manager or envelope encryption whose data keys live outside the app. The type ProductionCredentialStore marks that implementation. Pass credentials, selections, and ledger into createAIConnectionsApp. assertProductionStore checks the kind field.

Do not ship the development file store, and do not use this demo’s anonymous sessions, as production auth. Scope every secret by the tenant and user your auth system resolved. Keep plaintext keys in memory only for the provider call that needs them.

Serve the host over HTTPS. Keep the master key or the secrets-manager credentials in the platform secret store. Avoid screenshots, traces, and analytics that include the key field.

A model without a reviewed price entry shows “Cost unavailable”, not zero. POST /api/ai/invoke with stream: true responds with server-sent events. router.invoke still returns one buffered result.

Framework integration

Next.js App Router

The demo app mounts the handlers on a catch-all route. Compare origin to the public host when you are behind nginx or a Cloudflare tunnel, not to the internal bind address.

app/api/ai/[[...path]]/route.ts
import { getSession } from "@/lib/auth";
import { getServices } from "@/lib/services";

async function handle(request: Request): Promise<Response> {
  const session = await getSession();
  const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host");
  return getServices().handlers.dispatch(request, {
    scope: session ? { tenantId: session.tenantId, userId: session.userId } : null,
    csrfHeader: request.headers.get("x-csrf-token"),
    expectedCsrf: session?.csrf ?? null,
    origin: request.headers.get("origin"),
    host,
  });
}

export const GET = handle;
export const PUT = handle;
export const POST = handle;
export const DELETE = handle;

The catch-all forwards POST /api/ai/invoke to handlers.dispatch. In-process code can still call router.forScope. Set the cookie Secure flag from X-Forwarded-Proto when TLS terminates at the proxy. Native clients use Authorization: Bearer and transport: "bearer".

Node HTTP

The starter zip on the downloads page is a node:http server that binds to 127.0.0.1:8787 and forwards /api/ai/* to handlers.dispatch. It uses the development file store so you can see BYOKI_MASTER_KEY. Replace its fixed local user before you expose it.

Any framework that can build a Fetch Request can call handlers.dispatch. The handler does not depend on Next.js.