Skip to content

feat(platform): serve OpenAI- and Anthropic-compatible model endpoints - #3812

Merged
yannickmonney merged 12 commits into
mainfrom
feat/model-api-door
Sep 29, 2026
Merged

yannickmonney merged 12 commits into
mainfrom
feat/model-api-door

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Developers can now use their organization's approved models from their own tools — opencode, Claude Code, and scripts on the OpenAI or Anthropic SDKs — with a personal Tale API key. Tale 0.3 had an OpenAI-compatible /api/v1/chat/completions; the 0.4 rewrite removed it. This adds a bare, governed model door in its place (not the workspace assistant: no Tale tools, no threads, ids name models, not agents):

  • POST /api/v1/openai/chat/completions and GET /api/v1/openai/models — OpenAI Chat Completions, streamed (SSE) and not, with tools / tool_calls and images for vision models. Base URL https://<host>/api/v1/openai.
  • POST /api/v1/anthropic/v1/messages — Anthropic Messages, streamed and not, with tools and images. Base URL https://<host>/api/v1/anthropic (ANTHROPIC_BASE_URL for Claude Code).

REST contract 3.7.0 (3.6.0 went to #3810, members create tasks).

How it works

Auth. The routes sit inside the existing REST door: Authorization: Bearer <personal key>, X-Organization-Slug for a multi-organization key, the same rest:api rate-limit bucket and request id. The global x-api-key refusal is untouched; on the Anthropic path its 401 now says to use ANTHROPIC_AUTH_TOKEN / authToken and leave ANTHROPIC_API_KEY unset. Every refusal on these paths — the door's own 401/400/403/404/429/413/500/503 included — is reshaped into the wire's error shape (OpenAI {error:{message,type,param,code}}, Anthropic {type:"error",error:{type,message,code},request_id}), with the REST door's stable code in code. Query parameters are ignored on these paths (Anthropic SDKs send ?beta=true).

Governance, off by default. The switch is a field of the existing model-access policy (modelApi.enabled in model-access.yml), shown as a second section of Settings → Governance → Models → Model access ("Model endpoints for API keys"), independent of the rules' own switch; no second allowlist, no new policy type. Owners, admins and developers may call by role; any other member through one new closed capability, tale:models.api ("Call models over the API") in the competence register. GET /api/v1/me answers capabilities.modelApi. Every request re-reads the policy strictly (unreadable → 503, never open), applies the model-access allow/block rules for the key holder (403 MODEL_API_MODEL_FORBIDDEN), and serves only models the listing admits.

Listing. GET /api/v1/openai/models = the composer's governed listing (each provider's servable catalog under its default credential, the credential's model allowlist applied, chat models only, model access applied), narrowed to direct credentials (API key / env) on fixed-endpoint connectors. Ids are <providerSlug>/<modelId> on both wires (split at the first slash; the catalog id keeps its own slashes).

Serving — reused, not forked. Each request is relayed to the sandbox LLM gateway's own vendor-compatible doors (/openai/v1/chat/completions, /anthropic/v1/messages — the doors the managed harnesses already use) under a virtual key minted for that one request by provisionSessionGatewayKey (fail-closed provider push, applyGatewayConfig, pricing overrides, mintVirtualKey bound to the org's upstream key and that one model). A provider with a native Anthropic endpoint serves the Anthropic wire natively, as it does for Claude Code turns (ridesAnthropicHarnessEndpoint, split out of agent_serving.ts). Raw provider keys never leave the platform; the gateway port stays unpublished; no client header reaches the gateway except anthropic-version/anthropic-beta (Bifrost reads x-bf-* headers as instructions), and the gateway-only body field fallbacks is dropped. Answers name model as the id the caller sent; gateway routing names (which carry the org id) are replaced in refusals. I checked Bifrost transports v1.6.11 (integrations/openai.go, anthropic.go, lib/ctx.go) for both routes and the Bearer virtual-key extraction.

Metering. reserveTurnBudget now takes an explicit subject and a model-api kind: it measures the key holder (teams, role) and the key against every cap after booked spend and every hold in flight, and records the request's hold — its worst case at the catalog price, prompt estimate plus the output cap once per requested answer (n) — on an app.sandbox_session_ops row (session_id model-api:<key id>, stamped with the person, __direct_api__ and the key). A reached cap is the chat lane's coded 429 BUDGET_EXCEEDED with Retry-After (and x-should-retry: false), in the wire's shape. After the answer ends, the shared settleGatewayKey reads the key's spend from the gateway, books it into app.usage_ledger under the person, __direct_api__ (Usage shows "Direct API") and the API key together with the token counts the relayed answer reported, then deletes the key. What that attempt cannot finish goes to the existing sandbox.gateway_key_reconcile job and the sandbox watchdog's settlement sweep; the watchdog also closes a request op whose process died mid-answer (no heartbeat for 5 minutes).

Guardrails. The organization's input chain a chat turn runs (chat filter → PII → moderation, built by buildTurnGuardrails) judges every text the caller sends before the relay (see the review round below): a block answers 400 MODEL_API_GUARDRAIL_BLOCKED (the chat turn's sentence), a mask rewrites the text the model receives, a fail-closed step failure answers 503 MODEL_API_GUARDRAIL_UNAVAILABLE, and a PII policy in tokenize mode — which needs to restore data into the answer — is refused (403 MODEL_API_GUARDRAIL_UNSUPPORTED) rather than skipped. Output is not filtered (documented). Images and non-text documents are relayed unread. Long texts are judged in pieces at the chain's own 50 KB scan limit (the filters would otherwise relay a masked text cut short), and a verdict is remembered per organization, policy version and exact text for 10 minutes, so a stateless client resending its whole conversation is not re-moderated (or re-logged) every turn. Events land in the guardrail log under model-api:<request id>.

UI. Model access gets the switch section; the competence register gets the capability; Settings → API gets a Models tab (next to REST / MCP / WebDAV) with both base URLs, the org slug, the models the member may call, copyable opencode (@ai-sdk/openai-compatible with baseURL + headers), Claude Code (ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_CUSTOM_HEADERS) and OpenAI SDK setups, and a clear "not enabled for your organization" state (with the way to Model access for admins). EN/DE/FR strings.

Design choices and deviations (and why)

  • Per-request virtual key, not a cached short-lived one: it keeps one ledger request per call (request caps count calls) and exact per-request attribution; the cost is a handful of internal gateway management calls per request, the same set a session create makes.
  • Op rows, not a new table. A door request borrows app.sandbox_session_ops (kind model-api, not an agent kind, so the sandbox, run-card and metric readers never see it): that is where the reservation holds, the attribution stamp and the reconcile sweep already live. The review round added nullable settlement columns (0135), two indexes (0136), a request-id column on guardrail events (0137) and a 7-day sweep of settled rows.
  • Token counts (superseded in the review round: the relay's counts now sit on the op row, so every settle path books them). The settle waits 2 s after the answer because Bifrost's governance plugin books a key's usage in a goroutine after the response (plugins/governance v1.6.14 PostLLMHook). If the inline settle cannot run (process dies, gateway down), the job/sweep books the gateway's cost figure without token counts; cost caps stay exact, token caps under-count in that case.
  • Unsettled op holds now count against their API key's caps (budget-reservations.ts selected NULL for an op's key). This applies to keyed automation runs too; it is what the governance README already promised ("the key's own budget caps see the spend").
  • Vendor-run tools are refused (OpenAI web_search_options and non-function/custom tools; Anthropic web search/fetch, code execution, MCP toolsets, mcp_servers, container): they are neither metered nor audited, the same reason managed harnesses deny WebSearch/WebFetch. Claude Code's WebSearch tool therefore fails through this door.
  • Members holding tale:models.api can open Settings → API → REST and Models (MCP and WebDAV stay developer-only): without the REST tab a member could not mint the key the capability is for.
  • Images and documents may ride as data: or https: URLs only; input_audio is refused; count_tokens and other Anthropic routes are not served (404 in the Anthropic shape); body cap 32 MiB (Anthropic's own request limit); created is 0 in the model list.
  • readEvent (the chat turn's SSE decoder) moved to core/chat/stream_decode.ts so the relay reads usage with the same decoder without importing the chat host; the composer's listing walk is shared as listGovernedChatModels.

Checklist

  • bun run check — not fully green on this machine, for reasons outside this branch: format:check and 53 of the 55 turbo tasks pass. @tale/sandbox-runtime-daemon#test fails two tests (stageFiles gives up on a stalled URL…, a partial exec request body already protects the runtime…) even when run alone; this branch changes nothing under services/sandbox-runtime, and the daemon imports no workspace package, so its code is identical to main. @tale/platform#test:ui lost one test (enterprise-sso-form.test.tsx, a 5 s timeout) under the pipeline's parallel load; that file passes alone and the whole UI suite passes when run by itself (below).
  • bun run lint:sast — opengrep over the 76 changed TypeScript files: 0 findings (tools/opengrep/run.sh <files>).
  • Translations updated in services/platform/messages/{en,de,fr}.yml; no de-CH override needed (no ß/ss-sensitive wording).
  • Docs updated in docs/{en,de,fr}/: the editor page (rewritten around the model endpoints), API reference, API keys, Models (model access), Competences, Guardrails, Policies and limits, How usage is counted, Rate limits, the developer overview and the 0.3 → 0.4 upgrade note. German in du, French in tu.
  • README.md / README.de.md / README.fr.md — N/A: the READMEs link to the developer docs, which cover it.

Test plan

All green on the rebased branch (7 commits on fac88dfc2):

  • services/platform: bunx vitest --run --project server --project pii — 913 files (1 skipped), 79,382 tests passed; bunx vitest --run --config vitest.ui.config.ts — 516 files, 4,430 tests passed; bunx tsc --noEmit and bunx oxlint --type-aware clean; bun run build passes (entry budget, service-worker manifest, boot shell).
  • The new and changed tests: backend/domains/model_api/*.test.ts (access, the two request readers, guardrails, metering, listing, relay, wire errors — 82 tests), backend/rest/v1-model-api.test.ts and v1-model-api.door.test.ts (the routes, and the REST door's own refusals in each wire's shape), v1-core.test.ts (capabilities.modelApi), the governance routes.test.ts (/my/model-api), budget-gate, budget-reservations and turn-budget tests, the OpenAPI and error-code guards (spec.test.ts, error-codes.test.ts: contract 3.6.0, fingerprint, byte caps, code registry), and on the UI model-access-editor, model-endpoints-section, use-api-settings-access, settings-rail and use-settings-menu-groups.
  • packages/shared: vitest (40 files, 623 tests), tsc, oxlint.
  • services/docs: vitest (36 files, 200 tests: links, anchors, locale outlines, frontmatter), tsc.
  • bun run lint:manual (1,307 boxes) and check-guide.ts on governance.md and settings.md; bunx knip; bun run format:check.

With a stack in mode B (sandbox model gateway running), a reviewer can walk it end to end:

  1. As an admin, turn on Settings → Governance → Models → Model access → Model endpoints for API keys.
  2. Create a key under Settings → API → REST; open Settings → API → Models and check the base URLs, the slug and the model ids.
  3. curl -H "Authorization: Bearer $KEY" <host>/api/v1/openai/models, then run the tab's OpenAI SDK snippet and Claude Code variables; a WebSearch in Claude Code should fail with MODEL_API_VENDOR_TOOL_UNSUPPORTED.
  4. Check Governance → Usage: the calls sit on one Direct API row under the key holder.
  5. The manual boxes: GOV-F38–GOV-F44, GOV-B14–GOV-B16, GOV-A6 in governance.md; SET-F64–SET-F68, SET-B23–SET-B26, SET-A10 in settings.md.

Not verified

Nothing here ran against a live stack (Docker was down for this work), so none of the following is observed:

  • No request went through a real gateway. The relay, the virtual-key mint and the settlement are proven against a mocked gateway HTTP surface and a mocked provider catalog only. Bifrost's routing of <record>/<model> on its /openai/v1/chat/completions and /anthropic/v1/messages doors, its SSE framing per provider, and the usage figures it reports were read from the v1.6.11 source, not exercised.
  • No real client was pointed at the endpoints: no opencode, no Claude Code (including its ?beta=true queries, anthropic-beta flags and background Haiku calls), no OpenAI or Anthropic SDK run, no vision or tool-call round trip. The snippets in the Models tab and the docs follow the vendors' documented configuration.
  • The 2-second settle delay assumes Bifrost's governance plugin has booked the key's usage by then; if it has not, the reconcile job books the cost later without token counts.
  • SSE through the production proxy (Caddy, compression) is not checked for buffering.
  • The real-Postgres suite (backend:integration) was not run; the SQL is covered by unit tests with a fake sql only.
  • Pricing tiers. A request that sets service_tier (OpenAI, Anthropic) or a long-context beta is relayed as sent and booked at what the gateway's pricing computes; that was not compared with a vendor bill.
  • Row growth. Each model call leaves one settled row in app.sandbox_session_ops, as each agent turn does; that table has no retention sweep yet, which a busy organization will want as a follow-up.
  • The UI was not driven in a browser, and the docs pages were not rendered; both are covered by component tests and the docs guards only.
  • No docs screenshot of the Models tab or the switch yet: the capture pipeline (tests/docs-screenshots/) needs the live dev stack, so extending its manifest and retaking is a follow-up.

Review round (2026-09-29)

An adversarial review found a metering blocker and eight should-fixes; all are fixed on this branch (commits 2bb48d192..abfc0729f, then a merge of main):

  • Broken-off calls are booked (blocker). Bifrost v1.6.11 neither cancels a whole answer when the caller hangs up nor keeps a cut stream's usage. A cancelled whole answer now settles only after the gateway's request timeout (its virtual key kept until then), a cut stream books at least its prompt plus the relayed output at the catalog price, and a gateway reading of 0 for a priced answer waits and then books the expected cost. Upgrading Bifrost (≥ 2.2) is recorded in the debt ledger.
  • Memory/CPU bounds. The verdict cache is bounded by bytes (masked text kept only when small), pieces are cut linearly, more than 2 MB of text under a guardrail is refused (413 MODEL_API_TEXT_TOO_LARGE), moderation calls are bounded, and a person or key has at most 8 requests in flight (429 MODEL_API_CONCURRENCY_EXCEEDED).
  • Every caller text is judged on both wires: assistant turns and prefill, tool calls, results and definitions, documents given as text, search results, predicted output. Guardrail policies are read strictly on this surface.
  • The worst case is enforced: a request whose worst case does not fit a cap's room is refused whole (BUDGET_EXCEEDED, naming the binding cap and the affordable max_tokens); n is capped at 8; media are counted by part type.
  • Retention and erasure: settled model-endpoint op rows are swept after 7 days and erased with the person; harness readers use a new (org_id, kind, started_at_ms) index.
  • Provisioning per call: config apply memoized, provider/pricing checks cached, request id in the virtual key name, no sandbox admission lock.
  • Tokens: the relay's counts are stored on the op row for every settle path; Anthropic cache tokens count as input; holds carry tokens.
  • Lifetime ceiling: every request has a deadline that aborts upstream, closes the stream and settles; a key whose id could not be recorded is revoked.
  • Refused fields: vendor-account files (file_id, file sources), non-default service tiers, audio output and store: true; upstream error text is redacted of internal hosts; guardrail events carry the server's request id beside the caller's.

Docs (EN/DE/FR), the OpenAPI spec (3.7.0), the manual register and the debt ledger are updated. Merging main renumbered the migrations to 0135–0137 (main's 0134 is image generation) and this PR's governance boxes to GOV-F40–F46 / GOV-B15–B17 (main's image boxes kept F38/F39/B14).

The model endpoints for personal API keys are an organization's to turn
on, and every call through them is held to the model-access allow and
block rules — so the switch lives on that policy rather than in a second
policy or allowlist: `modelApi.enabled`, optional, and absent (like an
absent file) reads as off. It is independent of the rules' own `enabled`
flag. `modelApiEnabledOf` is the one reading of it.
Three pieces the model endpoints for API keys reuse rather than copy, moved
where a second caller can reach them without pulling in the chat host:

- `readEvent` and its decode state leave `core/chat/turn_action.ts` for
  `core/chat/stream_decode.ts`, so a relayed answer's usage is read by the
  decoder a chat turn uses;
- the composer's catalog walk — each provider's servable catalog under its
  default credential, allowlist and model access applied — is exported as
  `listGovernedChatModels`, and the direct-credential test the REST send
  inlined is `servedByDirectCredential`;
- the harness serving decision whether a wire rides a connector's native
  Anthropic endpoint is exported by wire (`ridesAnthropicHarnessEndpoint`)
  as well as by harness.

No behaviour changes.
The reservation stamps the API key a keyed run started with on the turn's
op row (`sandbox_session_ops.api_key_id`), but the in-flight holds read
the op's key as NULL: a key's own budget caps saw a keyed chat turn's
hold and never a keyed run's managed turn, so concurrent keyed runs could
each size themselves off the same remaining key balance and overshoot it.
The hold now carries the key the reservation stamped, as the governance
README already promised.
Developers could use Tale's knowledge from their tools over MCP, but not
the organization's approved models: the OpenAI-compatible layer of 0.3
left with the 0.4 rewrite. This adds a bare, governed model door for
personal API keys — no Tale tools, no threads, ids name models:

- `POST /api/v1/openai/chat/completions` and `GET /api/v1/openai/models`
  (OpenAI Chat Completions) and `POST /api/v1/anthropic/v1/messages`
  (Anthropic Messages), streamed and not, with tools and images, inside the
  REST door: Bearer key, `X-Organization-Slug`, the `rest:api` bucket and
  the request id. Every refusal — the door's own included, reshaped by
  `modelApiWireErrors` — is in the wire's error shape with the REST code;
  the `x-api-key` refusal names ANTHROPIC_AUTH_TOKEN on the Anthropic path.
- Off until the organization turns `modelApi` on in its model-access
  policy; owners, admins and developers call by role, other members
  through the new `tale:models.api` capability. The policy is read strictly
  on every request and its allow/block rules apply; the listing is the
  composer's (credential allowlists, model access, chat models) narrowed to
  what the gateway serves, under `<providerSlug>/<modelId>` ids.
  `GET /api/v1/me` answers `capabilities.modelApi`.
- Served through the sandbox LLM gateway's own OpenAI and Anthropic doors
  with a virtual key minted for the one request by the session
  provisioning path; no client header but the Anthropic version headers
  reaches the gateway, and its `fallbacks` field is dropped.
- Metered like a managed turn: `reserveTurnBudget` (kind `model-api`, the
  subject named by the door) holds the request's worst case against every
  cap of the person, their teams, the org and the key, and records it on an
  op row; the shared settlement books the gateway's figure and the relayed
  token counts under the person, `__direct_api__` and the key, then deletes
  the key. A reached cap is 429 `BUDGET_EXCEEDED` in the wire's shape. The
  sandbox watchdog closes a request whose process died mid-answer.
- The organization's input guardrails judge the system and user text
  first: block refuses, mask rewrites, a tokenizing PII policy is refused
  rather than skipped; the answer is not filtered.

REST contract 3.6.0: the three operations under their own tag and preamble
section, the wire error schemas, twelve `MODEL_API_*` codes.
The admin and developer halves of the model endpoints for API keys:

- Settings → Governance → Models → Model access gets a second section,
  "Model endpoints for API keys", whose switch writes `modelApi` on the
  same policy file. Every save of the rules now writes the switch back
  beside them (the editor rebuilt the file from the rules alone, which
  would have turned the endpoints off on the next rule edit), and a failed
  switch save puts the switch back.
- The competence register offers "Call models over the API".
- Settings → API gets a Models tab next to REST: both base URLs, the
  organization slug, the models the member may call (a new member-readable
  `GET /api/app/governance/my/model-api`), and copyable opencode, Claude
  Code and OpenAI SDK setups built from those facts — or a plain "not
  enabled for your organization" state, with the way to Model access for
  an admin.
- A member holding the grant without a developer role opens the API
  section with the REST and Models tabs only — REST is where the personal
  key the capability is for gets made; MCP and WebDAV stay developer-only.

Strings in EN, DE and FR.
The pages said Tale had no model endpoint an editor could use; they now
say how to use the governed one, and what each governance page means for
it:

- Use Tale from your editor or a script gets the model endpoints as a
  fourth path: prerequisites, connection settings, opencode, Claude Code
  and SDK setup, what Tale checks on every call, what is not served, and
  a table of refusals with what to do about each. The MCP and 0.3
  sections keep their anchors.
- The API reference gets the three routes, the id format, the refusals
  in each interface's shape with their codes, the 32 MiB body cap and
  capabilities.modelApi (contract 3.6.0).
- Models (the switch), Competences (the capability), Guardrails (input
  only, tokenize refused), Policies and limits and How usage is counted
  (the hold, Direct API), API keys, Rate limits, the developer overview
  and the 0.3 upgrade note say what changes for them.

EN, DE (du) and FR (tu).
The boxes cover what a headless run cannot judge about the model
endpoints for API keys — real vendors through the sandbox model
gateway, the OpenAI and Anthropic SDKs, Claude Code and opencode
against the endpoints, the metered cost in Usage, a failing moderation
provider, the Models tab's clipboard and keyboard, and the grant
holder's view of Settings → API.

- governance.md: GOV-F38–F44, GOV-B14–B16, GOV-A6 (69 boxes).
- settings.md: SET-F64–F68, SET-B23–B26, SET-A10 (107 boxes), with the
  Models route and the grant holder's exception to the API role gate.
- error-codes.md: how to provoke each MODEL_API_* code, and the
  model-endpoint forms of BUDGET_EXCEEDED and the x-api-key 401.
- automation.md: what the unit, route and component tests already own.
- pins.md: why x-api-key stays refused on the Anthropic path.
- A call the caller breaks off is still booked: a whole answer settles
  only after the gateway's request timeout, with its key kept until then;
  a cut stream books at least its prompt and the relayed output at the
  catalog price; a gateway reading of 0 for a priced answer waits, then
  books the expected cost. The settlement hints live on the op row.
- Settle and reconcile book the relay's tokens, Anthropic cache tokens
  count as input, and in-flight holds carry their tokens.
- A request whose worst case does not fit a cap's room is refused whole,
  naming the binding cap; `n` stops at 8; a person or key has at most 8
  requests in flight (429 MODEL_API_CONCURRENCY_EXCEEDED).
- The input guardrails judge every caller text on both wires, read their
  policies strictly, bound their verdict memory by bytes, and refuse more
  than 2 MB of text (413 MODEL_API_TEXT_TOO_LARGE).
- Vendor-account files, non-default service tiers, audio output and
  `store: true` are refused; upstream error text is redacted of internal
  hosts; a request has a lifetime ceiling that aborts upstream.
- The gateway provisioning is reused across calls, virtual keys carry the
  request id, and the sandbox admission lock is skipped.
- Settled model-endpoint op rows are swept after 7 days and erased with
  the person; guardrail events carry the server's request id beside the
  caller's.
Every caller text is judged, a worst case that does not fit is refused, eight calls may run at once, broken-off calls are still booked, and the refused request fields are listed, in English, German and French. The German guardrails page names Aktuelle Ereignisse as the UI does.
# Conflicts:
#	docs/de/platform/admin/governance/policies-and-limits.md
#	docs/de/platform/admin/governance/usage-attribution.md
#	docs/en/platform/admin/governance/policies-and-limits.md
#	docs/en/platform/admin/governance/usage-attribution.md
#	docs/fr/platform/admin/governance/policies-and-limits.md
#	docs/fr/platform/admin/governance/usage-attribution.md
#	services/platform/backend/domains/chat/budget-admission.ts
#	services/platform/backend/domains/governance/README.md
#	services/platform/backend/domains/governance/budget-reservations.ts
#	services/platform/lib/shared/constants/api-contract.ts
#	services/platform/scripts/openapi/contract-fingerprint.json
#	services/platform/tests/manual/suites/governance.md
#	services/platform/tests/manual/suites/settings.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant