Repository navigation
feat(platform): serve OpenAI- and Anthropic-compatible model endpoints - #3812
Merged
Merged
Conversation
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
This was referenced Sep 29, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/completionsandGET /api/v1/openai/models— OpenAI Chat Completions, streamed (SSE) and not, with tools /tool_callsand images for vision models. Base URLhttps://<host>/api/v1/openai.POST /api/v1/anthropic/v1/messages— Anthropic Messages, streamed and not, with tools and images. Base URLhttps://<host>/api/v1/anthropic(ANTHROPIC_BASE_URLfor 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-Slugfor a multi-organization key, the samerest:apirate-limit bucket and request id. The globalx-api-keyrefusal is untouched; on the Anthropic path its 401 now says to useANTHROPIC_AUTH_TOKEN/authTokenand leaveANTHROPIC_API_KEYunset. 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 incode. 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.enabledinmodel-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/meanswerscapabilities.modelApi. Every request re-reads the policy strictly (unreadable → 503, never open), applies the model-access allow/block rules for the key holder (403MODEL_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 byprovisionSessionGatewayKey(fail-closed provider push,applyGatewayConfig, pricing overrides,mintVirtualKeybound 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 ofagent_serving.ts). Raw provider keys never leave the platform; the gateway port stays unpublished; no client header reaches the gateway exceptanthropic-version/anthropic-beta(Bifrost readsx-bf-*headers as instructions), and the gateway-only body fieldfallbacksis dropped. Answers namemodelas 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.
reserveTurnBudgetnow takes an explicitsubjectand amodel-apikind: 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 anapp.sandbox_session_opsrow (session_idmodel-api:<key id>, stamped with the person,__direct_api__and the key). A reached cap is the chat lane's coded 429BUDGET_EXCEEDEDwithRetry-After(andx-should-retry: false), in the wire's shape. After the answer ends, the sharedsettleGatewayKeyreads the key's spend from the gateway, books it intoapp.usage_ledgerunder 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 existingsandbox.gateway_key_reconcilejob 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 400MODEL_API_GUARDRAIL_BLOCKED(the chat turn's sentence), a mask rewrites the text the model receives, a fail-closed step failure answers 503MODEL_API_GUARDRAIL_UNAVAILABLE, and a PII policy in tokenize mode — which needs to restore data into the answer — is refused (403MODEL_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 undermodel-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-compatiblewith 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)
app.sandbox_session_ops(kindmodel-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.plugins/governancev1.6.14PostLLMHook). 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.budget-reservations.tsselectedNULLfor 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").web_search_optionsand non-function/customtools; 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.tale:models.apican 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.data:orhttps:URLs only;input_audiois refused;count_tokensand other Anthropic routes are not served (404 in the Anthropic shape); body cap 32 MiB (Anthropic's own request limit);createdis 0 in the model list.readEvent(the chat turn's SSE decoder) moved tocore/chat/stream_decode.tsso the relay reads usage with the same decoder without importing the chat host; the composer's listing walk is shared aslistGovernedChatModels.Checklist
bun run check— not fully green on this machine, for reasons outside this branch:format:checkand 53 of the 55 turbo tasks pass.@tale/sandbox-runtime-daemon#testfails 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 underservices/sandbox-runtime, and the daemon imports no workspace package, so its code is identical tomain.@tale/platform#test:uilost 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>).services/platform/messages/{en,de,fr}.yml; node-CHoverride needed (no ß/ss-sensitive wording).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 --noEmitandbunx oxlint --type-awareclean;bun run buildpasses (entry budget, service-worker manifest, boot shell).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.tsandv1-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 governanceroutes.test.ts(/my/model-api),budget-gate,budget-reservationsandturn-budgettests, 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 UImodel-access-editor,model-endpoints-section,use-api-settings-access,settings-railanduse-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) andcheck-guide.tsongovernance.mdandsettings.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:
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 withMODEL_API_VENDOR_TOOL_UNSUPPORTED.GOV-F38–GOV-F44,GOV-B14–GOV-B16,GOV-A6ingovernance.md;SET-F64–SET-F68,SET-B23–SET-B26,SET-A10insettings.md.Not verified
Nothing here ran against a live stack (Docker was down for this work), so none of the following is observed:
<record>/<model>on its/openai/v1/chat/completionsand/anthropic/v1/messagesdoors, its SSE framing per provider, and the usage figures it reports were read from the v1.6.11 source, not exercised.?beta=truequeries,anthropic-betaflags 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.backend:integration) was not run; the SQL is covered by unit tests with a fakesqlonly.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.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.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):MODEL_API_TEXT_TOO_LARGE), moderation calls are bounded, and a person or key has at most 8 requests in flight (429MODEL_API_CONCURRENCY_EXCEEDED).BUDGET_EXCEEDED, naming the binding cap and the affordablemax_tokens);nis capped at 8; media are counted by part type.(org_id, kind, started_at_ms)index.file_id,filesources), non-default service tiers, audio output andstore: 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).