Skip to content

Inference API (/v1)

The inference API is the public, OpenAI-compatible surface that applications call to run model requests through a gateway. Every inference path is served under /v1/. The gateway accepts the OpenAI chat completions request body for all providers and translates it to each provider's native wire format automatically.

Data-file preview bounding (request mutation). A user-message text block in the gateway's inline data-file format — first line exactly [File: <name>] where <name> ends in a spreadsheet extension (.xlsx, .xlsm, .csv, .tsv, .ods), followed by a blank line and the extracted text — is treated as a shrinkable preview, not as prose. Before dispatch the gateway MAY truncate such blocks (appending a visible notice inside the block): down to the routed model's context window when the request would otherwise be refused with context_overflow — for self-hosted models the preview budget is computed worst-case (digit characters count as one token each, since local tokenizers split digits individually) with the full potential output budget reserved, because those models share one window between input and output and enforce it with their own tokenizer — and down to a ~16 KiB head when the raw file is available to the code interpreter's staged-input channel for this conversation (the sandbox reads the full file; the preview is orientation only). Blocks in any other format, assistant/tool messages, and nested tool-result content are never touched. API clients that need their text verbatim must simply not use this exact block format.

Inline text attachment size. Text and source-code attachments (Markdown .md, HTML .html, plain text .txt, code) are inlined into the turn as ordinary message text. Accepted: an attachment of any size up to the upload limit. Truncated: the web app sends an over-512 KB text attachment through POST /chat/files, like the other inline-extracted formats; the server cuts the text at the 512 KB ceiling and reports truncated, and the app shows a notice under the reply that only the beginning of the file reaches the model. The attachment is not refused. Server-extracted text that is inlined via POST /chat/files (.docx, .doc legacy binary Word, .eml e-mail (headers, body and attachment list), .pdf, .pptx, image OCR, and a spreadsheet routed through the inline-extract path) is likewise truncated at the same 512 KB ceiling with a model-visible notice inside the text — not rejected. (A spreadsheet uploaded to the provider's Files API rides as a raw file_id, not inline text, so it is neither inlined nor truncated.) Note there is no dedicated server-side byte cap on inline text that arrives as plain message content (it is indistinguishable from a paste): the server's size backstop is the window-relative context gate, which now auto-compacts an over-window turn (summarizes older history, head+tail-clips the current message, and proceeds — see context_overflow) rather than refusing, so an oversized paste no longer dead-ends the turn (except when a self-serve workspace's prepaid wallet refuses the summary call: then the request answers the wallet's typed refusal, uncompacted); the context_overflow 413 fires only for a single message that alone exceeds the window even after clipping (and is skipped when the routed model has no known context window), plus the upstream provider's own limits. Direct API callers should size their own request bodies.

Inline binary (image / PDF) and total request-body size — client-side CDN guard. A vision-capable or PDF-capable (Anthropic) model receives images and PDFs as native inline base64 (image_url / a document block) carried in this request body, not via POST /chat/files. Because the whole request body — the base64 media plus the entire conversation history — travels to this inference host, which caps the /v1 request body at 10 MB (a larger body is refused with a JSON 413 payload_too_large carrying max_body, an X-AIG-Error and an X-Request-Id header, and the endpoint's CORS headers; a body whose declared size is over 11 MB is refused one hop earlier by the ingress, with the same JSON shape but no CORS headers, which a browser's fetch sees as an opaque network error — see Request body size limits), the web app enforces two client-side guards before sending: (1) a per-attachment limit of about 7.4 MB of raw file bytes (~10 MB base64, conservatively under the 10 MB /v1 limit) — an oversized inline image is first downscaled + re-encoded in the browser to fit this budget (the pinned vision models accept far higher resolution than the edge allows — measured HTTP 200 up to 9.4 MP, with the edge, not the model, being the binding limit — so a fitted image is equivalent), and only a non-image or an image that still cannot fit is rejected with a specific "…is too large to upload (max ~7.4 MB)…" message; (2) an assembled-body preflight — if the fully-serialized request body (media and history) would exceed that budget, the web app first replaces the oldest inline images and PDFs of earlier messages with a short text placeholder (the current message is never changed), and only if the body is still over the budget is the send refused with a "This message is too large to send… remove or shorten large attachments, or start a new conversation." message. Both turn the CORS-blinded 413 dead end ("the gateway is unreachable, keep retrying") into an actionable message. These are UX guards, not part of the endpoint contract; direct API callers are not bound by these browser guards, but a body above the 10 MB limit is still refused with 413 payload_too_large (and, independently of bytes, an input over the model's context window with context_overflow). The admin POST /chat/files upload path is a separate host with its own, larger cap (140 MB edge → a ~110 MB client guard), so a large document uploaded for extraction is bounded independently from an inline attachment — see Client-side upload size limit in the Conversations reference.

Base URL: https://<your-gateway-host>


Endpoint paths

Every inference request follows the same four-segment shape:

POST /v1/{tenant}/{gateway}/{provider}/chat/completions
Segment Meaning
{tenant} Tenant slug, spelled exactly as stored.
{gateway} Gateway slug within the tenant, spelled exactly as stored.
{provider} A registered provider name, or the pseudo-provider compat.

Slugs match the stored spelling byte for byte. A different case (ACME), an accented or padded form (acme%20) is not an alias: the request is answered 404 tenant_not_found, before authentication. A slug longer than 255 bytes is refused the same way.

The {provider} segment selects how the request is routed:

  • Pinned provider — naming a real provider (for example openai, anthropic) and ending the path with /chat/completions pins that exact provider with no model-name guessing.
  • Compat (unified) — compat is a pseudo-provider; the gateway guesses the provider from the request body's model field and always returns an OpenAI-shaped response.
POST /v1/{tenant}/{gateway}/compat/chat/completions

For the full list of supported providers, the compat model-resolution tiers, and the native endpoint table, see Providers overview.

Base URL for OpenAI-compatible clients

Tools that speak the OpenAI API (SDKs, SIEM and monitoring integrations, chat front-ends) usually ask for a base URL and append /chat/completions themselves. Give them the gateway-specific base URL, not the bare host:

https://<your-gateway-host>/v1/{tenant}/{gateway}/compat

This is the Endpoint URL shown on the gateway page in the admin console, with compat selected, without the trailing /chat/completions. Two wrong base URLs are refused with 400 invalid_request before authentication, and both messages name this fix:

  • https://<host>/v1 (the generic form other providers document): the client sends /v1/chat/completions, which has one or two segments after /v1/ instead of three. The message is fixed text and the request path is not echoed back:

    URI must be /v1/{tenant}/{gateway}/{provider}/... - a tenant, gateway or provider segment is
    missing. For an OpenAI-compatible client, set the base URL to
    https://<gateway-host>/v1/{tenant}/{gateway}/compat (the endpoint URL on the gateway page in the
    admin console with compat selected, without the trailing /chat/completions).
    
  • https://<host>/v1/{tenant}/{gateway} (missing /compat): the client sends /v1/{tenant}/{gateway}/chat/completions, so chat is read as the provider. The message is Unknown provider: chat. followed by the same base-URL sentence.

A path that does not start with /v1/, and /v1/ with nothing after it, are refused with 400 invalid_request (URI must start with /v1/).

Model list: the gateway does not answer GET …/models on the inference lane. The path passes the endpoint allowlist below, but a request without a body is then refused with 400 invalid_request (Empty request body). Enter the model id in the client by hand (for example qwen3.8-27b) instead of relying on a model-list lookup.

Anthropic-native passthrough

Provider paths that do not end in /chat/completions are forwarded to the upstream provider in its native wire format. The supported case is the Anthropic Messages API, used by Anthropic-native clients such as Claude Code:

POST /v1/{tenant}/{gateway}/anthropic/v1/messages

💡 Note: On the native passthrough path the request and response bodies are the provider's own format, not the OpenAI chat-completions shape. Use the /chat/completions suffix whenever you want the OpenAI-compatible translation.

💡 Note: Anthropic's Messages API rejects unknown top-level fields. An OpenAI-style reasoning_effort on the native route is dropped by the gateway and the request is re-sent once (see Unsupported-parameter strip-on-400). To control reasoning on this route use thinking / output_config.effort. A sampling parameter the model has deprecated (temperature, top_p, top_k — e.g. `temperature` is deprecated for this model. on claude-sonnet-5-5) is dropped and the request re-sent in the same way, even when it follows the reasoning_effort strip (see Deprecated sampling parameters, and chained recoveries).

💡 Note: A streamed request that belongs to a conversation turn (it carries x-aig-conv-id and x-aig-turn-id) is settled when the stream ends. This applies to every native passthrough route, that is any provider path that does not end in /chat/completions. If your client stays connected to the end, the gateway stores nothing for that turn (your client keeps its own copy) and the turn is closed at once, so the next turn on the conversation is accepted and not refused with 409 turn_in_progress. If your client disconnects, the gateway keeps what it had already relayed. A disconnect mid-stream stores the partial answer marked as stopped (stop_reason client_gone when the conversation is read), and a disconnect after the final message_stop event stores the full answer. A disconnect after usage was billed but before any text arrived stores a short "Stopped before an answer was produced." note. A disconnect with nothing relayed and nothing billed stores nothing. In every case the turn is no longer reported as running and a follow-up turn is not refused with 409 turn_in_progress.

Only servable endpoints are accepted

The entire provider path is validated against a fixed allowlist of servable endpoints before the request is authenticated. Any other path is rejected with 404 endpoint_not_found — the request never reaches the provider and nothing is dialed upstream. The accepted paths (an optional /v1 version segment is allowed on each) are:

Path Endpoint
/chat/completions OpenAI chat completions
/completions OpenAI legacy (text) completions
/embeddings OpenAI embeddings
/v1/messages Anthropic Messages
/v1/messages/count_tokens Anthropic token counting
/v1/models list models (read-only OpenAI-SDK helper)

On a streamed legacy /completions request the answer text travels in choices[0].text (there is no delta). The gateway counts that text as delivered, so a stream that is cut, or that ends without a finish reason, is billed from its estimate rather than as zero output tokens. The streamed text must be a string: an absent or null value means no text, and any other type (an array included) is dropped, logged once per stream and never billed. This is stricter than a non-streamed legacy body, which also accepts an array of text parts. The bytes relayed to you are the provider's own.

POST /v1/{tenant}/{gateway}/{provider}/v1/anything-else         → 404 endpoint_not_found
POST /v1/{tenant}/{gateway}/{provider}/internal/x/embeddings    → 404 endpoint_not_found

The match is on the whole path, not a trailing suffix: a path such as /internal-admin/embeddings that merely ends in a servable name is rejected — an attacker must not be able to smuggle an arbitrary upstream path in front of a known endpoint. A missing path (a bare …/{provider} URL) and a bare /v1 are rejected with 404 endpoint_not_found — append an explicit endpoint such as /chat/completions. An absent path fails closed exactly like a present, unrecognised one: the two share the reject outcome, never a permissive dial (before, an absent path was forwarded to the provider's bare base URL and 502'd for every path-forwarding provider). Providers that build their endpoint from the model rather than the path — Gemini, Bedrock, Cohere, Vertex, Azure — previously tolerated a bare URL; they now require an explicit endpoint too, for one uniform rule. This is an authorization boundary, not a convenience check: every real provider forwards the path verbatim into its upstream URL, and the platform-managed myra provider attaches Myra's platform credential, so an unvalidated path would be a server-side request forgery. The allowlist is exactly the set of priced/known endpoints, so no accepted request escapes usage metering.

💡 Note (model-list probes). …/models passes this allowlist on both the explicit-provider path (/v1/{tenant}/{gateway}/{provider}/v1/models) and /compat (…/{gateway}/compat/models), so it is not refused as an unknown endpoint. The gateway does not answer it with a model list, though: a GET without a body is refused with 400 invalid_request (Empty request body). See Base URL for OpenAI-compatible clients.

The Messages API is not available under /compat

The /compat surface speaks the OpenAI schema in both directions — requests are read as OpenAI chat-completions and responses are always OpenAI-shaped. An Anthropic Messages request sent to a compat sub-path is therefore rejected with invalid_request (400) rather than partially processed:

POST /v1/{tenant}/{gateway}/compat/v1/messages        → 400 invalid_request

The same rejection applies to /compat/…/v1/messages/count_tokens. Use the native route for an Anthropic-native client, which is where the Messages wire format is actually served:

POST /v1/{tenant}/{gateway}/anthropic/v1/messages     → Messages in, Messages out

This also rejects the common SDK misconfiguration of appending /v1/messages to a base URL that already ends in /compat/chat/completions.

Error shape on the native Messages route

Refusals the gateway authors on /v1/messages and /v1/messages/count_tokens (bad token, duplicate key, body too complex, body too large (413), unknown model, quota, no provider available, gateway not ready) use the Anthropic error envelope, {"type":"error","error":{"type":…,"message":…,"code":…}}, with the gateway code in error.code; the HTTP status and X-AIG-Error do not change. See Error codes.

Held-back streams on the native Messages route

When a gateway holds a stream: true answer back for inspection (a response guardrail that has to see the whole answer, such as a block, scrub or flag rule), the gateway keeps the connection alive with SSE comment lines (: hb) at least every 16 s while the provider works, then sends the Anthropic events (message_start … message_stop) once the answer is released. Anthropic SDKs ignore the comment lines. Because the first comment commits the response to 200:

  • an error after that point arrives as one in-stream event: error frame in the Anthropic envelope ({"type":"error","error":{"type":…,"message":…}}), whose type follows the HTTP status of the failure (429 is rate_limit_error, 503 and 529 are overloaded_error, 504 is timeout_error, any other server error is api_error), never the type string of the provider's own answer; a response blocked by a guardrail is an invalid_request_error, and a provider answer the gateway cannot read is an api_error. SDKs raise their API error from that frame;
  • an error before the first comment is an ordinary HTTP error with its normal status;
  • response headers that are only known at the end of the request (for example cost headers) are absent once the response has started;
  • a connection cut during a long stream cannot be resumed; send the request again.

Usage metering on the native Messages route

/v1/messages is the Anthropic Messages endpoint, and the gateway meters it as such whichever provider serves it. A provider whose upstream forwards the native path — the self-hosted myra fleet (served by LiteLLM) is the practical case — relays the Anthropic response verbatim to the client. The gateway selects its usage reader by the endpoint it actually dialed and confirms it against the response's own envelope (a message_start or error frame on a stream, a type: "message" object on a stream: false turn); an upstream that answers that path in another dialect keeps that provider's own reader. On a confirmed Anthropic response the recorded leg carries:

  • input_tokens / output_tokens from message_start and message_delta (or the Messages object's usage), plus the cache_creation (5m / 1h) and cache_read buckets — the same counters a Claude-served turn on this route records, read with the same rules, so spend accrual against the gateway/tenant budget and cap enforcement follow the same path. Prefix-cache parity with /chat/completions: a prefix-cached prompt is booked as input = prompt − cached, cache_read = cached on both routes. On /v1/messages the relaying LiteLLM adapter nets the cached share out of input_tokens and surfaces it as cache_read_input_tokens, which this reader books as cache_read. On /chat/completions the gateway reads the OpenAI-compat usage.prompt_tokens_details.cached_tokens (a subset of prompt_tokens) and performs the same split itself (cached_tokens is netted out of input and booked as cache_read). So the same prefix-cached prompt books the same buckets on either route. Two contingencies, both fleet-side (not the gateway): the self-hosted fleet only reports a cached share at all when vLLM prefix-token-details reporting is enabled, and /v1/messages parity additionally requires the fleet's LiteLLM to map cached_tokens → cache_read_input_tokens (a stock adapter nets the share out but drops it, leaving cache_read = 0 on that route). When no cached share is reported, both routes book input = prompt, cache_read = 0. Pricing note: a model with no configured cache_read_per_1k bills the cache_read bucket at the input rate (an explicit 0 means free), so splitting the bucket never turns cached tokens free by default;
  • request_log.model_version = the served model the response announced;
  • on a gateway with payload logging and PII masking, the audit response_raw of the streamed answer.

The relayed bytes are never altered by this accounting. Two related rules on this route:

  • /v1/messages/count_tokens ({"input_tokens": N}, no content — a success by spec) is recognised by the dialed endpoint on every provider whose upstream endpoint carries the path, so it is never filed as an empty answer.
  • The gateway's server-side tool loop on the native Messages route runs only where the provider can read the Anthropic dialect it serves: anthropic itself, or a routed provider that dials its own endpoint. A provider that forwards the path to an upstream answering in the Anthropic dialect through an OpenAI-compatible reader (myra, groq, together, …) gets a transparent passthrough instead: gateway tools are not injected, and a request carrying MCP connector references is rejected with invalid_request (400) naming the reason. The rule is decided by the request's primary provider; a fallback provider in the routing chain that would relay the dialect is skipped at dispatch on a tool-loop turn (the primary keeps its tools), never folded with the wrong reader.
  • Gateway server-side tools run on the native Messages route only when the turn is buffered: "stream": false, or a "stream": true turn the gateway buffers for a response-phase guardrail and re-emits as Anthropic SSE. A plain "stream": true (the JSON boolean true; any other value does not count) is a transparent passthrough with no gateway tool offered and none promised in the system prompt; the tools you send yourself are forwarded untouched, and MCP connector references are rejected with invalid_request (400). The provider's own server-side web search, when you have opted in with the X-AIG-Web-Search header, is unaffected: it is still added under its usual conditions (a model that supports it, no sovereignty restriction, not for Claude Code clients). For streamed gateway tools use the OpenAI-compatible route.
  • The gateway's own inner legs — the tool loop's compaction summary (the max_rounds_reached summarize-and-continue step) and the fetch-and-read helper the agentic fetch tool runs — are OpenAI-shaped stream: false chat completions whatever the parent turn's wire was. They never dial a parent's native /v1/messages path: on a path-forwarding provider that path is dropped for the inner leg in favour of the provider's canonical chat endpoint (e.g. a native-Messages parent on anthropic, cohere, gemini or bedrock whose agentic fetch runs on the myra default model), while a parent that is already on a chat-completions path keeps it (the inner leg dials exactly the parent's endpoint). The parent's path is restored once the inner leg returns, on every exit. When Myra's spend or wallet check refuses that inner leg (wallet empty or frozen, spend limit, balance could not be verified), the fetch is not run, the model is told why in plain words, and the turn's further paid model calls are refused with the same reason. An inner leg is built from a clean request. None of the client's feature headers reach it: x-aig-web-search (native web search), x-aig-skill (skill container), x-aig-thinking-budget, anthropic-beta, and the x-aig-provider-* overrides. Two exceptions apply when the inner leg dials with the parent's own key. It keeps x-aig-provider-openai-organization / -openai-project, so the call is billed to the organization the client chose. The compaction summary (not the fetch read, which is capped far below any window and may run on another model) also keeps a context-window anthropic-beta token (context-1m-…), so a summary of a 1M-context conversation still fits the window. Neither turns on a feature. So a summary or a fetched-page read never runs native search, a skill container or extended thinking just because the client turn asked for them. Its reply is read with the dialled provider's own reader (the same one the main path uses), so any provider can serve it — for example a Gemini or Cohere agentic_fetch.model, or a compaction on a Gemini turn. A 200 reply that cannot be read fails that inner leg (… response could not be read); the reader's error, which can be the provider's own error text, is logged (redacted) and not passed on. An error status keeps its existing detail (… upstream <status>: <first 200 bytes>). These inner legs are billed like any model call: each is its own leg in the request log (kind compaction or agentic_fetch_inner), its cost is part of the request's cost (the X-AIG-Cost-Micros / X-AIG-LLM-Cost headers, the budgets, the usage views), and on a self-serve workspace past its allowance it first reserves its full cost from the prepaid wallet — an inner leg is never shortened: it runs whole or is refused (see Budgets — Wallet).
  • Thinking escalation for Myra Qwen (web app and agents only). On the Myra fleet, a qwen3* turn that runs with thinking off starts that way and stays that way while it makes progress. Only when the turn is stuck does the gateway switch the rest of the turn to thinking on, once and for good: the same call recurred twice (reason a), or the same tool failed with the same gateway-side error twice (reason f; the third identical failure ends the loop instead). Neither the number of tool rounds nor the number of code_interpreter calls triggers it. From the next model call on, enable_thinking is true and the vendor thinking sampling applies (temperature 1.0, top_p 0.95, top_k 20, min_p 0, presence_penalty 0; a value the request set itself is kept). This replaces the 0.3 code_interpreter temperature for those calls. The closing no-tools answer call and the gateway's own inner legs (compaction summary, page read) stay thinking-off. Escalation applies only to the Chat (web app) and to agent invocations, never to API tokens, whose requests are untouched, and only when the thinking flag is off or absent and the output limit is absent or at least 4096 tokens. It is announced by one thinking_escalated aig_status frame (reason a, f or i, plus round) to clients that opted into the aig_* frames (x-aig-extensions: 1); buffered and agent invocations carry no frame, but the trace records a thinking_escalated step. A third trigger, i, applies from the first call: the conversation already holds a generated image and generate_image is offered on this call (an image edit follow-up), so a request that sent enable_thinking: false is switched to thinking on. An explicit enable_thinking: true needs no switch. A tool_choice of "none", or one that forces a different tool, keeps trigger i off. For trigger i the thinking_escalated frame (reason i, round 0) arrives with the first streamed frame, on the call that opened the answer and only when that call ran with thinking; it is not sent when that call's output limit is below 4096 or the turn failed over to another provider. On a guardrail- or PII-buffered Chat turn the frames of every trigger (a, f, i) are replayed once with the buffered reply. The output-limit floor is also checked on every model call after the switch, against the limit that call is actually sent with: a call whose limit is absent or below 4096 (for example one the gateway shrank to fit the context window) keeps thinking off and the 0.3 temperature, so reasoning cannot use up the whole budget and leave an empty answer. The same hold applies to the thinking the client itself asked for: on a web-app (Chat) turn on a Qwen model, a client chat_template_kwargs.enable_thinking: true is sent as false on the call right after an output-limit cut (a cut tool call, or a text answer that was cut and is continued) and the 0.3 temperature rule of the code interpreter still applies; the next call uses the client's value again. Other fields of chat_template_kwargs are kept. A request with a malformed chat_template_kwargs is never repaired by this. API-token requests are never changed. Because the hold now states the flag explicitly, a web-app turn or an agent run that did not send enable_thinking at all also gets enable_thinking: false on that held call (an agent run's own explicit true is kept). Recovery from a reasoning-only cut. When a Qwen model on the Myra fleet is cut by the output limit after reasoning but before any visible text, the gateway re-sends the same request once, with no extra message, with thinking off, instead of ending the turn with the "internal reasoning but no visible answer" notice. This applies to web-app turns and agent tool-loop runs only, at most once per turn (a second such cut ends the turn as before), and never to API-token requests, which are never reshaped. A cut caused by the time limit of a runaway generation is not retried. Two further holds apply to every trigger (a, f and i), per model call and never permanently: the call right after a round in which a tool call was cut by the output limit, or the automatic continuation of a text answer that was cut, and any later call of the tool loop made with less than 120 seconds left of the remaining time budget of the tool loop (or of a delegated agent run, when that is tighter), run with thinking off and the 0.3 temperature. The first call of a turn is never held for time. The next call that is neither of those thinks again. For triggers a and f the thinking_escalated frame (and trace step) is sent when the escalation latches: it marks the decision to switch, and a held call that follows still runs without thinking. When the stuck signal appears with less than 120 seconds left, the gateway does not switch at all: nothing is latched and no note is sent, because no later call could think; the request trace records a thinking_escalation_refused step (reason, round, remaining milliseconds). The step is recorded for each stuck round whose switch is refused, so a turn that stays stuck with little time left can show several. Exactly 120 seconds left is not "less than" and still switches. Separately, on a Chat (web app) turn that runs with thinking off, the one model call that follows the first tool round with a successful code_interpreter run (exit code 0, not timed out, non-empty stdout, output not withheld by a refused output cut) runs with thinking on and the thinking sampling, so the model reads its own program output before it answers. It happens once per turn and does not latch: retries, automatic continuations and every later call run as before. It is skipped with less than 120 seconds left of the remaining time budget (recorded as a thinking_after_code_refused trace step) and never applies to API-token requests or to a request that already thinks.
  • A tool loop that the gateway has to stop never dead-ends the turn with a bare note. Before giving up it makes ONE final no-tools model call (tool calling disabled) and delivers that answer as normal assistant content, followed by an honest note:

    • repeated_tool_call (a tool kept returning the same or an empty result and the model re-issued an identical call; or the same tool returned the identical gateway failure sentinel - a per-turn cap refusal such as web_search after its 8-per-turn limit or fetch_url after the fetch limit, a tool-not-available steer, a result withheld by a guardrail, an egress or PII block ([blocked: ...]), or a human reviewer's denial ([denied]) repeated identically - in 3 rounds in which that tool was called, in a row, without an intervening usable result from it, even though the model changed the arguments each time; rounds in which the tool is not called do not reset the count) → for the same-failure stop details.mode is same_failure, details.tool names the tool (the sanitized name; absent when nothing survives sanitizing) and details.count is the number of rounds, not calls; details.mode is cumulative when the identical call recurred 4 times in the turn; details.mode is absent for the N-consecutive-identical-rounds stop, which carries details.fingerprint. details.mode is length_cut when a call of the same tool was cut off at the output-token limit in 2 rounds of the turn (see "Undecodable tool input"); that stop makes no final model call, because the cut call was the answer. A round in which that tool also returned a usable result restarts the same-failure count. same_failure counts only results tagged [error] / [elided] / [tool result withheld / [denied] / [blocked:; untagged prose refusals are bounded by the round cap. A tool that reports a typed failure code (today edit_office_file) is counted by (tool, code), not by result text: edits that differ each time but fail with the same code (edit_failed, not_found, busy, unavailable, file_limit, invalid_arguments, and the office-run codes - every code counts) stop after 3 such rounds. A result of that tool that is not a failure (a read, an applied edit) restarts the count. After the 2nd such round the result carries one gateway note ([gateway note: the same edit_office_file failure repeated ...]) telling the model to change the approach or answer; it is added at most once per tool per round and never when the loop stops in that round. The word "error" in a document never makes a successful read count as a failure, and text never creates or resets a failure code. A malformed code from the tool counts as a failure (as malformed_code), never as success. A call the gateway answered without running it (deferred, duplicate) neither restarts nor advances the count. When the turn already gathered usable tool results (for example searches before the search limit) the model answers from those results and its own knowledge, the note says so and the tool_loop_terminated event's details carry used_results: true (only when that answer was delivered); otherwise it answers from its own knowledge, with a note saying that. It does not tell the user to rephrase. When the stop is declined, the note names the stopped tool(s) (up to three, details.tools) so the user can see which one failed, and says the problem is with the tool, not the request.
    • tools_exhausted (every tool offered to the model was taken away for the rest of the reply by a per-reply cap or a fixed refusal, for example the only tool search_knowledge or web_search reached its per-turn cap; an empty tool list is invalid, so the tool cannot simply be removed from a request that offers only it): the turn ends in that round with ONE final model call that has tools disabled and is told, neutrally, that the tools are no longer available and to answer from the results gathered, saying plainly what could not be looked up. When that answer is delivered it is a normal reply with no stop note; the tool_loop_terminated event still reports reason: "tools_exhausted" with details.synthesized: true and carries neither can_continue nor round_limit, and no model-error record is written. When it cannot be produced the reply ends with a short note that the tools were no longer available and the event reports details.synthesized: false. On a documentation-only (knowledge-only) agent that undelivered case shows the one grounded "could not finish an answer from the documentation" note instead. The media tools (generate_image, create_video, remove_background) do not take part: their withdrawal never ends a turn. The guard ranks last: any other stop reason wins, and it is judged on the tools actually offered when the round ends.
    • max_rounds_reached (the 25-round per-turn tool-call cap) → the gateway first tries one conversation compaction (summarize_and_continue); when that cannot finish the task it delivers a best-effort answer and emits the typed tool_loop_terminated event with can_continue: true (to a streaming caller that opted into the side channel), and the note is actionable ("Ask me to continue …") on an interactive run; an unattended agent run (see Round limit stop note) gets a note that promises no follow-up, while can_continue stays true. The SPA turns can_continue into a one-click Continue affordance that resumes the same task in a fresh turn; the per-turn 25-round ceiling is unchanged and the fallback adds at most one bounded model call per turn. On an interactive run the tool_loop_terminated event also carries round_limit: true (absent otherwise, and never on an unattended agent run); the SPA latches it so the reply records the round-limit fact in the ghost header (below). The loop-termination notes the gateway appends (round limit, and the other stop notes it writes itself) are display text: when a conversation is replayed to the model, a note that is the exact, final suffix of an assistant message in the gateway's own wording (English or German) is removed from that message, so the model does not imitate it. Only that exact suffix is removed: a note quoted mid-text, a tool-result note, other gateway text (interrupted or provider-failure notes, guardrail text, the file heading) and a copy the user edited stay verbatim. A reply that ended at the round limit instead reaches the model as one short fact, so it can still offer to continue.
    • agent_spend_cap_reached (the agent's monthly spending limit was reached by this turn's own cost) ends the turn at once between tool rounds with a localized (en/de) note and the typed tool_loop_terminated event. It is the owner's configured limit working, not a fault: no synthesis call, no conversation compaction, no can_continue (Continue is not offered, a new turn is refused until the month rolls over or the limit is raised) and no model_error fault record. The note carries no top-up wording.
    • wall_clock_exceeded keeps its existing partial-synthesis behaviour. The tool loop's wall budget has ONE reference: the start of the request. The first model leg counts against it, and the round-limit compaction does not restart it. Every synthesis path fails closed: if the extra call errors or produces nothing, the turn ends on the honest stop note rather than a fabricated answer.
    • The instruction for the final no-tools call says explicitly that no tool may be called and that the answer is to be written as plain text. tool_choice: "none" alone was not enough: a Myra-hosted Qwen model answered it with another tool call, which produced no visible text.
    • A closing call that answers with a tool call anyway. A model can ignore the no-tools instruction and emit a tool call. The gateway never executes it. If the call produced no usable text, or only narration beside the call, the gateway makes ONE recovery call (so at most two no-tools calls per turn). The recovery call carries no tool definitions at all: the request's system message(s) stay as they are, and ONE user message carries the conversation so far as a plain-text transcript (text only; tool exchanges are omitted and an image becomes "[image omitted]" and an attachment "[attachment omitted]"; only the most recent part of a very long conversation is kept), the results gathered in this turn as text, and the instruction to answer from them. The call therefore alternates strictly (system, user) for every provider. It never makes a third call, and fails closed to the honest stop note like the first call. A provider event: error that ends a closing call is not announced when it happens: the error frame and the aig_status: "provider_error" banner are held back until the turn ends, and are written only if the last call still failed. If the recovery call answers, the client sees that answer and no error at all (live, on reload and on stream: false alike); if it fails too, the failure is written exactly once. Text the first call already streamed is not retracted. Both calls share the one 60-second bound below, and the recovery call is skipped when too little of it is left or the recovery request would not fit the model's context window.
    • No server-side tools on closing calls. Both closing calls leave server-side tools off: skills and web search, including a provider search the client itself requested (an OpenRouter web plugin or :online model suffix, OpenAI web_search_options, Gemini search grounding).
    • The final no-tools call may write up to 4096 output tokens and runs under a 60-second time bound (an answer still being written at 60 seconds keeps what it wrote), so it never extends the turn by more than that. It keeps reasoning to a minimum so its output allowance goes to the answer:

      • On Anthropic models the client's thinking settings are ignored for this call (the x-aig-thinking-budget header, and on the native route the request's own thinking / output_config.effort). Thinking is switched off where the model allows it.
      • A model that always reasons (for example claude-opus-5-5) runs at its lowest thinking setting (low effort), with the same 4096 output tokens. A smaller limit the client set is kept.
      • On the Myra fleet, or when the request carries chat_template_kwargs, enable_thinking is set to false.
      • OpenAI-style reasoning models (o-series) keep their reasoning effort (the client's, or the model's default) and can still end this call with nothing visible.

      If the call still ends with nothing visible, the turn ends on the honest stop note; the "no visible answer" apology is not shown for this call. When the model used up the gateway's own limit, that empty call is recorded as a gateway fault (pattern …@synthesis_cap), not as a fault of the model provider.

    • Exception — the prepaid wallet refuses the call. On a self-serve workspace past its allowance, when the wallet refuses one of these extra calls (the compaction, the follow-up call after it, or the no-tools answer) — or an earlier compaction / agentic-fetch inner call of the same turn was already refused — the turn ends on the typed refusal instead: wallet_insufficient (paid plan), trial_budget_exhausted (free trial), quota_exceeded (wallet top-up not offered), wallet_funds_reserved (other running requests hold the balance) or spend_unverified (a request the wallet carried whose reservation could not be placed): the provider-error frames with that code, then the stop terminator, persisted as the message's failure class. There is no stop note, no tool_loop_terminated event and no Continue (it would only be refused again). Try again is offered only for wallet_funds_reserved and spend_unverified. The same applies when the wallet refuses an automatic continuation of a length-capped answer.

    • On a stream, the final message_delta usage snapshot is cumulative and authoritative: a positive input_tokens / cache figure there supersedes the message_start snapshot (on an Anthropic server-tool turn the cumulative input is the billed one); a zero or absent figure never overwrites a value message_start already reported. Usage values are untrusted provider output: a numeric string is coerced, and a non-finite, negative or non-numeric value reads as "not reported".

Accepted compat sub-paths. /compat/chat/completions (and its /compat/v1/chat/completions spelling) for chat, plus the non-chat OpenAI endpoints such as /compat/embeddings, which are forwarded to the provider's corresponding OpenAI endpoint. /compat/models passes the endpoint allowlist but is not answered with a model list (a GET without a body is refused with 400 invalid_request). The Anthropic token-counting endpoint (/v1/messages/count_tokens) is a separate, non-streaming endpoint and is unaffected by the rejection above.

⚠️ Response-phase guardrails on a native stream: true request. When the gateway has a response-stage detector that cannot be applied incrementally — a content-safety block, a regex/presidio scrub, or a flag (i.e. anything other than the inline PII token-restore performed by pii_protector / custom_pii) — a native stream: true request is internally buffered: the gateway collects the full upstream answer, runs the detector, and then re-emits it as native Anthropic SSE events (message_start → content_block_* → message_delta → message_stop; no OpenAI [DONE]). The first byte therefore arrives only after the full generation completes (bounded by timeout_ms), exactly as for a native stream: false request — the latency cost of response-stage scanning. A gateway whose only response detector is an inline PII masker keeps streaming incrementally. A response-stage block on a native stream is delivered as an HTTP 400 guardrail_blocked error (the answer is never sent). SSE clients that enforce a short inter-event idle timeout should allow for this buffered window.

⚠️ Mid-stream provider failures on a buffered turn. When a PII-masking or guardrail configuration forces a stream: true turn onto the internally buffered path (or a stream: false tool-loop turn runs buffered by nature) and the upstream provider's stream fails mid-generation — a mid-stream error event such as Anthropic overloaded_error, an OpenAI-shaped data: {"error":{"message":…,"type":…,"code":…}} frame (any non-null error value counts as an error frame and fails closed; error: null is ignored; the provider's message and type are kept, code supplies the status only when it is a number that is 429 or 5xx), a read error, or a truncated stream — the gateway never answers with a clean HTTP 200 carrying an empty message. Instead it: (1) retries the attempt transparently (same provider, then the fallback chain) when nothing was delivered and no server-side tool has executed; (2) fails loud with the typed provider_error / all_providers_failed error (as an error frame + aig_status: "provider_error" event on an already-open SSE stream) when retries are exhausted or unsafe; or (3) salvages a partial — any text, files, or images the turn already produced are delivered and persisted together with the explicit error surface (on a streamed or app chat turn; a stream: false API request never salvages a partial, see below), which is the same one the live streaming wire carries for that failure kind: a provider error event (provider_error) is the error frame plus the aig_status: "provider_error" banner event; a read error or a truncated stream (stream_errored / truncated) is the single terminator error frame (provider_error "connection failed" / stream_truncated), no banner, and the visible answer ends with the persisted "The response was interrupted before it completed. Please try again." note described under Visible truncation note — so the salvaged turn reloads exactly as it rendered live. (A leg that reached a natural end and then hit a read error keeps the frame and gets no note — the answer is complete.) A closing (synthesis) leg that is cut (a truncated stream or a read error, with or without text) is judged the same on every egress (a partial cut stays the delivered answer; only a blank one is recovery-eligible): its interrupted note and its error frame are withheld until the tool loop ends, and are written only if no recovery leg then produced an answer. When the recovery leg answers, the wire carries just that answer (no note, no frame); when it is cut too, the wire carries [note][footer][error frame][stop] once, and the turn persists as a failure row. A plain stream: false API request does not get a partial: when the upstream stops mid-answer, the response is the typed error itself (HTTP 502 provider_error, or the typed code with its own status), never an HTTP 200 carrying cut-off content. The gateway does not retry after part of the answer was produced, and any file the turn had already written stays in the conversation. The interrupted note is written in the language of the request (German or English; otherwise the account's UI language, else English), by the same rule as the tool-loop note.

⚠️ The model call after a tool result fails. In a server-side tool loop the gateway calls the model again after each tool ran, carrying the tool result. If that call itself fails — a timeout before the first byte, a dropped connection, or an HTTP error from the provider — the turn is never ended as an empty success.

One automatic re-dial first. When the call fails transiently before any byte of the answer — a dropped or reset connection, a read / first-byte timeout, a connect error, HTTP 500 / 502 / 503 / 504 / 529, or an HTTP 429 whose Retry-After / retry-after-ms / x-ratelimit-reset-after-ms hint is at most 10 s (grammar: see Error codes) — the gateway re-sends the same request once per request, after a short backoff (or the hint). The tool results are reused: no tool runs again. This floor of one re-dial applies regardless of the gateway's retry_count (like the transient retry floor of the Myra-hosted leg). It is never done for any other 4xx, a context overflow, or a gateway policy refusal, and it is skipped when the model's circuit breaker is open, when the user stopped, or when the remaining tool-loop time budget (900 s (15 min) for a streamed turn, also while the answer is held back for inspection or web search; 360 s when the client receives nothing until the end (stream: false, or a held stream on a provider route other than /anthropic/v1/messages, which gets no keep-alive; a chat bridge turn is the exception and gets 900 s); 900 s unattended; measured from the start of the request) cannot fit the wait plus a 20 s first-byte window; the re-dial's own read deadline is capped at what is left. A recovered re-dial is invisible on the wire — the client receives exactly what a first-try success sends. The request log records it as meta.post_tool_leg_retry: {cause, outcome} with outcome = recovered, failed or skipped:<reason>; a model-error triage row is written only when the turn still fails (one row) — except for provider_key_rejected (below), which never writes one.

First-byte budget for local (Myra) models. On the model call after a tool round (and on continuation legs and a resumed regenerate) a Myra-hosted model gets a first-byte (prefill) deadline sized to the prompt: below 50 000 estimated prompt tokens it ramps linearly from 20 s at 0 tokens to 180 s at 50 000 (e.g. ~52 s at 10 000, ~119 s at 31 000); from 50 000 tokens it stays 180 s. It is bounded by the remaining tool-loop time budget and never below 20 s. It governs the first byte only — the gap between chunks of a streaming answer keeps its normal 300 s limit — and a routing rule's timeout_ms still overrides it. The ramp is sized from production time-to-first-token data (qwen3.8-27b p99 under 6 s up to 60 000 tokens; gemma-4-31b-it up to ~85 s at 40 000–60 000 tokens).

When the call (and its re-dial, if any) still fails, the failure is typed with one of these codes: request_timeout when the provider did not start answering in time, model_capability_mismatch when the tool result carries a document the selected model cannot read (switch model — the same request will not succeed on this one), provider_key_rejected when the provider rejects the customer's own provider key on that call (HTTP 401, or a 403 authentication refusal; when the first failure was transient and the one re-dial then answers 401/403, the re-dial's own response decides), the gateway policy code when the gateway itself refuses the call for a policy reason (below), and provider_error for everything else (a dropped connection, any HTTP 4xx/5xx — a 429 included — a platform (Myra) key's rejection included, or a context overflow the gateway could not recover from). The provider's own error text is never relayed.

A rejected own key is typed. provider_key_rejected names the provider: HTTP 424 for stream: false and the native route (with X-AIG-Provider on the buffered 424); on an open stream the error frame and the aig_status event carry error_class: "provider_key_rejected" and provider. The rejected own key is never re-dialled, the code is not retryable (no Try again in the web chat) and it writes no model-error triage row.

Policy refusals keep their own code. When the gateway refuses the post-tool call for a policy reason, the turn ends with that policy's code — data_residency_blocked (403), provider_not_allowed (403), provider_objected (403), configuration_error (500), model_not_found (a deprecated or unpriced model), model_disabled_on_gateway (403) or role_model_not_allowed (403) — instead of a retryable provider_error. These are non-retryable (no Try again) and write no model-error triage row. An observed-egress overflow of the residency or provider allowlist (a saturated Myra fleet routed the answer off the allowed set, see EU residency — the same condition the first model call retries) is not a policy refusal here: it stays a retryable provider_error (re-dialled once), with no model-error triage row.

What each client gets:

  • live stream (stream: true): the OpenAI error frame {"error":{"code":<that code>,…}} plus, for an extensions client, the aig_status: "provider_error" event with that code as error_class, then the terminal finish_reason: "stop" chunk and one [DONE]. In the web chat this is the provider-error bubble — with Try again for request_timeout / provider_error (not for provider_key_rejected, which names the provider and asks to update the key), with the model-switch remedy for model_capability_mismatch, and with the policy's own localized message (no Try again) for a policy code. A turn that had shown nothing yet is persisted as a failure row with that error_class and turn_committed names it, so a reload shows the same bubble. A turn that had already shown text or a file (e.g. a preamble before the tool call) is persisted as that partial answer with interrupted_class = the code (see Interrupted answers below).
  • stream: false (and PII/guardrail-buffered turns): when nothing was produced, the typed error itself — HTTP 502 provider_error, 504 request_timeout, 424 provider_key_rejected, 400 model_capability_mismatch, or the policy code with its own HTTP status (on an already-open stream as the error frame + aig_status: "provider_error" event). Tools already ran, so the gateway does not retry the turn transparently beyond the one re-dial above, and the error response carries x-should-retry: false — the header the OpenAI and Anthropic SDKs honour, so their built-in retry of a 5xx does not silently re-run the tools (the gateway's own scheduled prompt tasks and workflow agent steps honour it too: such a failure is recorded once, never re-invoked); a client that retries anyway re-runs them. A turn that already produced text or files fails the same way on a non-streaming request: the typed error, not a 200 with the partial (a buffered turn whose stream is already open gets the error frame + event instead). The x-should-retry: false header is set only when tools actually ran.
  • native /v1/messages (stream: false with gateway tools): an Anthropic error object ("type": "error") whose message names the code — HTTP 400 invalid_request_error for model_capability_mismatch; for a policy code its own status with permission_error (403), invalid_request_error (400) or api_error (500); otherwise HTTP 502 api_error — with x-should-retry: false. Text the turn produced before the tool call is not delivered on this route (a failed final leg always fails loud on the native route).
  • A Stop by the user while that call is being made ends the turn without an error and without a failure row.

The request log records the turn with meta.post_tool_leg_failed = the code. (The same rule does not apply to a length-cap continuation whose follow-up call fails: that answer is already visible and ends with its max_tokens terminal.) A later Try again / Regenerate of such a turn resumes from the saved tool results instead of running the tools a second time — see Resuming from saved tool results.

⚠️ Interrupted answers (interrupted_class). When a turn already delivered visible text (or a file) and then its final model call failed with a provider error — typically a preamble, a tool round, then the call after the tool failed — the partial answer is persisted with the message field interrupted_class = the typed failure code (e.g. provider_error, request_timeout, or a policy code). The turn_committed frame carries interrupted_class too (also on a ghost turn). The web chat renders the received text plus the notice The answer stopped early (localized) with the failure's localized reason — directly under the composer for the conversation's last answer — and, for a retryable code, a Start the answer again button — live and after a reload alike. The row is a real answer, not a failure row: a later failed retry does not delete it. A forked conversation copies the field. A truncated or read-error partial keeps the in-text interrupted note described under Visible truncation note instead (no interrupted_class). One value is a notice, not a failure: wallet_shortened — the answer is complete as far as it goes but was cut at the output length the workspace's prepaid wallet could pay (see Budgets — Wallet). It is set on an otherwise clean turn (never over a failure, which always wins), also when the turn's own shortened answer is empty (an empty answer that merely followed a shortened delegated sub-agent saves no message); the web chat shows an Answer shortened notice instead of The answer stopped early, with no Start the answer again. A second notice value, wallet_shortened_reserved, means the same cut happened because other requests of the workspace that were still running held the balance (the balance itself would have paid): the remedy is to try again in a moment, not to top up.

Machine clients: a stream: false request that is cut off mid-answer receives a non-2xx typed error: provider_error (the kind, such as a stream error or truncation, is in the message, not a separate code), request_timeout, or a policy code for a failed call after a tool result. The log row carries that typed status (for example 502), not 200. Treat it as a failed, interrupted run whose tools may already have executed, and do not retry when the response carries x-should-retry: false; without that header the gateway makes no such claim. The gateway's own unattended and delegated callers do exactly that: a scheduled agent run or scheduled prompt task is recorded failed (a typed 5xx records its own reason such as http 502; the 2xx backstop records "interrupted: the answer was cut off (<code>)"), is not retried (when the response carries x-should-retry: false) and does not deliver the partial; a workflow agent step fails (not retried when the response carries x-should-retry: false; the partial never enters run state; the step's on_error policy applies); a delegating supervisor receives an error saying the sub-agent was interrupted, its tools may already have run, and it must not be invoked again for the same task; and a chat bridge (Slack / Teams / Mattermost) posts a dedicated reply (see Chat bridge).


Authentication

Send a token on every request unless the gateway has authentication disabled. The token may be a gateway token or a personal access token.

The gateway reads the token from the first header present, in this order:

Order Header Form
1 x-aig-token Raw token value.
2 Authorization Bearer <token>.
3 x-api-key Raw token value.
curl -s -X POST "https://<your-gateway-host>/v1/myapp/prod/compat/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <token>" \
  -d '{
    "model": "claude-opus-4-6",
    "messages": [{"role": "user", "content": "Hello"}]
  }'

A missing or invalid token returns 401 unauthorized; an expired token returns a distinct 401 token_expired and a revoked token a distinct 401 token_revoked (each with an actionable message naming where to regenerate it). Branch your refresh logic on the stable code, not on the shared 401 status. See Authentication and Error codes.

Inference is refused for viewers

A request bound to a user whose role is viewer is refused 403 forbidden ("Viewer role cannot make inference requests") — before any model is called, so no credit is spent. This holds on both user-bound auth paths: a raw /v1 call and the chat / /easy playground path (the busier channel, where a viewer would otherwise burn trial credit). The check fails closed on an unconfirmable role too: a user whose role cannot be resolved to a known string (a legacy role-assignment gap) is barred exactly like a viewer, never allowed through by default. A GDPR Art. 18 processing restriction is evaluated first, so a restricted viewer receives 403 processing_restricted (the legal-hold code), not this one. Other roles — member, demouser (limited inference via its demo quota), ki_manager, tenant_admin, admin — are unaffected. The mirror control on the admin session plane (a viewer's chat writes) is Viewers cannot spend credit or reshape a conversation.


Request body

All providers accept the OpenAI chat completions body. The common fields are:

Field Type Notes
model string Required. Must be a non-empty string. On compat, this also selects the provider.
messages array Required. A non-empty array of OpenAI message objects (role, content).
stream boolean When true, the response is a Server-Sent Events stream. Absent or null means buffered. Any non-boolean value ("true", 1, an object) is refused with 400 INVALID_REQUEST before any provider is called — a malformed flag never silently picks one mode.
max_tokens integer Upper bound on generated tokens. Optional — see the default policy below. Must be a non-negative whole number; null, 0 and absent all mean "use the default". A string, negative, fractional, boolean, array or object value is refused with 400 invalid_request ('max_tokens' must be a positive integer (or null / 0 / absent for the default)); NaN, Infinity and out-of-range numbers are refused by the JSON number check. The same rule applies to max_completion_tokens and to max_tokens on /v1/messages.
tools array OpenAI tool/function definitions. Refused with 400 invalid_request on Gemini, Vertex, Bedrock and Cohere models, which cannot carry client tools (see Client tools per provider).

Provider-qualified model ids (pins)

On /compat, a model that starts with a provider namespace pins the request to that provider: ionos/openai/gpt-oss-120b is served by IONOS AI Model Hub and by no other provider, even when another provider on the gateway lists the same model id. The gateway strips the namespace before the upstream call (the upstream receives openai/gpt-oss-120b), and the request log and the x-aig-provider response header name the pinned provider.

Accepted prefixes (matched case-insensitively, longest match wins, so IONOS/ works like ionos/):

Provider Accepted prefixes
gemini gemini/
vertex vertex_ai/
azure azure_ai/, azure/
groq groq/
mistral mistral/, text-completion-codestral/
together together_ai/
fireworks fireworks_ai/
nvidia nvidia_nim/
sambanova sambanova/
ionos ionos/
deepseek deepseek/
xai xai/
perplexity perplexity/
cerebras cerebras/
cohere cohere/
bedrock bedrock/
openrouter openrouter/

Rules:

  • myra/ is an exception. A myra/<id> (and any self-hosted vllm id) is not a pin: the prefix is stripped as before and the model is served by the Myra fleet.
  • A pin never hijacks a real model id. When the full string is itself a catalogued model id of any provider (for example OpenRouter's openai/gpt-4o), it is that model, not a pin. A prefixed id whose remainder has no row under the named provider keeps its earlier prefix-routing behaviour only when that behaviour already lands on the named provider (for example ionos/<new-id>, or openrouter/<vendor>/<new-id> on a gateway that configures openrouter); it is then not a strict pin. Otherwise it is refused before any upstream call: 400 provider_not_configured when the gateway does not serve the named provider (for example perplexity/<new-id> or cohere/<new-id> on a gateway that only configures openrouter), or 400 model_not_found when the provider is served but has no row for that id (for example an uncatalogued xai/<id> or cerebras/<id>). OpenRouter no longer receives these ids.
  • OpenRouter's sub-vendor spelling. A request for openrouter/<vendor>/<model> (for example openrouter/openai/gpt-oss-120b) is the pin for the OpenRouter row <vendor>/<model>: it is served by OpenRouter only, with the pin rules below. There is no separate catalogue row under the prefixed spelling, and the catalogue refuses to store one (PUT /model-prices answers 400 invalid model id). If the gateway does not configure OpenRouter the request is refused with 400 provider_not_configured; an openrouter/<vendor>/<model> id with no OpenRouter row passes through to OpenRouter uncatalogued when the gateway configures it. OpenRouter's own ids openrouter/auto, openrouter/free and the like are unchanged.
  • Pin integrity. A pinned request is never moved to another provider. Complexity routing and attachment routing are skipped. A routing rule or the self-serve outage failover swap that would send the request to a different provider is refused with 409 model_pin_conflict. Fallback chains and upstream failover drop every leg on another provider, so a 5xx from the pinned provider is returned as such instead of being retried elsewhere. A rule that only rewrites the model on the same provider still applies.
  • Explicit provider routes and saved agents. An explicit /{provider}/chat/completions route whose model is that same provider's pin id (for example /ionos/ with ionos/openai/gpt-oss-120b) is pinned exactly like /compat when the id is catalogued; an uncatalogued id with the same prefix passes through unpinned, as before. So is an agent saved with a catalogued pin id: the pin is checked at save time and again at every run, and routing rules, fallback chains and failover cannot move it. An explicit route whose model prefix names a different provider is unchanged.
  • The pin does not bypass any gate. The provider allowlist, data residency and key checks run on the pinned provider.

Rejections (all before any upstream call):

Condition Status Code
Empty, whitespace, control character, leading / or otherwise malformed remainder (ionos/, ionos/ x, ionos//x) 400 model_pin_invalid
The gateway does not serve the named provider (no key, no base-URL override) 400 provider_not_configured
The pinned provider is not allowed by the gateway's provider allowlist 403 provider_not_allowed
The gateway requires EU hosting and the pinned provider is not EU-hosted 403 data_residency_blocked
A routing rule or the self-serve outage failover would move a pinned request to another provider 409 model_pin_conflict
The pinned model is deprecated or unknown to the provider 400 model_not_found

The picker feed GET /admin/v1/models advertises the exact string to send as pin_id. See Models.

max_tokens default policy

max_tokens is a ceiling, not a target — the model may stop earlier. The gateway applies a single catalog-driven policy at dispatch:

  • Omitted, null or 0 on a self-hosted model (our own vLLM fleet): the gateway fills it from the model's catalog output ceiling (model_price.max_output_tokens). This prevents the serving stack's own tiny per-model default (a thinking model can otherwise spend its whole budget on hidden reasoning and return an empty answer). The injected budget is bounded to a sane output ceiling and window-fitted against the estimated prompt; when only a sliver of room remains (fewer than ~512 tokens) the ~512-token useful floor is injected instead of a starvation budget, and when no safe room remains at all nothing is injected and the serving default applies. If the catalog has no ceiling for the model, nothing is injected and the serving default applies.
  • Omitted on a third-party provider (Anthropic, OpenAI, Bedrock, OpenRouter, …): the gateway does not inject a value — the provider applies its own default and enforces its own minimum/maximum. (Anthropic, which requires max_tokens, is filled from its own per-model ceiling — on both the OpenAI- compatible and the native /v1/messages paths.)
  • Larger than the model's real ceiling (any provider): the value is clamped down to that ceiling so the provider does not reject the request. Exception: on the native Anthropic /v1/messages passthrough path an over-large value is forwarded verbatim (a genuine Messages client may know a newer model than the gateway's catalog, so clamping to a possibly-stale ceiling would truncate its intended budget); Anthropic then applies its own limit.
  • Within the ceiling: an explicit value is sent verbatim — except for the self-hosted window budgeting below.

Native context management / compaction (context_management)

Anthropic's native context-management field on /v1/messages — context_management: {"edits": [{"type": "…"}]} — is untrusted client input and is sanitized at the gateway boundary. The compact_20260112 compaction strategy is only valid on models that declare support for it (sonnet-class; haiku does not), and Anthropic returns a 400 if it is sent to an unsupported model.

  • Accepted: a context_management whose edits is a JSON array. A compact_20260112 edit is forwarded only when the resolved (post-routing) model supports it. Other strategies (e.g. clear_tool_uses_20250919) are separate features and pass through untouched.
  • Rejected / stripped (fail closed): when the resolved model does not support compact_20260112, the gateway strips that edit from context_management.edits (and removes the context_management field entirely if no edits remain) and removes the compact-2026-01-12 anthropic-beta token — so the gateway never forwards a request Anthropic would 400. The routed model, not the client's model, is authoritative (the gateway may route a compaction-capable request to an incapable model), so this adapts rather than erroring. A context_management whose edits is not an array (an object, a scalar, or absent) is left untouched — a malformed body is the client's own 400.
  • /v1/messages/count_tokens: this sub-endpoint accepts no context_management (any model, any strategy); the gateway strips it wholesale.
  • Gateway-injected compaction merges, never clobbers: when the gateway itself enables compaction (context_compaction config) for a supported model, it appends its compact_20260112 edit to the client's existing context_management.edits array (deduped), preserving any client edits — it does not replace the field.

Self-hosted window budgeting (our own vLLM models)

A self-hosted model enforces a hard rule: input_tokens + max_tokens must not exceed the model's context window (max_model_len). A large max_tokens on top of a large prompt therefore overflows the window and the request is rejected, even though the input alone fits. For our self-hosted models only (never third-party providers, whose windows are much larger and are not policed this way), the gateway keeps input and output inside the window automatically:

  • Pre-flight clamp. Before dispatch, max_tokens is reduced so that the estimated prompt plus the output budget fits the window. The result is only ever smaller than the value you sent — a request that already fits is untouched. If the input is so large that no useful output budget remains (below ~512 tokens), max_tokens is left as-is rather than shrunk to a useless near-zero value. Inline data-file previews are additionally window-fitted pre-flight in a worst-case token frame with the full potential output budget reserved (see Data-file preview bounding above), so a near-window preview is shrunk before the serving stack can reject the request. The gateway's prompt-size estimate includes the tool definitions it sends to the model (not only the messages), so a request with a large tool catalogue is clamped against its real size; the same estimate prices the input of a turn that is aborted mid-stream.
  • Overflow repair (one resend). If a request still overflows (the estimate under-counts, or a multi-step tool loop grew the prompt), the model returns a context-window error. When that error shows the input still fits the window, the gateway resends the request once with a reduced max_tokens; your full input is preserved and the answer is generated. The budget depends on what the error actually reports:
    • a measured input count (the serving stack printed its real tokenizer count): the remaining budget minus a 128-token safety margin (window − measured input − 128) — the margin absorbs re-count drift between serving layers;
    • an "at least N input tokens" figure: this is a derived lower bound (the smallest input consistent with the rejection), not a measurement, so no remaining-budget arithmetic is trustworthy — the gateway resends with the minimum useful output budget (~512 tokens) instead, which succeeds whenever a useful rescue is possible at all. The answer may be shorter than usual on this last-resort path.
  • Conservative fallback when the counts are unreadable. If the overflow error is recognisable as a context-window rejection but its token counts cannot be safely parsed (missing, malformed, or implausible numbers), the gateway still resends once, with a budget computed purely from its own prompt estimate and the model's catalog window, reduced by a further 4096-token margin and always strictly below the budget that just failed. No number from the error body is used on this path. If no useful budget remains (below ~512 tokens), the request is not resent.
  • Genuine input-overflow is not repaired here. If the input alone exceeds the window (no output budget to reclaim), the request is not resent — it surfaces the standard context_length_exceeded error (see Error codes).

The window-error bodies the gateway parses are untrusted model/serving output: only the specific captured vLLM/LiteLLM phrasings are recognised, and any implausible value (a count ≤ 0 or > 10,000,000, an input that meets or exceeds the window, or a missing input count) is rejected — those bodies take the conservative-fallback path above (which consumes no numeric value from the error body) or, failing its guards, the original error is returned unchanged. In every case the resend happens at most once — a second overflow surfaces the standard error.

Validation

The gateway validates the request body at the trust boundary before any inference runs. A request is rejected with 400 invalid_request when:

  • the body is empty (Empty request body) or is not valid JSON (Invalid JSON body);
  • the body is valid JSON but not a JSON object — a bare scalar, boolean, or null top-level body (e.g. 123, true, null) is rejected (Request body must be a JSON object). (A top-level JSON array is likewise not a valid request; it is rejected on the required model field below.);
  • messages is present but is not an array ('messages' must be an array);
  • messages is an empty array [] ('messages' must not be empty) — an empty array is a malformed request, not an empty conversation, and never reaches a provider;
  • any element of messages is not an object (each 'messages' entry must be an object);
  • model is missing, empty, or not a string (Missing or invalid 'model' field).

A JSON null messages value is treated as absent (equivalent to omitting the field), not as an empty array.

Numbers in the request body are forwarded exactly

Every number in a request body (a temperature, a tool schema's minimum, a number inside a tool call's input, an ID in a message) reaches the provider with the same numeric value; its written form may be normalised (1.0 → 1, 1e-5 → 1e-05), but no number is rounded. 0.30000000000000004, 3.141592653589793 and 123456789012345 arrive with all their digits, also when a guardrail masks text elsewhere in the same body. A whole number whose magnitude is 1e14 or more but below 2^63 (a card number sent as a number, for example) reaches the provider as the plain digits of its exact 64-bit value, not in exponent form (5.1051051051051e+15); an accepted whole number of magnitude 2^63 or more keeps exponent form (1e+19).

Only the text of such a number differs from the usual encoding: a body that carries one keeps the object key order and the array and object shapes of any other body, and a negative zero is written -0.0.

A number the gateway cannot hold exactly is refused up front with 400, before any cache lookup or provider call (so a cached answer is never served for a request that would have been refused):

  • number_not_exact - a well-formed number that is not exactly representable: an integer literal (digits only, no fraction or exponent) that a 64-bit double cannot hold exactly (9007199254740993 would become 9007199254740992) or that lies beyond +/-2^63, or a decimal that is not exact. A decimal is exact when it has at most 17 significant digits and reads back as the same digits from the 64-bit float it parses to, so 0.1, 3.141592653589793 and 0.10000000000000001 pass, while 1.00000000000000000001 and 0.100000000000000001 (more than 17 digits) and 1e400 (outside the double range) are refused. Send the value as a string.
  • number_invalid - a number-shaped token that is not valid JSON (NaN, Infinity, 0x10, 01, 1.).

A body that is not JSON at all is still invalid_request (Invalid JSON body).

Repeated keys and body complexity

The inference routes (/chat/completions, /v1/messages, /responses, /embeddings) read the request body once, with the same checks as the rest of the API, before any cache lookup, guardrail or provider call:

  • duplicate_key (400) - an object in the body repeats a key at any depth ({"temperature":0,"temperature":1}). A JSON parser keeps only the last value, so a guardrail that reads the first value and a provider that honours the last would see different requests; the gateway refuses the body instead. Nothing is sent to a provider, cached or billed. Send each key once.
  • body_too_complex (413) - the body holds more than 1,048,576 JSON structural elements (each {, [, , and each string, counted outside string contents). One long string (a base64 image) counts as one element, so large prompts, long histories and embeddings requests with hundreds of thousands of token ids are not affected. Not retryable as sent: split the request.

When a body has several defects, body_too_complex (413) wins over everything else (it is checked first, so a body that is also malformed or repeats a key answers 413), and the number errors above and invalid_request (Invalid JSON body) win over duplicate_key. Operators: each refusal increments the aig_inference_body_refused_total metric (labels code and route), is logged as a throttled warning, and raises one alert per hour for each tenant, gateway and code (see the billing runbook, inference_body_refused).

A regex or keyword guardrail hit inside a number (a card number, a timestamp or ID a pattern matches, the fraction digits of a float) blocks the request with the reason pii_in_number. That is a policy refusal, not an error code of this list; see JSON number fields.

Numbers in a native tool call's input are exact or refused

On the native Messages route, a number the model writes inside a tool_use block's input reaches you exactly or the turn is refused by name; it is never rounded.

  • The live native stream and a plain stream: false answer are the model's own bytes, unchanged.
  • Where the gateway rebuilds the message (a stream that the gateway buffers because a response guardrail has to see the whole answer first, and then replays as events), every number keeps its value: it is written in its shortest round-trip spelling (1.0 becomes 1, 3.141592653589793 and 0.30000000000000004 keep all digits), and the order of keys in the input object is not significant.
  • On that replay the gateway checks every number in the response. A number it cannot hold exactly is refused with 502 and an api_error (if the response has already started, the stream ends with an event: error frame carrying the same error body instead of a 502 status) whose message names response_number_not_exact: an integer a 64-bit double cannot hold exactly such as 9007199254740993, or one beyond +/-2^63, or a decimal that is not exact, meaning one with more than 17 significant digits or whose digits do not survive a 64-bit double (0.12345678901234567, 1e400). 0.10000000000000001 has 17 significant digits that survive a 64-bit double, so it is accepted (it arrives as 0.1). A number-shaped token that is not valid JSON (NaN, 0x10) is refused as response_number_invalid. Both carry x-should-retry: false, because a retry would get the same number. The check covers the whole response, not only the tool arguments, so a number outside a tool_use can also trigger it; the trace of such a turn ends in an error carrying the same name.
  • Separately, when the gateway renders a buffered native turn itself (a /v1/messages turn it runs through its own tool loop) and the final answer carries a client tool_use whose input holds a number it cannot hold exactly (an integer a 64-bit double cannot hold, or a decimal that is not exact), the turn is refused with 502, an api_error and the code tool_input_number_not_exact. A number-shaped token that is not valid JSON (NaN, 0x10) in that input is refused with the code tool_input_number_invalid. The error body reads tool_use input refused (<code>): a number in the model's tool arguments cannot be represented exactly, and the response carries x-should-retry: false, because a retry would get the same number. The value is never echoed. This is a different check from the replay gate above, which names response_number_*.

The same holds when the PII response mask rewrites a response: the masking step never rounds a number. It keeps every number in the answer value-exact, or refuses the response by name. A response with a number it cannot hold exactly is not delivered, and the unmasked original is never sent in its place, even when the detector is set to fail_open. The reachable case is the native Messages route: it answers 502 with an Anthropic api_error whose message names response_number_not_exact (or response_number_invalid), also for stream: true, which the gateway buffers when a response guardrail is set. A refusal that happens before the first heartbeat (under about 15 seconds) is a 502 JSON body with no SSE bytes. Once a heartbeat has gone out, the client already has HTTP 200 with text/event-stream and : hb comment lines, so the refusal arrives as one event: error frame (api_error with response_number_not_exact, or invalid_request_error for a guardrail block) and the stream ends without a message_stop. See Error codes - response-phase blocks. The OpenAI-compatible route folds a provider stream into one object before the mask runs, so a provider-spelled number does not reach the mask there; the compatible-route code path (502 with {"error": {"code": "response_number_not_exact"}}, or an error frame ending an already started stream) applies only if a re-encoded compatible body ever carries such a number. Both carry x-should-retry: false. The workspace chat shows a plain message that the answer could not be delivered because it contains a number that cannot be kept exactly.

When a tool loop ends early (the time budget ran out, or a tool kept returning the same result), the gateway appends a short note to the answer saying so. Adding that note never changes a number: every number in the answer and in usage keeps its value. If the answer holds a number the gateway cannot keep exactly, the answer is delivered unchanged, without the note, and the gateway logs a warning that names the reason. The note still appears in the saved conversation.

Trailing assistant turns are normalized (Anthropic)

A well-formed chat request ends with a user turn. For Anthropic models on the compat path, if the conversation ends with one or more trailing assistant turns (an accidental assistant-message prefill — never intended in a chat flow), the gateway drops the trailing assistant turn(s) so the array ends with the preceding user/tool-result turn before the request is sent. This is required because the Anthropic 4.x reasoning family rejects a last-assistant-turn prefill with a provider 400 ("this model does not support assistant message prefill; the conversation must end with a user message"). The normalization is trailing-only — interior assistant turns and tool-call/tool-result pairings are untouched — and a conversation that is entirely assistant turns (no user turn at all) is left unchanged and rejected by the provider. It applies only to the compat path; the anthropic native passthrough forwards the body verbatim (where an intentional prefill is the caller's own choice).

Per-provider nuances — system-prompt extraction, extended thinking, prompt caching, model name prefixes — are covered in Providers overview and the individual provider pages.

chat_template_kwargs — the adaptive-thinking flag

Accepted shape: an optional object {"enable_thinking": true|false} (the vLLM/Qwen chat-template knob; the Chat sends it to every non-Anthropic model). Only the strict boolean false is read as "thinking off"; the gateway itself can turn thinking on for the rest of a Myra Qwen web-app or agent tool-loop turn (see the tool-loop section); the gateway translates or drops the field per provider and never forwards it where it would be rejected. Strict cloud providers (Mistral, Groq, OpenAI, Cohere, IONOS) never receive the field itself; where the model has a reasoning knob the OFF signal is translated instead — Groq's gpt-oss/qwen3 get reasoning_effort for OFF only (low / none). Mistral, IONOS and the Myra-served Mistral get it in both directions, per model: Mistral mistral-small-2603* and mistral-medium-3-5* / mistral-medium-3.5* (high / none), mistral-large-4* (high / low) and Magistral (high / none); IONOS gpt-oss (high / low) and Qwen3 (nothing for ON, none for OFF). low is the lowest effort the model accepts, not "no reasoning". Models without a switch (IONOS Llama 3.3, Mistral Small 24B and Qwen3-Coder, Mistral -latest aliases except Magistral) get no translation and the Chat shows no toggle for them; the Chat toggle defaults to off. A Mistral thinking content part in a response is surfaced as reasoning, never as visible text. Its thinking is a string or an array whose items are: a string (text), a {type:"text", text:string} item (text), an item with any other string type such as {type:"reference", reference_ids:[...]} (skipped, not an error), or null (absent). null or missing thinking, or item text, also counts as absent. Flagged as malformed: thinking that is neither string nor array, an array item that is an untyped object, has a non-string type, is a nested array, a number or a boolean, or a text that is not a string. A malformed thinking part never rejects the answer: non-streamed: all reasoning from thinking parts in that response is dropped; streamed: the malformed item is skipped and valid items in the same chunk are still shown; in both cases the visible answer is kept and one warning is logged. Mistral's Agents (web-search) path carries no thinking control. Cohere's command-a-reasoning-* gets thinking: {type: "disabled"}, Gemini 2.5 gets thinkingBudget: 0, OpenRouter gets reasoning: {effort: "low"}; models without a knob (OpenAI direct, Gemini 2.0/3.x, Mistral models other than those listed above, …) get no translation. A Myra-served Mistral-tokenizer model (mistral-small-4) never receives the field itself; the gateway translates it to reasoning_effort (true -> "high", false -> "none"; a reasoning_effort you set wins; a malformed value adds nothing) (see Myra). Qwen fleet models receive it unchanged, except that a Qwen (qwen3*) request without chat_template_kwargs and with max_tokens below 1024 is sent with enable_thinking: false on that call; the request as you sent it is not modified, so other calls and a fallback to another provider use your own value. Gemma 4 fleet models (gemma-4-*) ignore the value: the gateway always sends enable_thinking: false for them, and replaces a malformed chat_template_kwargs with exactly that, because after a tool call the serving stack would otherwise return the model's reasoning as ordinary answer text. Gemma 4 models also get one reordering of the messages history: an assistant message whose tool_calls is a non-empty array of objects and whose content carries visible text (a non-blank string, or a parts array whose string elements or text parts (type absent or "text") carry non-blank text) is sent as two messages, first an assistant message with that content and nothing else, then the original message with content set to "" and its tool_calls and other fields unchanged, so the model reads the text before the call. Nothing is dropped or rewritten. Messages are carried over unchanged when content is absent, null, blank, an empty array, a parts array without a text part, or any other type, when tool_calls is empty, not an array or contains an entry that is not an object, and for every non-assistant message; a messages value that is not an array is passed through as sent. Qwen 3 fleet models (qwen3*) get the messages history as sent; a history ending in a tool message is sent as is (a trailing tool message is the shape the model continues from; the gateway adds no extra user turn after it, also when the request goes to a tenant's own Myra endpoint). The one exception: when such a history contains no user message at all (for example assistant with tool_calls, then tool, from a raw API client) does the gateway insert one user message with the content " " before the assistant's tool call (after a leading system message), because the model's chat template requires a user message. A history that contains any user message is never altered, and your request body is not modified. Other models are not affected. Rejected/ignored: a null, non-object or otherwise malformed value is treated as absent by every adapter (one shared null-safe test — no translation, and the field is still dropped where the provider would 400 on it); it never causes a gateway error. A reasoning_effort you set yourself always wins over the translation.

temperature on Myra Qwen code-interpreter turns

On the Myra fleet, a Qwen (qwen3*) request that carries the code_interpreter tool on its wire and sends no temperature (absent or null) goes out with temperature: 0.3 instead of the fleet default 0.6; this makes the long code-writing tool loop (for example creating an HTML deck) more reliable. An explicit temperature is always honoured, any value including 0, and is never replaced, even when malformed (the upstream validation owns that). Plain chat, RAG, Qwen turns without code_interpreter, and every other model keep the fleet default. The rule is evaluated per upstream attempt, so a fallback to a non-Qwen model never inherits the 0.3. On the raw /v1 API, a caller that supplies its own function tool named code_interpreter on a Qwen model also gets 0.3. Once a web-app or agent turn has escalated to thinking (see the tool-loop section above), the remaining calls of that turn use the thinking sampling (temperature 1.0) instead of 0.3, unless the request set its own temperature; a held call (after a tool call was cut by the output limit, on the automatic continuation of a cut text answer, or a later tool-loop call with under 120 seconds left of the tool loop's remaining time budget, or of a delegated agent run's when that is tighter) keeps the 0.3. The client's own enable_thinking: true on a web-app turn is likewise sent as false for the call right after an output-limit cut.

A self-hosted (Myra) model id containing a character outside the catalogue id charset (whitespace, %, a backslash or a non-ASCII character) never names a model and is answered 400 model_not_found; see Models.

Retired model ids upgrade to their successor (Myra fleet)

When the Myra fleet retires a self-hosted model in favour of a newer one, the retired id is deprecated in the catalogue (GET /model-prices shows deprecated_at) and would normally be refused at serve time with 400 model_not_found (see Models). For the fleet's own retired ids the gateway carries a successor map, so an integration that pinned the old id keeps working instead of hard-failing on the day of the rollover:

Requested model Served as
qwen3.6-27b, qwen3.6-35b-a3b qwen3.8-27b
gemma-4-26b-a4b-it gemma-4-31b-it

Accepted shape. The rewrite applies to the model field of an inference request — bare (qwen3.6-27b) or provider-prefixed (myra/qwen3.6-27b), on the provider-native myra route and on /compat/... — once the id has been normalised exactly as any other id is (provider resolved, prefix stripped), to a routing rule's actions.model and each fallbacks[].model when the rule remaps onto a retired id (the same resolver; an upgraded fallback target is only logged — the response headers and the request log always describe the model that served the turn; a rule whose model condition names a retired id simply no longer matches, see Routing rules), and to a gateway's agentic_fetch.model override (the inner fetch agent runs on the successor; no response signal, the inner leg does not serve the turn). It happens before cost, capability checks and the request log read the model, so every downstream surface names the model that was actually served: request_log.model, the cost figures and the analytics rows carry the successor; the requested id is kept for attribution in request_log.meta under the gateway-owned key aig_model_upgraded_from (a client cannot set it — x-aig-meta-aig_* headers are dropped like every other reserved key).

Stored model no longer permitted. On a self-serve workspace, a run whose model comes from stored configuration — an agent's model (/agents/{slug}/invoke, scheduled runs, workflows, delegated sub-agents), a scheduled prompt task's model, the Copilot document-AI model — that the plan or the EU-Gov add-on no longer permits runs on the pinned gateway's Auto choice instead of failing (see Tenant entitlements). request_log.model and the cost name the model that ran; the stored model is kept in request_log.meta under the gateway-owned key aig_substituted_from. A model the caller sends is never substituted.

What the response says. Every response to a rewritten request — buffered or streamed, and including any error raised after the rewrite (a guardrail block, a plan or gateway refusal of the successor, a provider error) — carries the headers below. Responses produced before the model is read — authentication, the IP allowlist, rate limiting, the tenant/token budget 429, and an exact-match cache hit — never do.

Header Value
X-AIG-Model-Upgraded-From the retired id the request — or the matching routing rule's rewrite — named (qwen3.6-27b)
Deprecation RFC 9745 form @<unix-seconds> — when the retired row was deprecated. Sent only when the client's own model was retired (a routing rule's rewrite and an agent's stored model — on /agents/{slug}/invoke and scheduled runs — are the tenant's configuration, which the caller cannot act on: those carry X-AIG-Model-Upgraded-From only), and absent when the catalogue no longer has the old row at all. The RFC defines the field for the resource; here it qualifies the requested model, and it only ever appears together with X-AIG-Model-Upgraded-From — the endpoint itself is not deprecated
X-AIG-LLM-Model (buffered) / X-AIG-Model (streamed) the successor that served the turn

Both new headers are CORS-exposed to browser clients.

What is NOT rewritten (each fails closed toward the existing behaviour — the deprecation gate answers 400 model_not_found, or the block 403 model_disabled_on_gateway):

  • an id with no entry in the map — the gateway never guesses a successor from the name (qwen3.5-27b stays a 400);
  • the same id on a non-Myra provider (openrouter/qwen3.6-27b is a passthrough serve, not the fleet);
  • a retired id the tenant admin disabled on this gateway (Disabling a Myra model) — a rename never sidesteps an admin's block;
  • a retired id whose catalogue row is live again (an operator un-deprecated it, or the fleet re-serves it) — the operator's decision wins, the request goes to the id as named;
  • a successor that is itself not a live catalogue row (the map is single-hop; chains are not followed);
  • platform-owned targets applied after routing: a self-serve plan's fallback / degrade_model naming a retired id is still refused at the serve-time gate (400 model_not_found) — platform operators update those at a rollover;
  • a catalogue read that fails — the request proceeds unchanged (and the deprecation gate, which fails open on its own read, decides).

Two consequences of "the successor is what the request now names": a plan's model allowlist and a gateway's disabled-model list are checked against the successor — a request for qwen3.6-27b on a gateway where the admin disabled qwen3.8-27b is answered 403 model_disabled_on_gateway naming qwen3.8-27b (with X-AIG-Model-Upgraded-From on the response), and a plan that lists only the retired id refuses the successor by name. At a rollover, update plan allowlists and gateway blocks to the successor id.

The exact-match response cache is keyed on the id as requested, so qwen3.6-27b and qwen3.8-27b are separate cache entries; a cache hit on the old id serves the stored answer without dispatch and therefore without the two upgrade headers (the entry records the model that produced it).

Stored picks are covered too: a project default model, an agent's model or a conversation's pinned model that names a retired id resolves to the successor at dispatch time through the same resolver (the stored value itself is not rewritten — the conversation keeps showing the retired id until the user picks again, while every turn it sends is served on, logged as and billed to the successor), and /compact (its summary is recorded under the model that wrote it), the save-time pin checks and a scheduled task's plan check use that resolver too, so they agree with what an inference request would serve. A soft pin — a project default model without a gateway, or a user's personal default model — that names a retired id is resolved to the successor when a new conversation is created (a retired Gemma pin lands on the Gemma successor, not on the Auto pick); that ladder honours a block recorded under the old name on a gateway (a sibling gateway without the block serves it — gateways stay independent; with no such sibling the pin degrades to the Auto pick, as an unmapped pin does) as well as the successor's own availability. Note for the chat UI: a conversation whose stored pin is a retired id shows the picker label Auto (the catalogue has no row for it) while its turns are served on, and labelled with, the successor; picking a model again stores the live id. The pre-rollover model unavailable recovery bubble does not appear for a mapped id — the transparent upgrade replaces it.


Empty responses & inline dead-turn retry

On the normal buffered (non-streaming) path, a 2xx provider body that is not a JSON object (an array, a scalar, a whitespace-only body, or non-JSON text) is an unreadable response and follows the usual retry / fallback path like any other failed provider call. A completely empty 2xx body is not unreadable: it gets the empty-answer handling described below. The same applies one level down: a field the gateway reads the answer from (for example choices, content, candidates, parts, a content block, its type or text, or tool_calls) that is present with the wrong JSON type is an unreadable response, not an empty answer. A field that is absent or null stays an empty answer. Providers' error envelopes are handled before this check.

A model can finish a turn cleanly (finish_reason: stop) yet produce no visible answer — 0 output tokens, a few tokens of internal reasoning with nothing user-facing, or a handful of whitespace-only tokens (the instant-EOS "dead turn" some self-hosted models emit on certain prompts: a \n\n preamble, then stop, before any real token). A visible answer that is empty or contains only whitespace (matched against the same whitespace set as JavaScript's String.trim(), so a \n\n or an ideographic-space answer counts as blank) is treated as no answer; any substantive character (e.g. a terse 4 or Ja.) is a real answer and is delivered unchanged. The gateway substitutes a short fallback message in content and records the event for the per-release empty-rate metric. The notice is written in the conversation language (German or English): the language of the request when it is recognised, otherwise the language of the user's earlier messages in the same conversation, otherwise the account's interface language, otherwise English. The sentences below are the English wording; German conversations get the same notices in German. The wording is chosen on the response's output_tokens (the completion-token count, which for a reasoning model includes its reasoning tokens): > 0 → an empty-answer notice; == 0 → "The model returned an empty response. Please try again or rephrase your prompt." For the > 0 case the notice is further split by whether the turn actually produced reasoning content: a reasoning turn that spent its budget on hidden reasoning gets "The model produced internal reasoning but no visible answer. Try rephrasing your prompt or turning off Reasoning…", while a thinking-off turn that simply emitted no visible content (the instant-EOS dead turn — no reasoning at all) gets "The model ended the turn with no visible answer. Please try again or rephrase your prompt." — the "turn off Reasoning" advice is dropped because reasoning was never on. On a streamed OpenAI-compat response the count is only final after the trailing usage chunk, so the classification is made once the whole response has been read. The fallback applies whether or not tools were offered on the turn: a first-party conversation turn (where the file tools are offered whenever the model can call tools) that finishes with a whitespace-only answer gets the same fallback as a tool-free request. It is the leg's terminal fallback — it is not added to a leg the turn is about to continue or recover: a tool call the loop will run, a length-cap continuation, the broken-promise nudge (a file was asked for and none produced — the nudged leg answers; a second blank leg, or a nudge that never runs because its dial failed or the loop's budget ended the turn first, gets the one fallback — after any earlier leg's text), or a turn that already shows a file (the bare re-download card, an unchanged file served again, or a file, image, audio, video or code-interpreter artifact earlier in the loop), or a turn that already showed the model's text on an earlier leg — e.g. an answer written beside a write_file or web_search call, followed by a blank closing leg: "no visible answer" under that answer would be false, so the closing leg adds nothing, and the sources footer, if any, closes the turn — also under text written beside a tool call, which the gateway cannot tell apart from a short "let me look this up" lead-in. Once the gateway re-drives the turn — the broken-promise nudge, the file-claim re-dial, or the steer after a phantom "file card" claim — nothing shown up to that point counts any more (it was judged not to be the deliverable): a re-drive that ends blank, or never runs, gets the fallback. On a buffered tool-loop response — stream: false, or a stream: true turn the gateway buffers and re-emits (PII masking, a response schema, an output guardrail) — only an answer leg that hands no tool call on counts (that body carries only the final leg's text, so the fallback is the only thing the client would see). The one exception is a turn stopped by its time budget: its buffered body returns everything the turn produced (the text of every round, the synthesis if any, and the stop note once), so paid work is never discarded. A write that failed shows no file, so a blank leg after it — with no text shown — still gets the fallback; where the answer claimed the save, the "No file was created" note reports it. On a streamed turn a blank leg whose read failed after its finish chunk still gets it (nothing else covers that bubble); on a buffered turn that cut attempt is re-dialled or reported like any other failed attempt (see the buffered-failure rules below), and a leg that ended with a provider error event gets that banner, not this fallback. Three tool-related shapes get something else: a leg whose visible content is empty because an inline tool call was stripped and recovered continues the loop into the real answer; a leg whose only content was a tool tag the gateway could not turn into a call gets the "unparseable tool" retry hint below; and a leg whose only content was a stripped non-tool tag (a <memory> proposal, which was delivered as its own event) gets no wording at all — the model did produce content, so "no visible answer" would be false (the gateway logs the strip). A turn the client aborted is recorded as aborted, not as empty.

Client disconnects. The gateway notices a client that goes away, including on large requests. What happens depends on where the request was:

  • A streamed answer is cut at the disconnect; the tokens generated so far are billed and the request is recorded as aborted (aborted=1).
  • A request whose provider has not yet sent its response headers (the wait for the first byte), streamed or not, is cancelled the moment the disconnect is noticed: the connection to the provider is closed at once instead of being held until the provider answers or its time limit passes. Billing is unchanged. The request is recorded as aborted (aborted=1). The request status is 499 when the client received no response headers; once response headers were sent, the status the client received is kept (and the request is still recorded as aborted). So a non-streamed request, a collected answer or a buffered tool loop is 499 at any model call; a live stream, or a streaming request whose head the gateway sent early while it buffers the answer (for example for PII checks or forced buffering), is 200 with the request marked aborted. The cancelled provider call is shown as a cancelled, partial call with zero tokens. In a tool loop this applies to every later model call as well. If the client is already gone before a model call would start, that call is not made at all and no provider call is recorded for it. The exception is a disconnect during the header wait of a retry or fallback attempt after an earlier attempt of the same call's chain already failed (the primary model call and its fallbacks; the same holds inside the web-search model call's own fallbacks, but a web-search model call that failed completely while the client was still connected does not count toward the main chain, whose first attempt is then recorded as a plain cut, 499 with aborted=1; the same holds for a web-search model call answered with a client error (4xx) that is not a refusal of web search itself: it is retried on the normal path and never counts as an earlier failure): that request is recorded as the honest failure it was (aborted=0, with its failure row), the cancelled call is still shown as a cancelled call with zero tokens, and no further attempt is made. The same holds for the wait for the response body of a non-streamed request, including a native /v1/messages request with stream: false (the time between the provider's response headers and the end of the body: the wait for the first body byte, which can be long on self-hosted models, and any pause in the middle of the body): a disconnect during it closes the provider connection at once (within about two seconds of the disconnect), discards the partial body, the request is recorded as aborted (aborted=1) and the cancelled provider call is shown as a cancelled, partial call; the request is logged with the same status rule as above (499 when the client received no response headers, otherwise the status already sent). As in the header wait, a disconnect during the body wait of a retry or fallback attempt after an earlier attempt of the same chain already failed is recorded as that chain's honest failure (aborted=0, with the chain's final failure status, for example 502 after a 503), as long as no reply content had reached the gateway yet (any text, reasoning or tool call (including the start of a tool call) the model sent counts, even one the gateway still holds back or strips, such as an inline tool-call block or a partial memory tag; an empty reasoning piece does not); a disconnect after the reply started is the user's Stop (aborted=1) as usual. This holds for streamed answers, collected answers, buffered tool loops and native /v1/messages streams alike. An error response (non-2xx) is read to its end so its text can be kept as the failure evidence. In a tool loop this applies to every model call. Other phases behave as described in the neighbouring entries.
  • The same holds for a native /v1/messages pass-through stream: when the client disconnects, the gateway stops reading from the provider at once, whether the read was waiting for the first byte or paused in the middle of the answer, and the provider call is recorded as a cancelled, partial call.
  • A non-streamed answer is cut as well; the provider leg is recorded as partial and the request as aborted.
  • The same holds for the gateway's own inner model calls, the compaction summary and the page-reading call of an agentic fetch: when the client disconnects while such a call is waiting for its reply body, the provider connection is closed at once, the inner call is shown as a cancelled, partial call of its own kind (compaction or agentic_fetch_inner) with zero tokens, no compaction is applied, and the request ends as the user's Stop rather than as a summarizer failure: it is recorded as aborted (aborted=1) with the same status rule as above (499 when the client received no response headers, otherwise the status already sent).
  • The same holds for the gateway's own helper model calls made on your behalf: the reading of an uploaded image for a model that cannot see images, the input guard check, the inline claim check and the text clean-up before read-aloud. When the client disconnects while such a call is waiting, its connection is closed at once instead of being held until the helper's own time limit. A guard check cut by a disconnect ends the request as the user's Stop (499, aborted=1): it is never counted as a pass of the check, never blocks the request, and is not reported as a guardrail outage, even when the guard is set to let requests through if it is unavailable. No model call is made for the request afterwards.
  • The same holds for the gateway's own knowledge search and connector-tool selection: when the client disconnects while the query embedding or the rerank of a search_knowledge call or of the narrowing search inside a read_file call on a large document, or the Qwen tool selector call of a connector, is waiting, that connection to the Myra fleet is closed at once instead of being held until its own time limit. The request ends as the user's Stop (499, aborted=1), not as a search failure: no model call follows, the search is not reported as having found nothing, a narrowed document read is never replaced by the whole document, and the selector does not fall back to keyword ranking.
  • A client that disconnects after the provider has already sent its end marker (the final message_stop or [DONE], with no error before it) did not cut the call: the provider call is recorded as complete with the tokens the provider reported, the request is not recorded as aborted, and the provider connection is closed rather than reused. A disconnect before the end marker stays a cancelled, partial call as described above.
  • In a tool loop, no further model call starts once the disconnect is noticed. A call already running is billed for what it used, and the request is recorded as aborted (aborted=1).
  • Opt-in exception: x-aig-detach-on-drop: 1. A CDN or proxy cutting a long-lived connection is not the user leaving. A client that sends x-aig-detach-on-drop: 1 (exactly 1; any other value, or a repeated header, is ignored and logged, so a disconnect aborts as above) on a turn-owned OpenAI-compatible chat request (x-aig-turn-id, not a ghost conversation) is detached when its connection drops: nothing is aborted, the turn runs on to its end, the answer is saved under the turn id, the request is not recorded as aborted (aborted=0), and no stopped partial is written. Output to the dropped connection is skipped. The client fetches the result with GET /admin/v1/conversations/<ID>/turns/<TURN_ID>. An explicit Stop still stops the turn. Without a turn id, on a native endpoint or in a ghost conversation the header has no effect and a disconnect aborts. While such a turn runs, a second turn on the same parent message is refused with 409 turn_in_progress. A turn whose answer the gateway holds back (a response guardrail, PII screening or a server-side web search) is detached the same way: the first keepalive comment is preceded by the turn's stream_start frame, so a client that was cut during the hold can tell that the turn is running server-side and fetch its result.
  • A disconnect before any reply started, while a failing retry chain is running, stops the chain. The request is recorded as the honest failure it was (aborted=0), not as a cut answer.

A third case takes priority on a max_tokens (length-capped) empty turn: when the prompt itself ~filled the model's context window (prompt_tokens ≥ 90% of the routed model's known context window), the turn produced no answer because there was no output budget left. The gateway returns a distinct fallback whose wording follows the turn count of the request — on a first turn (exactly one user message in the request, so the prompt is the conversation) "Your input is too large for this model's context window. Shorten it, remove attachments, or pick a model with a longer context."; on any later turn "This conversation is too long for the model's context window. Start a new chat or shorten the conversation, then try again." — and, because a same-prompt retry would re-send the near-window prompt and deterministically fail again (and re-bill the input), suppresses the retry — the inline dead-turn retry below never fires for this class, and the chat UI hides its regenerate affordance on the bubble. When the routed model has no known context window (the catalog lacks max_input_tokens) this class is not selected — the turn falls back to the reasoning-only / empty wording above.

For self-hosted (inline) models a "dead turn" — an empty-visible clean finish with ~0 output tokens (an instant-EOS glitch) — is transparently retried once on a buffered (stream: false) request before the fallback is returned. This includes a buffered request that runs the gateway's tool loop (a stream: false request with gateway tools such as web search or file tools): a dead first leg is retried once inline. The discarded attempt is not delivered or billed; it is recorded as a non-billable leg with error_class dead_turn_discarded. If the retry produces a real answer you receive it normally; if the turn is still dead the fallback is returned and a provider fault is recorded (and, for a sustained storm of dead turns, the provider's circuit breaker opens so traffic fails over). The retry is capped at one attempt and never applies to third-party providers. A dead turn is an instant end of turn (finish_reason: stop): a max_tokens (length-capped) empty turn is not one — the model was still generating when the cap cut it, typically because the caller asked for a tiny max_tokens (a one-token health probe) or, on a model with no known context window, because the prompt filled it. Such a turn is delivered once with the fallback above, is never retried (the identical request would end identically), and counts as neither a success nor a failure for the provider's circuit breaker.

A live-streaming (stream: true) request gets the same single inline retry when its first attempt is a dead turn and nothing but the stream head had reached you: no content and no reasoning (a whitespace-only or reasoning-only dead turn already put bytes on the wire and keeps the fallback). The retried answer arrives as one continuous stream: one role opener, one finish, one usage chunk and one [DONE]; the discarded attempt is recorded as a non-billable leg with error_class dead_turn_discarded and does not appear in usage. The retry applies only to a plain client; a client that opted into the gateway's extension frames (x-aig-extensions: 1) keeps the fallback, as does a request with retry_count: 0. If the retry's own dial fails after the stream head was sent, the stream ends with exactly one in-stream error frame, and the X-AIG-Provider / X-AIG-Model headers still name the first attempt (headers cannot be resent).

Reasoning runaway: a bounded reasoning phase

A self-hosted reasoning model can keep "thinking" for tens of minutes and never produce an answer. The gateway therefore bounds a leg that has produced only reasoning — no visible text and no tool call yet:

  • Reasoning budget (per model). Each model has a reasoning budget in tokens (model_price.max_reasoning_tokens; default 32768 for self-hosted models, unset for third-party providers, which enforce their own thinking budgets unless a value is set). Reasoning is counted per streamed reasoning token, with a loose byte ceiling for providers that batch many tokens into one delta. A leg whose reasoning goes past the budget is stopped. A malformed stored value (zero, negative, fractional, or above 262144 tokens) falls back to the default bound, never to "unbounded".
  • Wall-clock bound. A reasoning-only leg (no visible text, no tool call) is also stopped once the turn's wall budget (900 s (15 min) for a streamed turn, also while the answer is held back for inspection or web search; 360 s when the client receives nothing until the end (stream: false, or a held stream on a provider route other than /anthropic/v1/messages, which gets no keep-alive; a chat bridge turn is the exception and gets 900 s); 900 s unattended; measured from the start of the request — the first leg counts, and a round-limit compaction does not restart it) is used up. What happens next depends on whether the gateway runs a tool loop for the turn.

    No tool loop when one of:

    • the client supplies its own tools;
    • tool_choice is "none" with no connector (type: "mcp") tools attached;
    • the provider has no gateway tool loop;
    • no gateway tools resolved.

    There the leg is cut with finish_reason: "length" and the reasoning-runaway notice described below.

    Tool loop (ordinary chat and API turns): the per-model token budget bounds a leg too (for example 32768 tokens is about 6 minutes at roughly 90 tokens per second, longer on a slow pod). The between-rounds wall check still applies inside the loop (it uses the same request-start reference), and a reasoning-only leg is stopped mid-stream as soon as the loop wall budget runs out. The turn then ends like any other wall-clock stop: a partial answer built from the tool results this request gathered so far plus the "stopped early" note, or the wall-clock note when this request gathered nothing usable. Tool results that only sit in the conversation history you sent (earlier turns) do not count as gathered. The stream carries a tool_loop_terminated event with reason wall_clock_exceeded. The cut leg emits no finish_reason of its own; the stream carries exactly one finish_reason, stop, after the note (never length). The one exception is the final answer leg after the round limit (the compaction re-dial): it ends with finish_reason: "length" and the reasoning-runaway notice described below.

A leg that has relayed any visible text or started a tool call is never stopped by this bound: healthy answers are not cut. A client disconnect stays an ordinary abort.

What you receive: finish_reason: "length" (Anthropic-style max_tokens) and, as the assistant message, a short notice in the conversation language saying the model reasoned for too long and suggesting a simpler request or turning off Adaptive thinking. The stored message carries empty_answer_class: "reasoning_runaway" (streamed and buffered alike). The upstream connection is closed so the model stops generating, and the turn is billed an estimate of the reasoning streamed so far (input estimated from the request) — never zero and never the max_tokens ceiling. The request log leg has error_class reasoning_runaway.

Provider content-filter stop

When the model provider's own content filter stops a turn (for example an Anthropic refusal stop reason, normalized to finish_reason: "content_filter") and no visible text was produced, the gateway substitutes a short notice in content, in the conversation language, saying that the provider's content filter stopped the answer and that the user can rephrase or choose another model. The wire finish_reason stays content_filter. The stored message carries empty_answer_class: "provider_content_filter" (streamed and buffered alike). This is a request-side outcome, not a gateway fault: it is not retried, does not count towards the empty-answer rate, and does not trip the provider circuit breaker. A refusal that still produced visible text is delivered unchanged.

File names in the file tools — stand-in names

On a gateway that masks personal data, the model sees every stored file name as a stand-in — MYRA-FILE-<16 hex digits> followed by the file's extension when it is a known type (see PII Protector — File names). The file tools accept, as the name argument (read_file.filename / path, write_file.filename / path, edit_file.filename / path, code_interpreter.input_files[] and /input/<name> paths in its code, convert_document.file, edit_office_file.filename, image references inside the converted HTML):

  • a stand-in this conversation's request listed (any letter case) — resolved on the gateway to the stored file; a stand-in followed by another known extension names the derived file (MYRA-FILE-…​.docx for the converted ….html of a file outside a folder);
  • the stored name itself (e.g. copied from your own message) — unchanged behaviour;
  • a name carrying a protection token of the same request (copied from a masked attachment marker) — the lookup restores it, the reply never echoes the restored name.

Rejected: a MYRA-FILE-<16 hex> run that is not one of the request's stand-ins (invented, stale, another conversation's) — read_file answers File not found: … with the available stand-ins (at most 200, then how many more); the other tools answer a tool error and store / stage nothing (edit_file: "not a file name from the file list", nothing is looked up); a write_file or edit_file through a stand-in whose stored name the tool could not address directly (a folder path, non-Latin script) — a tool error ("names a file this tool cannot address" for edit_file). edit_file's messages always quote the name the model sent, never the stored name. (This rule is about stand-ins only: a name whose masked personal value is restored is stored under the restored value as before, whatever its characters.) Where personal-data masking is active, a name carrying a MYRA-FILE-<16 hex> run that is not one of the request's stand-ins — or such a run cut off at the end of the name — is not written, staged or converted (the answer and the stored name would show it as [file]). Likewise write_file refuses a name carrying a masked value that names never restore (a protected keyword's token) rather than overwrite whatever file the [redacted] placeholder would collide with; a sandbox / convert output keeps the placeholder (a name already in the file space gets a numbered variant), and an output named after a file whose stored name could not be written directly is saved under that name's last part with unusable characters replaced. A name in which Myra-File- (any letter case) is followed by exactly 16 hex digits (0-9, a-f) and no further hex digit, or by fewer hex digits that end the name (a cut-off stand-in), is read as a stand-in and treated as above; any other name containing Myra-File- (Myra-File-Deck.md, Myra-File-abc.md) is an ordinary name. Every name a tool returns for a stored file is its stand-in; the stored name is never echoed. The client-facing stream, the buffered body, the stored message and file cards carry the real names (the stand-in is restored like a masking token; one that cannot be mapped is shown as [file]).

Broken-promise recovery (Workspace file writes)

On a Workspace turn where the server-side file tools are offered, a model can narrate an action it never performs: you ask it to create or write a file, and it replies "I'll now create the file…" and stops — a clean finish_reason: stop with prose but no write_file call and no file produced. Because a clean stop with visible text is the tool loop's normal successful exit, the turn would otherwise end there with nothing written. When your typed request was to write a file and the turn produced no file and called no tool, the gateway re-drives the turn with a short instruction to use the tool now. The write intent is read from the text you typed — the contents and filename of an attached document are excluded, so attaching a file whose text happens to contain a word like "generate" does not trigger the recovery. Re-drives stop as soon as either a file is written or a nudged attempt again makes no progress: it answers with no tool call, or it only repeats a tool call already made in this turn with the same result (re-running the same check is not progress), so a turn that has genuinely finished is never re-driven repeatedly; no answer field of a standard response is altered. The instruction tells the model that the text it already wrote is shown and must not be repeated (after a tool round it says the requested file is not written yet, rather than that no tool was called). The recovery covers every provider's clean finish, including Anthropic's end_turn. This recovery applies only to Workspace/chat turns (identified by their conversation and turn ids); a plain OpenAI-compatible client is never re-driven and always receives exactly one finish_reason.

No repeated answer across tool rounds

A Workspace answer that runs several model calls (tool rounds, an automatic continuation of a long answer, the broken-promise recovery above) is one reply: each call's text is shown once, in order. A call the gateway started with a new instruction (a nudge to act, a file-claim re-dial, the next call after a tool round) begins on a new paragraph: the gateway inserts a blank line between the earlier text and the new call's text, unless the text shown so far already ends in a blank line (it adds a single line break if the text ends in one). So a closing sentence and a code block that follows it never run together. A plain length-cap continuation is joined directly, since the model may resume mid-word. The inserted break is part of the stored message and, for a nudge or a file-claim re-dial, of a non-streamed (stream: false) response too. Only the space, tab, carriage return and line feed characters count as whitespace for this rule (a form feed or vertical tab counts as visible). Trailing spaces, tabs and carriage returns after the last visible character do not change the rule: it looks at the line breaks that follow that character, however much whitespace there is. The one exception: a blank line followed by spaces, tabs or carriage returns that end the shown text still gets a single line break, so the new call's text never renders as an indented code block. Text that shows nothing at all gets no inserted break when it is empty or ends in a line break, and a single line break when it ends in spaces, tabs or carriage returns (for example a tool call that was preceded only by indentation). The new call's own leading blank lines are kept after the inserted break. Two rules keep a model from writing the same answer again in a later call:

  • Each call's text enters the model's context once. A continuation or recovery call sends the model only the text of the call that just ended (text from earlier calls is already in the conversation, attached to their tool calls). The gateway's own notes in the reply are never fed back as the model's words.
  • The close after a file is written. After write_file or edit_file, the tool result tells the model how to finish. On a streamed reply that has already shown text, it says not to repeat or re-summarize that text: a short summary of the file only if the text so far just announced it, otherwise one short sentence naming the file. On a reply that has shown nothing yet, the result keeps asking for a short summary. On a buffered (stream: false) reply, text counts as shown only when it is part of the final response: the text of a call that was continued (the broken-promise recovery, a long answer split across calls) is; the text a model wrote beside a tool call is not.
  • The close after a code interpreter file. The code interpreter closes differently: it adds a gateway note after the result, outside the untrusted frame. The note reads "If this request still needs other steps or files, do them first. Otherwise" followed by the same already-shown close as above, then "Do not write a note, a question or an offer from that text again either." It never names a file. It is added only when the run exited with code 0, did not time out, delivered at least one file for download, and nothing the call produced was dropped or elided (a file refused by the runner or the per-reply file limit, a storage fault, a chart over the media limit, or text carrying an elision placeholder), no requested input file had a problem noted in the result (a file that could not be loaded, is not available or is excluded from the chat's file selection, or was replaced by an earlier version), and the reply has already shown text. Otherwise nothing is added: a run that delivers only charts, a failed or timed-out run, a run with any dropped or elided output, a run with a noted input-file problem, and a reply that has shown nothing yet all get no note, so the model's own summary is the answer.

Tool-call arguments in the conversation history

When you send a conversation back (messages with an earlier assistant turn that carries tool_calls), the gateway checks the function.arguments of each earlier call before it forwards the request, for every provider. Some servers (vLLM, for one) answer 400 when one earlier call carries arguments that are not a JSON object, for example a call that was cut off at the output limit and stored as it came. The gateway fixes that call instead of failing the request:

arguments in your history What the provider receives
a string holding one valid JSON object the string, unchanged, byte for byte (on OpenAI-shaped providers)
an empty string, or absent / null "{}"
an object (not a string) the object written out as a JSON string
anything else: cut-off or invalid JSON, an array, a number, a string, text around the object, NaN, a lone surrogate escape such as \ud800 inside a string, invalid UTF-8 bytes anywhere in the text the fixed text {"gateway_note":"The arguments of this tool call were not valid JSON (for example cut off at the output limit) and were removed by the gateway."}

The check is deliberately strict: text that is not valid UTF-8 (a stray byte, a cut-off multi-byte character) is replaced by the fixed text even inside an otherwise complete object, while valid multi-byte text is kept byte for byte; a lone surrogate escape ({"a":"\ud800"}) is accepted by some JSON parsers but is replaced by the fixed text here, because it cannot be forwarded as valid text. An absent value and a malformed one are not treated alike: absent means a tool without parameters, malformed means the original bytes are gone. The call's id, its name and the matching tool results are kept, so the pairing stays intact. On the Anthropic translation the call's input is built from the same rule, and a number that is not exact (see above) also becomes the fixed text there. The original malformed bytes are never forwarded and never written to the log; the log records only the number of calls that were fixed (fixed=) and the total number normalised (normalised=), plus the position, kind and sanitised name of the first few.

Earlier file edits are re-inserted as tool exchanges (compat chat history)

On a Workspace chat turn through the compat endpoint, the gateway stores, per assistant reply, the successful file-writing calls of that reply (edit_file, write_file, edit_office_file, code_interpreter; at most 4 per reply, and a call whose arguments exceed 4096 bytes is not recorded). When the next request is built, the gateway inserts for each of the most recent such replies an assistant message with tool_calls (ids of exactly 9 alphanumerics, hx<6 characters hashed from the whole message id><n>, which every provider's id rules accept, the recorded name and arguments) and a tool message with the fixed result exit 0. Saved files: /output/<file> (new file), or (updated in place) instead of (new file) only when the call updated an existing file, directly before the text of that reply. The total inserted is bounded (16384 bytes; older exchanges are dropped first). If two stored replies would render the same id stem, the older one and everything before it get no exchange.

Nothing is inserted, and the request is otherwise unchanged, when: the request is not a Workspace chat turn on the compat route (native passthrough, API clients' own messages with tool_calls pass through untouched); the stored reply no longer matches what is in the history (edited, or bridge content appended); the reply came from a conversation with bridge-tainted content; the tool is not offered on that attempt; the provider serving that attempt is not one whose wire format carries tool calls (see below); the gateway has an enabled request-phase guardrail detector that does not inspect tool-call arguments for its configured action, or its guardrail configuration cannot be read (see below); or the budget is exhausted. The inserted messages are never stored in the conversation and never shown to the user, and a fork of the conversation starts without them.

Gateways with request guardrails keep the exchange when every enabled request-phase detector either masks tool-call arguments or cannot be triggered by the inserted exchange. The inserted arguments and results then pass through the same guardrails as the rest of the request. Detectors that mask tool-call arguments, so personal data in them is replaced before the provider sees it: PII protector, custom PII and Presidio (every action), and regex and keyword detectors with the scrub or block action (a block hit confined to earlier history is masked, so the turn is still answered; arguments are emptied to {} only for tool calls your own client sent). Regex and keyword detectors with the flag action act on the text as for any other history: the exchange is forwarded unchanged and the flag is recorded. All of them read the request per JSON level, so a value hidden behind a \uXXXX escape inside a tool call's arguments is found. Detectors that do not read the earlier tool exchange in a way the insert could affect: prompt guard and prompt injection read the newest user message only; gibberish and JSON schema have no request check; contains-code, jailbreak and language detectors with the flag action act on the text as they do for any other history. Contains-code and jailbreak detectors set to block also keep the exchange. A language detector does not count the inserted exchange. A gateway gets no inserted exchange when it has a keyword detector for classified markings set to block, a detector of an unrecognised type, or guardrail settings that cannot be read. How request guardrails treat a match in the inserted exchange (leave-out, the request log's inserted: removed, refusal) is described in Earlier conversation turns. Block and flag verdicts still apply to the new user message as usual.

The inserted messages are sent only to providers whose request format carries tool calls and results: OpenAI, Myra, Mistral (chat completions; the Agents API never receives them) and Anthropic (translated to tool_use and tool_result blocks). They are never sent to any other provider (for example Amazon Bedrock, Cohere, Google Gemini and the other OpenAI-compatible hosts), including on a fallback to one of them: that attempt's request has no inserted messages, and the signed Bedrock request body is built without them.

Tool-call arguments the gateway cannot decode

The gateway runs a tool only when the model's arguments are one JSON object (an empty argument string means a tool without parameters). Nothing is repaired or guessed: arguments the gateway cannot decode never reach the tool. Refused are an array, a string, a number or null instead of an object; single quotes, comments, trailing commas, unquoted keys; text around the object or after it (a code fence, a second object, {"a":1}x); a NUL byte anywhere in the arguments; a number that cannot be represented exactly (see below); and arguments over the 1 MiB cap. A raw tab inside a JSON string is accepted. Whitespace around the object is accepted.

Instead of running the tool, the model gets one corrective tool result (and the client receives a tool_error event), with a constant text per kind that never repeats the model's own bytes:

kind When What the model is told
over_cap the arguments exceeded 1 MiB the input was over the cap and truncated
length_cut the arguments end inside an unfinished value and the call's output hit the token limit that was sent for it (a cut write_file is told to work in smaller steps or several files instead, and edit_file is named only when it is available) Generic text: tool call was cut off: the response reached its output token limit before the tool arguments were complete. A tool call does not fit in the remaining output budget - answer the user directly in plain text without calling a tool. For a cut write_file the text starts with the same tool call was cut off: prefix but names the way forward instead: nothing was saved, do not resend the same content in one call, change only the affected passages with edit_file or append further parts with it (only when edit_file is offered on that request), otherwise split the content into several smaller files or tell the user in plain text that it is too long. Reasoning and file content share the same output budget, so the model is told to keep its reasoning short before the next write. A second cut of the same tool ends the turn, so each part should be at most about half the size of the cut one.
incomplete the arguments end inside an unfinished value, no token limit was reached the input ended before the JSON object was complete; call again with the complete arguments
invalid_json the text is not a valid JSON object (see above) the input was not valid JSON; call again as one JSON object matching the parameters schema
not_object valid JSON that is not an object the input did not decode to a JSON object; call again as one JSON object
number_not_exact a number in the arguments cannot be represented exactly (see below) tool input was refused (number_not_exact): a number would be rounded; an integer must be held exactly by a 64-bit double within ±2^63 and a decimal must have at most 17 significant digits that survive a 64-bit double, otherwise send the value as a string
number_invalid a number token that is not valid JSON (NaN, Infinity, 0x10) tool input was refused (number_invalid): use plain decimal numbers, or send the value as a string

Numbers are never rounded. A number the model writes in a tool call's arguments reaches the tool with its value intact, or the call is refused by name and the tool does not run. Integers keep every digit (a whole number the double holds exactly, such as 100000000000000000, passes; the gateway writes one of 2^63 or more in exponent form, 9.223372036854776e+18); a decimal arrives as the same 64-bit double, possibly re-encoded in its shortest form (0.10000000000000001 reaches the tool as 0.1). An integer literal (digits only, no fraction or exponent) that a 64-bit double cannot hold exactly (9007199254740993, 1234567890123456789) or that lies beyond ±2^63 is refused; ±2^63 itself is accepted. An integer such as 100000000000000000 or 18014398509481984 is a double exactly and passes. A decimal is accepted only when it has at most 17 significant digits and reads back as the same digits from the 64-bit float it parses to, so 0.1, 1.50, 2e3, 3.141592653589793, 0.10000000000000001 (arrives as 0.1) and 0.79999999999999993 (17 digits; arrives as 0.7999999999999999) pass, while 0.100000000000000001 and 0.799999999999999931 (18 digits) are refused; so is a number too large or too small to be a finite value (1e400, 1e-400, 4.8e-324). Digits inside a JSON string are data and are never checked. To pass an identifier or value outside these limits, send it as a string. The refusal goes to the model as a tool result, not to the API client, so the error codes are unchanged. The same rule applies to a tool call the gateway recovers from a model's plain-text reply, and to a call held for human review: an approval that was suspended before this rule existed and carries a non-exact number is refused by name when it is resumed.

A built-in tool the gateway's own policy denies stays denied for the reply. When a built-in tool call (web_search, fetch_url, agentic_fetch, the media tools, code_interpreter and any other built-in a policy block refuses) is refused by a rule that cannot change within one reply (an agent constraint that blocks the tool, a project that forbids egress, a tool policy floor, a block level of the agent's tool permission policy, a chat that cannot confirm or approve the call, or a built-in tool the agent's capability token does not list), the gateway withdraws that tool for the rest of the reply. The tool is removed from the tools offered to the model (unless it is the only tool offered; then the turn ends with one final no-tools answer, the tools_exhausted stop below), and a later call of it is refused straight away without running anything: the call still produces a deny access decision, and the model's tool result states that the tool is not available for the rest of this reply, that it must not call it again, and that it should tell the user it could not be used and answer from what it has. The reply therefore finishes with the model's answer instead of ending in repeated_tool_call. A call held for approval, a refusal that depends on the call's arguments, an argument-less transient failure (a provider or network fault) and a record failure do not withdraw the tool. Refusals by an MCP connector's tool are not covered. A withdrawn tool is withdrawn for the one reply only; the next request starts afresh.

A model that keeps sending an undecodable call is stopped by the repeated-call guard (repeated_tool_call). The corrective text is constant per kind, so the guard sees the same result every round: undecodable calls of the same tool with different arguments stop the turn after the third round with mode = same_failure; identical arguments stop it after the fourth round with mode = cumulative. A tool call cut off at the output-token limit is bounded sooner: the 2nd round of a turn in which a call of the same tool name was cut stops the turn with repeated_tool_call, details.mode = length_cut, details.tool (sanitized name) and details.count = 2. The user sees a short note (in the reply language) that nothing was run or saved and that the work should be split into smaller parts. On an unattended run (see Round limit stop note) the note tells the reader to make the task for each run smaller instead of asking for a follow-up turn, because nobody is there to answer one. On a resumed approval (human review) the cut information is not available, so a cut call is answered incomplete.

Each failure is counted in aig_tool_input_invalid_total{model, kind, outcome} (model is unknown when the request has no model). kind is one of over_cap, length_cut, incomplete, invalid_json, not_object, number_not_exact, number_invalid. The outcome is counted per failure episode of a tool: an episode starts with an undecodable call and ends with the next call of that tool that decodes.

  • corrected: an undecodable call that starts an episode (the tool's first undecodable call of the turn, or the first one after a call of that tool decoded). The corrective result was sent.
  • failed: an undecodable call of a tool whose episode is already open (it failed again without a decoded call in between).
  • recovered: a call that decodes and closes an open episode, labelled with the kind of the episode's last failure.

So fail, ok, fail, ok counts corrected twice and recovered twice. Tools are counted independently.

File references in Workspace answers ({{aig_file:NAME}})

On a streamed Workspace turn (conversation id + turn id, stream: true) where a file-producing tool is offered to a model with native tool calling, the system prompt asks the model to name a file that a tool created or changed in this turn as {{aig_file:NAME}}, and never to say a file was created, saved, updated or exported unless a tool result in this turn confirms it. The gateway renders every well-formed placeholder to the plain NAME before anything reaches you — on the live stream (also when a placeholder is split across chunks or legs) and in the stored message, so a reload shows the same text. A malformed placeholder (no closing }}, a line break or { inside the name, a name over 1024 bytes) loses its {{aig_file: opener; the bytes after it are kept. An empty placeholder {{aig_file:}} is removed entirely. The syntax never reaches a client: the rendered answer contains no {{aig_file: sequence (when removing an opener would splice one together from the surrounding text, a single space is inserted). Thinking ticks are rendered the same way. Plain OpenAI-compatible clients, agent runs and the native Messages route never get the instruction and are not rewritten. The request log keeps the raw model output (response_raw), placeholders included. Whether a placeholder names a file that was really created is part of the file-claim check (below).

File-claim check

For the same Workspace turns the gateway checks whether an answer says a file was created or changed in this turn although no file was produced — the "I've updated the file" answer with nothing behind it.

  1. Pre-filter (≈0 ms, every eligible answer): file names or nouns, file-action verbs in any tense, an attached or named file, or a placeholder naming a file no tool created this turn. A miss adds no latency and nothing else happens.
  2. Judge (a pre-filter hit on a turn that shows no file — no file created or changed, no re-served file card; a failed write does not count as a file): a self-hosted Myra model on the Myra fleet (EU), seeing the same (masked, where masking applies) content the serving model saw, with JSON-constrained output (below). On a tool turn that offers the file tools it runs before the end of the answer — the text has already streamed; the turn's final frames (turn_committed, [DONE]) wait for the verdict, with a hard 2-second limit (measured judge latency p50 ≈ 1.1 s, p95 ≈ 1.4 s). On a buffered (PII-forced) turn the whole answer waits that long. No verdict in time — timeout, error, malformed answer — means nothing happens. After three consecutive judge timeouts or connection errors a gateway worker stops waiting for the judge for 60 seconds. The judge is not billed.
  3. What the verdict does (only when the judge says the answer claims a completed file action this turn, framed in the past or present — a verdict that marks a claim but calls it a promise or no file action contradicts itself and counts as no verdict):
    • The user asked for a change (create, change, convert or save a file): the gateway re-dials the model once, in the same answer, with a short instruction that no file was produced and with only the file tools (write_file, edit_file, read_file (only together with one of the others) and code_interpreter — those the turn offers; code_interpreter is for a file built with code, such as a deck or a spreadsheet) for the rest of the turn. On a "change this file and give it back" turn, which offers only edit_file and read_file, the re-dial offers exactly those and asks for the change with edit_file; a new version saved by edit_file counts as a produced file. The tool choice is not forced — if the answer did not really mean a file, the model can say so instead of writing. The re-dial runs inside the turn's tool-loop time budget (it needs ≥ 30 s left), needs a file-producing tool (write_file, edit_file or code_interpreter) offered on the request (a turn whose tools the gateway narrowed to something else, for example to the image tools, has nothing to write with: the answer gets the note instead; a promise gets nothing), happens at most once per turn, never after another recovery already re-drove the turn (the broken-promise or file-claim steer), and the re-dial's own answer is never judged again. It is a normal, billed model call of the turn and counts as one of the turn's continuations; like the broken-promise nudge, the first part of the answer ends with its own finish_reason chunk before the re-dial's text follows (the stream still ends with exactly one [DONE]). It is not attempted when fewer than two tool rounds remain, or when the answer part is empty. On a web-search answer the sources footer is written once, after the re-dial's text.
    • Otherwise (no change requested, the re-dial produced no file, or a re-dial was not possible — when the re-dial call itself fails with an error the turn shows, such as a prepaid wallet refusal, that error notice is shown instead): the answer is committed with the "No file was created" note — turn_committed.file_claim_badge = "no_file", persisted on the message (Conversations › No file was created). The note's Create it now button regenerates the answer with x-aig-regen-reason: fileNotCreated (see Regenerate-reason provenance): when — and only when — the regenerated answer's stored note says no_file, that regenerate is offered only the file tools and is forced to call one where the provider supports it — except when the badged answer was a "change this file and give it back" turn: then it gets that turn's own offer back (edit_file and read_file only, not forced). The header alone changes nothing. A regenerate on a turn that offers no file-producing tool (for example one narrowed to the image tools) is a plain regenerate: it is neither narrowed nor forced.
    • An answer written at a loop limit. When the turn reached its tool-round, time or repeated-failure limit, the closing answer (the final summary the gateway asks for) is judged too. Nothing can be dialled after it, so it is never re-dialled: a claim there gets the "No file was created" note, whether or not the user asked for a change. A promise there is left alone. The closing no-tools answer leg (the one followed by a recovery attempt) is not judged when it produced no visible text. An answer that ends at its length limit is not judged.
    • Nothing is ever written in any other case.

A promised write. The judge also reports whether the answer promises to write the file right now ("I'll write the file now.") and then stops without a tool call, and whether the answer waits for the user (it asks a question or hands the decision back). A promise the answer does not wait on, on a turn where the user asked for a change, gets the same single re-dial as a claim. A promise never gets the "No file was created" note — nothing was claimed. A reply that waits for the user, or a turn where the user asked for no change, is left alone. When an answer is both a claim and a promise, the claim rules decide.

A claimed tool run. A second, separate judge call reads the same answer and reports one thing: whether it says the assistant itself ran or checked something in the code sandbox in this reply ("I just checked the sandbox", "Ich habe die Sandbox gerade geprüft") — what the answer says, whatever the tool log shows. The call runs next to the file check, at the same time, so it adds no more than a fraction of a second to the end of the answer; it runs only when the same conditions hold that make the file check run (the answer mentions a file or a document name), the code interpreter is offered on the turn, no tool ran in the turn at all (the gateway's own tool calls, a refused or denied call included, a connector, a web search — the gateway's or the provider's own built-in one —, a tool the client ran and sent back, including the legacy function_call / function-role form and Anthropic server_tool_use / web_search_tool_result / mcp_tool_use / mcp_tool_result content parts; an unreadable tool record, such as message content sent as an object instead of a list, counts as "a tool ran"), and the leg is not the one that ends the turn at the loop limit. Reasoning over text you pasted or uploaded, a capability statement, an offer to check, a check reported from an earlier reply, and how-to instructions are not a tool claim. A file claim decides first and a promise next: an answer that is a file claim or a promise never takes this branch, and if the file check gives no verdict the sandbox verdict is not acted on either. Otherwise the turn gets the same single re-dial, narrowed to the code interpreter, with a steer to run the check for real or say that it did not; when the re-dial is not possible (too little time left) and the client is still connected, the answer gets one honest note appended instead (German, Danish, English; anything else English): "Note: no tool was run in this answer, so the check described above did not actually take place - its statements about the environment are unverified." The note is part of the stored answer. A tool claim never sets the "No file was created" badge, and a leg that ends the turn without text gets neither re-dial nor note. A failing or slow sandbox call never delays or changes the file check, and it has its own circuit breaker. The request log records it as aig_cc_sandbox_claim and aig_cc_tool_note.

A claimed change. A third judge call, again next to the file check and at the same time, reads the same answer and reports one thing: whether it lists requested edits to a file as applied in this reply ("I changed the title on slide 2 and fixed the date") — what the answer says, whatever the tool log shows. It runs under the same conditions as the file check and only when an edit tool (edit_office_file or edit_file) is offered on the turn. When it reports such a claim, the user asked for a change, the answer is not a promise and no file was changed or produced in the turn, the turn gets the same single re-dial, narrowed to the edit tools and not forced, with a steer to apply the changes for real or say that they were not applied; when the re-dial is not possible and the client is still connected, the answer gets one honest note appended instead (German, Danish, English; anything else English): "Note: no file was changed in this answer, so the changes listed above as done were not actually applied." The note is part of the stored answer. A change claim never sets the "No file was created" badge, never acts on a connector turn, and has its own circuit breaker; a failing or slow change call never delays or changes the file check. The request log records it as aig_cc_change_claim and aig_cc_change_note.

The check judges a turn that used a connector tool too (inline wait as above), but there only a promise is re-dialled: a connector may have saved a file elsewhere, so a claim on a connector turn never triggers the re-dial or the note. The check never runs for plain OpenAI-compatible clients, agent runs, the native Messages route, ghost chats or resumed turns. A tenant that disabled request logging is checked like any other (the judge is the gateway's own self-hosted model and keeps no prompt or answer text); for it nothing about the check is stored in the request log (request logs). Answers that are not judged inline (no file tools offered, a turn that produced a file, a judge timeout) are still judged after the response for the request log only, as before. Operators control it with two platform settings: claim_check_shadow_enabled (the whole check; off → nothing runs) and claim_check_actions_enabled (the re-dial and the note; off → the judge's verdict is only logged) — see settings. Verdicts and outcomes are in the request log's metadata (logs).

Judge response (trust boundary). The judge's answer is untrusted model output. It is accepted only as a chat-completion body (≤ 64 KiB) whose first choice's message.content (≤ 4 KiB) is a JSON object with exactly the keys claims_completed_file_action_this_turn, refers_to_upload, user_requested_change, reply_waits_for_user, promises_file_write_now (JSON booleans), tense (one of past, present, future, none) and confidence (a finite number in 0–1). Anything else — non-JSON, a missing or extra key, a string "true" or a number where a boolean is required, null, a tense outside the set, NaN/Infinity, a confidence outside 0–1, an oversized body — is rejected and recorded as "no verdict" with an error class; it is never turned into a default verdict. The sandbox judge's answer is held to the same limits and must be a JSON object with exactly one key, claims_sandbox_run_this_turn, a JSON boolean. The change judge's answer is held to the same limits and must be a JSON object with exactly one key, claims_changes_applied_this_turn, a JSON boolean; anything else is "no verdict" and nothing acts.

Conversation record (what earlier replies delivered, and which were stopped)

So that a later turn neither denies an image or file its earlier reply really produced nor imitates a reminder as its own speech, the gateway tells the model in the system prompt which earlier replies of the conversation delivered an output and which were stopped before they finished:

## Conversation record (from the gateway)
Facts about your earlier replies in this conversation, recorded by the gateway (not text):
- Your reply beginning "Hier ist dein grüner Haken als…" delivered 1 generated image(s), shown inline to the user.
- Your reply beginning "Fertig." delivered the downloadable file(s) results.csv (stored in this conversation's files - read_file opens them; the code sandbox does not contain them).
- Your reply beginning "Die Termine sind…" was stopped before it finished: it is incomplete, and any tool results it was based on are not in this conversation. Do not complete it from memory - if the user asks about its subject, call the tool again and answer from the new result.
  • Stopped replies. When the user presses Stop (or the connection ends) while a reply is still being written, the partial text is saved and marked as stopped (in a workspace conversation; in a ghost chat nothing is stored, so the web app marks the reply itself, see below). The tool results that partial was built from are never stored, so a later turn could otherwise present the partial as a finished answer and fill the gap from memory. The record therefore lists a stopped reply with the line above (anchored the same way); a reply that also delivered an output says so in the same line. A reply that ended in a failure keeps its own failure marker instead, and one that had already completed when the connection ended is not marked. Up to the 5 newest stopped replies are listed in addition to the 20 that delivered outputs, so repeated Stops never push a delivering reply out of the record. Regenerating the turn clears the mark. The connector notice in the system prompt adds that results of tool calls from earlier turns are not kept, so a detail that is not written in the conversation is fetched again by calling the tool.

  • Workspace conversations (x-aig-conv-id naming a saved conversation the requesting user may read — their own, or one shared in a project they are a member of, e.g. while driving a live room): the facts come from the database — the replies with a stored file card, a generated image or audio clip, or a ready video — never from the request. Up to the 20 newest such replies are listed (≤ 10 file names each, then "and N more"). A reply that a regenerate is replacing is not listed. Each entry is anchored by the opening words of that reply (cut at a word boundary, ≤ 40 bytes; control characters, square brackets, double quotes and backticks removed — except a whole PII masking token such as [MYRA-REDACT-PERSON:…], which keeps its brackets and is never cut in half). Anchors are stored conversation text and are PII-masked like every other stored piece of the composed prompt; file names are shown exactly as the prompt's file list shows them (their stand-ins when this turn masks file names); anchors that cannot be masked are left out (the counts and names are still listed). The record is appended after the other composed blocks; a conversation with no such reply gets none.

  • Ghost (unsaved) chats store nothing, so the web app sends the facts of its own replies in the x-aig-ghost-outputs request header and the gateway prefixes the latest user message with a one-line note in the same wording: [Gateway record, not written by the user. Outputs your earlier replies … delivered …]. The note is added as the last step before the model call (so it never steers the reply language or any other reading of the user's request) and is PII-masked there like every other stored piece; if masking is unavailable the note is left out — the turn proceeds. The web app also marks a reply the user stopped: the header item carries stopped: true, and the note then lists that reply with the same stopped wording as above. stopped must be JSON true (or false/absent); any other value makes the gateway ignore the whole header. Only the newest 80 items are read.
  • The turn's attached picture is staged for the code interpreter. The one picture attached to the latest user message is placed in the sandbox as /input/attached_image.png, .jpg or .webp (named by the file's magic bytes, not its declared type), ahead of the other inputs and counted within the 8-file and 16 MiB limits (a displaced file gets the usual cap note; the run is never aborted). It is read through the same turn reader as image edits: an unsaved request reads the request body; a saved conversation reads the stored message, where a co-driver gets inline pixels only and an uploaded file only the owner may open is not staged. A GIF, SVG or other type, a picture over 8 MiB, an unreadable one, or two or more pictures are not staged; the result then carries one note (once per turn) telling the model not to redraw the picture, and the run proceeds. On a ghost chat or a PII gateway without a fail-closed result mask nothing is staged and, if the message has a picture, the note says it is not available in the sandbox. A picture from an earlier turn is neither staged nor mentioned. Should a stageable file ever carry the name attached_image.* (case-insensitive), it keeps its name and the picture is not staged, with a log warning. The trace step input_files_staged reports image (0 or 1); the picture is not counted in its staged (data files only). When the model names the picture in input_files (or the code reads /input/attached_image.*) the result adds a one-line note saying what the file is; a list naming only the picture falls back to the /input/ references in the code like an absent list.
  • Ghost data files. A ghost chat cannot stage the raw attached file, so on a Workspace ghost turn (the same lane gate as x-aig-ghost-outputs, below) whose messages carry an inline data-file block the gateway removes the sentence that tells the model to load the file with code_interpreter from every such block (history included) and prefixes the latest user message with a second one-line note, [Gateway note, not written by the user. …]. The note says the chat stores nothing, so the sandbox input folder is empty for that reason, that this is not a fault, and that the model must not call it a technical or transfer problem or ask for a re-upload; it points to a regular chat for whole-file analysis (naming the per-file limit) or says whole-file analysis is not available on the gateway. It names no file and is PII-masked like the outputs note. This step does not need the x-aig-ghost-outputs header and a malformed header does not suppress it. A code_interpreter result on such a turn carries the same reason (once per turn, also for code that names no file), and the document tools' errors for such a turn state it in their own words. A saved conversation is unchanged.
  • Code-interpreter results carry the same fact (Workspace conversations only, not ghost chats). An empty sandbox probe (os.listdir("/output"), os.path.exists("results.csv")) used to beat the record, and the model denied its own file. A code_interpreter result now appends one gateway note (inside the untrusted-result frame) when the record lists stored files that the run did not stage, save or deliver (a file the run asked for but could not stage stays listed, without a how-to). It names them (up to 10, newest reply first, in the record's own sanitised form; matching against the run's names is case-insensitive in that same form) and says they are stored in the conversation's files, separate from the sandbox, and that not finding one there does not mean it was not created. A staging how-to (input_files → /input/<name>) is added only for the conversation's owner, only where staging is allowed (code interpreter available, a saved conversation, and on a PII gateway a fail-closed result mask), not when the run's own not-found note already gave it, and only for names that can be staged as shown and as stored: a stageable file type whose name the record shows unchanged (a name with [, ], " or a backtick, or longer than 120 bytes, is listed but not offered — the gateway's own file stand-ins on a name-masking turn are shown whole and stage as such), and — for a file written as text by write_file / edit_file — a text type (a write_file "plan.docx" is Markdown rendered at download and cannot be staged as .docx, so it is listed but not offered). Names are double-quoted; two stored names differing only in case are listed once. A project member driving a shared conversation gets the names without the how-to.
  • Nothing about earlier outputs is ever written into an assistant message, and the gateway no longer removes such notes from answers: stored answers were cleaned once (migration 0454, with a 30-day follow-up sweep of newer rows by the daily retention job). The cleanup matches the notes' exact, case-sensitive wording only; a stored answer with more than 64 note openings is left as it is.

x-aig-ghost-outputs (trust boundary). Honoured only on a Workspace ghost turn (x-aig-conv-id: ghost-… present, a signed-in user, a chat-completions body); ignored on every other request. Accepted shape: one header value, ≤ 6,000 characters, base64url (no padding needed) of a JSON array of objects { "i": <1-based position of the assistant message in this request>, "images": n, "audios": n, "videos": n, "files": [names], "ephemeral": [names], "stopped": true } (stopped optional: the user stopped that reply before it finished; the note then says the reply is incomplete); round_limit optional: the reply ended at the per-turn tool-round limit, so the note says the reply stopped there and can be continued. round_limit is accepted only as JSON true or false; any other value rejects the header (bad_round_limit). Only the newest 80 items are read. Rejected (the header is ignored, the turn proceeds unchanged — absent and malformed both mean "no note", which grants nothing): a repeated header, an empty value, a longer value, characters outside the base64url alphabet, an undecodable value, JSON that is not an array or is empty, an item that is not an object (a scalar or an array), an item whose stopped is present with any value other than JSON true or false. Inside an accepted item, a wrong-typed count or name field reads as nothing (0 / no names); counts are clamped to 0–64; at most 10 names are kept per list, each sanitised (control characters, square brackets, double quotes and backticks removed; whole masking tokens kept) and at most 120 bytes (a longer single-word name is cut and marked with "…"); an i that names no assistant message gives an entry without an anchor. The anchor is always read from the request's own assistant message, never from the header. A gateway release that predates this header ignores it; a browser whose request is refused at the CORS preflight by such a gateway retries once without it — only when the refusal comes within 3 seconds of sending (a later failure may be a dropped connection on a turn that is already running, which is never re-sent) and never after the user pressed Stop. When the gateway had to compact the turn's history to fit the model (older turns replaced by a summary), the positions i no longer match the messages, so the note's entries carry no anchors ("An earlier reply delivered …").

Image-claim check

A reply on a Workspace turn that says an image was generated, edited or is shown — although the turn produced none ("Here is your illustration:" with nothing behind it) is caught by the image arm of the file-claim check. What arms the check is evidence in the reply (an image link, a "here is the image" presentation (the existing generic pre-filter) or a reassurance phrase); no word list over the user's text decides whether the reply is looked at, so a request that names no image ("Create three variants of a lighthouse at sunset") is covered. The judge reads the request:

  • When (judge path): the turn produced no deliverable at all (no image, no file, no chart), used no connector tool, and the reply passes the image pre-filter — an image noun as a whole word or the head of a compound ("Titelbild"), or a reply of this conversation that delivered an image (the conversation record's facts), and a presentation or completion cue ("hier ist", "here is", "yeh raha", "her er", "generiert", "created", …). A reply that states a document file (a file noun plus a creation or saving verb, a document filename, or a file placeholder) stays with the file arm. Only statements count: a file mentioned only in a question sentence ("or should I save it as a file?") is ignored when choosing the arm, because a question claims nothing. Residuals: a claim phrased as a question is dropped too, and a URL ending in ? or a question in parentheses ("(right?)") followed by whitespace cuts the sentence there. One judge per turn — the image arm or the file arm, never both.
  • Routing details (which arm). An uploaded image counts as the user's image intent, never as a user file for the file arm; a document attachment still does. When the conversation holds a delivered image, short noun-less completion phrases also count as the presentation cue — "is now" / "are now", "ist jetzt" / "sind jetzt", "er nu", "added to the image", "added to the picture", "zum Bild hinzugefügt", "ins Bild eingefügt", "tilføjet til billedet", and a sentence-initial "Done —" / "Fertig:" / "Færdig," (anchored, followed by a dash, colon, comma or "!", so "I'm done with the summary" does not match). They are never consulted without that conversation fact. A noun-less reply that also names a file action goes to the image arm only when the user uploaded an image, asked for image generation in so many words, or the reply the user is answering (the newest finished assistant reply before their message, not an older one) itself delivered an image — a follow-up edit of the picture you just received; otherwise it stays with the file arm. So after a reply that delivered an image, a noun-less claim is judged on the image arm even when the request was textual. That last fact is read in the same query as the conversation record, so it costs no extra lookup and is absent when no record is available.
  • Judge: the same self-hosted judge, deadline and data blocks as the file arm, with its own question and its own breaker — plus one more data block: the end (at most 1200 bytes) of the assistant reply right before the user's message, when there is one (string content, or its text parts). So a short "continue" / "weiter" that accepts an offer there to make more images — the hand-off of the per-reply media limit — counts as an image request, and a reply that then claims "here are the last two" without a tool call is re-dialled. The block is client-supplied history: fenced and defanged like every data block; absent or not text → no block.
  • Action: when the judge says the reply claims an image shown or produced this turn (past or present framing) and the user asked for an image, the model is re-dialled once in the same answer with only generate_image and an instruction that no image was shown. It may call the tool, or say in one sentence that no image was produced. The re-dial follows the file arm's rules (time budget, at most once per turn, never after another recovery re-drove the turn, its own answer is never judged). A chart, plot or diagram of the user's data (their numbers, a file they gave, or data already in the conversation) is not an image request for the judge, even when the user calls it a "Grafik" or "image", so it never triggers this re-dial: a data chart is not drawn by generate_image. A picture that only looks like a chart (a poster in the style of a bar chart) is still an image request.
  • The "Image not produced" record (image_claim_badge). The same claimed verdict (past or present framing, from the judge only - never from the deterministic note or the "it is in the chat" phrase gate on its own) is also recorded on the turn: when the committed answer is a normal answer and the turn ended with no image, no image note, no deliverable and no tool that ran, the turn is committed with turn_committed.image_claim_badge = "no_image", persisted on the message (Conversations › Image not produced). This also covers a turn that offered no generate_image (an advice reply that still speaks as if it showed a picture): that turn is judged and recorded, but never re-dialled, because the model has no image tool to retry with. A turn on which any tool ran (a web search of either kind included) never gets the record (and when that turn did not offer generate_image, it is not judged at all). The web app shows the notice The assistant referred to an image, but none was produced. from this record alone; it has no word list of its own. A turn the judge did not call claimed, or did not answer in time, carries no record and no notice.
  • Image Markdown in a reply is never an image. An ![alt](address) in assistant reply text (model-written or a saved correction) is shown to the user as its alt text (or a neutral placeholder) and never loaded, whatever the address, in the chat and on a shared-conversation page; only a generated image (an image card) is a delivered image. Other Markdown surfaces (document previews etc.) load same-origin images and show external images as inert text. The web app adds no notice of its own for such a reply. The gateway's deterministic honest note (next bullet) covers the address forms it matches (https://…, //…, sandbox:…, data:image…) under that bullet's conditions. A relative file name (image1.png) or an attachment: address gets no fixed note: such a reply goes to the image judge instead (see the "relative or attachment: image link" bullet below).
  • Deterministic honest note (no judge, no re-dial) — fabricated image link only. Before the judge, a rule-based guard looks at the first 300 characters (of at most the first 4 KB) of the reply that ends the turn. Only one class gets the fixed note without a judge: a fabricated image link — ![](https://…), ![](sandbox:…), ![](data:image…) (each also in the <…> form) (a bare HTML <img> tag is not flagged). It acts only when the turn produced nothing, the image backend is not busy, the user's own text names an image (or a drawing request) or carries an uploaded image or the conversation already holds an image — a bare noun ("list the docker images", "check my photos") does not count — and no tool ran this turn, the turn is not a resumed one and no connector was used (a search, fetch or connector result may legitimately carry image links, and an earlier request may already have produced the image). A malformed internal state (an unreadable busy flag or tool record) means no note. The action is one honest note appended to the answer (the claim itself is already on the wire and cannot be retracted), in the language of the request (German, Danish, English; anything else English): "I did not actually produce an image in that reply …", or, when the conversation already holds an image, the same plus "I will not silently work on an older image — please tell me which image to change". The note is part of the stored answer, so a reload shows exactly what was streamed. Nothing is generated and no tool is forced. Never flagged (exemptions): a reply that states plainly it cannot / did not make the image (a refusal stands), alt-text and accessibility answers, a how-to / explain question, README badges, code blocks (fenced with `` or ~~~, inline, or indented), markdown the user wrote themselves, an image URL the user pasted that the reply echoes back as markdown (only when every image URL in the reply is one the user wrote, each matched as the exact, complete URL - a URL that is only the start of a longer one the user wrote still gets the note; a URL the user never supplied still gets the note), and "show the earlier image again" (also "von vorhin"). This exemption applies only when the conversation already holds a gateway-produced image, the request contains a re-display verb (show*, display*, send, resend, where is / where's / where are, visible, zeig*, anzeig*, schick*, sichtbar, wo ist / wo sind, vis / vise / viser, hvor er, synlig) together with an again-marker, and the request carries no generation intent. With no gateway image in the conversation there is nothing to re-show, and a bare retry or edit like "nochmal, aber in blau" or "try again" also gets the note. A request to generate or draw an image that merely contains "again" / "nochmal" (a retry, e.g. "generate the image again") is a generation request, not a re-show, so a markdown image without a produced image still gets the note. The same holds when the image is a placeholder in a requested text document (README, newsletter, blog post): the link is not one the gateway created, so it gets the note too. Accepted residuals (each costs at most one missing honest note or one skipped judge run, i.e. a missed re-dial): the alt-text / badge exemptions match anywhere in the reply head ("an accessible entrance", "your badge image"). When the user's text has no image request, no uploaded image and the conversation holds no earlier image, the same link does not get the fixed note: it goes to the image judge instead (as the relative link below), which reads the request; only aclaimed` verdict for a request that asked for an image leads to the re-dial, anything else does nothing. The generic claim ("here is …") is not acted on by the guard; it stays with the judge above (also when the judge is unavailable).
  • The "it is in the chat" phrase class goes to the judge, not to a note. A reply that says the picture exists "directly in the chat" / "added directly to the image above" / "the complete set of N images" (recognised in English and German, e.g. "im Bild oben eingefügt", "added directly to the picture") used to get the fixed note on a phrase match alone. A phrase match cannot tell a claim from a negation ("was not added directly to the picture because I cannot edit images"), a question ("Would you like the cat added directly …?") or a conditional, and it appended a wrong note to correct, honest answers. The phrase now only selects the turn for the inline image judge (the turn produced nothing and no tool ran; no make or change verb in the user's text is needed — the judge reads the request). The judge's verdict decides: claimed gives the ordinary single image re-dial; not_claimed, no verdict (timeout, malformed answer, breaker open) or anything else gives nothing — the turn fails closed and no note is appended. The log row carries aig_ic_prefilter = "phrase", the judge's keys and aig_ic_action, and no aig_ic_det. Danish "it is in the chat" / "added to the image" phrases are not recognised yet.
  • A relative or attachment: image link goes to the judge, not to a note. A model-written ![alt](address) whose address is an attachment: id or has no scheme at all (![](image1.png), ![](./a/b.png), ![](attachment:…), also in the <…> form) cannot be told apart by rule from an honest reference (a README example, a description of a picture the user uploaded, a link to a document in the conversation). Such a link in the first 300 characters of the reply therefore only selects the turn for the inline image judge, when the turn produced nothing, no tool ran and the image backend is not busy. The user's text does not have to name an image: the judge reads the request. A reply that names a file, a document file name or a file type (also "Dateien", "image file"), or a turn whose user ATTACHED a document (or typed a document file name), goes to the file check instead (file-specific evidence). Accepted residual: a request for a document ("Write a report on Q3", "Make a slide deck") whose reply only shows an image link next to a bare "created / saved / written" verb ("I've written the report and saved it: Revenue") is judged by the image judge, not by the file check; it is re-dialled only if the user asked for an image. A bare make or update verb next to an image link ("Ich habe es aktualisiert: Diagramm") is not file-specific: the image judge decides, and a file claim in that same reply is not judged by the file check. claimed gives the ordinary single image re-dial; not_claimed, no verdict or anything else gives nothing: the turn fails closed and no note is appended. A reply that also says it cannot make the image is still judged. A requested document that itself names an image ("a README with a logo", "a landing page with a hero image") whose reply shows only a placeholder link may be judged claimed (the judge reads the wording of the reply) and then gets that one re-dial, so the image is actually made; either way it never gets a note. A document request that names no image ("a README for my tool") whose reply carries a placeholder is judged too; the judge's reading of the request decides (a README placeholder is not an image request), so nothing happens (unless the reply names a file or document, which sends it to the file check instead). Accepted residual: a prose-only claim with no image word, link or phrase in the reply is not judged. A reference-style image (![Katze][1] with [1]: katze.png) is an accepted residual: it is not recognised and gets neither the judge nor a note. Examples in code blocks and any other scheme (https:, mailto:, file:) are not affected by this class. The log row carries aig_ic_prefilter = "link" (also for an https: / sandbox: / data:image link on a request that did not name an image), the judge's keys and aig_ic_action, and no aig_ic_det.
  • Not checked: private (ghost) chats, and any turn outside the Workspace chat lane.
  • Switch: platform setting claim_check_image_actions_enabled (settings) — independent of the file arm's switches. Outcomes are in the request log's metadata (aig_ic_*, logs).

  • After a file re-dial (no judge). The answer of a file-arm re-dial, or of the "Create it now" click leg, is never judged. But the leg's own text gets the deterministic fabricated-image-link check as above (the "it is in the chat" phrase class gets no note here: it needs a judge, and this leg is never judged), checked on that leg's text only and only when the turn offered generate_image on its original request. A hit appends the same honest note, once per turn, and the stored message equals what was streamed. The turn's log row then carries both the file-arm keys and the image keys, with aig_ic_after_redial set. The re-dial leg's own "no file was created" admission does not silence the note (the file question is settled by the re-dial); the other suppressors (a tool ran, an image was produced) still do. A blank, cut or failed leg gets no note, and the image arm's own re-dial is not checked again.

Unverified URLs in the answer. On a request that carries a client-asserted conversation (the x-aig-conv-id header, a ghost conversation, or an unusable id), every http(s):// / www. URL the model writes into the visible answer is checked at the end of the turn against what the conversation saw: user text, tool results, persisted sources and the gateway's own citations. A URL that was never seen is made non-clickable and followed by the label (unverified link) ((nicht verifizierter Link) in a German answer): a bare URL is shown inside a code span, a Markdown link [text](url) loses its target, and an image ![alt](url) with an unknown URL is rendered inert too. Code blocks and inline code are left alone. Streaming is unchanged: the answer is streamed as the model writes it. When the finished answer contains at least one unverified URL, the gateway sends one SSE frame {"aig_status":"answer_replace","turn_id":"…","content":"…"} carrying the whole marked answer, before turn_committed (or persist_failed); a client that applies it replaces the streamed text. The frame is additive (no aig_schema change), is sent only on a server-owned turn, and is not sent for a turn that ended in an error or whose client disconnected. answer_replace is an aig_* extension frame: a client receives it only when it opted into the extension channel (x-aig-turn-id or x-aig-extensions). The marked text is what is stored, so a reload shows the marked answer. A buffered (stream:false) response carries the marked text directly, in the message of every choice (n > 1).

Two gates decide whether a response is checked at all, and they are independent: (a) only OpenAI-compatible requests are checked; the native /anthropic passthrough never is, even with the conversation header; (b) only conversation requests are checked (x-aig-conv-id or the web UI). Anything outside both gates is passed through byte for byte.

Image judge response (trust boundary). Accepted only as a chat-completion body (≤ 64 KiB) whose first choice's message.content (≤ 4 KiB) is a JSON object with exactly the keys claims_image_shown_this_turn, user_requested_image (JSON booleans), tense (past, present, future, none) and confidence (0–1). Anything else — including a file-arm answer — is "no verdict" and nothing happens.

Workspace capabilities (what this chat can do)

So that the assistant neither denies a feature this workspace has (for example "there is no Playground" or "I can't search the web") nor offers one it does not have, the gateway adds a short, generated list to the system prompt of every chat turn in the web app:

## What you can do in this chat
From this workspace's live settings. Answer capability questions from it: never deny an item marked available, never offer one marked not available.
- Word/PDF/PowerPoint/Excel files: available (delivery rules above)
- Run Python code (calculations, charts): available
- Edit a copy of a PowerPoint/Word/PDF/Excel file: available
- Create images and edit the user's images: not available here
- Cut out an image's background: not available here
- Create short videos: not available here
- Open web links the user pastes: available
- Web search: switched in the + menu of the message box; when on, you have a web search tool
- Voice: microphone button in the message box (speech to text), Read aloud on replies: available
- Workspace areas: Playground (/playground, compare models): available; Agents (/agents): available; Workflows (/workflows): not in this workspace's plan

Nothing in the list is maintained by hand. Each line comes from the same check that decides whether the feature is actually offered:

Line Decided by
Word/PDF/PowerPoint/Excel files always available in the web chat: every answer has the Download menu (and the code sandbox or write_file where offered) — how to deliver is in the prompt's delivery rules
Python sandbox, edit an existing PowerPoint/Word/PDF/Excel file the same availability the code interpreter and edit_office_file tools are offered under
Images, background removal, videos the gateway's image / video generation settings, the platform switches, and the project's access tier — exactly as the tools are offered. While image editing is available, the background cut-out line is shown only when the cut-out tool is on (image editing can change a background, so "cut-out: not available" would read as a denial of that)
Links the egress rule that offers fetch_url (blocked in a local-only project)
Web search only for models served by the Myra fleet (whose search is the gateway's own web_search tool): not available when the gateway has no search set up or the project is local-only; on every message when the gateway's web search mode is always; otherwise the Web search switch in the message box's + menu
Voice whether the speech service behind dictation and Read aloud is configured; if its settings cannot be read at that moment, the line is left out (never "not available" because of a read error). On a spoken voice turn the capability block omits this line
Connector setup whether the assistant may offer to set up a connector (the setup_connector tool). On a spoken voice turn the capability block reports connector setup as not available (the tool is not offered there: a voice conversation does not use connectors)
Workspace areas the tenant's plan: Playground and Agents follow the tenant's feature switches; Workflows also needs the user's workflow-author permission. A permission lookup that fails leaves the role part out ("in this workspace's plan") instead of saying no. The tenant is the one that owns the gateway the turn runs on (for a platform administrator chatting on another tenant's gateway, that tenant's plan). If the tenant row cannot be read, there is no area line
  • Only in the web app's chat. The list is added when the request carries x-aig-mcp-best-effort: 1 (the chat surface's marker); an API call with x-aig-conv-id alone gets no list, because the list refers to buttons in the app.
  • Tool lines only when tools can reach the model. When the model's provider has no tool loop, the client brought its own tools or declined tools, the model cannot use tools at all, or the web-search step answers the turn itself (a provider without reliable chat web search with search switched on, or an OpenAI-style / Mistral model whose turn the gateway's tool loop cannot take — normally it does, see web search beside the other tools), the tool lines are left out — neither claimed nor denied.
  • When the backend later refuses the gateway's tools (the automatic retry without tools), the list is rebuilt without its tool lines.
  • Multiple attached images. When the user's latest message carries two or more images, one last line states the count and that the image tools never pick one of them (edit, animate, cut out, combine, or carry something from one onto another). The model raises the limit only when the user asks for one of those, and otherwise says nothing about it; anything else about the images works as usual.
  • Size: at most 1000 bytes (about 250 tokens) for the standing list; the multi-image line (at most 770 bytes) comes on top.

The product description in the system prompt no longer names optional features (web search, image and video generation, Agents, Workflows) as present; it says they depend on the workspace's plan and settings, and the list says which are on.

Models that cannot use tools

For a model the gateway knows cannot call tools, the gateway removes every built-in tool from the request. The system prompt then no longer describes the code sandbox, file saving or any other tool, the project's file list is left out (its files can only be opened with those tools — the project's own instructions stay), and the prompt says plainly:

## Tools on this turn

The model serving this turn cannot use tools, so the gateway offers none of its tools: no code sandbox, no file saving, no image or video generation. This also applies where a note in the conversation (for example under an attached file) mentions a tool. No gateway tool is callable on this turn — if this prompt names another one, you cannot call that either. Everything else this prompt tells you (your instructions, how to format, what the user asked for) still applies.

Notes elsewhere in the conversation that mention a tool — for example the note under an attached data file that points to code_interpreter — are covered by the same notice. A large data file attached on such a turn is not shortened to a preview with a "the full file is available to code_interpreter" note; it is only trimmed if it does not fit the model's context window. This does not apply on a gateway that enforces EU data residency: there the tools are not removed up front. For today's tool-less models (Perplexity Sonar through OpenRouter) such a turn is refused before dispatch with data_residency_blocked; otherwise it is handled as described for model_capability_mismatch.

Client tools per provider

Client tools (and the legacy functions / function_call) are never silently dropped. A provider either carries them or the request is refused with 400 invalid_request before any upstream call.

Provider tools legacy functions / function_call
OpenAI-compatible providers (OpenAI, Myra, Mistral, and the like) forwarded forwarded
Anthropic forwarded refused
Gemini, Vertex, Bedrock, Cohere refused refused

tool_choice does not change this, including "none". A web-search marker in tools (an entry with name: "web_search", no function key, no parameters key, and type absent or a string starting with web_search; so {name, description, input_schema} and type: "web_search_20250305" count) is not a client tool on Gemini and Vertex only: the provider's grounding consumes it and the request is served. On Bedrock and Cohere the same entry is refused like any other client tool. A configured fallback to a provider that carries tools still serves the turn. When the gateway would have added a web search to a refused request, the turn reports the search as not run with the reason client_tools.

Your own tools on a web-search turn

A request can carry its own function tools and ask for a web search (X-AIG-Web-Search: 1, or a gateway in always mode). Your tools are not hidden by the search:

  • The first model call offers your tools beside the gateway's web_search tool.
  • After the search, the second model call offers your tools again and no longer offers web_search. It is never pinned to tool_choice: "none", so the model can call your tool with the search results in hand.
  • A tool_choice you sent is kept on the second call, unless it forced a specific tool (required or a named function). That forcing choice applies to the first call only.
  • If the model calls your tool and web_search in the same first reply, the search is run and the model is asked again with the results. The conversation replays only the gateway's own search calls, each with exactly one result.
  • The number of web_search calls the gateway takes from one model reply is capped at web_search.max_searches_per_turn (default 8, never more than 999); further calls in that reply are dropped and the drop is logged once. Every call the gateway replays carries a unique id: the id the model gave is kept when it is 1 to 128 characters of letters, digits, _ or - and not already used in that reply; otherwise (empty, longer than 128, other characters, a repeat) the gateway issues its own aigws0001-style id.
  • The gateway's search_knowledge tool is capped per answer at knowledge.max_searches_per_turn (default 12). Past the cap the tool is no longer offered, and a call that still arrives is answered with a gateway notice instead of passages. A search that returns only passages an earlier search of the same answer already returned carries a note that nothing new was found.

The response you receive is an ordinary tool call (finish_reason: "tool_calls") for your function. Run it and send the result back as usual.

Which search runs beside your tools depends on the provider's web-search mechanism (listed per provider under Web search); the request must be a chat completions call. The cases this section changes:

  • Myra models (Qwen, Gemma on vLLM): the gateway's search runs as described above.
  • OpenRouter with a forced gateway search (an EU search provider is configured, or the gateway's data-residency floor is armed): the gateway's search runs as described above.
  • Anthropic with a forced gateway search: no search runs, your tools are passed through unchanged, and the response says so (below).

A run that has processed untrusted outside content runs no search beside your tools on any provider that supports web search, and the response says so.

Providers whose own search runs server-side (Anthropic and OpenRouter without a forced gateway search) keep doing so beside your tools, within that provider's own limits (for example an Anthropic model without native web-search support gets none). On Gemini and Vertex client tools are refused, so no search runs beside them (see Client tools per provider). Providers listed as not supported refuse a search request with web_search_not_supported.

When a requested search could not run, the turn still proceeds and the response carries the header X-AIG-Web-Search-Notice: not_run (also readable by a browser client through CORS). The request log of that turn records the reason in meta.aig_web_search_not_run. The header is never sent when the search ran or was not requested. Every case and reason is listed under When a requested search cannot run.

Streaming

Set "stream": true to receive an SSE response. The gateway emits OpenAI-shaped chunks and terminates the stream with a data: [DONE] sentinel.

data: {"id":"...","object":"chat.completion.chunk","created":1753718400,"model":"...","choices":[{"delta":{"content":"Hello"},"finish_reason":null}]}

data: {"id":"...","object":"chat.completion.chunk","created":1753718400,"model":"...","choices":[],"usage":{"prompt_tokens":676,"completion_tokens":127,"total_tokens":803}}

data: [DONE]

What a plain client receives

A plain OpenAI-compatible client is one that sends neither x-aig-turn-id nor x-aig-extensions: 1. Every data: frame it receives is either [DONE] or a JSON object carrying choices (an array — empty on the final usage chunk) or an error object. Nothing else. This is a hard contract: clients that validate each chunk against the OpenAI schema (the Vercel AI SDK's @ai-sdk/openai-compatible provider and everything built on it) abort the stream on the first non-conforming frame.

The gateway's own aig_* extension frames — aig_status (all values, including thinking), aig_tool_call, aig_tool_input, aig_sources — are suppressed for such a client. They are a first-party side channel for the chat UI, described throughout this page; a client opts into them explicitly:

Signal Who sends it Effect
x-aig-turn-id: <id> the chat UI, every turn turn ownership and the side channel
x-aig-detach-on-drop: 1 the chat UI, on a turn-owned stream a dropped connection does not abort the turn; it finishes and is saved (see "Client disconnects" above). Anything but exactly 1 is ignored
x-aig-extensions: 1 a first-party client with no turn (agent Try-It, the playground) the side channel only
x-aig-voice-lang: <lang> gateway-internal: the voice session's own loopback call (not for browsers, not in CORS) marks a spoken turn: voice persona, reply language, answered by the tenant's local model (with a well-formed x-aig-conv-id a cloud model is replaced for the turn by the gateway's local Auto pick, a provider-qualified pin is overridden, and the replaced model is recorded in the request log meta as aig_voice_model_from; the id is checked for format only, and the swap only ever moves to the gateway's own local model; without it nothing is replaced and a cloud model is refused with 403 voice_model_not_local; 403 voice_model_not_local when no local model could be used (the gateway has none, or a transient routing fault; see error codes); in a Local only or tier-unresolved project the project's own refusal answers instead), non-local fallbacks removed, never cached; a malformed value is 400 invalid_voice_lang (Voice conversation). Together with x-aig-parent-msg-id the parent user message must exist when the answer is stored: if it does not, no streaming claim is written, no answer is stored and one soft-deleted marker row is left instead (Speculative answer start). The same check runs before the first gateway tool of the turn: if the parent user message does not exist yet, no tool runs and the turn ends with the marker row, so a cancelled speculative answer never has a side effect. An external caller that sends it gets a local-model-only turn, never cached, with the voice persona when the request names its conversation with x-aig-conv-id: with a valid conversation binding a cloud model is replaced by the gateway's local pick, and without one a cloud model is refused with 403 voice_model_not_local

Accepted values for x-aig-extensions are 1, true, yes, on — matched exactly, so TRUE and On do not count. Any other value is legal to send and is treated as absent (fail closed): 0, an empty value, an unknown word, a non-string, or a repeated header whose first value is not one of the four. The stream then stays pure OpenAI.

Replay record: the conversation's attachments

The turn replay record lists the files attached to the conversation named by x-aig-conv-id. The header is client-supplied and is never trusted as a grant: the list is read only for the conversation's owner (or its current co-driver) in the gateway's own tenant, for the user row named by x-aig-parent-msg-id. A conversation of another user or tenant, an unknown or unusable id (a repeated or malformed header) and a parent message that is not a live user message of that conversation each record no attachments, with a status that says why (turn_row_bad, conversation_id_unusable, …) — never an empty list that reads as "no files".

A turn whose x-aig-conv-id names no live conversation (unknown, deleted, or deleted while the turn was still being answered) is served as usual, but no replay record is stored for it.

Turn persistence is tenant-fenced

A turn-owning request (x-aig-turn-id) that also names a Workspace conversation with x-aig-conv-id has its assistant answer persisted into that conversation. Both headers are client-supplied, so the conversation named by x-aig-conv-id is not trusted as an authorization grant: a conversation is pinned to the tenant of the gateway that owns it, and the gateway persists an answer into it only when that conversation belongs to the same tenant as the gateway the request routed through (the tenant is derived server-side from the gateway, never from the request body or a header).

  • Accepted — the conversation is in the caller's tenant. This includes a conversation reached through a different gateway of the same tenant (a platform admin routing across the tenant's gateways); the answer persists normally.
  • Rejected — the conversation belongs to another tenant. The turn still runs and the answer is returned to the caller (it was a legitimate request on the caller's own budget), but nothing is written into the foreign conversation: no assistant message and no streaming placeholder row. From the caller's tenant that conversation does not exist, so the gateway treats it as a ghost — no error status, the answer simply is not saved anywhere the other tenant can see. This closes a cross-tenant write (an attacker cannot inject a chosen answer, or a stalling placeholder, into someone else's thread).

Within a tenant, a second check — the same write-permission rule the Workspace UI applies — decides whether the answer is saved into the named conversation:

  • Accepted — the caller is the conversation's owner, or a member of the project it is shared into who currently holds the live-driver turn (the collaborative co-editing lock). This also covers a server-produced artifact (an image or generated file) persisted under an absent or non-conforming turn id.
  • Rejected — a same-tenant conversation the caller may not write: not the owner and not the current driver (for example a read-only shared member, or someone with no access at all). As with the cross-tenant case the answer is still returned but nothing is written — no assistant message and no streaming placeholder — so an attacker cannot inject an answer into, or stall the reload of, a colleague's private (or read-only) conversation.
  • A service token with no user identity persists into no conversation on this path.
  • The driver lock is evaluated at the start of the turn (when the placeholder is claimed), not re-evaluated at save time — so a long-running turn whose lock lapses mid-answer is still saved, never dropped. A transient database error while checking permission is surfaced as a retryable failure (the answer is reported as not-yet-saved), never silently discarded.

Consequences worth planning for as a plain client:

  • Errors arrive as frames, not statuses, once the stream is open. A failure detected after the response head is committed is delivered as data: {"error":{"message":"…","type":"gateway_error","code":"<code>","param":null}} followed by [DONE] on an HTTP 200 — the full official OpenAI error shape (message, type, code, and the nullable param; the gateway never attributes an error to a request parameter, so param is always null). Before the head is committed a failure is still an ordinary HTTP error response. The terminal chunk of such a stream stays inside the finish_reason enum (stop), so treat the error frame, not the terminal, as the failure signal.
  • A long reasoning or tool phase carries no data: frames. The thinking frames that used to fill those gaps are extension frames. To keep the connection alive the gateway writes an SSE comment line (: hb) after 15 s of silence — never while content is flowing. This also covers a turn whose answer the gateway holds back until it has been checked (a response guardrail, a slow PII scan, or a server-side web search): the connection carries a comment at least every 16 s (the 15 s interval plus at most 1 s of scheduling slack) while the answer is withheld, and the answer follows as ordinary frames. Because those comments commit the 200 response head early, a non-2xx status for a failure that happens after the first comment is not available on such a turn; the failure arrives as an in-band error frame instead (see above). On a server-side web-search turn X-AIG-Provider and X-AIG-Model are still sent, because the gateway sets them before the first comment can commit the head; headers that depend on the outcome of the later legs are not. On the /easy chat (the gateway's own web app) the keepalive covers only these held-back phases, never a live stream: once the answer streams, silence is left visible so a stalled stream is detected. A turn-owned stream (one that carries x-aig-turn-id and a conversation id) gets a stream_start data frame before its first : hb once the gateway has claimed the turn; a plain client, without a turn id, gets no such frame. During a slow PII scan the first comment can come before the turn is claimed: a client that polls by turn id may read none that early and should re-send; the gateway still runs one turn. A comment is ignored by every conformant SSE reader (EventSource, @ai-sdk/openai-compatible, openai-python); a reader that JSON.parses whole blocks instead of following the SSE framing must skip lines that do not start with data:.
  • Exactly one data: [DONE]. The stream is terminated once; nothing follows it.
  • Exactly one non-null finish_reason — even across a server-side tool loop. When the gateway runs a tool for you (an MCP connector, web search, the code interpreter, file writes), it may call the model several times in one response. Only the final leg's terminal reaches the wire; the intermediate finish_reason: "tool_calls" legs, where the gateway executes the tool and continues, are suppressed. So a client that treats the first non-null finish_reason as the end of the turn still gets the whole answer. Server-side tool execution is the only thing that runs several legs for a plain client. The same holds for every other re-dial inside one turn — the file-claim re-dial, the broken-promise steer, the reasoning-cut recovery and the length-cap auto-continue: the leg that is followed by another leg does not stream its finish_reason, so the turn carries exactly one. An auto-continued long answer therefore ends with a single stop (the intermediate length is no longer streamed); if the continuation call cannot be made, the stream still ends with one finish_reason. The same holds when the loop ends on a budget stop (token budget, wall-clock, repeated identical calls, or the round limit): the closing answer the gateway has the model write from the gathered results emits no finish_reason of its own, and the stream carries exactly one, stop, after the stop note. The one exception is the compaction re-dial after the round limit: it keeps its own single finish_reason, which may be length (see the length-cap section below). A loop the gateway stopped ends with stop — on the stream, in the stream: false body and in turn_committed.finish_reason — even when the closing answer was cut (length) or filtered (content_filter) by the provider; the stop note says why. The one exception is a stream: false body the gateway delivers unchanged (a structured-output body, or one carrying a number it cannot re-encode exactly, see the number note above): it keeps the model's own terminal and gets no stop note. This is distinct from a turn where you supplied the tools (tools in the request body): there the gateway forwards finish_reason: "tool_calls" to you as the legitimate, single terminal — you run the tool and continue the conversation with a new request. The reverse holds too: a tool call the gateway executes itself (an MCP connector, the code interpreter, web search) is never forwarded to you as delta.tool_calls (nor as message.tool_calls or a tool_use block when buffered), and a turn that ends on one finishes with stop (end_turn on the native surface), so a client never sees a call it did not offer and cannot answer. This holds when you force a named tool too: the provider then ends with stop, and the gateway still forwards the call with finish_reason: "tool_calls".
  • A wallet-capped answer ends with finish_reason: "length". On a self-serve workspace past its allowance, each model call reserves its share of the prepaid wallet before it is sent; when the free balance pays for only part of the answer, the call is sent with a lower output cap (max_tokens / max_completion_tokens lowered to the longest answer the reservation fully pays for) and the answer ends there with the provider's own finish_reason: "length" — no gateway text is added to the content. It is never continued automatically, and the request makes no further paid model call. A balance that cannot pay a minimal answer is refused before the call with 402 wallet_insufficient (429 wallet_funds_reserved while other running requests hold it) — see Error codes. The gateway's own reservation amount must be a whole number of micro-USD between 0 and what the call asked for; anything else refuses the call like an empty balance, and the call is never sent uncapped.

created and system_fingerprint

Every chat.completion.chunk carries created — the completion's creation time as a unix timestamp in seconds. Every chunk of one response carries the same value (it stamps the completion, not the frame), and the buffered chat.completion body carries it too, so a re-serialising proxy (LiteLLM and similar) accepts either shape.

A response served from the gateway's response cache replays the body it stored, so its created (like its id) is the original completion's — not the time of the cache hit. The X-AIG-Cache: HIT response header tells you which case you are in.

system_fingerprint is deliberately never sent. It identifies the backend configuration a completion ran on; a gateway routes one model id across heterogeneous providers, regions and adapters, so there is no value it could report that would stay true. The field is optional in the OpenAI schema — treat its absence as intentional rather than as a gap.

The final usage chunk

The last chunk before [DONE] carries token usage with an empty choices array:

data: {"id":"chatcmpl-…","object":"chat.completion.chunk","created":1753718400,"model":"…","choices":[],"usage":{"prompt_tokens":676,"completion_tokens":127,"total_tokens":803}}

One deliberate difference from OpenAI: OpenAI sends this chunk only when you ask for it (stream_options.include_usage: true); the gateway sends it by default and honours stream_options.include_usage: false as an opt-OUT.

A turn can run several upstream legs — a server-side tool loop, or an auto-continued long answer. A plain client receives exactly one usage chunk per response, carrying the turn total summed across every leg, as the last frame before [DONE]. You may assign it or add it; both give the same number. Because the gateway sums it rather than relaying one leg's block, provider-specific breakdowns that do not add up across legs (prompt_tokens_details, reasoning_tokens) are not carried; Anthropic's cache_creation_tokens / cache_read_tokens / cache_deletion_tokens are, when non-zero. The upstream's prompt_tokens_details.cached_tokens is consumed, not forwarded: the gateway nets it out of prompt_tokens and books it as cache_read_tokens instead (so the summed chunk reports prompt_tokens = the uncached prompt plus a cache_read_tokens bucket, the same shape an Anthropic-origin turn already reports on this envelope). Only a finite non-negative cached_tokens no greater than prompt_tokens is accepted; a null / non-numeric / NaN / ±inf / negative value is treated as no cache hit (cache_read = 0), and a value exceeding prompt_tokens is clamped to it.

Usage counts are exact or zero. Every token count the gateway writes to you (the usage chunk, the usage object of a buffered response, the native usage block) is an exact integer up to 9007199254740991 (2^53 - 1), the largest integer a JSON number carries without loss. A count or a sum above that, a negative value, a fractional value as the gateway decodes it, or a non-numeric value from the upstream is written as 0 rather than as a rounded number, and the gateway logs a server-side warning that names the field. A count the upstream omits is 0 without a warning. Usage stored for billing and request logs follows the same rule: the stored count equals the count in the response, exact up to 9007199254740991, and a count beyond it is recorded as 0.

If the gateway cannot write a buffered compat response exactly (a number in it cannot be encoded), it answers with a 500 error whose message names response_encode_failed, and logs the failure server-side. A buffered native (/anthropic/v1/messages) response that cannot be written exactly is answered with a 502 Anthropic api_error whose message names encode_failed. On a stream, a usage chunk that cannot be encoded exactly is left out of the stream (the stream continues) and the gateway logs the failure.

A client that opted into the gateway extensions (x-aig-turn-id / x-aig-extensions) instead receives one usage chunk per leg and must SUM them for the turn total — that cadence exposes the leg structure first-party tooling reports on. It is the only place the two audiences see different bytes at all; finish_reason, created and every other standard field are identical for both.

The gateway normalises each provider's stop reason to a consistent OpenAI-compatible finish_reason:

finish_reason Meaning
stop Normal completion (Anthropic end_turn/pause_turn, Gemini STOP, Cohere COMPLETE also map here), and the fallback for anything the gateway cannot classify.
length Output truncated at the token limit (OpenAI length, Anthropic/Gemini/Cohere/Bedrock max_tokens/MAX_TOKENS, Mistral model_length map here).
tool_calls The model requested a tool call (provider tool_use). Also a completion that ends with stop although it streamed (or returned) a structured tool call whose arguments are complete JSON — what vLLM and OpenAI send when the request forced a named tool (tool_choice: {"type":"function","function":{"name":…}}). Such a call is forwarded to you when you supplied the tools; a call the gateway runs itself on a gateway tool loop is never forwarded and its leg reports stop. When you supplied the tools, a streamed call whose arguments are cut off (not a complete JSON object) keeps stop and is not forwarded (with stream: false the cut call is returned in message.tool_calls next to finish_reason: "stop", so check the arguments before running it); on a gateway tool loop a streamed leg still counts as a tool call and the cut call is answered to the model with an error, so no terminal finish_reason is ever followed by more output.
content_filter The model refused or was blocked (Anthropic refusal, Gemini SAFETY/RECITATION/PROHIBITED_CONTENT/BLOCKLIST/SPII, Cohere ERROR_TOXIC, Bedrock guardrail_intervened/content_filtered).

That enum is closed, and it is the same for every client and every egress — the streaming wire and the buffered chat.completion body, whatever headers you send. An unrecognised or future provider stop reason is mapped, never relayed verbatim, and a stream aborted mid-flight reports stop with an accompanying error frame (below) rather than inventing a value. function_call is accepted as the legacy enum member but the gateway never mints it.

This matters most for agents that continue automatically when a response was cut off: they key on length. A value outside the enum does not make a strict client abort — it makes such an agent stop silently, with a half-finished answer and no error.

Internally the gateway keeps a richer terminal vocabulary (that is what drives server-side auto-continue, the truncation indicator, and the rule that an abnormal turn is never persisted as a durable summary). It is deliberately not on this field: a standard OpenAI field carries the OpenAI value, and the gateway's own reason travels on the aig_* side channel, where extensions belong.

This normalisation now covers every provider. Gemini/Vertex, Cohere and Bedrock previously reported no terminal reason at all, so a truncated or content-filtered turn on them was mislabelled a clean stop: the "response was truncated" indicator never appeared, auto-continue never armed, and a truncated compaction summary could still supersede the conversation history. Their parsers now surface the real terminal, so these behave like OpenAI/Anthropic.

On the Anthropic-native response shape (/anthropic/v1/messages), the stop_reason field is always one of Anthropic's own enum values (end_turn, max_tokens, stop_sequence, tool_use, refusal) even when the request is routed to a non-Anthropic model — a foreign provider's terminal (Gemini MAX_TOKENS, Cohere COMPLETE, Bedrock guardrail_intervened) is translated to the matching Anthropic value, and an unrecognised foreign reason resolves to a clean end_turn rather than being emitted verbatim. A genuine Anthropic leg's stop_reason (including pause_turn and any newer value) is relayed unchanged.

A long answer that fills the model's context window is auto-continued across legs; if a continuation leg cannot proceed (the input plus the answer so far already exceeds the window), the turn ends truncated, and the gateway terminates the stream with finish_reason: "length" — never a clean "stop" — so the client can surface that the response is incomplete. Route context-heavy jobs to a larger-window model to avoid truncation.

A turn truncated at the model's own output limit is reported as length on every egress — the live SSE stream, the buffered response body, and the buffered re-emit (below). Web-search turns are included: a search-augmented answer that hits the limit is labelled truncated, not clean.

Buffered re-emit turns carry the same tool telemetry

A gateway whose only response detector is an inline PII token-restore masker (pii_protector / custom_pii) streams incrementally on both the native and the compat (OpenAI-format) wire: PII tokens are restored on the live wire (visible answer, reasoning, tool-call args, grounded-excerpt quotes, filenames, web-search queries all carry real values), so these turns are not internally buffered and their tool-loop telemetry streams live. (On a wholly-local Myra/EU model leg no PII scan/restore happens — masking is skipped; see PII Protector — Local model legs are not masked.)

On a native streaming passthrough ("stream": true on a provider route) the provider's SSE bytes are untrusted input to the restore. The per-event restore runs on the native Anthropic Messages wire (/anthropic/v1/messages, also when a non-Anthropic fallback provider answers that endpoint) and on every provider response labelled Content-Type: text/event-stream (media type compared case-insensitively, parameters ignored). Off the Messages wire, a response with any other, an absent or a repeated Content-Type is cleaned on its raw bytes instead: it may carry no blank-line framing to cut events on. Line ends may be \n, \r\n or a lone \r; the restored stream is re-sent with \n line ends, and a blank line ends an event. As in an SSE client, a UTF-8 byte-order mark at the start of the stream is dropped, several data: lines of one event are joined with \n and the last event: line names the event; id:, retry:, comment and other lines are kept and re-sent in front of the event. A data payload that is valid JSON except for a lone UTF-16 surrogate escape is read with that escape (and any other surrogate escape of the event) replaced by U+FFFD. An event whose data is a JSON object is read by its shape; its restorable strings are restored on their decoded text, per block, and the event is re-encoded with the restored text (JSON key order and escaping may differ from the provider's bytes; the values are the same):

Wire (event shape) Restored strings Group / block Block ends before / at
OpenAI-dialect chunk (choices array) delta.content (a string, or Mistral's text / thinking content-chunk array), delta.reasoning_content, delta.reasoning, delta.refusal, delta.audio.transcript, delta.tool_calls[].function.arguments, delta.function_call.arguments, legacy text choice index / field (tool call: its index) the choice's finish_reason; data: [DONE]
Gemini (candidates array) content.parts[].text candidate index (absent = 0) / thought or answer text the candidate's finishReason
Responses (type response.*) delta of response.output_text, .refusal, .reasoning_text, .reasoning_summary_text, .audio.transcript, .function_call_arguments, .custom_tool_call_input, .mcp_call_arguments, .code_interpreter_call_code .delta item_id / event type + content_index / summary_index the family's .done and response.output_item.done of the item; response.completed / .failed / .incomplete
Cohere v2 (type content-delta …) delta.message.content.text (or delta.text), tool-plan-delta delta.message.tool_plan, tool-call-delta delta.message.tool_calls.function.arguments index / event type content-end / tool-call-end / tool-plan-end of the index; message-end
Anthropic (type content_block_*) text_delta.text, thinking_delta.thinking, input_json_delta.partial_json index / delta type the block's content_block_stop, a re-started block; message_delta / message_stop

A string from another block of the same group also ends a block (the answer starts after the reasoning, the next tool call starts). On every wire an error event, an {"error": …} chunk without restorable text and the stream end close every block. A token split across deltas is held back until it is whole. A block's remainder is sent before the event that ends the block as one extra delta of that block (an Anthropic content_block_delta with the block's index as written; a chat chunk repeating id / object / created / model / system_fingerprint with finish_reason: null; a Gemini chunk repeating modelVersion / responseId; a Responses delta repeating item_id / output_index / the part index, without sequence_number; a Cohere delta with the block's index). When the ending chat or Gemini chunk itself carries text of the block, the remainder is appended to that text instead. Tool-call argument deltas are JSON text: a restored value in them is JSON-escaped, so the reassembled arguments stay valid JSON. Blocks are keyed by the index as written — a string of digits counts as that number — so a malformed index (a fraction, another string, absent) is still restored with the holdback, not per event. Every other string of a restored event, and every other event — an unknown shape, a non-string field, an undecodable or non-object data: — is cleaned as a whole (tokens restored or replaced by a placeholder), never forwarded with a whole token in it. Every event except the known slot-less events listed below gets one rule more, so the first part of a token split across events never reaches the client. Every string value of the event (never an object key) other than its restored text is cleaned as a whole, and then a trailing [, [M, [MY, [MYR or [MYRA (any case) is removed; a longer start of a token at the end of a value is already replaced by a placeholder. This covers text in a field the table does not list (for example OpenRouter's delta.reasoning_details[].text next to delta.reasoning), a malformed field (a text field or a container of the wrong type, a choices or candidates that is not an array), an unknown or absent type, and an unlisted delta event (response.*.delta, a Cohere *-delta, an Anthropic delta type the table does not list). It also covers a data: payload that is not a decodable JSON object but is JSON-like: a JSON array, nesting deeper than the decoder accepts, or a JSON string. A legitimate value that ends in one of these characters loses them. An event with restored text is re-encoded as described above. An event without restored text keeps every byte outside a changed string (numbers exactly as the provider wrote them, key order), with one data: line per line of the payload and its id: / comment lines in front. The known slot-less events end a block or stand alone, so they carry whole strings and are cleaned as a whole only: error, Anthropic message_delta / message_stop / content_block_stop / ping, Responses response.completed / .failed / .incomplete / .output_item.done / .content_part.done / .reasoning_summary_part.done / .output_text.annotation.added and the .done of every restored delta family, and Cohere content-end / tool-plan-end / tool-call-end / citation-start / citation-end / message-end / debug. A field such an event does not normally carry (a stray delta on a .done) does not change that: nothing is appended to a whole event's strings. An event that opens a block is not one of them, because a client appends the block's deltas to its strings: Anthropic message_start / content_block_start, Responses response.created / .queued / .in_progress / .output_item.added / .content_part.added / .reasoning_summary_part.added, and Cohere message-start / content-start / tool-call-start get the trailing-prefix rule on every string value — except the one string the block's deltas continue, which is restored with the block's holdback like a delta of that block: Anthropic content_block_start content_block.text (a text block) / content_block.thinking (a thinking block); Responses .content_part.added part.text (output_text, reasoning_text) / part.refusal (refusal), .reasoning_summary_part.added part.text (summary_text), .output_item.added item.arguments (function_call, mcp_call) / item.input (custom_tool_call) / item.code (code_interpreter_call); Cohere content-start delta.message.content.text and tool-call-start delta.message.tool_calls.function.arguments. A token split between such an opener and the block's first delta therefore reaches the client restored. If anything else releases the held remainder first (the block ends with no delta, a re-start, another block's event), it gets the trailing-prefix rule after all: a bare [ … [MYRA is removed, a longer unfinished token is replaced by a placeholder and sent as one extra delta of that block. An opener re-encodes the event as described above. A block still holding text under its own key (a re-start of the block) is released first, with the same trailing-prefix rule; the opener does not end the other blocks of its group (an Anthropic content_block_start still ends the other delta types of its index). The other strings of an opener (Anthropic message_start, Responses response.created, a message item's content, a tool_use block's input) keep the trailing-prefix rule. An event without a type (every chat and Gemini chunk, a usage chunk included) is never a known slot-less event. A data: payload that is not JSON at all, or a JSON number, boolean or null, is cleaned as a whole only. A non-finite number in a re-encoded event (1e400) is sent as 0. An integer of 16 or more digits in a re-encoded event (a sequence_number, an id) is sent exactly as the provider wrote it, including one of 2^63 or more (12345678901234567890 stays 12345678901234567890) and one too large for a double. A fraction or exponent form keeps the double value a JSON client reads from it (0.10 may be sent as 0.1). The extra delta that carries a block's remainder repeats the envelope of the event that opened the block and is cleaned the same way. When the request masked PII (the token map is not empty), log probabilities are emptied where the providers send them: a chat or completions choice's logprobs, a Gemini candidate's logprobsResult, a Responses event's logprobs, its part.logprobs and the logprobs of the content parts of its item and of its response.output items. A non-empty array becomes []; an object or string becomes null. A number or boolean, such as a parameter echo, is kept, and so is avgLogprobs. Log probabilities are the model's token-by-token copy of the masked text, split at model-token boundaries, so they cannot be restored truthfully. A logprobs key anywhere else (inside a tool call's arguments, an echoed tool schema) is left alone. A payload too deeply nested to decode is not emptied: each of its strings gets the rule above. On a request that masked nothing, log probabilities are forwarded as sent. Two limits end the stream as a failed leg (no terminator; the offending bytes are not sent): an un-terminated event larger than 2 MiB, and more than 256 blocks holding back a partial token at once. Nothing is sent after either.

A "stream": true turn is still force-buffered internally when a response detector the live stream cannot satisfy is active — a content-safety block, or a regex/presidio scrub (mask) — or when the turn runs buffered by nature (a stream: false tool loop). On that path the whole answer is produced, scanned, and then re-emitted to the client as a normal SSE stream. That re-emit replays the turn's tool-loop side-channel events — aig_status values tool_call, tool_result, tool_deferred, tool_error, ephemeral_file and file_preview — in their original order, before the answer content. A PII-protected turn therefore carries the same tool telemetry as a live stream — to a client that opted into the aig_* side channel; a plain OpenAI-compatible client receives it on neither path. With that telemetry a client can tell a genuinely computed code_interpreter answer from a model estimate, render tool chips, show file-write notes, and receive a live-delivered generated file.

The tool_result frame of a call that stored a file carries that file's file_id and filename, whichever tool stored it: write_file, edit_file, edit_office_file, convert_document or code_interpreter. The web app accepts the pair only when the tool name is a non-empty string, the filename is a non-empty string and the file_id is a non-empty string of letters, digits, _ and -; a frame that fails this check, or that has no file (a read, a refused or failed call), shows no file card and triggers no refresh. When a call stores several files, the first one stored is reported.

Bounds (the replayed frames originate from model-driven tool calls and are treated as untrusted): at most 256 events are replayed per turn, and an unencodable frame is dropped. An event whose encoded size exceeds 64 KiB is replayed with its args removed and "args_truncated": true set. ephemeral_file (and file_preview, the layout-check picture) is exempt from both the size check and the encodability check — its payload is the user's file (picture) and every field of it is gateway-constructed; its size is bounded at the source instead (see below). Statuses the buffered tail already reconstructs from its own state (thinking, pii_masked, tools_skipped, aig_sources) and mid-stream control signals (provider_error, compacted, pause_turn) are not replayed — no event is ever delivered twice, and no stale control signal outlives the turn it steered. Plain non-streaming requests ("stream": false) are unaffected: their single JSON response never contains side-channel frames.

When the buffered answer is a tool call — the model returned tool_calls (for example a client-provided tool, or a web-search direct answer that called the client's own tool) with no visible text — the re-emitted stream carries those tool_calls as a normal OpenAI delta.tool_calls chunk followed by a terminal finish_reason: "tool_calls", exactly as a live stream would. A streaming client is never handed a silent empty turn on a tool-call answer. (If the tool call's arguments were truncated by the token limit the terminal is length, not tool_calls — the truncation signal wins. An empty or non-array tool_calls is not emitted.)

pii_masked — what the PII layer masked on this turn

Sent just before the end of a streamed ("stream": true) OpenAI-compatible response when personal data was masked anywhere on this turn — in the prompt, the conversation history, the project's knowledge and instructions the gateway adds, or a tool result such as a knowledge-file snippet (also masks carried over from an earlier turn of a regenerated answer), and only to a client that opted into the side channel (x-aig-turn-id or x-aig-extensions). Live-session only (not stored with the conversation).

{"aig_status": "pii_masked", "types": "PERSON,EMAIL_ADDRESS", "custom_count": 1,
 "counts": {"PERSON": 2, "EMAIL_ADDRESS": 1},
 "files": [{"name": "brief.txt", "status": "masked", "types": {"PERSON": 2}},
           {"name": "notes.md", "status": "nothing_masked"}],
 "files_more": 0}
Field Meaning
types comma-separated entity types masked anywhere on the turn, each listed once (string, may be absent)
source_types optional: the subset of types that is no longer masked in the user's own text — masked only in sources: tool results and tool-call data in the request (whoever ran the tool, including an API client's own tools) and everything the gateway added to the turn (web search results and queries, fetched pages, file and knowledge reads, composed instructions and memory) (comma-separated string). On a wholly-local model leg, where the user's text is not masked at all, every listed type is a source type. Absent when every listed type is still masked in the user's text, or when the gateway cannot tell (a resumed tool turn); a client then lists all of types as masked in the message. types and counts keep describing the whole turn
custom_count distinct custom keywords masked (integer, may be absent)
counts optional: distinct masked values per entity type across the whole turn (prompt, history, added knowledge, tool results), e.g. {"PERSON": 2} — entity types and numbers only, never a value or a token; a value the user sent unmasked is not counted unless it is still masked somewhere in the request (for example in a tool result); custom keywords are counted in custom_count, not here; absent when no entity was masked
files optional: the files attached to this message (its last user message) and what happened to each — at most 20; absent when the message has no attachment, when masking does not run on this turn (a wholly-local model leg) or when the masking set is unknown
files[].name the file name as the client sent it (≤ 120 characters)
files[].status masked (with types: distinct masked values per entity type; incomplete may carry them too), masked_other (changed by another masking rule — a regex / keyword scrub or an anonymizer placeholder), nothing_masked, not_checked (the analyzer was unavailable and nothing was masked), incomplete (masked, but the analyzer was unavailable, so names may remain)
files_more optional: attached files beyond the 20 listed

Display-only: nothing in the gateway depends on it. The SPA treats counts as a whole too: unless it is an object whose keys are entity types (A–Z, digits, _, at most 41 characters, at most 64 keys) and whose values are positive integers, the whole map is ignored and the chip lists the types without numbers. A types entry that is not an entity type in that shape is not shown. A client should treat the list as a whole — the SPA ignores the entire list if any entry is malformed (a name that is not a non-empty string of at most 120 characters, an unknown status, a non-integer or negative count). Files the model read through tools are not listed; a file masked at upload time (the cut of a very large text) shows as masked_other.

ephemeral_file — a generated file delivered live and stored nowhere

When the code interpreter produces a file in a conversation that cannot store files — a private (ghost) chat — including one opened inside a project, where the gateway refuses to write to the project's knowledge base — or any request without a conversation to write to — the file is not persisted and there is no download route to point at. Instead the gateway sends the bytes once, inline on the turn's own stream:

data: {"aig_status":"ephemeral_file","name":"report.xlsx","mime_type":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","size":8134,"data":"UEsDBBQ..."}
Field Type Meaning
name string Bare filename, at most 100 characters. Never a path, never a leading dot, never a Windows-reserved character (: * ? " < > |) and never a control byte.
mime_type string One of the 17 accepted types: text/csv, text/plain, application/json, the .xlsx workbook type, image/png, Word (.docx), PowerPoint (.pptx), PDF (application/pdf), OpenDocument (.odt, .ods, .odp), and the audio types audio/mpeg, audio/wav, audio/ogg, audio/mp4, audio/aac, audio/webm (an audio clip, for example a text-to-speech result, delivered as a download).
size integer Size of the raw (pre-base64) bytes.
data string Base64 of the raw bytes.

Nothing is written server-side for such a file: no conversation row, no knowledge row, no stored blob, and no id — the event is the file's only existence, and it is gone once the client discards it.

Opt-in. The event is sent only to a client that identified its turn with the x-aig-turn-id header (the chat UI always does) or opted in with x-aig-extensions: 1. A plain OpenAI-compatible client that sends neither never receives it, and the generated file is reported as not shown instead. This is a delivery contract, not an authorization boundary.

Bounds. A turn delivers at most 25 MiB (26 214 400 bytes) of raw bytes this way — the code-interpreter artifact-size limit, whose default is that ceiling — and at most eight deliveries in total, of which at most four code-interpreter files and four images or audio clips combined (the same per-turn budgets the stored path uses; files written with write_file count toward the eight). An artifact that does not fit, or that cannot be delivered (for example on a non-streaming request), is reported to the model as "could not be shown to the user" rather than silently dropped.

Client-side validation. A consumer must treat this event as untrusted, exactly like every other stream frame. The chat UI rejects — and renders nothing for — an event whose name contains a path separator, a control character, or a leading dot, whose mime_type is outside the list above, whose size is not a positive integer within the budget, whose data is not plain base64, or whose size and data length disagree (padded base64 length is a function of the raw length, so the two must match). The filename rule is the same list the gateway applies before emitting — a path separator, a Windows-reserved character, a control byte, a leading dot, or a name over the byte ceiling is REJECTED, never "repaired" into a different file, and yields no download card. Because both sides apply the same list, an artifact the gateway delivers always renders; one whose name would fail it is never delivered at all — the model gets the honest "could not be shown" note instead. Cosmetic trimming (collapsing runs of whitespace, stripping trailing dots) happens only at render time and changes how the name looks, never which bytes are written.

Tool-loop termination note on the buffered egress

When the gateway's own tool loop stops a turn early — the per-turn tool-call limit, a detected tool-call loop, an exhausted time budget (including the "answer is based on partial results" label when the gateway synthesized a partial answer over the results gathered so far), or a sub-agent deadline — it appends a short human-readable note to the answer. The note is written in the language of the request (German or English; when the latest message is too short to judge, the language of the user's earlier messages in the conversation; for any other language the account's UI language, else English), and the same goes for the interrupted-turn note and the unparseable-tool-call hint below. On a streaming turn that note is relayed live as its own content delta.

A turn ended by the time budget, by the maximum number of tool rounds, or by a client Stop keeps what it had produced (including the content of a file the model was still writing with a write_file or edit_file that the gateway runs (not one your client supplies), shown as an "Unfinished file ..." or "Unfinished change to ..." (not saved) block; no file is created or changed; the same block is kept when the model call itself dies mid-stream while that file is being written) and is marked with stop_reason (wall_clock_exceeded / client_gone) on the saved message; see "Stopped turn" in the conversations reference. When the time budget ends a turn without a partial synthesis, the note says the limit for one answer was reached and that what was produced is kept, so the client can ask to continue in a follow-up request; an unattended run's note instead suggests a smaller task per run, because its recipient may have no conversation to continue. The notes carry no number; the budget itself is documented in the agents reference.

A streamed completion that asks for the exact same tool call (same tool name and byte-identical arguments) more times than the parallel-call limit allows is cut short: the gateway stops reading that completion, closes the upstream connection instead of reusing it, and does not run the extra copy. The extra copy's tool card shows it was already done and not run again (duplicate_effect_call), and the reply continues with the results already received. Calls to the same tool with different arguments are never affected, however many there are. The gateway only stops a completion once the arguments of every call received so far are complete. If a provider announces several calls before sending their arguments, the gateway reads the completion to its end instead and answers each extra copy without running it. The same applies when a provider keeps adding argument bytes to an earlier call. A call whose arguments are not valid JSON is counted too, at the end of the reply. A tenant's higher parallel-call limit (max_parallel_tools) widens this bound accordingly. The same applies when the turn pauses for approval and resumes.

On the buffered compat egress (a "stream": false request, or a PII-force-buffered "stream": true turn re-emitted as SSE) the note is included in the delivered response body's message content — choices[0].message.content on a direct non-streaming response, and the re-emitted content on the PII path — so a buffered client sees the same stop/partial label a streaming client does, on the first response, matching the persisted turn (a reload shows the same text). The note is appended exactly once and never onto a tool_calls body, an error envelope, or a structured-output (response_schema) answer. A native /anthropic/v1/messages direct non-streaming response gets the note folded into its last text content block as well; only the native PII-force-buffered turn is excluded — it is re-emitted through the compat-shaped tail, an existing limitation outside this scope.

When the turn ends because the prepaid wallet refused the tool loop's final call (see the exception under the tool-loop bullets above), there is no note: the buffered response carries the typed wallet failure the same way any failed final model call does (the typed error response when nothing was answered yet, otherwise the partial answer delivered with that failure).

Malformed upstream streams (fail-closed)

On the buffered path the same untrusted-input rule applies to the provider's JSON body: see "Empty responses & inline dead-turn retry". In streams and buffered bodies alike, a content part without a type and without a text (for example a tool call or an inline image part) is a non-answer part and is skipped silently; a text that is present but not a string is malformed.

The upstream provider's SSE bytes are treated as untrusted. A single Server-Sent Events line (the text between two newlines) has an internal size ceiling of 1 MiB. Legitimate event lines are far smaller — token deltas of at most a few kilobytes, and providers split even a large tool-call payload across many newline-terminated delta events — so this ceiling never truncates a well-formed stream regardless of the total response size (only the size of one un-terminated line is bounded). A broken or hostile provider that streams bytes without a terminating newline past the ceiling is cut off rather than allowed to grow gateway memory without limit: the affected leg fails closed. On the compat (unified) path the stream terminates with a final chunk (emitted when no terminal chunk had yet been sent) and then ends without a data: [DONE] sentinel — the sentinel is suppressed on an errored stream. A plain client receives the failure the way the OpenAI schema carries one: a data: {"error":{"message":…,"type":…,"code":…,"param":null}} frame before that final chunk, whose own finish_reason is the in-enum stop (error is not an OpenAI enum member, so it is never written to this field). The code is stream_truncated when the upstream closed early and provider_error when the connection itself failed; when the provider announced the failure with its own error event, the code is the gateway's classification of it (a rate-limit or overload class) and type is the provider's own error type, so an SDK's retry policy can read it. This frame is delivered to every client, first-party included — once the terminal has to stay inside the enum, the error object is the only thing distinguishing a truncated turn from a short one, so no audience may be left without it. A client that also opted into the extensions still gets its aig_status:"provider_error" banner event.

Such a leg is not re-dialled on the same provider. Both the per-line ceiling above and the per-leg total stream ceiling (64 MiB) are properties of the request/response pair, not of the moment: an identical retry downloads the same oversized response and fails identically, while the provider generates — and bills for — the output again. The gateway therefore skips the remaining same-provider attempts and moves straight on to the next provider in the routing chain, which may well be a model that answers. Only if the whole chain is exhausted does the request end in all_providers_failed, and the recorded cause names the ceiling that was hit rather than a bare stream error. Transient mid-stream failures (a dropped connection, a read timeout) are unaffected and keep their full retry budget. Models that return generated images inline in the stream are the common way to hit the per-line ceiling — their base64 payload arrives as one un-terminated line — and such a model cannot be delivered on this path at all; pick a text model, or one whose images are returned by reference.

One case is deliberately not treated as a truncation: an Anthropic-style two-phase terminal where the model's message_delta already carried a natural stop_reason (end_turn/stop_sequence/pause_turn) and only the trailing message_stop was lost to a socket close. That answer is complete, so the gateway emits neither the stream_truncated error frame nor the visible note below — only the finish chunk (still the in-enum stop). A genuine cut-off, where no terminal stop_reason ever arrived, is unaffected and still gets both. (A max_tokens terminal is a real length cap, not a natural end, so it keeps its length truncation signal.) On the native passthrough path the raw stream simply ends without a terminator (which conforming clients treat as an error). In both cases the upstream connection is closed rather than returned to the pool, and any pending tool call the truncated leg had begun is discarded (never executed).

What the request log records for a cut stream. The wire carries HTTP 200 (the status line was already sent) — on the OpenAI-compatible path with the error frame before the final stop chunk; a native passthrough stream simply ends — but the request log row records the logical outcome: the typed error status (for example 502 for stream_truncated), not 200. The row's token usage is that of what was actually delivered — the provider's own figure when it arrived, otherwise an estimate from the text relayed, since a cut stream never receives the provider's closing usage. The same applies to a native Anthropic Messages stream that ends without message_stop or with an error event; on other native wires a stream counts as cut only on a connection read error. A client therefore must treat the error frame, not the trailing finish_reason: "stop", as the failure signal.

Visible truncation note (persisted), so a cut-off is never silent to a human. Because the wire terminal reads the in-enum stop, a partial answer would otherwise render — live and on reload — as a clean, complete one. On the compat path the gateway therefore appends a one-line "The response was interrupted before it completed. Please try again." note (in the request's language, German or English, by the same rule as the tool-loop note) to the visible answer — as its own content delta after whatever partial text had already streamed (one blank line between the partial and the note; when the partial already ends in a blank line the note follows it directly, and a dangling whitespace-only last line is closed first so the note is never indented into a code block), or as the whole bubble when nothing had — and records it into the persisted turn, so a reload shows the truncated turn the same way it rendered live. The note is not part of ctx.stream_accumulated_content, which carries the model-authored content only (the footer is a separate event); the persisted turn does contain it. The note is gateway-authored prose in the request's language (German or English; see above), not model output. The chat UI additionally raises a non-fatal response may be incomplete banner off the error frame's code. A turn that instead ends with an actionable provider-error banner (aig_status:"provider_error") or a context-overflow recovery banner gets neither the generic note nor the banner — those surfaces already name the failure. This note follows the same rules as the tool-loop termination note above (never onto a tool_calls body, an error envelope, or a structured-output answer). It is the same on the buffered / PII-force-buffered egress: a turn the gateway buffers internally (a PII-masking or guardrail configuration, or a stream: false tool-loop turn) whose upstream dies after partial bytes delivers the salvaged partial with the note and the terminator error frame when the egress is a re-emitted SSE stream; a plain stream: false JSON egress returns the typed error status instead (see the Mid-stream provider failures on a buffered turn callout under Anthropic-native passthrough) — and a conversation-owned turn persists exactly those bytes; it used to persist the bare partial as a clean-looking complete answer. The one verdict is shared: a leg that reached a natural end and only lost its message_stop is complete on both egresses (no note, no frame), and a provider_error event gets its banner and no note on both. A leg that will continue in the tool loop gets no note — and only a leg that finished cleanly (its finish event arrived — the finish_reason chunk on the OpenAI wire, message_stop on Anthropic — with no read error and no provider error) with pending tool calls continues. A leg that did not finish cleanly is dead: nothing that would make the turn continue is synthesized from it (no inline <tool_call>, no unwrapped file tool, no file-claim steer), structurally delivered tool calls are discarded (Anthropic tool_use blocks included — even after message_delta, if message_stop never came), the gateway logs and traces dead_leg_no_continue, the note is appended, and the error frame is terminal — Regenerate is the remedy. (A leg that reached a natural end and only lost message_stop on an otherwise clean close is complete for the wire and the row — no note, no error frame, its finish chunk emits — but equally never continues: nothing may follow that terminal. If such a leg carries a tool call its death cost it — one the gateway would have run had the finish event arrived: a recovered <tool_call> marker, an unwrapped <write_file> / <read_file>, a write_file sentinel, or a structurally delivered call (an Anthropic tool_use block, an OpenAI tool_calls delta) — it is not treated as complete: it gets the note and the error frame, because its prose is a preamble to work that will never happen. Text the gateway discards on a clean finish too (an anchored bare-JSON or pseudo-call naming write_file / read_file, which the inline channel never dispatches) does not change that verdict — the answer stays complete — but the discard is always logged, so a dropped write is never silent. A pending bare-re-download card is not such a marker — on a streaming turn, and on a PII-force-buffered turn (whose captured card the buffered re-emit replays), that card is re-served on any leg that neither hit a read error nor carries the interrupted note (a leg that ended in a provider error does get it), so a re-download does not go silently missing; a leg that carries the note re-serves no card on either egress — a card under an "interrupted" note would contradict it, and Regenerate re-serves the file — and on a non-streaming (stream:false) turn the card has no wire to ride, as before.) So a partial on a tool-capable turn (the common first-party conversation turn, where file tools are always offered) is a cut-off like any other and carries the note, live and on reload. The same holds for an API turn that supplies its own tools: if the provider dies after tool_calls deltas but before the finish chunk, those calls are discarded and the note is appended to the visible answer — the turn is a cut-off, not a tool turn, and no tool_calls body is emitted for it.

The client's own connection dies mid-stream (a laptop lid, Wi-Fi gone at 80 % of a long answer). The gateway sees the client abort, stops reading the provider at once and closes the provider connection (the model stops generating for a turn nobody will receive), then persists the partial answer it had already streamed once, synchronously, under the turn's id — nothing is lost server-side and nothing is doubled; the request is accounted as a client abort (request_log.aborted = 1, the leg status 499 / error_class cancelled / partial = 1). The chat app treats the read failure the browser raises for a dropped connection as exactly that — one predicate accepts each engine's wording for both moments, before a response and mid-body: Chrome Failed to fetch / network error, Firefox NetworkError when attempting to fetch resource. / Error in body stream, Safari Load failed / The network connection was lost. — and keeps the partial the user was watching on screen as the assistant turn, raises the same non-fatal response may be incomplete banner, re-enables the composer, and adopts the persisted row (which may carry a token or two more than the client received) through the same bounded reconcile a Stop uses — so live and reload show one partial, once. If the network is still down when the reconcile runs, the partial simply stays as rendered — no blank, no "no response received" row — and the next load shows the persisted partial once. (The same failure while nothing had streamed yet is a plain error banner — there is no partial to keep.)

Exception — a client that opted into detach-on-drop (x-aig-detach-on-drop: 1 on a turn-owned request): the abort contract above does not apply to a dropped connection. The turn is not cut, the provider connection stays open, the whole answer is persisted once under the turn id and the request is logged with aborted = 0. While it runs the turn's row carries a liveness stamp refreshed every 15 seconds (given up after 60 seconds without a refresh, or after one hour in total). The client learns the outcome from GET /admin/v1/conversations/<ID>/turns/<TURN_ID> (running, committed, failed, stopped or none).

The provider's HTTP body framing. Before any of the above, the gateway frames the provider's response body itself (its own coroutine-free reader over the connection — the receive belongs to the coroutine that is cancelled on a client abort, so an abort really closes the provider connection). Accepted: Transfer-Encoding: chunked with a hexadecimal chunk-size line (as tonumber(line, 16) reads it — the SSE case), a Content-Length body read to exactly that length, or — with neither header — a read-until-close body. Rejected, and surfaced as a read error that ends the leg (never a fabricated length, never a silent end): a chunk-size line that is not hex (a chunk extension such as 1a;name=value, a non-hex token) or is negative; a Content-Length that is not a single non-negative integer (4.5, a duplicated header) is ignored and the body is read until close, so a truncated read can never leave stray bytes on a pooled connection. Sizes are honoured in bounded pieces (at most 64 KiB per read without a caller limit), so a size the socket cannot honour ends the leg as a read error. HEAD / 1xx / 204 / 304 responses have no body and are never waited on.

Structured / malformed content values. A provider's delta.content (streaming) and message.content (buffered) are equally untrusted. Accepted shapes are a plain string, null, or an array of parts; the gateway flattens an array into the visible answer text (the text parts concatenated; the same flattener, with a separator between the parts, also joins a user message's text parts where a route needs a single string — the reply-language detection and the Mistral web-search fold). Array normalization is two-tier: recognized typed non-text parts (a part whose type is a string other than "text" — e.g. a thinking or citation part) are omitted from the visible text silently; garbage shapes (non-object/non-string elements; text-equivalent blocks — type absent, null, or "text" — with a non-string or absent text; blocks with a non-string non-null type; content values that are neither string, null, nor a table with a leading element sequence) are dropped fail-closed with a gateway WARN log (deduplicated per stream leg); an empty array yields empty text silently. The same fail-closed guards apply to the per-part text fields of the native Anthropic, Gemini, and Cohere parsers, and the compat streaming dispatcher additionally drops any non-string delta a provider parser might emit (one WARN per leg) instead of letting it abort the live stream. Before these guards, a structured content part could kill a streaming turn mid-leg with no finish event — the user saw a silently dead chat.

Source citations (aig_sources)

When an answer draws on an uploaded document, the gateway emits a structured, deterministic source list as a dedicated SSE chunk on the final leg of the turn — built from the turn's actual document-retrieval calls (reading a file by name or the search_knowledge hybrid search over the project corpus), not from model text:

data: {"aig_sources":[
  {"file":"budget-report.pdf","loc":"p.1","kind":"page"},
  {"file":"budget-report.pdf","loc":"p.2","section":"Section 3.1","kind":"page"}
]}
Field Type Meaning
file string The document the answer drew on (required, non-empty).
loc string The locator that was retrieved, e.g. p.2 (required, non-empty).
section string Section/heading within the document, when known (optional).
kind string Locator kind — page, slide, sheet, para, line (optional).
excerpt string The verified passage of the document the answer is grounded on, at most 500 characters (optional). It is real document text, so it is left out when a shared project member who has no access to the document reloads the conversation.

The list is deduplicated by file + loc + section, ordered by first retrieval, and reflects only the portions actually delivered to the model (a document truncated to fit the context window does not contribute citations for the pages that were cut). It is bounded — at most 100 entries, each field at most 300 characters — so a many-page document cannot produce an unbounded list. A turn that retrieved nothing emits no aig_sources chunk. Consumers must treat every field as untrusted input and ignore malformed entries. Like the other aig_* gateway-extension events, aig_sources is emitted only in streaming mode; a non-streaming ("stream": false) response returns a plain chat.completion JSON object with no citation channel.

OCR retrieval is cited and marked. Segments extracted by OCR (confidence='ocr': image regions r.N, scanned PDF pages p.N) are served to the model as document text and are cited, but the entry carries "confidence": "ocr" so a consumer can show that the wording is machine-read and the location best-effort. The field is present only with the exact lowercase value "ocr"; absent means an exact text layer. Consumers must ignore any other value. The same field is stored with the persisted citations and returned on reload. For an image region the SPA shows the file name only (the region number carries no meaning for a reader).

Citations persist. The same list is stored on the assistant message, so the citations rehydrate when a conversation is reloaded (not just for the live stream). The persisted list is re-validated through the same bounds above before it is returned, and a turn that produced no answer stores no citations (a citation attributes an answer).

Earlier sources are visible to the model on the next turn. When a prior assistant turn ended with a sources footer, a short note listing those sources is added to the newest user message in the request sent to the provider, so the model can answer follow-ups about them. The note is masked like any other stored conversation content. The stored conversation and the gateway's own checks (guardrails, PII, tool selection) see the conversation without it, so it is never treated as text the user wrote. Compaction, admin summarize/replay, inner tool-loop legs and delegated child agents do not receive the note.

fetch_url / agentic_fetch pages range (untrusted model input). For a long PDF truncated to its first pages, the model may re-fetch the same URL with an optional pages argument to read a specific window. Accepted shape: a string - a 1-based range "START-END" (e.g. "110-125") or a single page "117"; surrounding whitespace is tolerated - or a positive integer number (117). The window is [START, END] and its span is clamped to the 200-page extraction cap; a start beyond 1,000,000 is clamped to 1,000,000 (past any real document). Absent: pages omitted or null reads from the first page. Everything else is refused with a tool-result Error: 'pages' must be a 1-based page number or range such as "3" or "2-5" ... and the URL is not fetched: a non-string/non-number value (boolean, table), an empty or non-numeric string, a reversed range ("10-2"), a zero or negative page ("0-3", 0, -4), a fractional, NaN or infinite number, and any page number longer than 15 digits (string "1000000000000000" or number 1e15 and above). A refused pages never silently becomes a first-page read, so the model can correct the call. pages applies to PDFs only (DOCX/XLSX/web pages ignore it). A range that begins beyond the document, or hits only text-less pages, returns a served notice ("Requested pages start beyond … the N-page document"), not an extraction failure.

Document read limit. The extracted text of a fetched document is cut at the per-call text budget of 10240 bytes (about 10 KB) for both fetch_url and agentic_fetch (the same budget that caps one web page; a pages range is cut to it too). A cut is disclosed by a gateway line — the first line inside the frame for fetch_url, a line above the answer anchor for agentic_fetch (and the first line of the inner model's content): [gateway: document text truncated – the extracted text exceeded the read limit on page K of Z; content after the cut is missing]. The page is named for a PDF only, when the extractor's page index locates the cut; otherwise a PDF's line gives only its page count (… read limit (a Z-page document); …) and other documents get the line without either. To read further, fetch the same URL again with a pages range starting at page K (or one picked from the table of contents). When the inner input cap of agentic_fetch cuts a document (a second time, or after PII masking grew it past the cap), and in web-search auto-fetched results (re-capped as a whole), the line names no page. The cut is masked for PII with the dropped text as context. If that masking fails closed, a fetch_url result is [tool result withheld: PII scan unavailable] (or the blocked placeholder when an operator block detector matches at the cut); agentic_fetch answers its framed failure shape instead ([gateway: the inner agent failed for this part] above the anchor). Both tools refuse a url longer than 8192 bytes before fetching anything (Error: url too long …).

fetch_url web/text content types (untrusted third-party header). A fetched response that is not a PDF/DOCX/XLSX (detected by magic bytes) is read as page text only when its Content-Type is in the accepted set. The header is parsed to its media-type essence: everything from the first ; (parameters such as charset) is ignored, surrounding whitespace (space, tab, CR, LF, VT, FF) is trimmed, case is ignored, and the rest must be exactly type/subtype made of HTTP token characters, at most 255 characters long. Accepted: text/* (any subtype — text/html, text/plain, text/xml, text/csv, …), application/xhtml+xml, application/xml, and any application/<name>+xml (for example application/rss+xml, application/atom+xml, application/rdf+xml) — so a sitemap or feed served as Application/XML; charset=UTF-8 is read exactly like one served as text/xml, through the same text extraction, truncation notice and offset paging below. Rejected (the model is told the page "could not be read as text"; nothing from the body is returned): an absent header, a malformed one (no /, an empty type or subtype, inner whitespace or a missing ; such as text/html charset=utf-8, a comma-joined or repeated header, control bytes or non-ASCII, longer than 255 bytes), the JSON family (application/json, application/ld+json, application/feed+json), image/svg+xml, and every other type (application/octet-stream, application/gzip — e.g. a sitemap.xml.gz —, images, audio, video, archives). Absent and malformed share this one rejection — a header that arrives garbled is never treated more permissively than one that never arrived. The declared type is only a claim: a body with a NUL byte in its first 64 KiB is binary (archives, images, PDFs and UTF-16 text all carry NULs) and is refused the same way whatever type it is labelled with — this includes a page with a stray NUL byte near its start and a UTF-16 encoded page. Other control bytes (for example the ANSI colour codes of a plain-text log) do not refuse a page. XML is reduced to its text like HTML (tags stripped, a handful of entities decoded — a numeric entity for a control character becomes a space). XML is not parsed as XML, so no DTD, external entity or entity expansion is ever processed — and, as for HTML, a <![CDATA[ … ]]> section is treated as markup and dropped, so a feed whose titles or descriptions are wrapped in CDATA returns only its non-CDATA text (links, plain elements). Sitemaps (<loc> URLs) are unaffected.

A > inside a quoted attribute value does not end the tag. When tags are stripped, the gateway reads attribute values the way a browser approximately does, so a handler such as <a @click="open = a > b"> (Alpine, Vue and Knockout write comparisons like this) is removed whole and its code does not leak into the page text. This applies to element tags only: a < directly followed by an ASCII letter (A-Z, a-z), or </ followed by an ASCII letter. Comments, <!DOCTYPE …>, <?…?>, CDATA and any other < end at the first > after the <, as before. Inside an element tag, a quote opens a value only when the nearest byte before it that is not HTML whitespace (tab, line feed, form feed, carriage return, space) is = (so a = "x" opens a value, just as a="x" does); any other quote is an ordinary byte, as in a browser, and never triggers a fallback. A value counts only if its closing quote exists, the values counted within one tag total at most 64 KiB, and the closing quote is followed by HTML whitespace, >, / or the end of the page. As soon as one value does not count (an unterminated value, a value whose closing quote is followed by any other byte, values beyond the 64 KiB budget), the tag ends at the first > after its <, which is exactly the previous behaviour.

To keep the work linear in the page size, two cases switch quote-aware reading off for the rest of the page (from then on every tag ends at its first >, exactly the previous behaviour): an element tag that has no > outside its counted values, and a value that does not count in a tag whose first > lay inside an earlier counted value of that same tag. That tag itself ends at its first >. Text before that point keeps the quote-aware result; the rest of the page is never stripped worse than before.

This is an approximation, not a full HTML parser: only a tag in which every value-opening quote is accepted can hide more than the previous rule, namely its own counted values (at most 64 KiB in total) plus its unquoted attribute bytes up to its real >, approximately as a browser would.

A page that is only code is rejected. When an HTML or XHTML page (text/html, application/xhtml+xml) reduces to nothing but script or style code — an inlined bundle or stylesheet, a JavaScript-rendered shell — with no readable prose and no <pre>, <code> or <textarea> element showing code on purpose, it is refused like an empty page, and the model is told that the page content could not be extracted (the page probably needs a browser to render). A page that displays code in <pre>, <code> or <textarea> is returned as usual, and so is a JSON document that is served as text/html (it is data, returned as text, not refused). The check applies to HTML and XHTML only: plain text and the XML family are never refused for looking like code. The check judges the first 512 KiB of the page text: a page whose head is only code is refused even if prose follows later, and code that starts only after that head is not detected.

Plain text is returned verbatim. Only markup — text/html, text/xml, application/xml and every +xml type — is reduced to its text (tags stripped, whitespace collapsed, entities decoded). Every other accepted text/* body (text/plain, text/markdown, text/csv, a script or source file served as text/x-…) is the text itself and is returned as sent: its line breaks, indentation, <…> sequences and &…; sequences are kept, so a shell script or log keeps its lines and a literal <script> in a text file is returned as plain text (it is model context; nothing renders it). Everything else applies to plain text exactly as to a web page: the NUL-byte refusal, the "empty page" refusal (a body of only whitespace), invalid UTF-8 normalisation, the neutralisation of any in-text look-alike of the gateway's own [gateway: …] notices, the offset paging below and the guardrail masking of what is returned. Like document text (which has always kept its lines), plain text can contain lines that imitate the gateway's own structure — a ### Source: header between the pages appended to a web search, or ----- END PAGE ----- inside the agentic_fetch reader's prompt. They are not rewritten: all of it stays inside the untrusted-content frame, which the model is told is data, never instructions; only the gateway's [gateway: …] notice stem is neutralised (above). (Before this change a plain-text page was run through the HTML reduction too and arrived as one run-on line with anything between a < and the next > removed.)

fetch_url / agentic_fetch on a GitHub directory. GitHub's directory page shows only about 100 entries, so for a URL of exactly the shape https://github.com/<owner>/<repo>/tree/<ref>[/<path>] (also written http://, without a scheme, or with www.; a ?query / #fragment is ignored) the gateway reads the GitHub contents API (https://api.github.com/repos/<owner>/<repo>/contents/<path>?ref=<ref>) instead and returns a listing — a header line GitHub directory listing (read via the GitHub API) — repository <owner>/<repo>, ref <ref>, path <path>: N entries. followed by one line per entry (file <name> (<size> bytes), dir <name>/, link <name>, submodule <name>), paged with offset like any long text. It counts as one fetch. Every served result for such a URL — fetch_url's and agentic_fetch's (before its ## Answer for line) — names its source on a gateway line inside the frame (right after the window line): [gateway: GitHub directory listing from the GitHub API (the source is complete; the text served per page is capped) – offsets in this result refer to this listing, not to GitHub's page view], or — when the page had to be used — [gateway: GitHub's directory page view, which shows only about the first 100 entries – the complete listing (GitHub API) was not available, so this list may be incomplete] (the agentic_fetch reader is given this second line too). Once a result was served, the gateway keeps that source for the directory for the rest of the request. The directory is identified by owner, repository, ref and the decoded path, never by the URL text, so every spelling of it is the same directory: http://, www., no scheme, a query or fragment, a different letter case of owner or repository, and any percent-escaped form of a path character (%7E or %7e for ~, %21 for !, %C3%9C for Ü, and the raw or escaped form of a character a browser escapes, such as [slug] and %5Bslug%5D), so the next chunks never switch source and the API is not called again. The ref and the path are case-sensitive. When the API's answer is final (a 404, for example a branch name with /; another 4xx; the URL names a file; an invalid, empty or over-8-MiB body; an address the SSRF guard refuses) the page is the source, also for offset reads. When it is temporary (403 / 429 rate limit, a 5xx, a timeout, network or DNS-resolution failure) the page answers a read from the start, but a read with an offset that has no source yet in this request is refused with Error: the GitHub directory listing is unavailable right now … and GitHub's page is not fetched — that offset may belong to a listing served earlier, and is never applied to the (different) page text. The API returns at most 1000 entries per directory; at that ceiling the header adds that the directory may have more entries than listed. Accepted URL (model input): owner and repository of A–Z a–z 0–9 . _ - (≤ 100 characters, not ./.., repository not ending in .git); the ref is one path segment of A–Z a–z 0–9 . _ - (a branch name containing / is read as its first segment — the header names the ref and path that were read); path segments of URL path characters with valid %XX escapes (a raw non-ASCII byte, a space or one of " < > [ ] ^ ` { | } \ is accepted raw and treated as its %XX form). Each segment is decoded once and every check below applies to the decoded segment, so an escaped form is refused exactly like the plain one; an escaped % (%25) is one literal percent sign. Not treated as a directory listing (the page is fetched exactly as before): any other host (including gist.github.com, api.github.com, a userinfo or port in the authority), a blob/ or repository-root URL, a segment that decodes to nothing, ., .. or only dots and ; (also escaped, e.g. %2e%2e, ..%3B), a segment containing /, \ or a control byte once decoded (%2F, %5C, %00–%1F, %7F) or a Unicode line break (U+0085, U+2028, U+2029), a broken % escape, a ref carrying &, =, +, % or anything outside its character set. The API is called with one canonical spelling of the path (every byte other than A–Z a–z 0–9 . _ ~ - percent-encoded). API response (untrusted third-party input): must be a JSON array of at most 1000 objects, each with a name (1–255 bytes, not ./.., no /, no control byte, no Unicode line/paragraph separator U+0085/U+2028/U+2029), a type of file / dir / symlink / submodule, an optional size (an integer 0 – 2^53−1 or null) and an optional download_url (a string or null; a file entry whose download_url is explicitly null is a submodule — an absent one is a plain file). An empty array is an empty directory. Any malformed entry, a JSON object (the URL named a file), a non-JSON body or more than 1000 entries rejects the whole response — a partial list is never returned — and the page is fetched as before. Authentication and failures: the API is called with the platform's GitHub token (setting github_api_token) when one is provisioned, otherwise unauthenticated (GitHub allows 60 unauthenticated requests per hour per egress address). A 401 with the token is retried once without it; a 403 or 429 (rate limit or forbidden), a 404 (for example a branch name with /, a private or missing repository), a network failure, a timeout (the API attempts share an 8-second budget) or a body over 8 MiB fall back to today's page fetch — except that a read with an offset after a temporary failure, with no source yet in this request, is refused instead (see above). The token is sent only over HTTPS to api.github.com, never to a redirect target on another origin (nor to any hop after one), and never appears in a log line or a tool result.

fetch_url offset — paging a long web/text page (untrusted model input). A web page or text response (an accepted content type above — for example a sitemap.xml served as text/xml or application/xml) is converted to plain text and returned in chunks of about 6000 bytes (at most the budget in total). The text is first cleaned (menus nav/aside, the page-level header/footer, forms, buttons, svg, iframe and templates dropped; entities decoded; control bytes removed; repeated lines collapsed) and then capped at one per-page budget of 10240 bytes (about 10 KB) across all chunks: T in the notices is the size of the served (cleaned, capped) text, and no next_offset is issued at the budget. The same budget cuts a document's extracted text per call (including a pages range), the agentic_fetch inner input (formerly up to about 200 KB), web-search auto-fetched pages (formerly 64 KB) and text/plain files. The per-turn fetch count is unchanged. A chunk is never silently cut: when more text remains, the tool result's first line inside the untrusted-content frame (before ## Content of <url>) states the window, e.g. [gateway: page text truncated – bytes 0–6000 of 10235 shown; next_offset=5741]; the last chunk of a paged read says [gateway: page text bytes S–T of T shown (end of the served page text)]. To read on, the model calls fetch_url again with the same url and offset set to next_offset. Offsets are byte positions in the page's extracted text (not characters); a chunk ends just after a line break when one occurs within 512 bytes before the cut (so a CSV row, log line or listing entry of a plain-text page is not split), else just after a space (so space-separated items such as sitemap URLs are not split) — otherwise (e.g. CJK text without spaces, very long tokens) it is cut mid-token — and never inside a multi-byte character, and consecutive chunks overlap by at least 256 bytes, so some text repeats. Each page is one fetch toward url_fetch.max_fetches_per_turn, and each re-downloads the URL — offsets refer to the page as it is at that call, so a page that changes between calls (rotating content) can shift by a few bytes; the overlap absorbs small shifts. The web-search auto-fetch receives the same disclosure without a next_offset (it cannot page). agentic_fetch pages too — see below. Accepted shape: an integer 0–99999999 — a JSON number with an integral value (5741, 5741.0; cjson also decodes the hex spelling 0x166D), or an all-digit string of at most 8 digits ("5741"). ABSENT (omitted or JSON null) → 0, read from the start. MALFORMED → refused with a tool error (Error: 'offset' must be a whole number from 0 to 99999999 …) before anything is fetched or counted: a negative number, a fraction (1.5), NaN/Infinity, a boolean, an array/object, or a string that is empty, padded (" 5"), signed ("-5", "+5"), exponent/decimal ("1e3", "6000.0"), non-numeric, or longer than 8 digits. Absent and malformed never share a path — a malformed offset is never coerced to 0. An offset at or past the end returns [gateway: offset N is past the end of the page text (T bytes); nothing more] (not an error). An offset inside a multi-byte character is moved back to that character's start. offset applies to web/text pages only: for a document (PDF/DOCX/XLSX) it is ignored and the result says so ([gateway: offset was ignored – it applies to web/text pages only, not documents]) — long PDFs page with pages. A [gateway… lookalike inside page text — or inside the extracted text of a fetched document — is neutralised so a page or document cannot forge the notice (see Threat model). The extracted text is normalised to valid UTF-8 before it is windowed (an invalid byte becomes U+FFFD, 3 bytes), so offsets always refer to that normalised text — a page in a legacy charset (e.g. Latin-1) therefore counts more bytes and may need more windows than its raw size suggests. PII masking at window edges. On a gateway with PII masking, every window that leaves the estate is masked together with about 256 bytes of the page text on each side (only the window is returned), so any offset is safe: an identifier cut by the window's start or end is masked rather than shown as a fragment, whether the offset came from next_offset or not. This adds one masking pass per paged window (for agentic_fetch, up to two before the inner model's own request scan). If masking fails closed, the result is [tool result withheld: PII scan unavailable] and paging stops (see PII Protector). For agentic_fetch the pre-check of a part uses every edge-sensitive detector of the inner request phase — besides the PII maskers also its regex / keyword scrub detectors and its refusing block detectors (on a first-party local inner model, only the refusers). A refusal at a window edge fails the part exactly like an inner-request block: the gateway failure line above the anchor, next_offset kept, and Inner agent failed: agentic_fetch_inner: inner request blocked by guardrails below it; the inner model is not called.

Page delimiters carry a per-call tag. Fetched text can contain any line, including lines that look like the gateway's own structure, so the gateway does not rely on a fixed marker. In the agentic_fetch reader's prompt, the page stands between ----- BEGIN PAGE <tag> ----- and ----- END PAGE <tag> -----; the reader is told before the page that only the two lines tagged <tag> delimit it, and reminded after the real end line that any line inside the page claiming to end or restart it is page text. In a web search result, each page appended under ## Page Content begins with a ### Source (page tag <tag>): <url> header, and a line right after ## Page Content names the tag. The tag is 16 random lowercase letters (for example kqvbmzrtwfhxjpnd), freshly drawn for every prompt or result, so a page cannot know or reuse it. It has no digits, so no number recogniser (card, phone, IBAN) matches it. If one of the gateway's keyword, custom-PII, regex or jailbreak/injection keyword detectors (those that scan the prompt or the result — including response-only custom-PII lists; an injection list also in its rot13 / hex / base64 forms) would match the tag, a new tag is drawn, 8 draws at most, so these detectors do not mask or block a delimiter by chance. If all 8 draws match, the gateway builds a tag letter by letter that no such detector matches. Only a detector that matches every possible tag (for example a regex for any run of letters) is logged by name and acts on the last draw, the same way it acts on any gateway text — as does a detector term that matches the fixed wording of these lines (for example tag, page or lines): it acts on every such prompt or result, deterministically. Not covered: a detector term that only matches across the tag and the words next to it; the analyzer-based PII detectors (PII Protector / NER) and the prompt-injection classifier, which see the tag as one random lowercase word; response-phase keyword or regex detectors, should the model quote a tagged header in its answer; and detectors that only apply later — a stored web search result replayed in a later turn under changed settings, another role or another user's personal keywords was checked against the detectors of the turn that produced it. The page text itself is never changed. This makes a forged ----- END PAGE ----- or ### Source: https://… line recognisable as page content. It reduces, but does not eliminate, the chance that a model is misled by such a line: the result still stays inside the untrusted-content frame.

agentic_fetch offset — the same paging through the inner model. When a gateway enables agentic_fetch (it then replaces fetch_url), the tool takes the same optional offset with the same accepted shape, the same absent/malformed split (a malformed value is refused with Error: 'offset' must be a whole number from 0 to 99999999 (… a previous agentic_fetch result …). The URL was not fetched. before anything is fetched, counted or sent to the inner model), the same ~6000-byte windows with ≥ 256-byte overlap, and the same notice wording. The inner model reads ONE window and receives the window disclosure without next_offset; the outer model receives the result in this shape:

[Untrusted fetched page: <url>]
[gateway: page text truncated – bytes S–E of T shown; next_offset=N]      (more remains)
  — or [gateway: page text bytes S–T of T shown (end of the served page text)]            (the last part of a paged read)
  — or [gateway: offset N is past the end of the page text (T bytes); nothing more]   (offset ≥ T)
[gateway: offset was ignored – it applies to web/text pages only, not documents]   (document + offset)
[gateway: document text truncated – the extracted text exceeded the read limit on page K of Z; content after the cut is missing]
                                                                                   (document cut at the read limit; "on page K of Z" only for a PDF whose cut page is known)
[... note: only the first N of M pages were extracted ...]                         (PDF page cap, no byte cut)
  — or [... note: pages X–Y of Z shown ...]                                       (a requested `pages` range, no byte cut)
  — or [... note: some pages were too dense to fully transcribe; …]                (dense OCR pages, also after a byte cut)
[gateway: the inner model's answer reached its output limit – it may be incomplete] (inner answer cut)
[gateway: the inner agent failed for this part]                                    (inner leg failed / part withheld)
## Answer for <url>

<the inner model's answer — or "Inner agent failed: <detail>" — or "[tool result withheld: PII scan unavailable]">
[End of untrusted content]

A <url> longer than 512 bytes is shown as source label omitted (too long) in both places (never cut — the URL is the model's own tool argument, and each result answers its own tool call).

Gateway lines are only those before the first ## Answer for line; everything after it is the inner model's (page-derived, untrusted) text, in which any [gateway… lookalike is neutralised, and a trailing unterminated masking token ([MYRA-REDACT-… without its ], e.g. an answer cut mid-token) is collapsed to [redacted]. The model is told (trusted tool description) to page on with the same url and instruction and offset=next_offset only when the instruction needs the whole page (a list, all items, a count) or the inner answer says not in this part; to retry a failed part once and then skip it with its next_offset (telling the user that part could not be read), stopping after two consecutive failed parts; and to tell the user a part's list may be incomplete when the output-limit line appears. Each part costs one fetch toward url_fetch.max_fetches_per_turn and one inner-model call; an offset at/after the end returns the past-end notice and does not call the inner model. When the content is a window, the inner prompt asks for the answer from this part only, every matching list item verbatim, and the exact reply not in this part when the part has nothing relevant. Before an external inner model reads a part, the part is masked with its surrounding page text using the detectors the inner request runs (as for fetch_url above); a local inner model whose answer goes to an external outer model gets only the edge-crossing identifiers masked. When that masking fails closed, the part is reported with the failure line and its next_offset, the body is the withheld placeholder, and the inner model is not called. The inner call asks for up to 4096 output tokens with reasoning switched off (chat_template_kwargs.enable_thinking=false — effective on the default Myra-fleet inner model; another provider configured as agentic_fetch.model decides its own reasoning, and a resulting truncation is disclosed by the output-limit line, detected from the provider's finish_reason / stop_reason; an absent or unrecognised value means "not cut"). The inner call keeps the gateway's timeout_ms as its read deadline; a part that times out is reported with the failure line (its next_offset kept), not retried by the gateway. Paging is sequential, so a very long page may not finish inside one turn's tool-loop wall-clock budget (measured from the start of the request) — the model then answers from the parts read and says how far it got (bytes read of T) so the user can ask it to continue.

💡 Note: A guardrail block in streaming mode returns HTTP 200 with a synthetic SSE error chunk (the refusal text as a normal assistant delta.content chunk) followed by data: [DONE], rather than a non-200 status. This wire shape is unchanged for external API clients — integrate against the assistant message as before. See Error codes — guardrail_blocked.

First-party turn-owned streams (the web app) additionally receive a {"aig_status": "guardrail_blocked", "error_class": "<class>"} gateway-extension event so the app can render a distinct policy-block notice instead of a normal reply. Like every aig_* event it is emitted only in streaming mode and only on a turn-owned stream; a plain API client never sees it (see What a plain client receives). error_class is one of guardrail_blocked (content policy), guardrail_pii_mandatory, guardrail_pii_media, guardrail_role_model, or guardrail_unavailable (treat the set as open) — a stable, non-sensitive slug (it never carries any request content). A guardrail_blocked event caused by a built-in data-protection rule additionally carries an optional category (credit_card, bank_account, id_number, tax_id or health_insurance — a closed set, see Conversations); it is omitted for every other rule. A keyword or regex block may carry where, the part of the request that matched (Keyword guardrail — match location). A stream that is not turn-owned but sent x-aig-extensions: 1 (an agent's Try it) also gets the event. On a turn-owned stream the refusal delta.content is a generic, sub-category-free message; external clients keep the detailed prose.

🔒 File attachments on a PII-protected gateway: because PII guardrails scan content as text, a gateway with an active PII protector rejects a request that embeds inline base64 file media (an image_url/video_url data: URL, an input_audio/file block, or an Anthropic-native image/document with a base64 source) with the block reason pii_media_unmaskable — such binary would otherwise reach the provider unmasked. Attach files through the Chat view, which extracts each PDF/image to text server-side first so the text is masked before it leaves the gateway. Text-extracted blocks and Files-API file_id references are accepted. A request served wholly by a first-party local (Myra/EU) model is exempt from this block — there is no third-party egress to fail closed for. See Data protection — file attachments on a PII-protected gateway.

♻️ Model-unavailable recovery (extensions-enabled streams): when the pinned model is no longer routable (deprecated/renamed/deleted upstream), the gateway ends a STREAMING turn from a client that opted into the side channel with HTTP 200 and a single aig_status recovery event instead of a cryptic provider error (a plain OpenAI-compatible client, and ANY non-streaming request, gets the typed model_not_found HTTP error instead — see the closing sentence of this note): {"aig_status": "model_unavailable", "old_model", "old_display", "fresh_model", "fresh_display", "fresh_gateway_id"} when a replacement default exists, else {"aig_status": "no_default_available", "old_model", "old_display"}. The suggested (fresh_gateway_id, fresh_model) is policy-legal by construction: it is validated against the conversation's permission tier and PII posture with the SAME predicate the conversation-route PATCH guard enforces (see Route policy validation), so the server never proposes a route the app would then be refused. If the only available default would be illegal for the conversation (a cloud model for a local_only project, or a non-scrubbing gateway under a PII mandate) — or the tier can't be proven during a transient fault — the event fails closed to no_default_available rather than offering an illegal target. Like every aig_* event it is emitted only to a client that opted into the side channel (x-aig-turn-id / x-aig-extensions: 1) and asked for a stream; every other caller — a plain OpenAI-compatible client, or any "stream": false request — receives the typed HTTP error model_not_found (400) instead of an SSE body it did not ask for. That error names the model id — e.g. the model '<id>' is not available on this gateway. (the exact wording varies by path) — so an integrator can see which id was wrong without reading the gateway's logs.

What counts as "no longer routable": any 404 from the upstream on the chat-completions call, whatever its body says. It used to depend on the provider's prose — the same fault classified three different ways depending on whether the upstream happened to name the model in its error text, so a {"message":"not found"} body was reported to the user with the generic "The request could not be completed.", the same sentence the product uses for a timeout. A 404 is now always a model failure: it is never retried against the same id (definitive, not transient), and it reaches this recovery. A 404 whose body describes a MORE specific fault (a capability gap, for instance) still classifies as that fault — the status is a floor, not an override.


Data files in a private chat (x-aig-ghost-files)

A private (ghost) chat turn can hand data files to the code interpreter without storing them. Add a top-level field x-aig-ghost-files to the request body:

{"x-aig-ghost-files": [{"name": "sales.xlsx", "data": "<base64>"}]}
  • At most 8 files (GET /admin/auth/me shows it as limits.ghost_input_files_max_count); name is a plain file name, data is canonical standard base64. The web app sends this field for a private chat that carries data files (xlsx, xlsm, csv, tsv, ods, json), together with the request header x-aig-ghost-files: <count>.
  • The decoded files add up to at most 5,000,000 bytes per turn (GET /admin/auth/me shows it as limits.ghost_input_files_max_bytes). The file bytes travel with the request, are held in memory only, are not written to the conversation, the request log or any trace, and are gone when the turn ends. The response cache is bypassed for such a turn.
  • request_size_bytes in usage records reports the request size without these files.
  • The whole request body, including the conversation history, must stay under 10 MiB; a larger body is refused by the web server with 413 before it reaches the gateway.
  • Refusals: 400 invalid_ghost_files, too_many_ghost_files, ghost_files_not_ghost (the turn is not private, or the route is not chat completions), ghost_files_unsupported_type; 413 ghost_files_too_large (with max_bytes); 500 ghost_files_spooled. They honour x-aig-collect-log: 0. See Error codes.

Per-request header overrides

The provider pass-through supports an optional control header:

Header Effect
x-aig-byok-alias Selects which stored BYOK key alias to use for the resolved provider on this request (see Provider key management). Accepted shape: 1 to 64 letters, digits, ., _, -, starting with a letter or digit. Absent or empty → the default alias; default in any letter case is the default alias. A malformed value is rejected with 400 byok_alias_invalid (checked before the response cache). A well-formed alias that does not exist is rejected with 424 provider_key_missing — there is no silent fallback to default, and no fallback to a tenant-level key. Applies only to the primary provider; a fallback attempt on the same provider uses the alias this request selected, a fallback on another provider its default-alias key.
x-aig-extensions Opt into the gateway's aig_* SSE side channel (streaming only). Accepted: 1, true, yes, on. Anything else — including 0, an empty value, an unknown word, a non-string, or a repeated header whose first value is not accepted — is rejected and treated as absent, so the stream stays pure OpenAI. Implied by a valid x-aig-turn-id. This is a verbosity switch, never an authorization signal: it unlocks nothing about any turn but the caller's own. See What a plain client receives.
x-aig-image-gen Client opt-in for the generate_image tool (see Image generation). The tool is offered to the model only when the gateway has image_generation.enabled: true (see config reference) and this header carries a plain value other than 0 / false — the web chat always sends x-aig-image-gen: 1. Accepted: any single plain-string value except 0 and false — the match is exact and case-sensitive, so an empty value, FALSE, no or off all count as opt-IN (unlike x-aig-extensions, which is an allowlist). Absent, 0, false, or a repeated header (which arrives as a list, never as a plain string) → the tool is not offered; a non-string can never arm it. On a gateway with image generation disabled the header has no effect. Saved/scheduled agents never carry it. The same header also arms the remove_background tool, which is offered only when, in addition, the platform setting background_removal_available is on and the background-removal backend is configured (see below). Edit source (untrusted input): an edit takes the image from the data: image URL in the user's message of this turn (never from a gateway continuation step), accepts PNG, JPEG or WebP by magic bytes up to 12 MB, and re-encodes it (upright, ≤ 1448 px longest side, no metadata) before the image model sees it; an undecodable image is rejected before anything is sent — the full contract is in Image generation.
x-aig-video-gen Client opt-in for the create_video tool (see Video generation). Same acceptance rule as x-aig-image-gen: the tool is offered only when the gateway has video_generation.enabled: true, the platform setting video_generation_available is on, the deployment has a blob store and the video backend configured, the conversation is saved, and this header carries a single plain-string value other than 0 / false (exact, case-sensitive match; an empty value, FALSE, no or off count as opt-IN). Absent, 0, false, or a repeated header (arrives as a list) -> the tool is not offered. Saved/scheduled agents never carry it.
x-aig-connector-setup Client capability announcement for the setup_connector confirmation card (see The setup_connector chat tool). Send it only if your client renders aig_status: "connector_setup" frames. The web app chat (/easy) sends x-aig-connector-setup: 1 on every send and renders the frame as an inline Connect card. The frame (and the tool's "a setup card is shown" wording) is produced only when this header carries a single plain-string affirmative value: 1, true, yes or on (exact, case-sensitive), on a turn that also sent x-aig-turn-id. Absent or an explicit opt-out (0, false, no, off) -> no frame; the model is given a link to the Connectors page instead. Anything else is rejected: an empty value, an unknown word, another case (TRUE, On), a padded value, or a repeated header (arrives as a list) is treated as absent and logged as a warning when the header is consulted (a one-click connector on a turn with x-aig-turn-id; the value itself is not logged). Unlike x-aig-image-gen / x-aig-video-gen, "", no and off do not opt in. Saved/scheduled agents never carry it.
x-aig-provider-* The x-aig-provider- prefix is stripped and the remaining header is forwarded to the upstream provider only if the stripped name is on a short allow-list — anthropic-beta, openai-organization, openai-project. Any other stripped name (a credential such as authorization, a request-framing header such as content-length / transfer-encoding / connection, or any unrecognised name) is dropped and logged at warn; it never reaches the upstream request. At most 16 overrides / 8 KB total are forwarded; the excess is dropped.
x-aig-knowledge-ids Per-request knowledge-source ALLOWLIST. A comma-separated list of project/conversation knowledge-document ids the assistant may consider for THIS request. Tri-state by presence: absent → all knowledge (the default); present → exactly the listed ids; present with no valid id (e.g. a single - sentinel) → no knowledge. At most 200 ids are read; a longer list is truncated (truncating an allowlist only narrows what the assistant may use). The selection is intersected with — never widens — the caller's already-authorized project/conversation scope, and is enforced for auto-injected knowledge, the read_file tool, and the search_knowledge hybrid-search tool (the model can neither read nor search a deselected document). It also governs the sandbox tools: a project file or earlier generated file the selection excludes is not staged by code_interpreter / edit_office_file, not converted by name by convert_document or used as a verify_render asset, and not offered in the system prompt; the tool result carries a note that the file is excluded from this chat's selection (see Code interpreter). Conversation attachments are never filtered. search_knowledge itself accepts a single query string (natural language or exact terms such as a section/form number); a blank query is rejected, and the search is always confined to the caller's own project/conversation and tenant — a document from another project or tenant is never searched or returned. edit_file (see The edit_file tool) honours it too: a stored file excluded by the selection is neither read nor changed. A file the assistant creates or changes during this request (via write_file, edit_file or the code interpreter) is always readable by that same request's tools, whatever the selection says — the selection describes the pre-existing knowledge, not the request's own output. The selection is part of the cache key, and the semantic cache is skipped when it is present. Saved/scheduled agents do not honour caller headers, so they always use all knowledge. Ids are matched case-insensitively.
x-aig-knowledge-exclude-ids Per-request knowledge-source DENYLIST — the complement of the header above, and what the chat UI sends when you uncheck a file. A comma-separated list of knowledge-document ids to EXCLUDE from this request; everything else in the caller's authorized scope stays in, including documents added after the client last looked. Absent → nothing excluded. Unlike the allowlist this header is honoured in full or not at all: if any token is not a document id (internal whitespace included), if the header carries no usable id at all (an empty value, or only the - sentinel), or if more than 200 ids are listed, the request is rejected with 400 invalid_request — silently dropping an id would feed the model a document the caller asked to exclude. There is no "exclude everything" value; use x-aig-knowledge-ids: - for "no knowledge". Both headers may be sent together, in which case the allowlist is applied first and the denylist removes from it; neither can ever widen the caller's authorized scope. Same enforcement points as the allowlist, and the same carve-out for a file created during the request. A request carrying this header is not cached (see Caching). Saved/scheduled agents do not honour caller headers. Ids are matched case-insensitively.
x-aig-privacy-state The privacy mode the web app showed when this message was sent (for the first message of a new chat on Auto, the mode the home screen showed; "Decided on send" sends no header; voice-mode turns send none), recorded in the request log as meta.privacy_state (see Privacy state of a chat turn). Format: mode=<protected\|masked\|public> plus, optionally, ;control=<pill\|switch>;outcome=<switched\|blocked> and, for blocked, ;block=<reason>; at most 160 bytes, ASCII, no repeated or unknown key. It is a client claim that is only recorded: it never affects routing, masking, caching or any access decision. Absent → nothing is recorded. Present but malformed (or repeated) → the row records the state as invalid; the value itself is never stored. Saved/scheduled agents do not honour caller headers.
x-aig-leg Marks a request the chat interface made on its own behalf, rather than a message the user sent — currently followup_suggestions (the follow-up chips under an answer) or title_generation (the automatic conversation title). Both are ordinary completions and are guardrailed like any other, but they follow the user's turn and would otherwise be indistinguishable from it in the logs: an operator inspecting "the newest request" was inspecting one of these. It never affects routing, guardrails, billing or any access decision, and a value outside the two above is dropped (the request is logged exactly as it would be without the header). The label appears as the leg kind on request_log_legs.kind and on the log row, where the Logs list badges it. It also decides which bounded store keeps the request's turn replay record: a labelled request is kept with the chat interface's other side requests (the newest 50 per gateway by default; platform setting replay_side_ring_cap, 1 to 500), so it never pushes a user's turns out — a caller can only move its own requests there. Saved/scheduled agents do not honour caller headers.
x-aig-debug-system-prompt-encoding Development and test instances only (the instance runs with AIG_DEBUG_SYSTEM_PROMPT=1; production never does, and there the header is ignored). Such an instance echoes the system prompt it composed for a Workspace chat turn (a request with x-aig-conv-id) in the response header x-aig-debug-system-prompt (base64) — cut at 32 KiB, with x-aig-debug-system-prompt-truncated: <composed length in bytes> when it was cut. Sending this header with the value zlib (case-insensitive, surrounding spaces ignored) asks for the whole prompt instead: it arrives zlib-compressed and base64-encoded in x-aig-debug-system-prompt-zlib (any zlib reader decodes it, e.g. Node zlib.inflateSync, Python zlib.decompress), and x-aig-debug-system-prompt is not sent. A prompt whose compressed form is over 32 KiB is not sent at all — only x-aig-debug-system-prompt-truncated, never a partial stream. Any other value — an unknown word, an empty value, or the header sent twice — sends no prompt and x-aig-debug-system-prompt-error: <reason> instead; it never falls back to the cut plain form. The turn itself is served either way. On a stream whose response head was already sent, the same values arrive as the aig_debug_system_prompt, aig_debug_system_prompt_zlib, aig_debug_system_prompt_truncated and aig_debug_system_prompt_error keys of one SSE event (with x-aig-extensions).
X-Request-Id Your own correlation id for this request. The gateway always mints its own request id — returned in the response X-Request-Id header, and the id of the request's log entry; a value you send is never used as that id, so it can neither collide with nor suppress the logging of any request. Accepted shape: a single header whose value matches ^[A-Za-z0-9._\-:+]{1,64} anchored at the absolute end of the value — a trailing newline is rejected (the server anchors with \z, not a $ that would also match before a final \n) — it is recorded on the log entry as client_request_id (list and single-entry responses, the CSV export, the tenant export and JSON SIEM events). Rejected (dropped — not recorded, not echoed, the request is served normally and still logged): an empty value, more than 64 characters, any other character, or the header sent more than once. To the caller "sent nothing" and "sent something unusable" look the same — deliberately so, since the header unlocks nothing; the drop is logged server-side at info level (visible only with the error log at info; the shipped configs run at notice). Like the other correlation headers it is read from the first 100 request headers — placed beyond them it reads as absent. Saved/scheduled agents and delegated agent runs never carry it.

The x-aig-pii-overrides body field

Unlike the headers above, this control travels in the request body, as a top-level field next to messages. It carries the user's choices from the pre-send PII preview: values to send unmasked, and extra text to mask. See PII Protector - Manual unmask.

{ "messages": [ ... ], "x-aig-pii-overrides": { "unmask": ["Acme Foobar"], "mask": ["Project Zeus"] } }
  • Shape. An object with unmask and/or mask, each an array of non-empty strings (at most 512 bytes each, at most 64 entries). Unknown sibling keys inside the object are ignored.
  • unmask is all-or-nothing. One bad entry, more than 64 entries, or a value that is not an array rejects the whole unmask list, and the request is masked normally.
  • mask is lenient. Invalid entries are dropped and the valid ones apply. A value in both lists is masked: mask wins over unmask.
  • Unmask binds to the current message. A value is sent unmasked only if the gateway tokenised it in the message being sent now: the last user message (chat), the prompt (completions), a string input, or the last user input item (Responses). An embeddings input that is an array of plain strings counts as current in full.
  • Earlier content is never unmasked (the one exception: a whole-word part of an honoured person name in the client's own text, see Name parts below). A value that appears only in the conversation history, the system prompt, tool or function roles, tool_result blocks, function_call_output items or tool-call arguments keeps its token in those fields, and the request is forwarded masked.
  • Nested gateway steps keep values masked. Conversation summaries and the reading of a fetched web page re-scan other text on the same request. They never unmask anything, not even a value the turn itself sent unmasked.
  • A mandate denies unmask. Where masking is mandatory for the request, unmask is ignored in every pass over the request and the values stay masked.
  • Name parts follow a full person name. When an honoured value is a PERSON value, a separate PERSON value whose words are a whole, contiguous and strictly shorter run of its words (case as detected: Radev or Rumen of Rumen Radev; not Rad, Radeva, RADEV, and not Mette Nielsen of Mette Kjaergaard Nielsen) is sent unmasked too, in the client's own text fields only (the current message and the history). Tool results, tool-call arguments and the gateway's own additions keep their tokens, and a value of any other type that happens to equal a part stays masked. A part never makes the full name unmasked, and a part is never itself a parent. A malformed unmask list or a mandate unmasks no part either. Accepted cost: another person with the same surname or first name in the same request's text is sent unmasked too.
  • Audited first. Each pass that unmasks something new writes ONE audit event (pii.unmask: entity types, count = the newly unmasked distinct values with the name parts included, parts = how many of them are name parts; never a value) before the values are revealed. A value already unmasked in an earlier pass over the same request (a retry, a second detector) never gets a second event, also when it was first a name part and is then requested in full. If the event cannot be written, the new values stay masked.
  • Stripped before egress. The field is removed from the body on every gateway and never reaches a provider.

Sending the same header twice

HTTP allows a header to appear more than once, and some SDKs do send anthropic-beta on two lines. The gateway's rule depends on what kind of value the header carries, and it is never "whichever copy arrives first wins by accident":

Header kind Repeated Why
List-valued — anthropic-beta, x-aig-provider-*, user-agent The copies are combined into one comma-separated value (a, b), exactly as RFC 7230 §3.2.2 permits and as the front-end proxy already does for the same header. The header's own grammar is a list, so nothing is lost. Dropping the second copy would silently discard a beta flag and surface as an opaque provider 400.
Boolean opt-in — x-aig-web-search, x-aig-image-gen, x-aig-video-gen Treated as not set. An explicit : 0 sent twice keeps the capability off. The value is unusable, and an unusable value must never be more permissive than an absent one. In particular, an intermediary that appends the header cannot defeat your opt-out. (x-aig-extensions, a first-party verbosity switch, instead takes the first value on a duplicate.)
Capability announcement — x-aig-connector-setup Rejected: treated as not set (no connector_setup frame) and logged server-side at warn (when the header is consulted: a one-click connector on a turn with x-aig-turn-id). Even 1 sent twice does not opt in. A client that sends the header twice is not speaking for a single, known renderer; claiming a rendering capability the client lacks would show the user a card that never appears. Absent and malformed both mean "no frame", but only a malformed value is logged.
Scoping / identity — x-project-id, x-aig-conv-id, x-aig-skill, x-aig-thinking-budget No scope is taken from it, and the request is not cached. For x-aig-conv-id, and for x-project-id on a request without a conversation, the residency tier additionally fails closed (external models and tools blocked; no project data attached). A repeated x-project-id on a request that names an existing conversation is ignored — the conversation decides. These select a permission and residency scope. A duplicated value names no single scope, so the gateway declines to guess — and, where the header decides the residency tier, an unusable value is never treated as if nothing had been sent. Its response is never written to (or served from) the shared cache.
Correlation only — X-Request-Id, x-aig-turn-id, x-aig-regen-of-turn (a value that is sent but unusable — repeated, empty, over 36 characters or with illegal characters — is likewise not treated as absent: the response cache is not used for that request, and the image tools refuse to use any image of that turn) Treated as not sent and logged server-side (X-Request-Id at info, the x-aig-* ids at warn); the request is served and logged normally, with the gateway's own request id. An unusable x-aig-turn-id (or x-aig-conv-id) also makes the image tools refuse to use any image of that turn ("could not be read" — see The turn's images). These name nothing that decides routing, permissions or caching — a duplicated value is simply unusable as a correlation key, and an unusable value must never be recorded as if it were the one you meant.
x-aig-parent-msg-id Not used as a parent (logged at warn), the image tools refuse to use any image of that turn ("could not be read" — never the request body), and no stored "Use this image" confirmation is read for that turn — a sent-but-unusable value never falls back to the conversation's last user message (see "Use this image?"). It selects which stored confirmation applies; reading garbage as "not sent" would bind a different message's choice.

A duplicated header never returns 500. Before this rule a repeated anthropic-beta produced an internal error on the inference path that looked like a provider fault.

💡 Note: To pin a specific provider, address it in the URL path (/v1/{tenant}/{gateway}/{provider}/chat/completions) instead of the compat pseudo-provider. The compat endpoint resolves the provider from the model field, not from a request header.

x-aig-provider-anthropic-beta: interleaved-thinking-2025-05-14
is forwarded to the provider as:
anthropic-beta: interleaved-thinking-2025-05-14

See Providers overview — Compat model resolution and Provider header pass-through for the full behaviour.

💡 Note: Additional x-aig-* control headers are accepted for specific features (web search, projects, MCP tools, conversation threading). They are documented alongside the feature they configure.

🔒 Scope of caller control headers. On this OpenAI-compatible endpoint, the caller-supplied x-aig-* control headers are honored as sent — the gateway does not silently drop them here (unlike the saved-agent invoke path, which is owner-scoped and clears caller control headers). This is safe because the token is bound to a single user, and every header resolves against that identity: x-aig-conv-id, x-aig-policy-conv-id and x-project-id are workspace-scoped: they resolve only within the caller's own workspace (an id from another workspace returns nothing). What they resolve is the request's policy tier and — for x-aig-conv-id, or x-project-id on a request without a conversation — the project whose knowledge and files the turn may use (see Which project the knowledge and file tools act on below); that content is attached only after project membership and the project's gateway lock admit the caller, and always together with that project's tier. MCP connector references (tools:[{type:"mcp",connector_id}]) can invoke only connectors the caller owns or is granted (using the caller's own credentials), and x-aig-web-search merely toggles a capability the gateway must also have enabled and provisioned. No control header can disable PII protection. The client is never the authorization boundary — these headers convey the caller's own intent within the caller's own scope.

🔒 How the egress tier is resolved (residency / PII). A request's data-residency tier (local_only — no external tools/models; pii_mandatory — masking required) governs whether the turn may egress externally, and it is resolved only from the authoritative source, never from a value the client can vary:

  • A request that carries x-aig-conv-id (a conversation) resolves its tier solely from that conversation's committed project binding, server-side. A value the gateway cannot use — one that does not match the id shape, or the header sent more than once — is not treated as "no conversation was asserted": the turn fails closed, because otherwise a control could be defeated by sending the header twice. The x-project-id header is not consulted for a conversation-bearing request — so a stale or mismatched x-project-id can neither loosen a restricted conversation (no residency leak) nor spuriously restrict a plain chat. If the binding cannot be confirmed for the request, the turn fails closed (external tools/models blocked) and returns the retryable project_tier_unresolved (503), never a false permanent "only local models" — retry resolves it.
  • An id that names no conversation at all is not an unconfirmed binding, and is treated exactly as if the header had been omitted: the tier comes from x-project-id as below. Conversations are created only through the conversations API, never by an inference turn, so an id with no conversation behind it is a caller's own grouping key (together with the tenant and the signed-in user it also keys the PII token salt and id — so the tokens of a value are stable for the turns of that conversation — and the prompt cache). This grants nothing — omitting the header reaches the same place — and a restricted conversation is unaffected, because it has a real binding and takes the rule above.
  • A conversation whose project no longer exists (deleted) keeps failing closed, but the answer is permanent, not retryable: conversation_project_unresolved (403). The retryable 503 above is reserved for a binding that genuinely might resolve on a retry — promising "try again" for a project that is gone is a promise nothing can keep.
  • A request with no conversation (a raw /v1 caller acting within a project) resolves its tier from x-project-id, server-side and tenant-scoped — the header names a project; the gateway looks up that project's real tier. A cross-tenant or unknown x-project-id yields no tier.
  • A request that carries x-aig-policy-conv-id resolves its tier from that conversation's committed project binding, exactly as x-aig-conv-id would — but it does nothing else. It exists for the chat surface's own post-turn helper calls (auto-title, follow-up suggestions), which carry real conversation text and so must obey the same tier, but which cannot send x-aig-conv-id because that header also switches on server-side system-prompt composition and would replace the helper's instruction with the conversation's persona, memories and project knowledge. The header names a conversation; the gateway looks up that conversation's real binding, tenant-scoped, and fails closed when it cannot. Accepted shape: the same id shape as x-request-id (^[A-Za-z0-9._\-:+]{1,64}, end-anchored — a trailing newline is rejected). It is ignored whenever x-aig-conv-id resolved a conversation for this request, so it can never override a real conversation's binding. Anything it cannot use — a malformed value, an empty one, or the header sent more than once — is refused (the turn fails closed), never silently skipped: a header the caller deliberately sent must not be treated as one they never sent.
  • A conversation that provably has no project is a plain chat and is unrestricted; the header is ignored there too.

Which project the knowledge and file tools act on. The project whose knowledge is composed into the prompt — and on which read_file, write_file, edit_file, search_knowledge, the code interpreter's project files and project-scoped memories operate — is always the project the tier above was resolved from, never a second, independent reading of x-project-id. The tier that binds a turn and the project its tools read can therefore never be two different projects:

Request Project the tools act on x-project-id
carries x-aig-conv-id naming a conversation in a project that conversation's committed project ignored
carries x-aig-conv-id naming a plain chat none — the conversation's own file space, only if the caller owns that conversation (another member's conversation id attaches nothing) ignored
carries x-aig-conv-id whose binding cannot be confirmed (project deleted, database unavailable — even when the tier itself is served from the last-known-good value — or an unusable id) none — no project data and no conversation file space is attached, no memory suggestion is offered, and the answer is not cached ignored
carries only x-aig-policy-conv-id none (the header is policy-only) — unless the id names no conversation at all, which is treated as if the header were absent (next row) ignored
no conversation (raw /v1, a private chat, or an id with no conversation behind it) the project x-project-id names, when it is a live project of the caller's workspace — its tier then binds the turn honoured
a saved-agent run the agent's primary knowledge area (caller headers and any caller-named conversation are cleared); search_knowledge searches all of the agent's areas cleared

Web search follows the same answer: a request acting within a project runs its search through the gateway's own web_search tool (never a provider's built-in search), whether or not the header was sent; a stale x-project-id on a plain chat does not count as "in a project".

This holds for every role: an administrator (including a workspace administrator or a platform admin) naming a project of another workspace in x-project-id gets the same answer as any other caller (the project is not found: nothing of it is read or attached). /v1 has no cross-workspace project access.

Accepted: one non-empty x-project-id value. Ignored (the request proceeds, the value grants nothing): a value on a conversation-bearing request that is not that conversation's project — a stale ?project_id= after a chat was moved in another tab is the ordinary case, so it is not refused. The request log carries meta.project_header_ignored = true whenever a sent x-project-id is not the project the request acts within (a stale value, an unknown id, an empty or repeated header, a value a policy-only reference overrides); the gateway logs a warning when a conversation's binding overrode it, otherwise an informational line — so a client sending stale scope is visible. No project, no tier: an id that names no live project of the caller's workspace (unknown, deleted, or another workspace's) — an administrator included. Fails closed: the header sent more than once, or sent empty, on a request without a conversation — no project is attached and the turn is restricted as for an unresolvable tier (see Sending the same header twice). Access to the project's content is still decided by project membership and the project's gateway lock at the point the content is read.

If the database is briefly unreachable. Tier resolution always reads the database on the happy path, so a tier change takes effect on the very next request — the gateway keeps no read-through cache. It does keep a last-known-good value per gateway node, consulted only when that read fails, so a momentary database blip degrades to the last confirmed answer instead of blocking every project conversation. If nothing is cached, the request fails closed.

That fallback is an availability measure, not a guarantee, and it is worth stating what it does not promise. Moving a conversation between projects, or changing a project's access tier, clears the value on the node that handled the change — but each node keeps its own, so for up to 5 minutes another node can still answer a failed database read from what it last confirmed. Where the tier was loosened in the meantime that merely over-restricts. Where it was tightened — a conversation filed into a restricted project, or a project moved to a stricter tier — that node can treat the conversation as it was before, during a database outage, for up to that window.

Use Local only where that window is unacceptable: it constrains model routing itself, so a turn cannot reach a non-local provider regardless of what any cache answered.

Every such decision is recorded. Whenever a tier is served from the last-known-good value because the authoritative read failed, the request log carries meta.residency_tier_from_cache set to the value that was served — a tier, or no_project for a conversation last confirmed to have none. It is visible on GET /admin/v1/logs/{id} and accompanied by a [residency_tier_from_cache] warning in the gateway log. A healthy resolution is not marked, and neither is a request that failed closed: the marker means exactly "this answer may predate a change we could not read", so a compliance review can enumerate what was let through during an outage instead of inferring it.

The edit_file tool

edit_file changes only the affected passages of an existing text file instead of having the model regenerate the whole file. A model asked for a small change in a large file (a 100 KB HTML deck, a long Markdown report) used to re-write the complete file through write_file — tens of thousands of output tokens, which on a self-hosted model can take longer than the tool loop's time budget, so the file was announced but never saved. With edit_file the model sends just the replaced passage.

One change per call, plain-string arguments. Every argument of edit_file is a plain string and each call makes one change; several changes are several calls (the model may make them together in one response — they run in order, each on the result of the previous one). Reason: the self-hosted Myra models run behind vLLM's qwen3_coder tool parser, which streams a tool argument early only when its schema type is string; any other type (the former edits list) arrives as one piece when it is complete, so the stream was silent while the model wrote the edit (9–28 s per edit) and the fleet's 45 s idle timeout cut large edits. With string arguments the edit streams continuously.

When it is offered. Together with write_file, on a turn that has an owned, saved conversation and an authenticated user (not in a private chat). The system prompt then tells the model to use edit_file for a change and write_file only for a new file or a complete rewrite.

Which file it changes. Only a text file of this conversation:

  • the file a chat tool stored under that name (write_file, an earlier edit_file) — looked up by the same key the store step writes to (the chat's file space, or in a project chat the project's files that you wrote in a chat; the name is compared ignoring case and accents), including a file written earlier in the same turn. A file excluded by the request's knowledge selection (x-aig-knowledge-ids / x-aig-knowledge-exclude-ids) is neither read nor changed; or
  • the newest file of that name the user attached to the conversation (attachments of deleted messages do not count).

When both exist, the newer one is the base: the stored file's last write against the attachment's upload time (a tie goes to the stored file). So a file the user re-uploaded after an earlier edit is edited from the upload. The result is stored as a new version of the same file (same file id) — the reply shows its card, labelled Updated when an earlier version of the file is in the conversation (the very first edit of an attachment creates the stored file, so its card reads Created); the attachment itself is never changed.

An uploaded file's copy (project or conversation uploads). A stored upload of that name (a stored file that was not written in a chat) is not refused when it is readable UTF-8 text without NUL bytes within the size limit and fully ingested: it is the base of the edit, and the result is saved as the conversation's own copy under the next free name (deck-2.html), never over the upload. The copy is linked to the conversation that created it. Every later edit_file in that conversation — whether the model names the upload (deck.html) or the copy (deck-2.html) — resolves to that copy by its id and saves a new version of it (same file id), instead of making deck-3.html. Another conversation of the project never reuses the copy, a numbered file not written by a chat tool is not mistaken for one, and when the ownership lookup fails the tool reports a store error rather than guessing. An upload that is binary, oversize or still being ingested is refused as before.

Refused (nothing is changed, the model gets a sentence it can act on): a stored file under that name that was not written in a chat and is not a readable uploaded text file (a synced document, an administrator's note, an upload that is binary, oversize or not fully ingested; a readable upload is copied, see above); in a project, a file another member wrote (members of a shared chat may read it, but only its author's chats change it); a stored file whose download is a binary (an upload whose bytes are not UTF-8 text, a generated binary such as a code-interpreter document); an attachment that is not UTF-8 text without NUL bytes; a file larger than 2 MiB; a name with no extension or a binary extension. A stored file the caller may not read is treated exactly like a name that does not exist: with an attachment of that name the attachment is edited and the result is saved as the caller's own new file under the next free name (notes-2.md; a second edit in the same request continues that file) — the hidden file is never read or overwritten.

File names taken by another file. write_file overwrites only the caller's own text file of that name; a name held by anything else is not overwritten — the file is saved under the next free name (report-2.md, …) and the tool result tells the model that name (on a masking gateway as its stand-in). edit_file from an attachment takes the next free name only when the name belongs to a file the caller cannot see; the other cases are refused (see the list above). Across turns the same holds: a held name resolves to this conversation's most recently written chat-generated numbered variant, by its id (report.md held by an upload, a synced file or another member's file → this conversation's report-2.md), and write_file overwrites that variant as a full rewrite instead of making report-3.md. A file the model deliberately wrote as deck-2.html in this conversation counts as the copy of deck.html. Another conversation's copy, or another member's, is never reused; a numbered file not written by a chat tool is never taken for the copy. See Projects for the rule.

code_interpreter follows the same rule for a re-picked original: when a selected file the caller may not rewrite (an upload, a synced file) is enumerated for a run and this conversation already holds its chat-generated numbered copy, the sandbox receives that copy's latest content under the original's name, and an output with that name updates the copy in place (same id, new version) instead of creating name-3. The tool result names the swap. Asking for the original AND the copy's own name in one run stages the copy under both names, and each staged name counts its own bytes toward the 16 MB input total. An original that is newer than the copy (re-uploaded since), or a copy that is gone, unreadable or too large, leaves the original staged as before. edit_office_file and convert_document still start from the upload.

When the name carries an office extension (.docx, .pdf, .pptx, .xlsx, .odt, .odp, .ods, in any letter case) and the holder is a real document the user can see — a generated or uploaded document in the project, or a file attached to this conversation — write_file does not make a text copy under a numbered name: it stores nothing and answers with an error that points the model to edit_office_file (to change the document) or convert_document (to produce another format), each only when that tool is available in the request. In a conversation that keeps no files, a text written under an office name (by write_file or edit_file) is not delivered as a download either, because it could not be stored; the tool result says so, and a code-interpreter hint is added when that tool is available. write_file also refuses further binary extensions such as .xlsm, .docm, .pptm, .odg, .epub, .heic and .avif. The extension is read from the name that would be stored, so a masking stand-in that restores to such a name is refused too. write_file also refuses a name that ends in a dot or a space (browsers and Windows drop it on download, so report.pdf. would land as a second report.pdf); the error asks for a name without a trailing dot or space. edit_file is unchanged: it edits existing names.

Arguments (all model-generated, untrusted; validated before anything is read):

Argument Accepted shape Absent Malformed
filename (alias path) the file's name, the same rules as write_file (a plain name with an extension, no path parts, Latin script); on a masking gateway the file's stand-in, resolved to the stored file (see stand-in names) — an unknown stand-in is refused Refused Refused
old_text non-empty string, at most 64 KiB, valid UTF-8, no NUL — the exact current text to replace Refused ('old_text' is required) Refused ('old_text' must be a string for null / a number / an object / a list; empty, too long, invalid UTF-8 or NUL each refused with its own sentence)
new_text string (empty = delete old_text), at most 512 KiB, valid UTF-8, no NUL, different from old_text Refused ('new_text' is required — absent is not a deletion) Refused ('new_text' must be a string, …)
edits (the former list shape) — never accepted — Refused whatever it holds (a list — also with one entry —, an object, a JSON string, null), also next to valid old_text/new_text, with a sentence telling the model the new shape

Other unknown keys are ignored. Absent and malformed arguments are both refused, with different sentences — neither is ever read as "no change, success". Values are taken byte-exact (leading and trailing whitespace and line breaks included). An old_text or new_text that quotes an aig-elided-… placeholder (read_file's shortened form of an embedded font or image) is refused before matching — see Embedded resources in HTML and SVG files.

How an edit applies.

  • old_text must occur exactly once in the current text (overlapping occurrences count); zero or several matches refuse the call.
  • Per call: if the change fails, nothing is saved by that call. A multi-change request is several calls, so it is not atomic as a whole: when a later call fails, the changes of the earlier calls of that turn stay saved and the tool result says so ("the earlier changes to this file from this turn ARE saved — the file is partially changed"), also when the model addresses a file by the new name it was saved under, so the model can fix the change or tell the user which ones are missing. (An agent run that pauses for a human approval resumes each approved round as a fresh request; the note then covers the calls of that round.) The model is told to make changes that belong together and sit close to each other (a table's header and rows) as ONE call that replaces the whole passage. For a not-found old_text the error includes a short excerpt (at most 1,200 bytes) of the current text around the place where the quote stops matching (where it went wrong), so the model can correct its quote. The excerpt is shown only when at least 16 bytes of old_text match exactly one place. It is a cut out of the file, so it is PII-masked like every gateway cut (see PII Protector — gateway cuts); when that masking pass refuses, no excerpt is shown.
  • Matching is exact first. One adaptation: when the file uses Windows line endings and an old_text with plain line breaks has no exact match, that edit is matched and applied in the file's line-ending form.
  • Near misses are suggested, never applied. Models often copy a passage with small drift — re-indented lines, collapsed blank lines, typographic instead of straight quotes, plain instead of Windows line endings. When the exact match finds nothing, the file is not changed; the file and old_text are compared once more ignoring those differences (every run of whitespace counts as one space, typographic quotes as straight ones). old_text's own leading / trailing whitespace is not compared but marks a boundary: there the passage must be next to whitespace or the start / end of the file (" count = 0" never points into account = 0). If that finds exactly one place whose exact text also occurs only once, the error quotes the file's exact text of that place — in the same shape as old_text's edges — the line's indentation (and the line break before it) where old_text began with whitespace (a line break), the line break (and the next line's indentation) where old_text ended with them — (at most 4 KiB, PII-masked like every excerpt, inside the untrusted-content frame) and asks the model to resend the call with it as old_text and a new_text of the same form. Several such places → "matches more than one place"; a longer place → the error says so and asks for a shorter passage; none → the not-found answer above. If the masking pass withholds the passage, the error says a near miss exists and points to read_file (when offered) instead of quoting it.
  • Replays. A regenerated turn or a retried call that sends the same change again changes nothing: when the change is already in the file (an insertion that kept its anchor, with a new_text of at least 16 bytes, is recognised), nothing is saved and the file's card is shown again. A not-found old_text is never reported as success.
  • Per turn, a file can be changed by at most 20 edit_file calls (one change each; failed calls count). The tool loop's own limits (rounds, time budget) still apply, and of the tool calls in one model response only the first max_parallel_tools (gateway config, a whole number from 1 to 9007199254740991, default 4) run in that round — the rest are answered "this call was NOT run; call it again in your next response" and the model re-issues them in the next round of the same turn.
  • A concurrent save. The new version is written only while the stored file is still at the version the edit was applied to. If the user saved the file in the artifact panel in between, the edit is re-applied once to the user's saved text (so neither change is lost); if the file changes again during that second attempt the tool answers "changed again while this edit was being applied … No change was saved", and if it was deleted meanwhile "no longer exists … nothing was saved" (the store never re-creates the file it was rewriting; a retry may then start from an attachment of that name, as a new file). An edit based on an attachment never overwrites a stored file of that name that appeared meanwhile.

PII. On a turn with PII masking, the model sees placeholders; the old_text/new_text it sends are unmasked with the same reversible-placeholder rule as a write_file document before they are matched, so the stored file holds the clear values. Text outside the edited passages is stored byte-for-byte unchanged. Custom PII keywords are not unmasked (as for write_file), so an old_text quoting one does not match.

Change it and give it back. When the user asks to change the file attached to the message (or the one the previous answer wrote) and get it back, the gateway offers only edit_file and read_file instead of letting the model regenerate the file — see download-request tool forcing (the "Changing the existing file" rule). On such a request edit_file's messages never point to write_file, which is not available then.

Approval. An agent whose approval.tools lists write_file also needs approval for edit_file (it is a file write); listing edit_file gates only edit_file. edit_file makes one change per call: the calls of one response that run in that round (up to max_parallel_tools, default 4) are approved as one batch, further calls in their own round — a request with several changes can ask for more than one approval. See Agents.

Not covered. Office documents and other binary files produced by the code interpreter cannot be patched — the code interpreter rebuilds them. The tool is called natively only: an edit_file call printed as text by the model is not run.

Layout check after a file change (verify-after-edit)

After write_file stores an HTML file (.html / .htm) or edit_file stores a new version of one, the gateway renders the part that changed and checks its layout before the model's next step:

  • edit_file: the slide that contains the start of the change (a deck: .slide / [data-slide] / equal-sized <section>s, laid out exactly like the PDF export lays them out); on a page, the 1280×720 view around the change. A change outside the visible content (for example in the <head> CSS) is checked like a complete rewrite.
  • write_file (a complete file): the first slide whose text is cut off, else the first slide that renders empty, else slide 1; on a page, its top.

Entrance animations and transitions are finished before the check, so a slide is judged as it looks once shown. The render runs in the code-interpreter sandbox through the HTML converter's own hardened page loader (no network: pictures from the internet are not fetched; the conversation's own images that the file references are staged like for a conversion). One file is checked per tool round (the one changed last; the others get a one-line "not checked in this round"), at most 4 per request, one sandbox attempt each (waiting at most 8 s for one of the 4 check slots per node), only when at least 75 s of the tool loop's time budget are left, within at most 40 s (measured: about 3.5 s per render on the warm sandbox fleet; each check is bounded by 40 s, so four checks add at most ~2 min 40 s in the worst case). Verification never blocks, delays past that bound, or reverts the change.

What the model gets. The checked call's tool result ends with one gateway line:

[layout check] verdict=overflow; unit=slide 3 of 12; clipped_px=240; visible_text_chars=412; pictures=2 — …
verdict meaning
ok no visible text runs past the box that clips it
overflow text runs about clipped_px CSS px past the slide edge or another clipping box and is cut off (decorative shapes and cropped pictures are not counted)
blank the unit renders as a uniform picture (no visible text or graphics — also text in the background colour)
render_error the file could not be rendered for the check (e.g. the requested slide does not exist)
not_verified the check did not run or proves nothing (reason in brackets): busy (the per-node check slots are taken), sandbox_busy / sandbox_timeout / sandbox_failed (the sandbox fleet refused or failed the job), timeout (the render ran out of its time), limit (the 4 checks of this request are used), no_time_left / no_time_budget (the tool loop has too little time left), too_large (the file is over the converter's input size), bad_unit (a malformed unit from the calling tool), unavailable (the converter bundle is missing from the image), failed (the job failed in an unexpected way — its own input refused or an internal renderer error; logged), partial_scan (the unit holds more text than one check measures, so "nothing cut off" cannot be stated), sandbox_not_in_estate / sandbox_tier_unresolved (a Tier-1 / unresolved-tier run while the sandbox runner is outside the Myra estate), images_not_loaded (a blank render of a unit whose pictures could not be loaded proves nothing), not_shown_yet (a blank render of a unit whose text is hidden until a page script or a scroll shows it — the check stops page scripts once the page has loaded and, for a presentr-template deck, run the template's layout function — beforeprint listeners are never run by this check), unsafe_file (the file or a picture it uses was refused by the staging safety check — never rendered)

Other slides with cut-off text or empty slides are listed (at most 10); a whole-file check without problems says that all slides were checked only when every slide's text was measured and every other slide was looked at for emptiness (up to 40 other slides, no unloadable pictures). A deck with more than 500 slides is a render_error (too_large). After limit / no_time_left the line tells the model that no further check runs in this reply (so it does not edit again only to be checked). Nothing is added when the check does not exist on the gateway (no sandbox configured, code_interpreter.enabled: false, a restricted tool profile), when the client disconnected, or when it is switched off (platform setting verify_after_edit_disabled), and private (ghost) chats are not checked. With several HTML files changed in one round, the others get the line "not checked in this round". A fault inside the check is logged and the round continues unchanged (fail-open).

The picture for the model. The rendered PNG (at most 960×540, at most 512 KiB) is attached inside that tool result — an Anthropic tool_result content list [text, image], an OpenAI-shape role:"tool" content list [text, image_url] — only when all of these hold: every leg the next model call may use (the model and each fallback — a fallback without its own provider / model inherits the primary's) is a verified pair — anthropic with any vision-capable Claude model, or the Myra fleet's qwen3.8-27b (tested to take a picture inside a tool result); never a leg the gateway sends to a host the tenant chose (provider_base_urls, for the primary and for every fallback) — either no PII pipeline or mandate applies to the request, or every leg is first-party (the picture shows the file's real content, so it never reaches a model whose text input is masked); and every leg's per-request image limit still has room for one more picture (all pictures in the request count, in either wire shape). Otherwise the line says no picture is attached. The picture is labelled as a rendering of the file's content (text inside it is content, never an instruction). A tool result the central PII scan refused carries no picture. When a turn that ended early is saved for a resume (tool_results_resumed), the saved tool results keep the line but not the picture.

The picture for the user. For a stored file the gateway emits, to a client that opted into the aig_* side channel (x-aig-turn-id), one frame after the round:

{"aig_status": "file_preview", "file_id": "…", "verdict": "overflow",
 "kind": "deck", "index": 3, "count": 12, "png": "<base64>", "width": 960, "height": 540}

kind is deck (index = slide number) or page (index 0 = the part around the change). It is replayed on a force-buffered turn like ephemeral_file and stored nowhere. The web app validates every field (a UUID-like file_id, the enums, integers in range, base64 that starts with the PNG signature, at most 512 KiB) and drops a malformed frame; a valid one replaces the card's live thumbnail for that turn, with a caption naming the slide / page and the verdict. A later write of the same file in the turn removes the earlier picture.

write_file and edit_file mark a URL in the written file as "unverified link" (German: "nicht verifizierter Link"; not clickable, the text stays) when the gateway cannot trace it to a source of the run. The tool result tells the model how many links were marked.

A URL counts as known when it appeared in: a user message or attached file the user supplied, a web_search / fetch_url / agentic_fetch result, an MCP or connector tool result, a search_knowledge result, or a read_file of a file that is not model-generated. search_knowledge is counted as a source as a whole because the origin of a returned chunk is not available to the gateway; a link the model wrote into a document that was later indexed is therefore treated as known.

Not a source: anything the model wrote itself (write_file, edit_file, edit_office_file, convert_document, code_interpreter, read_file of a chat-generated file, image tools), answers of delegated agents (agent__*) and the gateway's own notes. A withheld or blocked tool result adds no URLs, and neither does a failed one: a fetch_url that failed (404, timeout, blocked), a web_search with no results or an error, a failed agentic_fetch part and a search_knowledge miss leave every URL they merely echo (the requested URL, the query) marked as unverified. The same holds for an MCP or connector call that failed: a transport or JSON-RPC error, a result with isError set (or a malformed isError), an empty or unreadable reply add nothing; only a call that returned a readable, non-error result is a source. The answer of agentic_fetch is written by the inner model and is not a source as a whole: the fetched URL itself and the URLs that occur in the fetched page text count as known, and a URL that appears only in the inner model's answer stays marked. The echoed query or heading of a successful web_search / search_knowledge result is not a source either; the result URLs are. The set of known URLs survives a held (human-approval) call, a regenerate-resume of a failed turn and delegation to a sub-agent (the child shares the parent's set).

Normalisation. Two URLs are the same when their keys match: the scheme is dropped (http and https of one address match), the host is lower-cased and loses a trailing dot and the default port, www. is not stripped, the path is compared byte for byte (case-sensitive, no percent-decoding) apart from one trailing /, the fragment is dropped, and the tracking parameters utm_*, fbclid, gclid, mc_cid, mc_eid are dropped from the query (the other parameters stay, in order). A near-miss path is a different URL and is marked. A URL that cannot be normalised (over the length limit, empty or invalid host, invalid UTF-8) is marked, never treated as known. The known set is capped at 20,000 URLs per request; beyond that more URLs get marked, not fewer.

Reserved hosts are never marked. localhost and *.localhost, example.com / .net / .org and their subdomains, the TLDs .example, .test, .invalid, .local, .internal, IPv4 loopback and private addresses (127/8, 10/8, 172.16/12, 192.168/16) and [::1] are placeholders that point at the reader's own machine or nowhere; they cannot be verified and are not sources.

Bare domains. In the model's text a bare myrasecurity.com (no scheme, no www.) is not a link in any renderer and is left alone. A bare domain the user or the instructions wrote (user message, system prompt, instructions; never a tool result, which only contributes full URLs: this holds for the gateway's own tool results and for client tool results in the request alike, so code such as os.path.join in a tool output never counts as a domain) makes exactly the root host and www.host known: if the user asks for a link to example-corp.de, https://example-corp.de/ is fine, https://example-corp.de/kontakt is a guessed path and is marked.

What is marked, per file format. The label is unverified link (German nicht verifizierter Link), in the conversation's language (other languages: English). The URL text itself always stays.

File Marked form Left alone
Markdown (.md, .markdown and the office formats built from markdown) [T](U) and ![T](U) become T (unverified link: `U`); <U>, a bare URL, and a link whose text equals the URL become `U` (unverified link); a reference definition [id]: U (also indented up to 3 spaces, inside a blockquote or list item, or with the destination on the next line) becomes \[id]: `U` (unverified link): the [ is escaped on purpose, so the definition is literal text and no longer a link, and a use such as [text][id] stops resolving and renders as plain text (fail closed) known and reserved URLs byte for byte; URLs inside fenced code and inline code spans (not clickable there; this also makes marking idempotent)
Plain text (.txt) U (unverified link) known and reserved URLs
HTML (.html, .htm, .svg) in an <a> tag the href is replaced by data-aig-unverified-href="U" (the anchor is not clickable) and the label (unverified link) is inserted inside the anchor, right after the opening tag; an unknown URL in a text node gets (unverified link); in an .svg the href / xlink:href is removed the same way, but the inserted label is bare text that SVG does not render, so it may not show every other attribute (xmlns, src, <link href>, content, ...), <script>, <style> and comments (ended the way a browser ends them: -->, --!>, and the empty forms <!--> and <!--->)

Code and data files are counted, not rewritten. For .csv, .json, .yaml, .xml, .py, .js, .sh and every other format not listed above the content is never changed (a URL in code is not a citation and rewriting would break the file). The unknown URLs are only counted, and the tool result tells the model so.

Marked text is not a source. A URL that appears in one of the marked forms is never counted as known when it is read back (for example by read_file of a chat-generated file or in a compaction summary), so labelling cannot be laundered into trust. Model-written text of any kind (history assistant prose, compaction summaries, delegation input) never widens the known set. Counted on purpose: user-confirmed memories in the system prompt, and a raw-API client's own compaction summaries (client material).

edit_file checks the applied text and considers only links overlapping the changed span. The model is told the stored form of a marked link differs from what it wrote; an edit that quotes its own earlier, now marked, text is re-served instead of failing.

Not covered (these links are marked, or not checked, by design):

  • Sources the model names without a URL (a book, a statute): there is no link to check.
  • A link found only inside the fetched page or MCP result of an earlier turn: those results are not stored, so only the URLs persisted with the conversation (search results and sources of earlier answers, user text) are known. The fetched URL itself is normally known because the user wrote it or a search returned it.
  • Researched turns older than the 30 most recent of a conversation: with x-aig-conv-id only the persisted sources of the 30 newest assistant turns that have any are read, so a link only an older turn produced is marked.
  • Footer sources beyond 100 in a request without a conversation id: a raw-API client that keeps its sources in the assistant footer is read up to 100 entries; with x-aig-conv-id the persisted sources are read from storage instead.
  • Chat answer text: this check covers files only; links in the streamed or buffered answer are not checked yet and stay unchanged.
  • The check follows the common forms models write. Not covered: malformed raw-HTML tags in a Markdown file (for example a tag without a space before an attribute), whose URLs are not marked; reference-definition labels that span several lines; namespace-prefixed SVG/XML anchors (svg:a, a custom XLink prefix); and links inside an <iframe srcdoc> document.
  • Attributes and elements that can load or navigate without a link click are not rewritten, for example <meta http-equiv="refresh">, <form action> / formaction, <iframe src>, <img src>, <object data>, <embed src>, <link href> (remote-loading elements), scripts and SVG internal-DTD entities. The in-app preview's content security policy blocks them; a file you download or host yourself is not protected against them.

Partial reads (read_file lines and slide)

read_file accepts two optional string arguments, so a model changing one passage of a large file does not have to read all of it:

Argument Accepted shape Absent (null, "") Malformed
lines a 1-based inclusive line range "A-B" (digits only, no spaces), A ≤ B, at most 2,000 lines the whole file, as before Refused, nothing is read ("5", "5-", "9-3", "0-4", "1 - 4", "a-b", a number, …)
slide a 1-based slide number "3" or inclusive range "3-4" of an HTML slide deck (digits only, no spaces), A ≤ B ≤ 999, at most 20 slides the whole file, as before Refused, nothing is read ("0", "3-", "4-3", "3 - 4", "a", a number, a range of more than 20 slides, …)

lines and slide cannot be combined: a call that sends both (neither empty) is refused.

Line numbers count \n line breaks; a final line break does not start a new line. A range that ends past the last line is clipped; a start past it is refused with the real line count. The result names the part (lines 120–180 of 812). Partial reads work for text files written in a chat (write_file, edit_file); uploaded and synced documents and documents with page anchors are read whole (their stored text can end at the ingest limit, and their citations need the whole-document view). Attachments of the conversation are already in the conversation and are not read by read_file. The part is a cut out of the file, so it is PII-masked at its edges like every gateway cut (see PII Protector — gateway cuts), and it is served inside the untrusted-content frame like every read_file result.

slide. Returns exactly the text of slide A (or slides A–B) of the file's current version, so a model can copy the old_text of an edit_file call from it instead of guessing the markup. The result names the part (slide 3 of 8, lines 141–188; a range reads slide 3–4 of 8, …). The slide is cut where its tag opens and closes; the cut is widened to the start (end) of its line only when nothing but whitespace lies between, so the indentation is exactly the file's and a slide that shares a line with a neighbour (a minified deck) is served without the neighbour's bytes. A text passage copied from the result occurs in the stored file, with three exceptions: an aig-elided-… placeholder (see below) stands for an embedded payload and is refused in old_text, so quote the text around it; the untrusted-content frame writes a literal "[Untrusted…" in the file as "(…"; and with the PII Protector on, an identifier masked at the edge of the cut is shown masked. A last slide number past the end is clipped; a first number past it is refused with the real slide count. The file must be an HTML deck the gateway can split into slides (slide elements balanced and not nested); any other text is refused with a pointer to reading it without slide. The availability, PII masking and framing are those of lines.

Embedded resources in HTML and SVG files (read_file elision)

An HTML slide deck built on the deck template is about 226 KB, about 200 KB of which are the fonts, logo and pictures it embeds as base64 data: URIs. A tool result is capped at 80 KB (its head is kept), so a whole-file read_file used to hand the model the style sheet and the fonts and never the slides. The stored file is the one source of those bytes; the model's view of it is shortened, and that view can never be written back.

What read_file shows. For a file named .html, .htm or .svg, read whole (a document without a page index) or in part (lines or slide), every data:<type>[;parameter…];base64,<payload> whose payload is 2,048 or more base64 characters (about 1.5 KB) is shown as data:<type>[;parameter…];base64,aig-elided-<12 hex digits> — the digits are the start of the SHA-256 of the payload, so the same resource gets the same placeholder on every read. The scheme and base64 are matched in any letter case; the type and parameters run to the first comma and may hold no quote, space or angle bracket. Smaller payloads stay inline (an icon costs less than its note). A payload that is not one unbroken run of base64 characters — line-wrapped, URL-encoded (%2F), or followed by a quote inside the run — is not elided and stays as it is. Base64 runs contain no line break, so the line numbers of a partial read are the ones of the stored file. Other file types, documents with a page index (read with citation anchors) and attachments of the conversation are unchanged.

The gateway note. A read that elided something is followed — after the result's untrusted-content frame closes, as gateway text that is never scanned as content and never names the file — by one note: how many resources (and how many KB) are shown as placeholders, that the view cannot be saved back, and the way forward on this turn: edit_file when it is offered and could change this very file (a text file written in this chat, or the caller's own project file, inside the request's file selection and within the edit size limit) — "quote only the text around a placeholder, never the placeholder"; code_interpreter when it is offered, loading files into the sandbox is allowed and the file can be loaded by name (HTML can, SVG cannot) — "the real file is at /input/<name>, read and write it in code, never print it"; when neither applies, that the file's embedded resources cannot be changed in this conversation. A partial read gets the note only when its part holds a placeholder. The note is part of the saved tool result, so it is in the conversation after a reload like the result itself.

What the store refuses. One shared check runs on every text file a chat tool stores or delivers live (write_file, edit_file, an HTML / text output of the code interpreter), before anything else is decided (so a chat that keeps no files does not deliver the view live either) and once more on the final stored text (after the PII restore, which can put back what the masked text hid). Nothing is stored or delivered when the content

contains examples refused as
the placeholder marker, in any letter case, with up to three non-letter bytes between aig and elid, also cut off aig-elided-3f9a0c1b2d4e, AIG_ELIDED, aig–elided (typographic dash), aig-elid the shortened view — a well-formed placeholder, a mangled copy of one and a stray literal all take the same refusing path; only text without the marker is stored
in an .html / .htm / .svg file: a ;base64, with fewer than four payload characters, or a payload cut off by ... / … src="data:image/png;base64,", url(data:font/woff2;base64,...) a stubbed resource — a model that replaced a placeholder by something else must not store a deck with dead fonts either (a Markdown note may show data:image/png;base64,... as an example: the stub rule is for markup files only)

Absent and malformed are different answers: text without the marker is stored as before; text with a well-formed, a mangled or a truncated marker is refused — none of them degrades to "stored as written". A binary output of the code interpreter (a PDF, a PowerPoint) is bytes the sandbox produced and is not scanned; the marker cannot reach the sandbox, because a code_interpreter call whose arguments (code, stdin, any nested value) carry it is refused before the program runs ("attached and project files are already staged; a file produced earlier needs input_files — read /input/<name>"), and so is an edit_office_file call. The refusal is one text, built from the tools really offered on the turn: nothing was saved, the file "contains aig-elided-… text", then edit_file ("quote only the text AROUND the placeholders") and / or code_interpreter ("fill /opt/assets/deck/deck-template.html" for a new deck; /input/<name> (plus input_files for a file produced earlier) to build on an existing file), or — when neither is offered — "write the file without any aig-elided- text". A refused write_file counts against the per-file cap like any failed write; once the cap is reached for a file whose attempts were refused this way, the cap's answer repeats that refusal (never "put the content in your reply", which would push the shortened view into the chat). edit_file refuses an old_text or new_text carrying the marker before matching (an old_text with a placeholder can never match the real bytes); its not-found excerpt is shown the way read_file shows the file (placeholders instead of payloads), and over such an excerpt no "resend it unchanged as old_text" suggestion is made.

Attached files. An .html or .htm file the user attaches (.svg only when an API client sends it as a text attachment) in the chat is sent to the model inline in the message, in every later turn of the conversation. The same elision applies to it, in the request the gateway forwards: in a user message, a text part that opens with the attachment marker ([Document: <name>, [Image: <name> or [File: <name>) naming such a file has every large base64 data: payload replaced by its placeholder before the guardrails, the context-window check and the provider see it (on the OpenAI-compatible and the native Anthropic routes alike). Everything else is unchanged: other file types, text the user typed that does not open with an attachment marker (even if it holds a data: URI), messages of other roles, a message whose content is a plain string, smaller payloads, and a part that already contains the placeholder marker. The stored message and the saved attachment keep the full bytes; only the copy sent upstream is shortened, and the shortened copy can never be saved back (the store check above). The real attached file stays reachable by its attachment name for edit_file and as a code_interpreter input file, where those tools are available; a reply that re-types the whole deck from the shortened view carries the placeholders, not the fonts and pictures. If the gateway cannot re-encode the request body after shortening (a body carrying a non-finite number), the request is forwarded unshortened on both routes (never a split view).

Consequences, by design. A file that itself contains the literal text aig-elided (only this documentation would) is shown unshortened and cannot be stored again by a chat tool. The file save in the artifact panel is the user's own typing and is not checked. A whole slide that holds a large embedded image cannot be moved or deleted with edit_file (its old_text would have to quote the payload or its placeholder); such a change is made in the artifact panel or by building the deck again in the code interpreter from the real file. On a gateway without the code interpreter a deck is created through write_file with its own content (never by copying a shortened view) and changed with edit_file.

The convert_document tool

convert_document turns a file of the conversation into another format. Arguments: file (the name of a file you attached, a project file or a file the assistant wrote earlier; see the list of file types you can attach. An .rtf source comes from a file the assistant wrote or an API request) and format (the target). It is offered wherever the code interpreter is, in saved conversations only.

Source Targets Converter
html, htm pptx, odp, pdf, docx, odt the HTML converter (the same one as the conversion menu on HTML file cards)
docx, odt, rtf, txt, md pdf, docx, odt the office-document converter in the sandbox

A conversion of a format into itself is not offered. The source is never changed; the result is delivered as a new file under the source name with the new extension, and counts toward the per-reply generated-file limit. The tool_result frame of a successful conversion carries the file_id and filename of the converted file. The family is chosen by the extension of the resolved real file name (a PII stand-in name is resolved first). Unsupported sources are answered in the tool result with the list of supported ones; a temporarily unavailable converter is reported as such. The tool description is static: it does not change with the feature. The office-document family is advertised wherever convert_document is, and has a per-turn conversion budget. When office editing is unavailable (the same safety gate as edit_office_file: the converter may not read stored documents), a request for an office-family file is refused in the tool result with the message "office documents cannot be converted here (this gateway's privacy settings do not let the converter read stored documents); HTML files can still be converted". Accepted pairs are the ones in the table above; a source converted to its own format, or to a target not listed for that source (for example rtf to pptx), is refused in the tool result with the list of targets that source supports. A file name that is not in the file list, a file whose content does not match its extension, a password-protected file and a converted file withheld by the safety check are each answered with a short reason, never with the stored file name. See Convert a Word, OpenDocument, RTF, text or Markdown file.

The edit_office_file tool

edit_office_file changes text in a PowerPoint (.pptx), Word (.docx) or PDF (.pdf) file, or cells in an Excel workbook (.xlsx, .xlsm) (see Editing a workbook) (the original is never changed; the edited file is saved as a new file, which gets a new name such as deck-2.pptx when the name is already taken, or is returned as a PDF only when asked) and/or returns it as a PDF, keeping the file's design: slide masters and layouts, the theme (colours, fonts), logos, pictures, charts and tables stay exactly as they were. The model never regenerates the document; it names the text to change, and the gateway applies the changes to a copy of the original file. The tool_result frame of an applied edit carries the file_id and filename of the saved copy; a read, a refused edit and a failed call carry none.

When it is offered. On every turn on which the original file could be staged into the code interpreter sandbox — the same condition as code_interpreter's input_files (sandbox available, an owned saved conversation, an authenticated user, and on a personal-data-masking gateway a fail-closed masking detector). The system prompt then tells the model to use it for any change to a .pptx/.docx/.pdf/.xlsx/.xlsm (or that file as a PDF) instead of rebuilding the file with code.

Which file it changes. The file of this conversation with that name, resolved exactly like code_interpreter.input_files: an attachment, a project file you can read and have not unchecked in the chat's file selection, or a file a tool made in this conversation (the newest of that name). The original is never changed — the result is a new file.

Arguments (all model-generated, untrusted; validated before anything is read):

Argument Accepted shape Absent Malformed
filename the name of a file of this conversation with extension .pptx, .docx, .pdf, .xlsx or .xlsm, as it was uploaded or saved (any characters an upload name may have — spaces, dashes, symbols; surrounding spaces are ignored; at most 1020 bytes); a stand-in name on a masking gateway Refused Refused (not a string, empty, a path separator or control character, longer than 1020 bytes, another extension — .pptm, .ppt, .doc, .xls, .xlsb, .ods — or an unknown stand-in); a name that matches no file of the conversation is answered with the resolver's note
edits a string holding a JSON array of 0–20 changes, at most 8 KiB in total (a real JSON array is accepted the same way). Each change is an object with old_text (non-empty, at most 2000 bytes), new_text (at most 4000 bytes, different from old_text; "" deletes) and optionally slide (an integer 1–9999, presentations only) or page (an integer 1–9999, PDFs only). Text must be valid UTF-8 without NUL or other control characters (tab and line breaks allowed; in a PDF a line break separates the lines of one multi-line change, only \n is accepted, and new_text "" deletes the whole block — so does a new_text of only blanks and line breaks; lines of new_text equal to those of old_text are refused as no change). For a workbook the changes have another shape and a 32 KiB cap — see Editing a workbook. No changes: read the file's current text (see below), or with output "pdf" export it as is Refused: not a JSON array, an array element that is not an object, an unknown key, a missing or non-string old_text/new_text, a too-long value, a control character, a non-integer slide or page, slide on a PDF or page on another format, a malformed multi-line block in a PDF change (an empty line inside it, a \r, more than 8 lines, one line of old_text changed into several, a no-break space at the start or end of a line of a multi-line block, a block that is only whitespace)
output "same" (the edited file in its own format), "pdf" (a PDF only) or "both"; without changes "same" reads the file and "both" is refused. For a PDF source only "same" (or absent) is accepted; for a workbook only "same" (or absent) is accepted and edits a copy; "pdf", "both", "read" and anything else are refused "same" Refused — any other value (also "PDF", a number, "") is never read as the default

edits is a string parameter because the self-hosted Myra models run behind vLLM's qwen3_coder tool parser, which streams an argument early only when its schema type is string (see edit_file above).

Reading the current text. A call with only filename (no changes, no PDF) delivers nothing; it answers with the file's current text — for a presentation slide by slide, one paragraph, bullet or table cell per line — exactly the text old_text is matched against. A model uses it for a file whose text it has not seen, typically the file it edited in an earlier turn. At most 40,000 characters are shown (the answer says when the file is longer). The text is the document's own content: it is fenced as untrusted content and masked like every tool result.

How a change applies.

  • old_text is matched against the file's visible text — what the model sees of an uploaded file: for a presentation, the slides in their order (shape texts and text boxes, group shapes and table cells); for a Word document, the body (paragraphs and table cells). Speaker notes, charts, SmartArt and slide masters are not part of it and are never changed — nor, in Word documents, headers, footers and floating text boxes. A Word field's code (and an inner field's cached value inside it) is not text.
  • Whitespace differences do not matter (a line break in old_text may stand for a paragraph, a bullet or a table cell boundary), and Markdown formatting copied from the chat's view of a Word document (# heading, - bullet, **bold**, | table | row |) is understood.
  • old_text must occur exactly once (on the given slide when one is given). Otherwise the change is refused and the model is told where the text occurs, or which similar passages exist.
  • new_text replaces it, keeping the formatting of the text it replaces. A new line in new_text starts a new paragraph or bullet with the formatting and list level of the line before it — this is how a bullet is added. A line whose text is deleted entirely is removed (a paragraph that also holds a picture, a field, a section break or a comment anchor keeps its place and is only emptied).
  • A change that would move text across paragraphs or table cells (joining two of them), add or remove table cells, or add or remove a word right at a paragraph / cell boundary that the model's old_text spans (the word could belong on either side) is refused. Splitting a paragraph moves its remainder into the new paragraph only when that remainder is one piece of plain text (its formatting is kept); a remainder with several formats, a link, a field or a line break is refused. Automatic fields (page numbers, dates, symbols) cannot be changed, and text cannot be inserted right next to them.
  • All changes of one call are applied together, in order — or none: if one cannot be applied, nothing is delivered and the model is told which change failed and why. The failed changes are listed numbered from 1 in the order sent, each with the start of its old_text in quotes (- change 2 ("Regional"): …), so the model names the change by its text, not by a bare number.

What is delivered. The edited file under the source file's name (deck.pptx; when that name is taken, the next free one, deck-2.pptx) and/or a PDF (deck.pdf), as download cards counted against the per-turn file limit. The tool result tells the model the saved name to use for further changes.

What the model is told. Each delivered output is reported on its own, in the same words for the edited file, for a PDF made with changes and for a PDF exported without changes: the original is unchanged, and the output was saved as a new file, replaced the version produced earlier in the same reply, or was delivered but not stored. Only an output that reached the user is followed by a note that the user already has it and the model must not create it again; an output that could not be delivered is reported as such and never as already delivered.

What is checked before delivery (the uploaded file is untrusted, and so is everything the sandbox returns):

  • In the sandbox, the file is opened in memory and never unpacked to disk. Refused, with "not safe to process":

    • more than 3000 package entries;
    • absolute, .., backslash, drive or duplicate entry names;
    • encrypted entries;
    • an entry over 64 MiB or more than 160 MiB in total ("too large");
    • any XML part with a document type declaration (XXE, entity expansion).

    A file that is not a package, or is encrypted or password-protected, gets "could not be opened".

    Also answered as "could not be opened":

    • a name inside the package (in a relationship target or in the content-type list) that is written with a \, # or ?, or with a percent-escape that stands for one of those or for /, % or a control character, or with a percent-sequence that is not valid UTF-8;
    • an entry name that is written with a # or ?, or with a percent-escape that stands for one of those, for /, \, % or a control character, or that is not valid UTF-8 once decoded, or that has an empty, . or .. path segment after decoding. A raw \ in an entry name stays "not safe to process";
    • two entries whose names are the same after percent-decoding and ignoring letter case (package part names are case-insensitive, as in Office);
    • a PowerPoint presentation whose slide list is broken (a slide named twice, an entry that names no slide, a missing, empty or duplicate relationship Id in the presentation's relationships, a slide link pointing outside the file, or an entry not typed as a slide), a presentation whose package relationships part is present but does not name its main part, both when the model reads the file and when it edits it; valid files are unaffected. Reading also refuses a presentation with no slides in its slide list (editing opens it and offers no slides). A presentation with no package relationships part at all is answered as "could not be opened" when the model edits it, while reading still reads ppt/presentation.xml when it exists;
    • a relationship Id that is given twice in one relationships part (also when the two spellings differ only by surrounding spaces), in a PowerPoint, Word or Excel file, when the model edits it, and in a PowerPoint or Excel file when it is read.

    Internal parts are looked up by one rule when a file is read and when it is edited: the spelling of a part's file name (letter case, percent-escapes such as slide%31.xml) does not change which part is meant.

    A name and the references to it are compared in one spelling, so a harmless escape such as image%201.png, image%281%29.png or docum%65nt.xml resolves to the part it names, whichever way the entry or the reference is spelled.

  • The sandbox returns only the changed slide or document parts. The gateway builds the delivered file from the original upload's own parts, so masters, layouts, theme, media, relationships and content types are the user's bytes. Each changed part is refused (and nothing is delivered) unless:

    • it is one of the presentation's slides or the document body;
    • it is well-formed XML without a DOCTYPE and with the same root element;
    • every element name and every element/attribute/value triple already occurs in the original part, and outside formatting only paragraphs, runs, text and line breaks became more numerous;
    • formatting blocks are copies of the original's;
    • it has no more fields, hyperlinks or external references, and no new field instruction, processing instruction or comment;
    • it is at most twice the original's size plus 1 MiB.
  • The PDF is rendered by LibreOffice in the sandbox (form fields are not exported as PDF forms). The gateway refuses it unless it passes the active-content check: no encryption, JavaScript, launch or other actions (only links to http/https/mailto and in-document jumps), embedded files, forms, rich media or non-link annotations, and stream filters only Flate/DCT. It is delivered as a re-saved copy of its parsed objects.

Personal data. On a masking gateway the model sees masked values; its old_text/new_text are restored to your real values before the edit (the same restore as write_file). A change whose old_text or new_text holds a masked value that cannot be restored — a custom keyword, or a masked value that is not one of this request's (stale, from another conversation, mangled or cut off) — is refused with a sentence naming the cause: the document never receives a placeholder such as [redacted] or [name]. Similar passages quoted back to the model are masked like every tool result. For a PDF, old_text and new_text are checked again after protected values are filled in: a filled-in value that changes the number of lines is refused (it would change the page layout), and so is a block that becomes invalid — a carriage return, an empty line inside the block, an old_text of more than 8 lines, a one-line old_text with a multi-line new_text, a no-break space at the start or end of a line of a multi-line block, or a new_text that no longer changes anything. The quote in a status line is the start of the old_text as the model sent it (40 characters at most, with … when cut; line breaks and control characters removed), so on a masking gateway it shows the masked placeholder, never the restored real value. Document hints and sheet names in a status line are likewise put on one line, stripped of control and format characters and defanged, and otherwise left unchanged so they can be copied.

Partial delivery. With output "both" each file is reported on its own: the model is told which file was saved, which was delivered without being stored (a private chat), and which could not be delivered (a file that replaced an earlier version from the same reply counts as saved). Only delivered outputs are reported as already in the user's hands. The model is pointed to the saved edited file (never the PDF) for further changes.

Approvals. For an agent with an approval list, listing code_interpreter also gates edit_office_file (see Agents); listing only write_file does not.

Limits. The file can be at most 8 MiB (the sandbox's input limit). The whole edit runs within 90 seconds, and the result is capped at the tenant's generated-file size limit (default 25 MiB).

Editing a workbook with edit_office_file

With an .xlsx or .xlsm filename the tool changes cell contents of an existing workbook. The original is never changed: the edit is made in a copy that is saved like any other edited file (budget-2.xlsx when the name is taken). Everything that is not a changed cell — styles, number formats, charts, drawings, defined names, other sheets, and in an .xlsm the macros — stays the user's own bytes. output accepts "same" (or nothing); a workbook edit keeps the workbook format and is not exported to PDF this way.

Reading. Reading is a call without edits: the model sees each sheet as a cell grid with values and formulas. The content is the user's data, shown fenced as untrusted content, and is masked like every tool result on a masking gateway.

Edit shapes. Each change is an object with an optional sheet (optional only when the workbook has exactly one worksheet; otherwise the change is refused and the worksheet names are listed) and one of:

  • cell with value (a string, number, boolean, or JSON null to clear the cell);
  • cell with formula (text starting with =);
  • range with values (a rectangle of rows of values, at most 1000 cells; at most 5000 cells per call).

At most 20 changes per call, 32 KiB for the whole edits argument. All changes are applied together — or none. The tool result lists one status per change, so the model can tell the user exactly which changes were made and which cell was refused and why. The list is numbered from 1 in the order the changes were sent, and each line also names the change itself (- change 2 (sheet "Umsatz", B5): …: the sheet, in quotes, when the change named one, and the cell or range), so the model reports a change by that label and not by its number alone.

Rejected by the gateway before anything runs. The edits of a workbook are checked in the gateway; a rejected call changes nothing and the model is told which rule failed.

Accepted Rejected
Keys sheet, cell, range, value, values, formula only; each change an object Any other key (the name is quoted, at most 40 characters); a change that is null, an array or not an object
Exactly one of cell / range Both, or neither
sheet: non-empty string, at most 255 bytes, valid UTF-8, no control characters at all (not even tab or line break) Empty, longer, not a string, control characters
cell + value (string at most 4000 bytes, finite number, boolean, null) A list or object as value, NaN / Infinity, a string over 4000 bytes or with control characters other than tab, line feed and carriage return, values on a cell, value together with formula, neither of them
An integer within ±2^53; a number token with at most 15 significant digits An integer beyond 2^53 (send it as text); a number token that does not survive the round trip as a double (more than 15 significant digits). The token-exact check applies to text input; a number that was already decoded is limited to 15 significant digits (a longer one is refused with the same message)
cell + formula: starts with =, not empty after it, at most 8192 characters, no control characters except tab, line feed and carriage return A formula without =, over 8192 characters, with other control characters; formula on a range (a formula goes into one cell)
range such as A1:C3 inside the grid (columns A–XFD, rows 1–1048576), at most 1000 cells, with values as a list of rows matching its shape exactly A malformed or out-of-grid range, over 1000 cells, value on a range, ragged rows or a row/column count that differs from the range
At most 20 changes, 5000 cells per call, edits at most 32 KiB More changes or cells; a larger edits
output absent, null or "same" Any other output ("pdf", "both", "read", "PDF", a number)

Protected values (a masking gateway) are filled in first and the limits are checked again on the result: a masked value that cannot be restored is refused; a sheet name over 255 bytes, a formula over 8192 characters or a string over 4000 bytes after restoring is refused as too long once protected values are filled in, and so is a restored edits encoding over 56 KiB.

Whole-file outcomes the model reports to the user: exit 17 (the spreadsheet engine is not installed — "editing spreadsheets is not available on this server yet"; the model must not rebuild the workbook with code_interpreter), exit 18 (formulas could not be recalculated in time, so no copy was made — try once more, then tell the user) and exit 19 (a "Strict Open XML Spreadsheet" cannot be edited — ask the user to save a normal .xlsx).

Refusals. A change that cannot be applied safely is refused with one of these codes, and nothing is delivered:

Code Meaning
bad_edit The change is not one of the accepted shapes
bad_sheet The named sheet does not exist (or the name is too long)
bad_cell The cell or range is not valid or is outside the sheet
bad_value The value cannot be stored in a cell
precision An integer beyond 2^53 would lose digits; pass it as text
merged_cell The cell is inside a merged range; the message names the anchor cell to use
protected The sheet or cell is protected
array_formula The cell belongs to an array formula
shared_formula The cell is part of a shared formula; the message names the master cell
table_header The cell is a table header, which also names a column
unsupported The cell holds something this tool does not edit
bad_formula The formula is not valid
unsafe_formula The formula is refused (below)

Formulas that are refused. A formula is checked on its full-width fold and on its _xHHHH_-decoded form. Refused are references to an external workbook, quoted references that look like a path or contain #, DDE references (app|topic!item), INDIRECT and FILTERXML (as a call or as a bare value), and the functions HYPERLINK, IMAGE, WEBSERVICE, IMPORTDATA, IMPORTXML, IMPORTHTML, IMPORTFEED, IMPORTRANGE, RTD, DDE, CALL, REGISTER, REGISTER.ID, EXEC, STOCKHISTORY, COPILOT, PY, TRANSLATE and DETECTLANGUAGE.

Recalculation. The edited sheet's formulas must show new numbers when the file is opened. The gateway therefore recalculates in the sandbox with a built-in evaluator that understands numbers, + - * /, unary minus, references to cells of the copied sheets, SUM, AVERAGE, MIN, MAX, COUNT, IF with one comparison and ROUND with a literal digit count. The state is reported once, as one line:

State Meaning
none No formula depended on a changed cell
ok Dependent formulas were recalculated; their cached values were updated
skipped_unsafe Recalculation was not done because a formula was refused
skipped_unsupported A formula uses something the evaluator does not know (other functions, circular references, array cells, "precision as displayed", or a sheet name containing ', [, ], *, ?, :, /, \ or =)

Only numbers and the errors #DIV/0! and #NUM! are written as cached values. In every case the workbook is marked fullCalcOnLoad="1", so Excel recalculates everything when it is opened: with skipped_*, the cached values of dependent cells may be stale until then, and the model is told so (stale, computed_on_open) and passes that on to the user instead of quoting an old number.

Whole-file refusals. engine_missing (the sandbox cannot run the edit), recalc_failed, strict_ooxml (Strict Open XML workbooks are not supported), too_large and not_office (not a workbook, or encrypted). The same package checks as above apply; the gateway builds the delivered file from the original's own parts and refuses any changed part that adds anything beyond cell contents.

Editing a PDF with edit_office_file

With a .pdf filename the tool edits the text of an existing PDF that has a text layer in place: the text is removed from the page's content and the new text is drawn with the same font, size and colour, so the rest of the page (images, drawings, other lines) stays as it was. The file is not converted: the result is a PDF, never a PowerPoint or Word file, and a PowerPoint or Word file cannot be turned into an editable PDF this way (use output "pdf" on that file for an export).

  • Pages. old_text is matched page by page; the text a read shows is labelled Page N:. A change may name its page (1–9999) to match on that page only; without it every page is searched, and a large file that cannot be read through within the time or text budget is answered as too large with the advice to name the page. old_text must occur exactly once (on the given page).
  • One line, or one block of lines. A match never spans two table cells or columns. A change on one line has old_text and new_text without a line break. A change over several lines is one change whose old_text holds the lines separated by \n: they must be whole, consecutive lines of one column of the page (they may belong to different paragraphs, for example a heading and the line below it), at most 8 lines, and new_text holds the new lines the same way (fewer lines than old_text is fine, the remaining old lines are cleared; more lines is overflow). Spaces and tabs at the edges of a line and empty lines at the start and end of the text are ignored; an empty line in the middle, a \r, a non-breaking space at the edge of a line, or a one-line old_text changed into several lines is refused. The lines of a block are applied all together or not at all: when one line of the block cannot be applied, the page is left as it was. This includes a line of the block that is not changed: one that is covered or drawn twice refuses the whole block, so change the other lines one at a time. An edited line is drawn anew and written back at the place the old line held in the page's text order, so copy, search and the next read show it between the same neighbours as before; a later multi-line change may quote an edited line together with an unedited one. Where the engine cannot prove that the line renders identically at that place (for example a line in the middle of a text object that also shows lines before and after it), the line is drawn at the end of the page's text order instead, as before, and the edit still applies. Left, right and centre alignment are kept; a line may grow only into free space. Several changes on the same line in one call are supported (a second change to the right of the first).
  • Whole cell first. When old_text is also a part of longer text (725 inside -725 or a sentence), a text that is exactly one visible cell or run on the page wins; otherwise the answer stays found more than once, with the hints, and the model names the page or a longer old_text. Two or more whole hits are a tie and are never resolved silently: a wrapped title's flat text (its lines joined by a space) that also stands as a one-line copy elsewhere (a footer) answers found more than once, and each hint says whether the place is a block of consecutive lines or one whole line. The model then quotes all lines of the block with a line break between them to change the block, or gives the page of the single line; a single line that shares its page with the block cannot be changed on its own, and the model reports it as not applied instead of retrying. At most three places are named in the hints, even when more tie.
  • Changes are independent. Unlike a presentation or Word file, a failed change does not stop the others (the lines of one multi-line change are one change: all of them or none; likewise, separate changes to whole, consecutive lines of one paragraph (one wrapped text block) of a page are all or nothing when one of them is refused as overflow or not supported: the others are then reported as NOT applied because a sibling line was refused, and the model does not retry them on their own): when at least one change applies, the edited PDF is delivered together with a list that gives every change, numbered from 1 in the order sent, as done, done, font substituted or NOT applied with a reason. Each line also carries the change's page (when known) and the start of its old_text, so the model names the change by that text and never by the number alone (a number is the position in the call and means nothing to the user), for example - change 4 (page 3, "Neukunden"): done. The model retries only a change that a different old_text or page can fix (not found, found more than once, spans lines that are not whole consecutive lines, bad page); not supported, overflow and sibling line refused are final: they are reported to the user and not retried, neither with edit_office_file nor by redrawing the text in the code interpreter. When no change applies, nothing is delivered and every reason is given. When a text is not found, the model reports it and never changes a similar text instead. For a PDF the model copies old_text from the tool's own page-by-page read (a read with only the filename); text printed by other PDF libraries may join or split words differently and then does not match.
  • Read hint. When the code interpreter opens a PDF, PowerPoint, Word or Excel file of the conversation (a file named in the code as /input/<name>) while edit_office_file is offered and has not been called in the turn, the code result carries one short gateway note per turn: the file can be changed with edit_office_file; call it once with only the filename to get the exact text, then put all changes into one call, because text printed by other PDF libraries often does not match old_text. The note is guidance inside the (untrusted) result block, not an instruction from the user.
  • Font substitution. A character the PDF's embedded font subset does not hold is drawn with a substitute face (reported as font substituted) or the change is refused. The simple fonts (TrueType, Type1, MMType1) PowerPoint writes into a PDF export (WinAnsi encoding, no text map) are reused as they are, so an edited line keeps the look and width of the rest; before drawing, the gateway checks for each new character that the face the page's own font loader draws for this font (for a corrupt embedded program: the fallback face MuPDF shows) really has a glyph for it and that this glyph, rendered on its own, shows ink. A new character the embedded font does not hold, either with no glyph or with an empty one, and any font program that is unusually large (over 16 MB) is drawn with a substitute face. A PowerPoint-font line with character spacing or horizontal scaling is redrawn in a substitute face.
  • Layers (optional content). A line that sits in a PDF layer (an optional-content group, as CAD and design tools write) stays in that layer after the edit, so switching the layer off in a viewer hides the new text as it hid the old. This holds for a line in one layer, also when it spans several scopes of that layer. The change is not supported, and the page left unchanged, when the page cannot be proven safe: a line in nested layers, a layer reference that is a membership dictionary, written inline or with an escaped name, or that does not resolve to a layer; two layers of one name; a layer set on a form; text on a layer that is switched off anywhere on the page; or a marked-content stream that cannot be read.
  • Reasons a change is not applied: the text is not found, is found more than once, spans columns or lines that are not whole consecutive lines of the PDF, would grow past free space (overflow), the page number does not exist, the change is not supported, or a whole line of the same paragraph that was changed separately was refused as overflow or not supported (sibling line refused: the paragraph is then changed completely or not at all). Changes to part of a line and to lines of other paragraphs or text blocks stay independent, and a retryable failure (not found, found more than once, ...) does not hold back the other changes. Not supported are: text that is not a plain opaque fill (invisible OCR layers over scans, outlines, clipping, transparency); text covered by an image or filled shape painted after it (the paint order is followed glyph by glyph, so a chart clip or shape that only sits beside the line does not block it); text that is not visible on the rendered page (at least a tenth of the old text's pixels have the colour of the background around them, for example white text drawn on a white page or under a white box; white text on a dark panel is fine); scaled, spaced or rotated text, rotated pages; right-to-left text and scripts that need shaping (Arabic, Indic and similar), bidi controls and other invisible characters; text drawn inside or cut by a clipping path (a rectangular clip that contains the whole line is fine; a clip of any other shape is refused); and a result whose page would change anywhere but the edited line (every change is verified by comparing renders and undone on doubt). An edit of text that an earlier change of the same call inserted may be refused.
  • Whole-file answers (nothing is changed or delivered): a file that is not a PDF, a password-protected PDF, a scan or other PDF without a text layer, a file over the size limit, a file with active content that the check below refuses, and, until the server's sandbox image carries the PDF engine, an answer that PDF editing is not available on this server yet and that nothing was changed.
  • Checks. The edited PDF passes the same active-content check as an exported PDF (no encryption, JavaScript, launch or other actions, embedded files, forms, rich media, annotations other than plain links such as comments, highlights and stamps, and images or streams encoded other than JPEG or Flate) and is delivered as a re-saved copy. A file the check refuses for its content is answered as refused (the model tells the user the file contains content that is not allowed); a file that exceeds the check's document budget is answered as too large; if the check itself fails (timeout, crash or an internal error), the answer is a plain failure, never a statement about the file's content. Download cards, naming (report.pdf, then report-2.pdf), storage, the per-turn file limit, personal-data masking, approvals and limits are as described for the other formats.

Slide numbers in HTML decks

Page numbers of an HTML slide deck count themselves, so adding, removing or moving a slide never needs a renumbering edit (measured before: asked to insert one slide, a model also rewrote the typed "n / 15" footer of every other slide). The model is told (in the write_file and edit_file descriptions) to make every slide an element with the class slide, all slides direct children of one container, and to write page numbers only as two empty elements:

element renders
<span class="aig-slide-no"></span> the number of the slide that contains it (its position among the sibling .slide elements)
<span class="aig-slide-total"></span> the number of slides in that slide's group of siblings

Any element with one of the two classes works; it is filled only while it is empty (CSS :empty) — a number typed into it is shown as typed. The numbers come from one constant style block, <style data-aig-slide-numbers>, which the gateway owns: it uses :nth-child(… of .slide) and :has(…) selectors, no counter() and no script, so the numbers are right in a deck that hides inactive slides with display: none, without JavaScript, in print, and in Chromium, Firefox and Safari. Browsers without :has() / :nth-child(… of …) support (Firefox before 121, Safari before 15.4) show the elements empty. Numbers and totals of 100 or more render empty (never a wrong two-digit number).

When a file is stored (write_file, edit_file, an HTML text file from the code interpreter, and the live download of a chat that keeps no files), for an HTML file (.html / .htm):

  • The style block is present exactly when one of the two class names or a stored footer (data-aig-page, below) appears in the file outside the block itself — also when a script builds the slides from a string: inserted right after the <meta charset> declaration (else after <head>, <html> or the doctype, else at the start), replaced by the current version when it differs, duplicates removed, removed when no number element is left. Nothing else in the file changes. This also runs on a file whose markup is not closed (an unclosed slide, a truncated comment at the end): the block is kept current from what can be read, so the numbers never depend on the file's history.
  • The icon sprite is added the same way. When a slide references a gateway icon (<use href="#i-audit">, #i-check, #i-doc, #i-lock, #i-shield or #myra-logo, also written with xlink:href, other quotes, an upper-case tag or attribute name such as <USE HREF="#i-check">, or a numeric character reference; the id itself is case-sensitive, so #I-CHECK is a different id) and the file defines none of those six ids itself, the gateway inserts its hidden <svg data-aig-sprite> (all six <symbol>s) right after <body> (else before the first slide). A block of ours is refreshed to the current version, extra copies are removed, and the block is removed again when nothing references an icon or the file defines one of the ids itself (the check is a raw-text scan, so an id inside a comment or script also counts as defined). A sprite <svg> that never closes (no depth-matched </svg>), is self-closing (<svg data-aig-sprite/>), or is nested in other SVG or MathML cannot be delimited: the file is then left byte-for-byte as written (neither the sprite nor the style block is touched). Both assets are applied in one pass over the file.
  • Template example slides are removed. The deck template the code interpreter starts from carries four EXAMPLE slides (a cover, two content slides, a closing slide). A model that fills the template but leaves one unchanged would otherwise store a deck with an extra slide, and "insert after slide 4" would land one off. A slide whose text (tags, digits and whitespace ignored) equals one of the four examples is dropped from the stored file, together with the whitespace before it, but only when at least one other slide remains and the slides are well-formed (balanced, no stray end tags, nothing unclosed); otherwise the file is left as written. A slide that differs in its words, or whose own <style> or <script> text differs, is a real slide and stays. Only the text is compared, so a slide that differs from an example only inside tag attributes (for example a swapped image src / alt, or a different icon) still counts as that example and is removed. The removal runs first, so the style block and the icon sprite are then computed on what is kept (a sprite block inside an example slide goes with it). Typed footers (below) are judged on the deck as the model wrote it, before the removal.
  • Typed page numbers (write_file only, never on an edit_file store): a footer such as 3 / 15, 3/15, Seite 3 von 15, Folie 3 von 15, Slide 3 of 15 or Page 3 of 15 is stored self-counting: the footer element keeps its tag and classes, its text moves into two attributes and renders through ::before while the element is empty — <div class="pagenum">ACME · 3 / 15</div> becomes <div class="pagenum" data-aig-page data-aig-pre="ACME · " data-aig-mid=" / "></div> (a script that later writes the element's text is shown alone, never next to the stored number). No element is added, so the page's own styles apply exactly as before. It happens only when the rendered text stays identical: 2–99 slides, all closed; the footer is an element whose whole content is one text run (text before the number may stay — at most 40 bytes of footer text in all —, after it only whitespace, which is dropped) of a plain kind (div, span, p, footer, small, td, li, headings, …; not inside SVG, MathML, a <select> or a <pre>); each slide shows either no such footer with the slide count as its total (an unnumbered title slide) or exactly one with its own position, all in the identical format, at least two of them; the slides are well-formed siblings (every end tag closes the innermost open element; slide tags div, section, article, main, aside, header, footer, figure, nav; no HTML tag and no <style> / <script> inside SVG / MathML); no element the styles could count differently (a .slide nested in a slide or on a void element such as <img class="slide">, a carousel slide, a case variant such as Slide, a <template>, a <noscript> mentioning slide, a script using the <!-- / <script escape states, CDATA, a class written with an entity); and the page's own styles (<style> elements and style attributes) do not mention before, :empty, data-aig, white-space, a CSS escape (\) or @import, and no <link rel="stylesheet"> is present. Anything else — custom numbering (another start, skipped slides, Roman numerals), mixed formats, a number split across tags or written with a character reference, two candidates on one slide, a quote or & in the footer text, a masked PII stand-in in it (its real value is restored only when the file is stored) — leaves the file byte-for-byte as written. When the rewrite happened, the tool result tells the model the stored form and that slides are never renumbered by hand.
  • edit_file also refuses a change that would add or edit a slide into one of the template's example slides (the store would silently remove it; nothing is saved). Its changed-slide offset for the layout check is mapped through any removal, so an edit after a removed example cover still checks the slide it changed. An edit that merely leaves an old example slide in a deck stored before this rule is not refused.
  • edit_file refuses a change that touches the gateway's style block or its icon sprite — inside it, across its edge or removing it (the store would undo it; nothing is saved). A write_file whose content carries a changed copy of either block stores the current block instead (or removes it when nothing references a canonical icon), and the tool result says so, naming the asset. The layout check looks at the changed slide even when the store added the style block in the head on that edit.

Input handling. The file is model output (possibly built from a user's attachment) and is treated as untrusted: the scan is one forward pass over the markup, linear in the file size; for the typed-footer rewrite anything it cannot delimit (an unclosed slide, an unterminated comment, tag or raw-text element) leaves the file unchanged. The HTML converter (convert_document, the conversion menu) and the layout check render the numbers like a browser; for PowerPoint, OpenDocument and Word output the converter writes each number element's rendered text into the slide as real text (an empty number element or a stored footer; at most 64 characters, quoted strings only). Because the numbers are generated by the style sheet, they are not part of the file's text: copy and paste, find-in-page, the knowledge-search text of the file and read_file show only the surrounding format text.

The generate_image tool — the image service's answer

generate_image (text→image and edit, see Image generation) sends one request to the self-hosted EU image service. Its answer is untrusted:

  • 200 is used only when the body is JSON with data[0].b64_json that decodes to a PNG (magic bytes) of at most 12 MiB; anything else — including a reply served from outside the Myra estate — is "temporarily unavailable", nothing is stored, and the attempt is recorded as failed.
  • 429 or 503 ("busy") — retried once: after the service's own wait hint when it gives one of 1–20 seconds (retry-after-ms, x-ratelimit-reset-after-ms in milliseconds, or Retry-After in whole seconds; digits only), else — no such header, or a value under 1 s such as 0 — after a random 3–6 s. A hint over 20 s is honoured by not retrying, and so is a hint header that is present but unreadable (an HTTP date, a negative, hexadecimal or exponent value, a repeated header): it may ask for a long wait. The retry runs only inside the turn's tool-loop time budget (at least 60 s for the retry plus 30 s kept for the closing answer), the whole call (both attempts and the wait) ends within 150 s of its start, and it is skipped once the client disconnected (a delegated agent's run cannot observe the disconnect and may still make its one retry). Still busy → the tool result is "Error: the image service is busy or temporarily unavailable — nothing was generated|edited. Tell the user to try again in a minute. Do not call generate_image again in this reply.", and every further image call of the same request (including delegated agents) answers that at once without contacting the service.
  • Any other status, a timeout or a broken connection — not retried: "temporarily unavailable"; for an edit, a 4xx other than 408/429 is "the uploaded image could not be edited".
  • The service's error body is never passed to the model and is logged only in redacted form.

Every attempt (including one whose connection failed before an answer) is recorded as a leg of the inference request (kind image_generation / image_edit, service flux, provider myra, its status, error_class busy / transport / failed or null; never billed).

The reply sentence after a finished image

A successful generate_image or remove_background result is a terminal status ("… It is shown to the user."): there is nothing in it for the model to relay. Left like that, some models write a tool call out as JSON text instead of answering the user. So the gateway ends the success result with one sentence, verbatim: "Also tell the user in plain prose that the image is ready." The sentence names no language, so the conversation's language rules (the system prompt) decide which language the reply is in. The sentence is additive: earlier instructions in the result (the transparency note, the note that a new picture was made from the text prompt only when the turn has attachments) stay in force. It names no tool and is appended whether or not the model wrote text before the call.

The sentence is omitted when the call added no image (a refusal, an Error:, a result that could not be shown, a call past the per-reply limit), on the call that fills the per-reply limit (its result ends with the hand-off below, which must stay the last instruction), and for create_video, whose result already names the next step. Any note about transparency (an opaque or unconfirmed cut-out) stays directly before the sentence.

The per-reply media limit — an honest hand-off

One reply shows at most 4 images, cut-outs, video clips and audio clips together (generated images, remove_background results, create_video clips, the code interpreter's charts and connector media share one budget). generate_image's tool description says so. When a request asks for more (for example "6 cartoons"), every place that meets the limit hands the rest on. The built-in image and video tools use "Tell the user plainly how many were made in this reply, name the requested ones that are still missing, and say that you will make them when they reply 'continue' (in the user's language). Never say that the missing ones were made or are shown."; connector media and code-interpreter images, which may not be reproducible, get a retry wording (below):

  • The generate_image / create_video / remove_background result whose call filled the reply (it raised the count to 4) adds, once per reply: "This reply now has 4 images or clips, the most one reply can hold; no further image or clip can be shown in this reply. If the user asked for more: …" plus the instruction. A result whose call did not add media (an early refusal while the budget was already full) gets nothing appended.
  • Once the budget is full after one of these tools ran, generate_image, create_video and remove_background are withdrawn from the tools offered to the model for the rest of the reply (the other tools stay; when they are the only tools offered they stay on the list, an empty tool list being invalid, and the media withdrawal never ends the turn). The tools are withdrawn only after one of them ran with the budget full — when charts or a connector filled the reply first, they stay offered until then. A well-formed call made while the reply is full is not run and answers "Not made: the per-reply media limit is reached — this reply already shows 4 images or clips, the most one reply can show. Do not call any image or video tool again in this reply." plus the instruction. It is not an Error: — there is nothing to retry in this reply. (A call the tool refuses for another reason first — invalid arguments, a blocked project, a busy service — keeps that answer.)
  • A connector's images or audio clips, or code-interpreter images, that one call returned but could not show because the reply is full: the tool's own (untrusted) output says only that they were not shown; after it — gateway text outside the untrusted-content frame, added after the central tool-result scan (so the scan never reads it as content) and not to a result the scan withheld — the gateway adds once per call: "[gateway note: N image(s) or clip(s) from this tool call were not shown: the per-reply media limit of 4 is reached. Tell the user plainly how many are shown and that the others were not shown, and that you can try again for them when they reply 'continue' (in the user's language). Never say that the others are shown.]"
  • The user's next message starts a new reply with its own budget, so "continue" makes the missing ones.

The generate_image arguments: seed, steps and guidance

generate_image takes an optional seed (see Reproducible images), an optional num_inference_steps and an optional guidance_scale. All three come from the model, are untrusted, and apply to a new image and to an edit.

seed:

Input Outcome
Absent or null A new image (or a new edit): the gateway draws a random seed from 0 to 4294967295 and sends it.
An integer-valued number, or a string of 1 to 10 digits, from 0 to 4294967295 Sent as the image request's seed, on a new image and on an edit.
Anything else (negative, fractional, over 4294967295, other text, a boolean, an object, NaN or infinity) Refused after the paused, egress and prompt checks, before the busy check, the image-confirmation offer and any call to the image service: "Error: 'seed' must be a whole number from 0 to 4294967295 — omit 'seed' for a new random image". Never replaced by a random seed (an empty string is malformed too).

num_inference_steps and guidance_scale:

Argument Valid Absent or null Malformed
num_inference_steps A whole number from 1 to 50 (40 or 40.0, or a string of 1 to 2 digits) Not sent: the image service uses its default Refused: "Error: 'num_inference_steps' must be a whole number from 1 to 50 — omit 'num_inference_steps' for the default"
guidance_scale A number from 0 to 20 with at most three decimals (a number, or a plain decimal string such as "5.5"; for a string the limit applies to the digits as written, so "5.0000" is refused) Not sent: the image service uses its default Refused: "Error: 'guidance_scale' must be a number from 0 to 20 with at most 3 decimals — omit 'guidance_scale' for the default"

A malformed value (out of range, more decimals than allowed, a boolean, an object, NaN, infinity, an empty or padded string) is refused at the same place as a malformed seed, with nothing sent to the image service and no image made. It is never rounded, clamped or replaced by the default. The ranges mirror the image service's own limits, so a value is refused here rather than silently changed there.

Each value is resolved once per call, so the one retry after a busy answer sends the same seed, steps and guidance. On a new image they are JSON numbers in the image request; on an edit they are multipart form fields. The offer to use an earlier image does not carry them over: the model repeats them when it calls again after the user confirms.

The result names what was sent: "Generated an image for '…' (1024x1024, seed 1234, 40 steps, guidance 5.5). It is shown to the user. The same seed, prompt, size and settings should reproduce this image on the same image service." The steps and guidance appear only when they were given. An edit reads "Edited the uploaded image as requested ('…', seed 1234, 40 steps, guidance 5.5). The edited image is shown to the user. The same source image, seed, prompt and settings should reproduce this edit on the same image service."

The seed sent is stored with the image, for an edit too, and returned as seed by the image route. The steps and guidance are stored with it too, when sent, and returned as num_inference_steps and guidance_scale (null when not sent): a seed reproduces an image only together with the same settings. An image (new or edited) that cannot be stored and is delivered live (for example in a private chat) is named image-seed-<seed>.png (a second one with the same seed is image-2-seed-<seed>.png).

Files a sandbox tool will not open (staging safety check)

Every file a sandbox tool is given — code_interpreter input files, the file edit_office_file changes, the HTML and pictures convert_document (and the conversion endpoint) turns into a document, the file the layout check renders, and the input artifacts of a workflow Code node — first passes ONE safety check. A file the check refuses is never placed in the sandbox, by any tool. The refusal does not depend on what the model is told or does: a file edit_office_file refused cannot be opened with code_interpreter instead.

What is refused

Reason The file
dtd an Office or OpenDocument file (.docx, .pptx, .xlsx, .odt, … — any zip holding [Content_Types].xml or mimetype) with a document type declaration (<!DOCTYPE …>) in any of its parts that is XML, whatever the part's name (pictures as SVG and embedded HTML pages excepted) — the same rule the upload text extractors and edit_office_file apply; or ANY file (and any file inside a zip) that declares an entity (<!ENTITY …>, internal or external), uses a parameter entity, or points its document type at a local DTD file (a SYSTEM id that is not an http(s) address)
unreadable_xml XML in an encoding the check cannot read (for example UTF-7, EBCDIC, UCS-4, an unknown encoding name); an XML part of an Office file that is not readable XML up to its first element within its first 64 KiB; a file inside a zip (or a compressed file's content) that has no XML root early on and is larger than 16 MiB — too large to search for declarations
bad_package an Office file whose entry list is unsafe (absolute, .., backslash, drive-letter, NUL or doubled-slash names, duplicate names, encrypted entries, more than 3000 entries); a plain zip with encrypted entries or more than 10000 entries; a file that starts like a zip but cannot be read as one; a tar with bytes (junk or zero blocks) in front of its first header, or with a header the reader cannot open
zip_bomb an Office file with an entry that declares more than 256 MiB uncompressed (the upload extractors' limit); any file whose check would have to read more than 256 MiB of unpacked content, or whose decompression would need more than 256 MiB of memory

A file compressed with gzip, xz, the older .lzma format or bzip2 is checked by its content, one layer deep, and EVERY concatenated stream of it is read (the way the standard decompressors read them: an empty stream, zero padding or trailing bytes between or after streams do not end the read). A compressed stream that breaks after producing output is refused (unreadable_xml — a reader may already have acted on what came out). The check never stops at the first reading of a file: the unpacked content, the bytes as markup, as a zip (found by its end) and as a tar are ALL judged, and the file is refused when any one of them is unsafe. A tar is recognised by a valid header at the start of the file (or of the unpacked content), or at a 512-byte boundary within its first 16 MiB (a header found there behind other bytes is refused). The check fails closed for what it recognises (a zip, a tar, a gzip / xz / lzma / bzip2 stream, markup) and cannot read, and when the check itself cannot run; formats it does not recognise are passed as opaque bytes (see Known limits). A file whose unpacked content is larger than 16 MiB is refused (zip_bomb) when that content starts with a zip archive or its last 64 KiB contain a zip end-of-archive signature (for example a zip, .docx or .xlsx among the last files of a large tar), and one whose content is XML is judged by its first 64 KiB as before; a compressed file inside a zip, and an archive inside an archive (one level deep), that is larger than 16 MiB is refused (zip_bomb; bad_package inside an Office file). A file that starts with a parameter-entity reference (%name;) is refused as dtd. XML in UTF-16 is checked with or without a byte-order mark. Tar archives (also compressed: .tar.gz, .tar.bz2, .tar.xz) are checked like plain zips. A compressed tar is opened in full whatever its unpacked size, as it unpacks (never held in memory whole), within the 256 MiB work budget — a few MiB of data.tar.gz that unpack to tens of MiB of CSV files pass; more than 256 MiB unpacked is refused (zip_bomb). Anything other than zero padding behind a tar's end (a damaged block, a second archive) is refused (bad_package). Two lenient-reader behaviours are matched: a member of an unknown type is read as a regular file and checked like one, and a tar header lying behind any other bytes at a 512-byte boundary in the first 16 MiB of the file (or of the unpacked content) is refused (bad_package). Not every lenient-reader behaviour is matched (see Known limits). A file inside an archive that is itself an archive — for example the workbook embedded behind a chart in a presentation — is opened one level deep with the same rules, when it starts like one (an embedded package too large to check refuses its Office file). EPUB books are plain zips here (their table of contents carries a standard doctype). A file that starts with markup but is not XML (an HTML or Markdown write-up, for example) and quotes <!ENTITY anywhere is refused too — the check cannot tell a quotation from a declaration a lenient reader would act on. A DOCTYPE anywhere in such a file is held to the same rules as one at its start; a stretch of the file that cannot be read as XML before its DOCTYPE (for example bytes in an encoding the check cannot decode) is refused as unreadable_xml. Every DOCTYPE that is more than a bare <!DOCTYPE name> counts toward a limit of 16 per file (in each of UTF-8 and the two UTF-16 byte orders): a file with a 17th is refused as dtd, so padding a file with decoy DOCTYPEs cannot push a real one past the check. A check reads at most 256 MiB of a file's content (unpacked); a file that needs more is refused as zip_bomb, as is a compressed file whose decoder would need more than 256 MiB of memory.

What is accepted — everything else, including HTML with <!DOCTYPE html> (any letter case), XHTML and SVG with a PUBLIC / SYSTEM doctype that declares nothing (also as pictures inside an Office file), CSV, text, logs, JSON, PDF, pictures and normal Office files (also when re-saved by LibreOffice). A zip is recognised by its end (the way readers open it), so a zip with other bytes in front of it is checked like any other. Plain zips and tar archives get only the entry rules above (encrypted entries, entry count) and the declaration check of their files; the archive and reader shapes listed under Known limits are not opened or not seen.

How the decision is kept. The verdict is a function of the file's bytes alone, kept per content hash (SHA-256) and checker identity (a hash of the check's own rules — any rule change re-checks every file): every copy of a file — a chat attachment, a project file, a connector-synced file, an API attachment, a file a tool made, a workflow artifact — shares one verdict. A file with no verdict yet (uploaded before this check existed, or whose verdict is older than 30 days) is checked the first time a tool stages it. The stored row holds no content, name, tenant or user. At most 8 checks run at once per server; a check that finds no free slot is answered like an unavailable check (below).

Entry points. Every way a file reaches a sandbox goes through this check at staging: chat uploads (the app already refuses a document with a DTD at upload), files attached through the API, project files and connector-synced files (also those whose text extraction failed), files the model made, and workflow artifacts. E-mail-trigger and form uploads reach a workflow as text, not as raw files. The program text itself (code, stdin) is not a file and is not checked.

What the model is told. code_interpreter drops only the refused file (the others are staged and the program still runs) and says which file was refused and why, and that it must not be opened, changed or rebuilt with any other tool; edit_office_file changes nothing and says the same; convert_document and the conversion endpoint refuse the conversion (422 convert_unsafe_file); the layout check reports not_verified (unsafe_file); a workflow Code node fails with code_unsafe_input (terminal).

When the check cannot run (the verdict store or the checker is unavailable) the file is refused too — the tools say "try again in a moment", a workflow Code node answers the retryable code_unavailable. A file is never staged without a verdict.

A file already in a running session. When a file is refused, the conversation's persistent code-interpreter sessions are ended and the rest of that reply runs without one; the next reply starts a fresh session. Ending a session is best-effort: if the sandbox cannot be reached to end it, a session that holds a file staged before this check existed ends on its own (after at most 2 hours idle, 12 hours in total).

Known limits. A file of any of the following shapes is NOT refused, although a reader inside the sandbox could open an XXE payload hidden in it. They are accepted for now, pending a decision on hardening the XML parsers inside the sandbox; none of them is a safety claim, and no timeline is stated.

  1. A tar header with a numeric field that GNU tar accepts but the check's tar reader does not (for example a devmajor, mtime or uid that is not octal) in the FIRST header of a tar with no other valid header in its first 16 MiB (in practice a single-member tar): the check's reader stops there, GNU tar extracts the member (also inside a .tar.gz). The same field in a later header, or in the first header when another valid header follows within 16 MiB, is refused (bad_package).
  2. A tar behind more than 16 MiB of other bytes or zero blocks inside a compressed stream (gzip, …).
  3. busybox tar ignores a pax size record and uses the header's size field, so it can extract members the check sees only as data of another member, deeper than it opens (item 8).
  4. GNU tar skips the data bytes declared by a symbolic-link header (reproduced: a member hidden there was extracted by GNU tar); the check (like python tarfile and busybox) treats link, device, fifo and directory headers as carrying no data, so a member hidden in those bytes is not seen. For the other data-less header types (hard link, device, fifo, directory) GNU tar did not extract a hidden member in our test; they are listed as possibly affected and are not relied on.
  5. Zip local entries that are not in the zip's central directory (busybox unzip reads local headers in sequence; LibreOffice repair finds them anywhere).
  6. An inner archive (one level in) with other bytes in front of it.
  7. Formats with no detector: cpio, ar, rpm, .Z (compress), lzop, lz4, brotli. These are the formats the sandbox image can unpack besides zip, tar and gzip / xz / lzma / bzip2 (GNU cpio, ar, busybox cpio / ar / rpm / lzop / uncompress, python lz4 / brotli); the image has no 7z, rar, bsdtar or Info-ZIP unzip.
  8. Archives nested more than one level deep.

A persistent session holding a file staged before this check existed can outlive a refusal when the sandbox cannot be reached to end it (at most 2 hours idle, 12 hours in total). Verdicts are kept per file content across all tenants, so whether a check was already cached (a faster answer) reveals, weakly, that identical bytes were staged somewhere in the last 30 days — never which tenant, user or file.

The create_video tool

When offered (see x-aig-video-gen above and Video generation), the model can call create_video. The call is asynchronous: the gateway validates the arguments, starts a job on the self-hosted EU video backend, and returns a short confirmation to the model. The clip is delivered to the conversation later (see Generated videos).

Every argument comes from the model and is untrusted. The gateway checks only the shape of each argument; which model, size, length and frame rate are allowed is decided by the backend (a single authority). Unknown keys are ignored.

Argument Accepted shape Absent or null Malformed
prompt Required (optional with based_on_video, where it replaces the stored prompt). String, trimmed, valid UTF-8, 1 to 2000 characters. Refused Refused
negative_prompt String, valid UTF-8, 0 to 2000 characters. Omitted (backend default) Refused
model String matching ^[a-z0-9.-]{1,32}$ (ltx-2.5 or wan-2.2). Omitted (backend default ltx-2.5) Refused (shape); an unknown name is rejected by the backend
seconds Integer-valued number or digit string, 1 to 60. Omitted Refused
fps Integer-valued number or digit string, 1 to 60. Omitted Refused
seed Integer-valued number or digit string (at most 10 digits), 0 to 4294967295. Omitted (backend draws a random seed) Refused
size String WIDTHxHEIGHT (3 or 4 digits each). Omitted Refused (shape); an unsupported size is rejected by the backend
audio true, false, "true" or "false". Omitted (backend default: audio on where supported) Refused
based_on_video Id of a finished video in this conversation (string, 1 to 64 characters). Re-runs that clip's stored settings. Not a re-run Refused (empty, non-string, or over 64 characters)
based_on_mode Exactly again, hd or continue. Required with based_on_video. Not a re-run (refused if based_on_video is given) Refused (any other value); refused without based_on_video
use_uploaded_image Strict: true, "true", 1, "1" start from the uploaded image; false, "false", 0, "0" or absent/null mean text-to-video. Text-to-video Refused (never degraded to text-to-video)
start_image Id of an image in this conversation (string, 1 to 64 characters): a generated image, or a user message that carries an uploaded image. Not with use_uploaded_image or based_on_video. No start image Refused (empty, non-string, or over 64 characters)

Absent versus malformed. An absent or null argument is simply left out and the backend default applies. A malformed argument is refused with a sentence naming the field, and no job is submitted; it is never coerced to a default.

Start image. With use_uploaded_image set, the gateway takes the image the user confirmed for this tool, else the image attached to the user's latest message (exactly one: with two or more image blocks no start frame is picked — see "Use this image?", "Several images") — the message the user sent for this turn, captured before any tool runs, so a gateway continuation step within the turn (a "Continue" or a steer note) never replaces it (the same rule applies to generate_image edits and remove_background; on a regenerate with a reason, see Effect 3 of x-aig-regen-of-turn); with neither, the newest chat image is offered — see "Use this image?". The image is a base64 data: image URL (remote URLs are never fetched), decoded and checked by magic bytes (not the declared MIME type), PNG, JPEG or WebP only, at most 10 MiB decoded. No attached image, undecodable base64, another format or an oversize image is refused before any submit. The gateway re-encodes the bytes to a clean base64 data URL for the backend, which validates the image again by its content.

Start image by id (start_image). The web app's Animate button places a draft that names an image's server id; the model passes it as start_image. It is used only when the user's latest message names that id (see "Use this image?"); otherwise the call is treated as use_uploaded_image. Generated images count only when their answer is live (not deleted or replaced by a regenerate) — this also applies to Again / Render in 1080p of a clip whose start image belonged to an answer that was since deleted or regenerated: that re-run is refused with "not available in this chat". After the conversation owner check, the gateway looks the id up in this conversation only: first as a generated image; only when no generated image has that id, as a live (not deleted) user message of this conversation, whose last photo is used — its last image_url block with an object { "url": "data:<mime>;base64,..." } and no filename (a document's embedded figure is never used), or, when the message stores no pixels (a gateway that masks personal data), its uploaded image file. The bytes get the same checks as an uploaded image (magic bytes, PNG / JPEG / WebP, at most 10 MiB) and go only to the video backend, never to the language model. Refusals (no job submitted): an unknown id, an id from another conversation, an assistant message, a deleted message, or a message without such an image all get the same answer ("not available in this chat"); a GIF or another format, an oversize or unreadable image; start_image together with use_uploaded_image or based_on_video. A storage error on either lookup answers "temporarily unavailable" (never "not available"). The clip's stored settings remember the id, so Again and Render in 1080p re-use the same image; a forked conversation drops it (the id belongs to the original conversation).

Re-running a clip (based_on_video). The web app's one-click actions (Again, Render in 1080p, Continue) place an editable draft in the message box — a short fixed sentence naming the server-minted video id — which the user may change and then sends; the model passes the id to the tool as based_on_video with based_on_mode, and the gateway loads the clip's stored settings server-side. A stored prompt is therefore never re-sent as user text. Modes: again uses the stored settings with a new random seed; hd uses them with the same seed at the clip's 1080p size; continue starts a new clip from the last frame of the source (ltx-2.5 only, source within the backend's 24 hour retention). The conversation owner check runs first. Merge rule: the stored settings are the defaults and only prompt and negative_prompt may be passed alongside (they replace the stored ones); any of model, seconds, size, fps, seed, audio, use_uploaded_image or start_image is refused. The merged input goes through the same shape validation as a fresh call. Refusals (no job submitted): an unknown id and an id from another conversation get the same answer ("not available in this chat", no existence oracle); the video is not finished; its settings were not recorded; again or hd on a clip that started from an image attached to the message or continues another clip, since that start image cannot be re-sent (a clip made from start_image re-uses its stored id; if that image is no longer available the re-run is refused with "not available in this chat"); hd when no 1080p size exists; continue on a non-ltx-2.5 clip or one without a backend job id; and a backend 400 such as "source video is no longer available" is relayed after the 24 hours.

Backend allow-lists. The backend rejects values it does not allow (for example a size that the chosen model does not support, a start image with wan-2.2, or audio with wan-2.2). Its 400 message is sanitized (control characters and brackets removed, truncated to 200 bytes) and relayed to the model so it can correct the call once.

Other refusals (returned to the model as an error string, no job submitted): the tool is not available (setting off, blob store disabled, backend not configured, egress-blocked project, unsaved conversation, no user); the conversation does not belong to the caller (the conversation id header is client-asserted and is checked against the owner); the model already called the tool three times in the reply; the model already started two videos in this reply (its own check — it holds even when a clip of the reply was cancelled or failed meanwhile); the user already has two pending videos (clips from earlier replies included); the per-turn media limit is reached. Backend 413 (image too large), 429 (busy), and any other backend or transport failure produce a fixed "too large", "busy" or "temporarily unavailable" sentence.

"Use this image?" — the image_confirm offer

generate_image with edit_uploaded_image, create_video with use_uploaded_image and remove_background with use_uploaded_image work on the image attached to the latest message. When that message has no image, the gateway never picks an older one by itself; it offers the newest image of the conversation and produces nothing:

  • Which image. The newest by the thread order (created_at, then seq) among: generated images of live, committed answers (images, charts, cut-outs), and live user messages carrying an inline data: image (their last such photo), and live user messages that record a photo only as its text extract (a gateway that masks personal data). Such an upload is offered like any other: the gateway checks its uploaded file (the message's image attachment — the pixels of that photo) against the tool's type and size limits, and the web app previews it from that file (GET /attachments/<id>; the card itself is the owner's only). That file is the ORIGINAL upload (without masking, a photo sent to a model with image input is stored as an inline copy reduced to the model's limit, about 7.4 MB), so an original over the tool's cap is offered with usable: false, reason: "too_large". When that newest image is a message with two or more photos, or one whose pixels never reached the chat (its upload failed or was refused), nothing is offered — never an older image — and no image_confirm frame is sent — see The turn's images. A pick in the app's Pick another list is an explicit choice (of the image it shows). Images of a deleted answer, of an answer replaced by a regenerate, of a still-streaming placeholder, and — on a regenerate — of the answer being replaced are not offered.
  • When. Only for a saved conversation the caller owns, and only to a client that renders the side channel (the web app: x-aig-turn-id, a delivering stream). A raw API call, a private chat, a non-owner (for example a live co-driver of a shared conversation) and a conversation without any image keep the previous answer ("attach an image"). An egress-blocked (local-only / Tier-1) project refuses the tool before any lookup.
  • The event. One aig_status: "image_confirm" frame per turn: { "image_id": "<uuid>", "kind": "generated" | "upload", "tool": "generate_image" | "create_video" | "remove_background", "usable": true | false, "reason"?: "too_large" | "unreadable" | "bad_type" }. usable: false means the newest image fails that tool's type / size checks (for example a GIF, or an image over the size cap); it is still shown so the user can pick another. On a PII force-buffered turn the frame is replayed with the other side-channel events. The app validates the frame (a lowercase UUID id and the listed values only) and drops anything else.
  • The model is told that nothing was produced and that the user should press Use this image; every image tool call in the rest of that turn is refused. Such a turn is never resumed from saved tool results (Try again runs it again, which re-offers).
  • The confirmation. The app sends a user message carrying image_source (see Conversations → The confirmed image). On that turn the gateway reads it from the turn's user message — the stored message x-aig-parent-msg-id names (the app sends it on Send again, Regenerate and edit-and-resend too; see The turn's images for a turn without one). For the tool it was confirmed for, every call of that turn works on that image: generate_image edits it even without edit_uploaded_image, create_video uses it as the start frame (a model-supplied start_image is ignored; based_on_video is refused), and remove_background uses it (a model-supplied image is ignored); it also wins over a file attached to the same message. The image is loaded after the owner check, from this conversation only, live messages only, with the tool's own checks. When the provider honours a forced tool_choice, leg 1 of that turn offers and forces only the confirmed tool (not when the client sent its own tool_choice, a Create it now click owns the turn, or the tool is not offered any more).
  • Refusals on a confirmed turn. The image is gone (deleted, replaced, another conversation's): "no longer available — ask the user to attach it". A stored confirmation that does not parse: "could not be read". A database error while reading the confirmation (or the owner check before it): every image tool of that turn answers "temporarily unavailable" — also a plain text-to-image call — never the unconfirmed path. A confirmation for another tool is ignored by this tool. The confirmation is read only for the conversation's owner; a malformed x-aig-parent-msg-id disables the last-user-message fallback (no confirmation is read).
  • An image produced earlier in the same reply is not stored on its answer yet: instead of offering an older image, the tool tells the model the new image can be used from the user's next message.
  • The turn's own message (its attachment and the ids it names) is the human message as it stood when the tool loop started — a continuation nudge appended later ("Continue") does not replace it.
  • Several images on the latest message → see The turn's images: edits, start frames and cut-outs produce nothing and pick no image; no image_confirm frame is sent.
  • Ids the model names. create_video's start_image and remove_background's image are used only when the user's latest message names that id as a whole word (the Animate / Remove background drafts do; on a reason-regenerate, the message before the reason). An id the model took from elsewhere in the chat goes to the offer instead.

The turn's images — one source per kind of turn

The image tools (generate_image edits, create_video start frames, remove_background) take their source from the user's message of the turn. The kind of turn decides where that message is read from — never the number of images:

Turn Where the images come from
Saved — any turn of a saved conversation with x-aig-parent-msg-id (the web app sends it for every send, Regenerate, Send again and edit-and-resend) The stored user message that id names: its count and its bytes. Bytes: the message's inline image (what the model was sent, already fitted to the inference budget); where the stored message carries no pixels — a gateway that masks personal data, or a model without image input, stores only the picture's text extract — the uploaded file (the message's image attachment), for the conversation's owner only (the image tools read attachment files for the owner only; the download also serves the file's author, see Conversations → Attachments); a co-driver's turn is then refused ("only the conversation's owner can use").
Unsaved — a private chat, or an API caller without the web app's turn headers The request body (the human message of the turn, captured before any tool runs).
Refused ("could not be read") x-aig-conv-id, x-aig-turn-id or x-aig-parent-msg-id sent but unusable; a parent id that names no live user message of this conversation; a web-app turn (x-aig-turn-id) without a parent id on a conversation that has user messages (the row is never guessed — the last user message is not necessarily this turn's); a token without a user; a caller who may not drive this conversation's turn. The request body is never used instead.
A web-app-shaped turn on a conversation without user messages (an API caller that sends the turn headers) Unsaved (the request body).

Because the web app now names the user message on a Regenerate too, the regenerated answer is stored with that message as its parent (like a normal send), and features that key on the turn's user message — the "change this file and give it back" check (edit_file only, see above) and the "Use this image" confirmation — apply to a regenerate of that turn as they did to the original send.

Who may read the stored message: a conversation of another tenant is never read (the tenant fence comes first); then the conversation's owner, or the live co-driver who holds the driver lease (the same check that lets them send the message). A read-only project member or a non-member reads nothing. A storage error answers "temporarily unavailable". Accepted residuals: a co-driver whose driver lease lapses while the answer is running is refused for that turn ("could not be read" — they send again); and a web-app bundle from before this rule, still open in a tab, sends no parent id on Regenerate, so its image edits are refused until the page is reloaded.

Counting the pictures.

  • Stored message: its photos are the inline image_url blocks without a filename, or — where the content carries no pixels — the text-extract blocks { "type": "image", "filename": … } (one per photo), and its image attachments (mime_type image/*); the larger count wins, so a file whose upload failed never makes two photos look like one. A Word file's embedded figures or a PDF's chart/table/figure page renders carry the document's file name and are not sources. A photo block that cannot be read (for example a remote URL) still counts. A recorded photo whose pixels are not in the chat (its upload failed, was refused or was too large) → "not available in this chat — attach it again"; never an older image.
  • Request body: every image_url, image or input_image block by type, whatever it contains (a remote URL, a malformed data URL, a native block without a source — malformed is never read as absent), except the app's text extract { "type": "image", "text": … } without a source; and every text block that starts (after leading whitespace) with [Image: or [Image — the app's stand-in for a picture sent without pixels — counted only when the message has no image block (a picture sent as both counts once). A Word file's embedded figures or a PDF's chart/table/figure page renders are plain image blocks here and count like photos. Accepted residual: in a private chat on a model without image input, the app drops a document's figures from the request without a stand-in, so they are not counted there.

Two or more pictures → an edit, start frame or cut-out produces nothing and picks none; the model is told that only one image can be the base and that the user should attach that one image again, on its own, with the change (naming it is not enough). A confirmation for the tool ("Use this image?", above) is checked first and wins; each tool's own earlier refusals (egress, saved conversation, media limit) answer first. Every further image call of that reply gets the same answer.

In the web chat the same count is also stated up front, as one line in the turn's capability block of the system prompt (only when an image, video or background-removal tool is on and the count is two or more; it comes from the same decision as the refusal above, not a second rule), so the model says the limit before it would pick. The line limits only the image tools that work on the attached images (edit, animate, cut out, combine, carry something from one onto another); the model raises the limit only when the user asks for one of those, and otherwise says nothing about it. Answering about the images, and a new picture or clip made from a text description, work as usual. API callers get no such line: the refusal in the tool result is their only notice.

A new picture or clip (generate_image text-to-image, create_video text-to-video) is never refused for attachments. When the turn carries attachments (images or files), the tool result adds that it was made from the text prompt only and does not contain, use or combine the user's images or files — so the model cannot present it as a composition.

Later turns. When the latest message has no image, the newest image of the chat is offered ("Use this image?"). A stored message with two or more photos is not offered (the card would show its last one), nor one whose photo never reached the chat (its upload failed or was refused) — in both cases the model asks the user to attach the image again, and an older image is never offered as "the most recent". One whose only pixels are its uploaded file (a gateway that masks personal data) is offered like any other and previewed from that file; a file over the tool's size limit is offered as unusable without being downloaded. An id the user named (Animate / Remove background / Pick another) is an explicit choice: that message's last photo.

The remove_background tool

When offered (see x-aig-image-gen above and Image generation), the model can call remove_background. The gateway sends one image to the self-hosted EU background-removal service and places the returned PNG in the reply like a generated image. The gateway inspects the returned bytes (it never relies on the model or on a setting): the tool result says "transparent PNG" only when the PNG carries transparency (colour type 4 or 6, or a well-formed tRNS chunk before the first IDAT). Otherwise the result says PNG and adds a note: an opaque PNG is reported as having no transparency, and a PNG whose structure cannot be confirmed (not a PNG, malformed, or more than 64 chunks before the image data) is reported as unconfirmed. Only the wording changes; the image is still delivered. The check reads chunk structure only (the CRC is not verified). generate_image results carry the same note. The call is synchronous (up to 60 seconds).

Every argument comes from the model and is untrusted. Give exactly one of the two sources; unknown keys are ignored.

Argument Accepted shape Absent or null Malformed
image Id of an image in this conversation (string, 1 to 64 characters): a generated image, or a user message that carries an uploaded image. Needs a saved conversation. Not this source Refused (empty, non-string, or over 64 characters)
use_uploaded_image Strict: true, "true", 1, "1" use the image attached to the user's latest message; false, "false", 0, "0" mean not this source. Works in a private chat too. Not this source Refused (any other value, e.g. "yes", 2, "TRUE")

Both sources, or neither, is refused. A malformed argument is refused with a sentence naming the field, and the service is not called; it is never coerced.

The input image. A confirmed image (see "Use this image?") wins over both arguments. image is used only when the user's latest message names that id, else the call is treated as use_uploaded_image. image is resolved like create_video's start_image, after the owner check (see the refusals below): first a generated image of this conversation, else a live user message of this conversation, whose last photo is used — its last image_url block with an object { "url": "data:<mime>;base64,..." } and no filename (a document's embedded figure is never used), or, when the message stores no pixels (a gateway that masks personal data), its uploaded image file. use_uploaded_image takes the latest message's attached image (a base64 data: URL; remote URLs are never fetched); with two or more image blocks on that message nothing is cut out (see "Use this image?", "Several images"). Both are checked by magic bytes (not the declared MIME type): PNG, JPEG or WebP only, at most 10 MiB decoded. An unknown id, an id of another conversation, an assistant message, a deleted user message, or a user message without such an image all get the same answer ("not available in this chat"); a storage error answers "temporarily unavailable".

The service's response is untrusted too. It is used only when the status is 200 and the body is a PNG (magic bytes) of at most 12 MiB whose header reads 1 to 2048 pixels per side. Anything else is "temporarily unavailable" and nothing is stored. Status 400, 413 or 415 answers "the image could not be processed"; 429 answers "busy, try again in a moment"; any other status (including 401, 404 or 5xx) or a transport failure answers "temporarily unavailable". The service's own error text never reaches the model.

Other refusals (the service is not called): the tool is not available (setting off, backend not configured, egress-blocked project); with image, the conversation does not belong to the caller (the conversation id is client-asserted and checked against the owner before any lookup; a failed check answers "temporarily unavailable"); the turn can neither store nor deliver live (an unsaved conversation without a live channel); a private chat already delivered the maximum number of files live in this reply (8); the per-turn media limit (4 images) is reached; the model already called the tool twice in this reply. If the result was produced but could not be placed in the reply, the model is told so without an Error: prefix and asked not to retry.

The setup_connector tool and the connector_setup frame

setup_connector is a built-in tool of the web app chat that helps a user connect a service from the connector directory. It is offered only on turns that sent x-aig-turn-id; a plain API call (also one with only x-aig-extensions: 1) never has it added to its tools. It mutates nothing. For a one-click connector it emits one aig_status: "connector_setup" frame only to a client that sent both x-aig-turn-id and the capability header x-aig-connector-setup: 1 (see the header table above) and the user confirms in the app. Without the capability header, or for any other connector, the model is given a link to the Connectors page instead, with wording that claims no card. Inputs, rejections, visibility rules and the exact frame are described under The setup_connector chat tool.

Forced on an explicit request (Myra models). When the latest message of the user begins with a clear request to connect or set up one directory service ("Connect Todoist", "Connect DeepWiki, then use it to …", "verbinde Notion", "Please set up Linear"), the gateway sets tool_choice to setup_connector for the first model call of the turn, so the card does not depend on the model choosing the tool. The directory name is matched as whole words, also with a space or hyphen ("deep wiki"). After the name (and an optional connector noun or "for me" / "für mich") the message must end, or continue with a full stop, "!" or "?" (any further sentence may follow: "Set up Gmail. How do I filter spam?" is forced), "please" / "bitte", "now" / "jetzt", or a separator (comma, colon, dash, "and" / "und") followed by exactly one of: "then" / "dann", a short list of imperatives (use, tell, summarise, show, list, find, search, give, check, create, add and their German forms), another directory name that ends the request, "please" / "bitte" or a language aside ("in English"). Anything else after a separator is ordinary prose and is not forced: "Set up Linear and logistic regression", "Set up Linear, logistic and ridge regression", "Set up Notion: what is the best template?". The words "my" / "mein" and device words such as laptop, phone or database are never a connector name; "mein GitHub-Konto" names GitHub. A message that connects one unknown single word ("connect outline") is forced too, so that the tool, not the model, tells the user the directory has no such connector. A question ("how do I connect Todoist?"), a message that only mentions a service, and a weak verb in the middle of a sentence ("add Notion to the table") are not forced. The force applies only when the tool is on the wire for the turn (so a user who may not create connectors, a turn without x-aig-turn-id, and a spoken voice turn never get it), only for Myra-hosted models (the provider alias myra, including its self-hosted vLLM models) and only for the first call: the forcing tool_choice is dropped for the next calls of the tool loop, and the automatic continuation that follows a click on Connect is never forced again. The unknown-word case is deliberately narrow: only "connect <word>" optionally followed by a connector noun, "please" or a language aside ends the sentence; "Connect sales, summarise Q3" is not forced. It is not applied when the client sent its own tool_choice, when another gateway force is already active (a file-claim regenerate, a calculation turn, a download turn), or when the model's capability data says it does not honour a forced tool; in all of those cases the request is left as it was; only the capability case (and a forced tool that is resolved but not on the wire) additionally logs a WARN. A forced turn logs [connect_force] with the request id and the matched connector at NOTICE, and the request's trace shows a connect_force_applied step. The message text is never logged.

MCP connectors from the API

Registered MCP connectors can be used from the inference API by reference — the gateway resolves the connector's tool list server-side, offers the tools to the model, and executes every tool call inside its own tool loop with the caller's stored connector credential (which never leaves the gateway):

{
  "model": "…",
  "messages": [{ "role": "user", "content": "What does ticket ABC-123 say?" }],
  "tools": [{ "type": "mcp", "connector_id": "<connector id>" }]
}

Accepted shape per entry: exactly { "type": "mcp", "connector_id": "<id>" }, plus an optional server_label (accepted for OpenAI-shape compatibility and ignored — gateway tool names are not label-prefixed). connector_id must be a non-empty string of at most 64 characters. Duplicate ids are de-duplicated; at most 8 distinct connector references per request.

Authorization. The API token's user is the credential identity: a user-scoped connector uses that user's connected credential (connect it in the UI first), and a private connector is visible only to its owner. A tenant-level token (no associated user) can use shared connectors; user-scoped ones return connector_credential_required and private ones connector_not_found. The connector's server-side tool_policy filters the offered tools and is re-enforced on every call (on the tool's own name). A connector tool name with the reserved agent__ prefix is silently dropped from the offer. A name that collides with a built-in gateway tool is offered as <catalog slug>_<name> for a catalog connector (Runway's generate_image → runway_generate_image) and dropped for a custom connector — see MCP: tools whose name collides with a built-in.

Per-tool shape narrowing. Every tool definition that reaches the model — whether discovered from a connector's tools/list or carried in the gateway-internal x-aig-mcp-tools body field — is treated as untrusted and narrowed fail-closed before it is offered: an entry must be a JSON object with a function object and a usable name (non-empty string, valid UTF-8, at most 200 bytes — resolved from the entry's name or function.name), or the entry is dropped; duplicate names keep the first entry only; at most 5000 entries per request are considered. A tool whose name is a built-in is renamed only when the gateway's own discovery recorded a usable catalog slug for the entry's connector (see the MCP page); no field of a body-supplied entry can set the prefix, and without a recorded slug the tool is dropped, exactly as before. Within each kept tool, non-conforming fields are repaired rather than failing the request — see MCP connectors — tool shape narrowing for the exact field rules.

Rejected inputs (all 400 invalid_request unless noted):

Input Behaviour
unknown / foreign / other member's private connector_id 404 connector_not_found (fail closed, request aborted)
connector requires a credential the token's user has not connected (or it expired) 424 connector_credential_required
connector server unreachable / tool discovery failed / discovery deadline exceeded 502 connector_upstream (fail-closed; but see x-aig-mcp-best-effort below — the chat surface drops the connector and proceeds instead)
mixing {type:"mcp"} references with client function tools in one tools array 400 — one loop owner per request
server_url, allowed_tools, headers, authorization, require_approval, or any other key on an mcp entry 400 naming the key — register a connector; restrict tools via its server-side tool_policy
more than 8 distinct references 400
combining references with the gateway-internal x-aig-mcp-tools body field 400 — one MCP source per request. (The legacy x-mcp-tools header was retired and is now ignored, never an error.)
tools contains any non-mcp entry (client function tools or provider tools), or a non-empty legacy functions array is present, together with the gateway-internal x-aig-mcp-tools body field (any value other than absent or null, including []) 400 invalid_request — one tool-loop owner per request: the client executes its own tools, so the carried connector tools could never be offered. tools: [], tools: null or no tools (and an empty or null functions) together with the field is not affected.
legacy functions that is not an array, is an object, or has an entry that is not an object 400 invalid_request — 'functions' must be an array, 'functions' must be an array of objects, or each 'functions' entry must be an object. functions: null counts as absent; an empty {} is treated as an empty array.
combining references with legacy functions / function_call 400
a non-empty legacy functions array, or a function_call of any non-null value (alone is enough), on a model whose provider drops those fields (Anthropic), or on a Mistral request the gateway serves through Mistral Agents for web search (a request with only function_call can reach that leg) 400 invalid_request — The legacy 'functions' / 'function_call' fields are not supported by this model's provider. Send the functions as 'tools' (type "function") and use 'tool_choice' instead. Streaming and buffered requests get the same JSON 400, before any upstream call. A configured fallback to a provider that forwards them still serves the turn.
any client tools entry that is not an mcp reference (and, on Gemini and Vertex only, not a web-search marker as defined under Client tools per provider), or any non-empty legacy functions / function_call, on a model whose provider has no tool translator (Gemini, Vertex, Bedrock, Cohere), whatever tool_choice says 400 invalid_request — Client-supplied tools ('tools' entries or the legacy 'functions' / 'function_call') are not supported by this model's provider. Use a model whose provider supports tool calling, or send the request without them. Streaming and buffered requests get the same JSON 400, before any upstream call. A configured fallback to a provider that supports tools still serves the turn. On those providers a legacy-only request gets this message too.
a forcing tool_choice ("required", a named function/tool, {"type":"any"}, allowed_tools mode required, …) 400 — the gateway drives the tool loop. Non-forcing forms pass: absent, null, "auto", "none", {"type":"auto"}, {"type":"none"} (shape-agnostic; the provider still enforces its own wire shape)
references on a non-chat endpoint (embeddings, …) 400
references on count_tokens 400 — connector tools are never included in a token count (a refs request cannot pre-count)
references on a chat request (/chat/completions, or native /v1/messages) with a model whose provider has no gateway tool loop (currently Gemini, Vertex, Bedrock and Perplexity) with x-aig-mcp-best-effort: 1 (the web chat): the references are dropped and the turn is answered without them, with a tools_skipped notice (category connectors_model) and a system notice to the model (see MCP connectors API). Otherwise 400 model_capability_mismatch (not invalid_request: the request is well-formed, the chosen model cannot run it — pick a model from another provider). Logged and recorded in the model-error triage queue. The check applies to the provider the turn resolved to (after routing rules and fallback substitution); a configured fallback model is not tried for this rejection, which happens before the turn is dispatched (an over-window turn may already have been compacted). On a gateway whose PII scan has already opened the response stream the error arrives inside the already-open 200 event stream instead: a provider_error event with error_class: model_capability_mismatch for a client that opted into the aig_* side channel (the web chat), or an OpenAI-style {"error":{"code":"model_capability_mismatch",…}} chunk followed by [DONE] for a plain OpenAI-compatible client. The same references on a non-chat endpoint or count_tokens keep their invalid_request rows.
references on native /v1/messages with stream: true 400 — connector references on /v1/messages require stream:false in this version
references on native /v1/messages with a provider that relays the Anthropic response through an OpenAI-compatible reader (the self-hosted myra fleet, groq, together, …) 400 — that provider dials /v1/messages but cannot read the Anthropic dialect, so no gateway tool loop can run there; without references the request is a transparent passthrough. A provider that dials its own endpoint (a routed cohere model) keeps the loop.
references in a local-only project / egress-blocked context 403 forbidden — "MCP connectors are not available for this request (egress blocked)"

Legacy functions. A non-empty legacy OpenAI functions array counts as client-supplied tools, exactly like a tools array of function entries: the client owns the tool loop, the gateway forwards the request transparently and injects no connector tool. In particular the gateway's own web search (two-leg flow, tool loop, Mistral agents, forced OpenRouter plugin) does not add its search tool next to functions; the turn then reports the search as not run with the reason legacy_functions. The unforced OpenRouter web plugin is not blocked either, because it adds no tool to tools: OpenRouter receives the client's functions unchanged and runs its web plugin server-side (see Web search). The legacy fields are forwarded as-is to OpenAI-compatible providers. Providers that cannot carry them (Anthropic, Gemini, Vertex, Bedrock, Cohere) refuse the request with 400 invalid_request instead of silently dropping the fields, so a request that relied on functions is never answered as if no function had been offered; this includes a request that sends only function_call. The same 400 applies when the gateway would serve a Mistral request through Mistral Agents (web search), because that leg rebuilds the body and drops the fields. Send the same definitions as tools (and function_call as tool_choice) for Anthropic. Gemini, Vertex, Bedrock and Cohere have no tool translator at all, so they refuse tools too (see below). A fallback chain moves on to the next provider, so a chain that ends in a provider that forwards the fields still serves the turn. Provider-native search (Anthropic native search tool, Gemini / Vertex grounding) is therefore never combined with functions either.

Operational notes.

  • Tool discovery (tools/list) runs server-side with an overall deadline of ~20 seconds across all referenced connectors (plus at most one in-flight operation); results are cached for up to 5 minutes per connector + user, so a connector-side tool change can take up to 5 minutes to appear. A failed discovery (server unreachable / deadline) is briefly negative-cached (~15s) so a persistently-down connector is not re-probed on every request.
  • A connector that (legitimately) exposes zero offerable tools does not fail the request — the turn proceeds with the gateway's built-in tools only.
  • tool_choice: "none" with references still performs the (billable) tool discovery for tools the model can then never call — omit the references instead.
  • MCP-carrying requests are never served from or written to the response cache.
  • A member-created private connector may only reach public addresses; a private-range/internal server_url surfaces as connector_upstream.

How connector tools reach the model, per provider. When a turn carries more than 40 tools (built-in tools + connector tools), the gateway narrows what it offers; the full rules are in MCP connectors API — Many connector tools: tool selection.

Provider of the resolved model More than 40 tools
Anthropic (direct), Claude model with native tool search every connector tool sent with defer_loading: true; search_connector_tools returns tool_reference blocks
Myra fleet, Qwen as the chat model every tool while at most 128 tools and the connector tool definitions use at most half the context window; above that, gateway search
every other provider with a gateway tool loop (OpenAI, Mistral, OpenRouter, Anthropic through a custom base URL, other Myra models, …) gateway search: previously used tools + up to 5 picked by the Qwen tool selector (BM25 as the fallback) + search_connector_tools
Gemini, Vertex, Bedrock, Perplexity (no gateway tool loop) no connector tools: the web chat answers without them; the API gets 400 model_capability_mismatch

Connector tool names are fitted to ^[A-Za-z0-9_-]{1,64}$, and a name offered by two connectors is namespaced <prefix>__<name> (see MCP connectors API — Tool names).

Your own defer_loading tools. On the OpenAI-compatible endpoint with a Claude model, a function tool you send with "defer_loading": true (exactly the boolean) is passed to Anthropic as is, for Anthropic's own tool search; any other value is dropped. Such a tool still counts in the gateway's context-window estimate and in a prepaid wallet's pre-claim: only tools the gateway itself defers are left out of them.

Connector provenance notice in the model's context

When at least one connector-backed MCP tool is injected, the gateway merges one system-level notice (sentinel [aig:mcp-connectors]) into the outgoing request that enumerates each attached connector's display name and its tool names, and instructs the model that these connectors are available — call their tools instead of denying access. (Without provenance, some models deny having an attached connector even though its tools are offered.)

Behaviour and guarantees:

  • Merged at most once per request — the sentinel makes re-injection across retries and tool-loop continuation legs a no-op.
  • Absent when no MCP connector tools are attached (built-in-tools-only turns, and agent-as-tool-only turns) — the notice never promises tools the model does not have.
  • Untrusted input is sanitized before embedding (fail-closed): connector display names and tool names are stripped of ASCII control characters and structure punctuation (quotes, brackets, braces, backticks, <>, |, backslash), whitespace-collapsed, and capped at 64 bytes (UTF-8-safe — accent and umlaut characters survive). A display name that sanitizes to nothing falls back to the connector id; if that is unprintable too, the connector is omitted from the enumeration entirely. Raw values are never embedded.
  • Flood-bounded: at most 20 tool names are listed per connector (then "and N more tools") and at most 16 connectors are enumerated (then "and N more connectors").
  • The internal provenance fields (connector_id, connector_name) never reach the provider's tools array.

x-aig-mcp-best-effort request header. Accepted value "1" opts the request into best-effort connector-reference resolution: a connector that fails discovery (connector_upstream / discovery deadline) is dropped and the turn proceeds with the remaining tools, and the drop is surfaced to the SPA via the tools_skipped progress notice instead of failing the turn. The same opt-in also governs the egress-policy drop: in a Tier-1 local_only project the referenced connectors are dropped (token connectors_policy) and the turn proceeds, where a fail-closed caller gets 403 forbidden. A run under a no-egress restriction (a request that sends the no-egress header) stays fail-closed regardless of x-aig-mcp-best-effort. Any other value, a repeated header, or its absence keeps the default fail-closed behaviour (a discovery failure aborts the request with the typed connector_* error above). The web chat sends x-aig-mcp-best-effort: 1 on every send — an auto-attached connector whose server is momentarily down must not break the chat; the raw API omits it so an explicitly referenced connector still fails loudly. Under best-effort, any discovery failure for a connector (including connector_not_found / connector_credential_required) drops that connector and proceeds; per-connector authorization is still enforced, so a dropped connector's tools are simply never offered.

The same value marks the request as the web chat surface for the system prompt: exactly "1" adds the generated workspace capabilities list (it refers to buttons in the app); any other value, a repeated header, or its absence adds no list.

The turn_committed frame (turn-owned streams)

A turn-owned stream (one sent with x-aig-turn-id) ends with one aig_status: "turn_committed" frame — the gateway's word that the answer is durably persisted (or that there was nothing to persist). Its fields:

Field Meaning
turn_id the turn this frame closes
message_id the committed assistant row's id, or null when nothing was persisted (an empty turn, or a ghost conversation — then ghost: true is also present). A turn whose provider sent a mid-stream error event before any visible answer (e.g. an Anthropic overloaded_error event before any content) is not an empty turn: it is persisted as a failure row (error_class: provider_error, the generic "The request could not be completed." text) and message_id names that row — so a reload shows the provider-error bubble, never a lone question. (A read error or a truncated stream normally ends with the visible interrupted note instead, which is persisted as the answer — see Visible truncation note; where no note could be shown, the same provider_error failure row is written.) The same holds when the model call after a tool result fails before anything was shown: the failure row carries the error_class the live error event named (request_timeout, model_capability_mismatch or provider_error) and message_id names it.
interrupted_class present only on a partial answer: the turn delivered text or a file and then its final model call failed with a provider error; the value is the typed failure code (provider_error, request_timeout, or a policy code) and is persisted on the row as the message field interrupted_class. Also present on a ghost turn. Absent on a clean answer — except the notice values wallet_shortened (a clean turn whose answer was cut at the length the prepaid wallet could pay; also when the turn's own cut answer is empty; never over a failure) and wallet_shortened_reserved (the same, caused by other running requests holding the balance — retry shortly). See Interrupted answers.
empty_answer_class present only when the committed answer is one of the gateway's empty-answer notices: zero_output, blank_turn, reasoning_only, context_exhausted, context_exhausted_first_turn, reasoning_runaway or provider_content_filter. It is persisted on the message row (field empty_answer_class) and is what clients read to recognise the notice — never match the notice text, which is written in the conversation language. Absent for a normal answer.
file_claim_badge present only as "no_file": the answer says a file was created or changed in this turn and the turn produced none — the "No file was created" note of the file-claim check, persisted on the row as the message field file_claim_badge. Absent otherwise.
image_claim_badge present only as "no_image": the image-claim check judged that the answer says an image was produced or shown and the turn produced none, persisted on the row as the message field image_claim_badge. Never present together with file_claim_badge. Absent otherwise.
files[], images[] artifacts the turn produced and claimed onto the row
usage input_tokens, output_tokens for the whole turn; plus cost_usd — the answer's charged cost in US dollars, the same amount stored on the message — only when the caller may see the per-answer cost (see Cost of each answer). Absent when the caller may not see it or when nothing about the answer could be priced; 0 for an answer from a model priced at zero. On an agent run the caller decides, never the agent's owner.
usage.cost_warning true only when cost_usd is present, the answer came from an external (non-Myra) model (decided by the gateway the answer was routed through), and its cost is at or above the tenant's cost warning threshold (see Cost warning for external models). Otherwise absent; only the literal true means a notice.
finish_reason the turn's final stop reason
reply_lang optional: the language the user wrote this turn's message in, as the gateway's reply-language detection resolved it (the same value that pins the answer's language — see Reply language) — an ISO 639-1 code, today one of de, en, fr, nl, da (the set may grow). When the latest message is ambiguous (for example "Was ist neu in Windows 11?" after German turns) it is the language of the conversation so far. Absent when the detection abstained and the conversation gave no language (an ambiguous or short first message, another language) or did not run, and on a regenerate with a reason whose reason turn the gateway could not set aside (the request does not also name the regenerated turn with x-aig-regen-of-turn, or its last message is not the reason turn right after an answer) — the detected language could then be the reason's. The web app names this language when it asks for the follow-up suggestions.
superseded_message_ids[] always present (an empty array when nothing was superseded): the message ids this commit replaced — the whole trailing run of the regenerated question: its prior answer(s) and the error rows among them (see x-aig-regen-of-turn below). The app removes exactly these rows in the same update that shows the new answer.
data: {"aig_status":"turn_committed","turn_id":"…","message_id":"…","files":[],"images":[],"usage":{"input_tokens":12,"output_tokens":48},"finish_reason":"stop","superseded_message_ids":["<prior answer id>"],"reply_lang":"en"}

A failed turn (a provider fault, or a guardrail block on the buffered response path) persists its failure row without a turn_committed frame; the app learns the outcome from the error frame and the next conversation load. (A request-phase guardrail block on the streaming path ends with a normal turn_committed — carrying the error/guardrail rows it superseded.)

How large an answer can be committed. Two ceilings, and anything that can be written can be read back. The row's own bound: an assistant message's large text columns — content, any later corrected_content or edit, and the sources / search-steps lists a web-search turn stores — may total at most ~15.9 MB (the largest payload one database packet can carry back — the wire protocol's own single-packet limit — less a reserve for the rest of the row); a write over it is refused before anything is written, atomically with the row it would have grown. The statement's bound: one row is written in a single statement whose packet may not exceed 16 MB. Text is escaped on the way in, so the worst case — an answer made entirely of characters that need escaping — leaves room for about 8 MB; ordinary prose grows by a few percent, so in practice an answer of ~12 MB still fits (the same statement also carries the turn's sources and search steps). A multi-megabyte answer — a long analysis, a big pasted document folded back into the reply — commits normally and reloads byte-identical. Beyond either ceiling the commit FAILS LOUDLY rather than silently dropping the answer: the turn takes the persist-failure path (aig_status: "persist_failed"), and the client sees the answer it streamed but is told it was not saved. Nothing is truncated behind your back, and no half-row is left in the conversation. On the read side the database driver is capped at the wire's single-packet limit, so a row that somehow outgrew it (written before this rule) fails to load with a clear error instead of loading as truncated phantom rows.

x-aig-regen-of-turn — regenerating a tool-backed answer: forced tool, and the prior answer superseded on commit

When the chat UI regenerates an assistant answer, it sends x-aig-regen-of-turn: <original-turn-id> — the logical-turn id of the answer being regenerated.

When that turn failed or was interrupted after its server-side tools ran, a regenerate without x-aig-regen-reason resumes from the saved tool results instead of running the tools again (no tool forcing applies then) — see Resuming from saved tool results.

  • Accepted shape: a string of at most 36 characters matching the request-id pattern (the same rule as x-aig-turn-id). Anything else — a non-string, an over-length value, or forbidden characters — is rejected (dropped, logged at WARN) and treated as absent. The value is used only as a parameterized query parameter, scoped to the caller's tenant (the leg lookup) and to the request's own conversation (the supersede), so a forged id cannot read or touch another conversation's data.
  • Effect 1 — tool forcing: if that original turn ran a model-driven tool loop (its persisted request legs include a tool_loop leg), the gateway forces the model to call a tool on the regenerate (tool_choice: "required") so it cannot decline and answer "no access". If the target provider/model does not support a forced tool choice, the gateway falls back to offering the tool (logged at WARN) rather than failing. When the header is absent, or the original turn used no tool, nothing is forced. (A forked copy of an answer carries a fresh turn id whose legs belong to the source turn — no forcing on it.)
  • Effect 3 — the image tools' source on a steered regenerate. When both this header and x-aig-regen-reason are present and the request body ends with an assistant message followed by a text-only user message (the reason the chat app adds when regenerating with a reason), the image tools (generate_image edits, create_video's uploaded start image, remove_background) take their source image from the user message before that reason message — the message the regenerated answer replied to. Neither header alone has this effect, and a body of any other shape is unaffected (the source stays the last user message).
  • Effect 2 — supersede on commit. The app no longer deletes the prior answer before regenerating; it stays visible while the replacement streams. When the replacement commits, the gateway — in the same database transaction — soft-deletes the prior answer and any error rows trailing it, and lists them on the turn_committed frame as superseded_message_ids. Rules:
    • Who: the conversation's owner only — the same predicate the message DELETE route applies (a project member's delete there is refused 403 not_conversation_owner, and so supersedes nothing here — not even as the current driver of a live session; their regenerate is appended beside the owner's answer). Decided once when the turn starts, never on the commit path. A non-owner, an API-key turn (no user), an invisible conversation, or a gateway-side fault ⇒ nothing is superseded, the new answer is simply appended (both remain visible), and the refusal is logged at WARN + recorded as the trace step regen_supersede_refused with a reason (not_owner, no_user, no_turn_id, not_found, db_error:<err>; and from inside the commit: no_anchor, not_trailing, self_anchor — the header named the turn itself). Note that the turn itself is not refused on ownership grounds: the streaming path checks the live-session lease, not conversation ownership (a pre-existing gap, tracked separately) — so a member's regenerate on a shared conversation still lands its answer in that conversation; only the supersede is withheld.
    • What: the answer with that turn id is the anchor (resolved even if already soft-deleted, so a stale tab regenerating twice still ends with ONE live answer — last-commit-wins); the whole trailing run is superseded — every assistant row after the question the anchor answers (the last user message at or before the anchor; with no such message, the anchor itself and everything after it) — but only if no live user message follows the anchor (a stale tab regenerating an older turn never deletes another question's answer: refused, logged at WARN, traced as not_trailing). So an earlier answer stacked under the same question (an appended non-owner regenerate, a rolling-deploy gateway) goes with the swap too. Live streaming claim rows of a sibling turn and the new row itself are never touched; the rows soft-deleted are exactly the live subset of the ids on the frame (an already-superseded row is listed so a stale tab removes it too, but is never deleted twice).
    • A failed regenerate never removes a real answer. A provider failure or a guardrail block persists a failure row that supersedes only the error/guardrail rows of that run — so the prior answer stays, the failure lands beneath it (and repeated failures never stack), and a later successful regenerate replaces both.
    • A stopped regenerate (the client aborts after tokens streamed) commits its partial and supersedes the prior answer like a full answer would.
    • Idempotent and atomic: a retried commit of the same turn re-runs the rules with no effect on already-deleted rows; the supersede and the new row commit together or not at all.
    • Rolling deploys: a gateway container still on the previous image supersedes nothing (both rows stay visible until the fleet has rolled); its turn-owned answers carry a turn id like any other, but rows it writes through the legacy paths (POST /messages, a bridge pair, a fork copy) have none and cannot be superseded later. Every assistant row written by a current gateway carries a turn id on every path (migration 0283 backfilled the historical ones).

Resuming from saved tool results (regenerate after a failed post-tool call)

When a conversation turn fails (or is interrupted, see Interrupted answers) after its server-side tools ran — a provider error, a timeout, or a stream that broke off mid-answer — the gateway saves exactly what the failed model call was sent after the conversation prefix — the assistant tool-call turn(s) and the tool results (already PII-masked as the model saw them) — plus only the PII token mappings those results need, encrypted at rest with the platform master key.

A regenerate of that turn — a request with x-aig-regen-of-turn naming it and without x-aig-regen-reason (in the web chat: Try again on the failure bubble, Start the answer again on the interrupted notice, or Regenerate) — resumes from the saved results: only the model call runs again, no tool is executed a second time, so side-effecting tools (sending e-mail, writing files, connector actions) never run twice. The resumed answer replaces the failure row as usual, and does not repeat a preamble the failed turn had shown. For an extensions client the event {"aig_status": "tool_results_resumed", "tools": [...]} is emitted before the answer (or by the re-emit of a buffered turn) — the reliable signal; the response header X-AIG-Tool-Resume: resumed is added too while the response headers are still unsent (it is absent when the stream had already opened before the tool loop started, e.g. a PII scan).

If the saved results cannot be used, the turn re-runs in full, including its tools, and says so: the event {"aig_status": "tool_resume_unavailable", "reason": "<reason>"} (and, under the same condition as above, the header X-AIG-Tool-Resume: unavailable); the web chat shows the warning "The saved tool results of the interrupted answer were no longer available, so the tools ran again for this answer." This happens when the results expired (after 24 h), the turn was stopped by the user, it produced files or images, it ended in a context overflow, a non-retryable / policy failure or a request the provider refused (an HTTP 4xx other than 408 / 429 — it would fail the same way again), another answer already used the saved results (e.g. a "Try again" in a second tab), a message of the conversation was deleted, the conversation was forked, the model or provider changed, a tool is no longer offered, the PII configuration that masks tool results changed (detectors, entity types, keywords — including the user's personal keywords — or whether PII masking is mandatory: tenant enforcement / project tier) or could not be read, the thinking settings changed, the saved data is invalid, or two resumed attempts already failed (a user's Stop of a resumed answer does not count as a failed attempt).

  • A regenerate with a steer reason (x-aig-regen-reason) always re-runs normally — it asks for a different answer. An unrecognized x-aig-regen-reason value is ignored, so that regenerate resumes like one without the header.
  • A regenerate of a turn that ran no tool behaves as before (no event, no header). The record that a turn's tools ran (a non-content tombstone) is kept for 30 days; a regenerate of such a turn after that re-runs its tools without the warning.
  • Only the user who ran the tools, in the same tenant and conversation, can resume them.
  • Regenerate requests are never served from or stored in the response cache.
  • Storage and retention of the saved results: see Conversations › Saved tool results.

Download-request tool forcing (server-side, no header)

When a chat turn's latest user message asks for a downloadable file — e.g. "gib mir die Datei zum Download", "erstelle mir eine Excel-Datei zum Download", "give me the file to download", "export this as a PDF" — the gateway forces a file tool on that turn so the model produces a real file instead of narrating a phantom "here is the file to download: X.xlsx" with no tool call (the prod class: no file, no download card). This needs no header; it is inferred from the user's message.

  • When it fires: the latest real user message is classified as a download request (a deliver-verb — gib mir / give me / erstelle / export / … — plus a file/format token, OR an explicit "zum download" / "as a download" phrase) and at least one file tool (write_file or code_interpreter) is resolved for the turn and the provider honors a forced tool_choice and the request carries no client/gateway tool_choice already.
  • A negated file request does not fire. A deliver verb, file token or download phrase counts only when no negation directly governs it. A download phrase ("als Datei", "as a file", "zum Download") counts only at the start of a word ("has a file" is none). The text is normalized first: the typographic apostrophe, NBSP, quotes and the Markdown marks * and ` become spaces, so "Do not create files" counts. Then, per negator (not / no / never / without / don't / nicht / kein(e) / ohne / nie / statt / anstatt / instead of / rather than ...):

    1. Head. The negation governs the first word after it that is not an article, a determiner, "new", als / as / to / zu / in / im / nach, me / mir, it / es or an adverb such as again / always / simply / even / wieder / schon / immer / gleich / noch (not einfach / just / only / nur). If that word is a file word, its noun phrase is negated (3); if it is a verb, the verb and its object are negated (2); any other word ends the negation. After "do / should / will ... not", "don't" and "never" that word is always taken as a verb ("do not email me a file"); English verb forms such as "creating" or "saving" count. After kein / keine / no / keinerlei / any / irgendein, or "not a" / "nicht eine", one more word may come first, followed at most by an article ("keine zusätzlichen Dateien", "not a downloadable file", "auf keinen Fall eine Datei"; "with no email as a CSV file" fires); a verb after that word is not negated ("Kein Problem erstelle mir eine Excel-Datei" fires).
    2. Object. A negated verb negates the file words after it up to the next punctuation mark (, ; : . ! ? ( ) / or a spaced dash), the next deliver verb, the next negator or a contrast word (but / sondern / aber / jedoch): "Give me the text and do not create a single file", "don't write it into a file". A deliver verb joined to it by or / oder / nor / noch is negated too ("Do not create or export files", "Don't use any tools or create files"); one joined by and / und only directly: after an object word it is free ("Do not change the numbers and create an Excel file" fires). A preposition followed by "the" / "die" / "der" / "das" ... ends the object, since it names a place in the file the user wants ("Do not use colors in the PDF, create it now" fires).
    3. Noun phrase. A negated file word also negates the file words directly after it, after als / as / in / im / into / to / zu / zum / for / nach (with an article), and in a list after "," "(" ")" "/" or oder / or / und / and / nor / noch ("keine Datei im Excel-Format", "weder eine PDF noch eine Excel-Datei", "not as a file", "keine Datei, PDF oder Word", "without a PDF or a Word file", "keine Word- oder Excel-Datei"). Any other word ends it. The deliver verb that governs the refused file word is negated too, directly before the negator ("Erstelle mir bitte keine Datei") or right after the noun phrase ("keine Datei erstellen"), so a file format named elsewhere does not bring the file back ("Erstelle keine Datei, ich nutze Excel" does not fire). A replacement negator (statt / anstatt / anstelle / instead of / rather than) governs only its own noun: "Statt einer PDF erstelle mir eine Excel-Datei" and "Gib mir statt der PDF eine Excel-Datei" fire.

    Contrast. When a file word follows a contrast word (also after a comma), the negated verb applies to that file: "Do not create a PDF, but an Excel file" and "Erstelle keine PDF, sondern eine Excel-Datei" fire; "Do not create a file but answer in the chat" does not.

    Also negated: a file word followed by a clause-final "nicht" / "not" ("Erstelle die Datei noch nicht."). "Why not" / "warum nicht" is a suggestion and "don't forget" / "vergiss nicht" a reminder; both fire. A negation anywhere else does not cancel ("Statt eines Textes erstelle mir eine Excel-Datei", "Erstelle ohne Rückfrage eine PDF", "Ich weiß nicht, erstelle mir einfach eine Excel-Datei" all fire), and a negation never reaches across a comma ("Do not, under any circumstances, create a file" fires). A free verb and a free file word may stand in different sentences. The separable "Lade die Datei herunter" fires only when "herunter" and lade / lad / laden are whole words in the same sentence.

  • What it does: for that first leg only, the offered tool set is narrowed to the resolved file tools {write_file, code_interpreter} and tool_choice is set to "required", so the model must call one of them (it still chooses write_file for text/HTML/office vs code_interpreter for computed/formatted output). Continuation legs are unforced (they answer from the tool result). A provider that cannot guided-decode "required" is not forced (logged at WARN); a rare 400 on the forced leg strips the force and retries once.

  • Calculation turns on Myra models → code_interpreter is forced. When the latest real user message explicitly asks to compute, recompute, total, check or compare figures (or adds figures to an earlier table) and code_interpreter is on the request, the provider is a Myra model and honors a forced tool_choice, and the request carries no client/gateway tool_choice already, leg 1 sets the named tool_choice {"type":"function","function":{"name":"code_interpreter"}} (the offered tools are not narrowed). Continuation legs are unforced. A download turn is owned by the download force above. A rare 400 on the forced leg strips the force and retries once (logged at WARN, kind=named:code_interpreter). The exact triggers are listed in the code interpreter page, section "Calculations on Myra models".
  • Changing the existing file → only edit_file (and read_file) is offered, nothing is forced. When such a turn asks to CHANGE a file and get it back ("Kürze die Tabelle auf Folie 16 … und gib mir die aktualisierte Datei"), the request offers only edit_file plus read_file (when it is available on the gateway) — on every leg, with no tool_choice (the model may also answer in text; the force above does not run). read_file only reads: it lets the model load a file the previous answer wrote, whose text is not part of the conversation history (only its name is), before it edits it. The file is changed as a new version of the stored file (an attachment itself stays unchanged; the edit is saved as a new file of that name, or as a new version of an existing saved file of that name), and no other tool (write_file, code_interpreter, convert_document, search, connector or agent tools) is offered or can run on that request: a model otherwise regenerates the whole file through write_file, runs into its output cap and saves nothing. Because nothing is forced, it also applies on providers that cannot honour a forced tool choice. It applies only when it is unambiguous (otherwise the force above runs):
    • the user's typed request OPENS with an imperative change of the file — its first sentence starts (after "bitte" / "please" / "dann" …) with a change verb (ändere, kürze, entferne, füge … hinzu, korrigiere, ersetze, change, fix, add, remove, replace, shorten, update, …), is not a question and has no negation, and whose change is about the file's content — not the delivery, the assistant's reply or the chat ("Ändere nichts", "Don't edit it", "…damit ich sie bearbeiten kann", "Add the file as a download", "Kürze deine Antwort", "Fix the download link", "Edit: …" do not count) — nor its name or place ("Ändere den Dateinamen …", "Add the file to my project"), nor the last answer ("Kürze das auf drei Sätze"); no new text is being authored ("Schreib mir …", "Fasse … zusammen", "Write a …", "Ich brauche …", "daraus") — and asks for no conversion, translation/rewrite, redirect, new or separate file ("als PDF", "übersetze", "schick an …", "erstelle", "eine neue Datei", "unter neuem Namen", "separat", "keep the original", "a copy");
    • the target is a file attached to this message or written by the previous answer (the assistant message right before it, from the server's records — a re-served download is not a write, and a failed or interrupted answer that wrote no file is skipped, so re-asking after it still means the file before it). There must be exactly one such file, or the user names one of them (every file name typed — a name with a known file extension — must be that same file); it is a prose/markup text file (.html, .htm, .md, .txt, .xml, .yaml, .yml) — a data file (.csv, .json) stays with the code interpreter — and no image or other file rides the message. The message is identified by the chat's x-aig-parent-msg-id header (the web app sends it); a request without it, or with an id that is not a live message of this user's conversation, gets the force above;
    • edit_file itself could apply an edit to it (the same checks an edit_file call runs);
    • it is not a regenerate (a regenerated edit would apply the change a second time — a regenerate keeps the general force above). An automatic "Continue" of such a turn keeps the offer (an edit replayed there is answered as already applied);
    • no other format is asked for ("…as a PDF", "…als Word-Datei", "…im PDF-Format") and a document attached to the message is that file. The trace records download_force_edit (target) or download_force_edit_skipped (reason).
  • What is classified: the user's typed words only — an attached document's content (inlined into the message) is ignored, so a word like "script" or "Code" inside an attached HTML file can neither cancel nor trigger the force, and a change verb inside it is not a change request.
  • Precision (fail toward NOT forcing): requests about a file — "gib mir eine Zusammenfassung / Analyse / einen Überblick der Datei", "give me a summary of the file" — and how-to / question / inability phrasings do not force (the user wants an inline answer, not a file). A genuine download ask this misses is caught by the honesty backstop below.
  • Backstop: if a turn still ends with the model claiming a download it did not produce, the claim-steer (detect_file_claim) re-legs it into a real write. The download card itself always renders from the durable chat_message_file relation, never from model prose.

Bare re-download → server re-serve of the existing file

A bare re-download — the user asks for the file they already have back with no change: "lade die Datei herunter", "download it", "gib mir die Datei nochmal" — is handled by re-serving the file that already exists, not by forcing a fresh creation. Forcing a new creation here is both wasteful and unsafe on a weaker model: at 1000-case scale gemma4's forced regeneration produced accepted=0 and then simply stopped, leaving the user with no download card even though a perfectly good file was sitting in the conversation.

  • When it fires: the turn is classified as a download request (as above) and carries no modifier — no format/conversion token (als PDF / as pdf / convert), no version verb (aktualisier / updated / upgedatet / Ändere / Überarbeite), no create verb (erstell / mach mir / create), no daraus / draus, and no redirect (email / slack / @). Any modifier → this does not fire and the normal download-force creation path runs, so "als PDF" still produces a real new PDF. (The modifier list dual-cases sentence-initial umlauts — Ä/Ü do not ASCII-lower to ä/ü — so "Ändere die Datei und lade sie herunter" is correctly treated as a modify, not a bare re-download.) Also never bare: a message that carries a new attachment (document, image or other file — the request is about new material), and a message whose first sentence is an imperative change request (see the edit_file-only rule above). The classification reads the user's typed words; an attached document's content is ignored.
  • What it does (two coordinated steps, model-INDEPENDENT): at turn setup the gateway looks up the conversation's most recent generated file (chat_project_knowledge WHERE conversation_id = ? AND chat_generated = 1 ORDER BY (filename = ?) DESC, COALESCE(updated_at, created_at) DESC — a file the user named wins over the most recently written one; an edited file counts as written when it was last changed) and, if one exists, skips forcing the model to regenerate and caches the row. Then at the streaming terminal it re-emits that file's download card deterministically — whatever the (now-unforced) model says or doesn't say, including an empty turn or an honest decline. It is the same card the original write_file/code_interpreter turn produced, reconciled into chat_message_file so it survives a reload. No new model creation leg runs, so a weak model can neither botch nor corrupt it, and no duplicate file is minted.
  • Neutral re-download card, not "Updated": the re-served link reuses the original file's file_id in a new message, so without a marker the client would read it as a same-name rewrite and label the card "Updated" (and mark the original "superseded") — implying a change that never happened. The re-serve therefore persists chat_message_file.reserved = 1 (migration 0257; from ctx.reserved_file_ids), and the conversation-message files[] relation carries a reserved: true boolean on that entry. A reserved link renders as a plain re-download: the client ignores it when inferring Created/Updated, so the original card stays Created and the re-download card carries no revision label. Every genuine write_file link is reserved: false.
  • Trust boundary (owner-gated, fail-closed): the lookup is keyed on the authenticated user_id via get_conversation_route_scalars (the owner gate, WHERE user_id) — never on the untrusted x-aig-conv-id header or any history marker alone. A nil/empty principal, a foreign/shared-reader caller, or a conversation with no owned generated file each yield no card (no metadata leak, no cross-tenant IDOR). A re-served id is tagged in ctx.reserved_file_ids so the artifact-drop guard does not misfire on it, and set in ctx.written_file_ids so the branch-e file-claim and promise steers do not double-fire.
  • Precision: if no owned generated file exists (e.g. the first turn is "download the file"), nothing is re-served and the normal download-force creation path runs — a bare re-download only short-circuits when there is genuinely a validated file to hand back.

x-aig-datafile-auto — permit a per-turn model upgrade for data-file turns

The web chat sends x-aig-datafile-auto: 1 when a conversation routed by Auto (no explicit model pick) sends a turn that carries an inline data-file block (an attached spreadsheet/CSV preview). The header is a permission hint, never an authorization: it only allows the gateway to consider upgrading this single turn to a more capable model; every decision input is validated server-side.

  • Accepted shape: exactly the string "1". Any other value — absent, empty, another spelling, an over-long value, or a repeated header — is treated as absent (no upgrade consideration; the request proceeds unchanged).
  • Effect: when the request also actually carries an inline data-file block (verified server-side — a hint without a file is inert), the resolved model is not reliably tool-capable per the gateway's curated capability registry (provider/catalog self-claims do not count) with a context window covering the request, and staging the raw file is possible on this gateway, the gateway rewrites this turn only to the best eligible model: providers the gateway can actually dispatch to (configured or managed fleet, intersected with data-residency and provider-allowlist enforcement) ∩ the plan's model allowlist ∩ usable chat models with registry-proven function-tool support and an adequate context window — ranked sovereign-first, then by price. In a Local only project (or while the project binding cannot be confirmed) only local Myra models are eligible. No eligible model → the request proceeds unchanged. The upgrade is never persisted to the conversation; a later turn without a data file routes by the conversation's own model again.
  • Disclosure: an upgraded turn reports the actually served model in the X-AIG-Model response header on streamed responses (X-AIG-LLM-Model on non-streamed ones), and the assistant message row is persisted with the served model — the web chat renders a per-turn "Answered by …" notice from it.
  • Security: because the target set is confined to models the caller could already select explicitly on the same gateway, a spoofed hint cannot cross a residency, plan, or authorization boundary — at most it moves the caller's own turn to another model the caller is already entitled to use.

x-aig-auto-complexity — permit a per-turn Auto complexity upgrade

The web chat sends x-aig-auto-complexity: 1 on every turn of a conversation routed by Auto (no explicit model pick), to mark that the turn used the conversation's sticky Auto model rather than an explicit choice the gateway must never override. Like x-aig-datafile-auto, it is a permission hint, never an authorization: it only allows the gateway to consider upgrading this single turn; every decision input is validated server-side.

  • Accepted shape: exactly the string "1". Any other value — absent, empty, another spelling, an over-long value, or a repeated header — is treated as absent (no upgrade consideration; the request proceeds unchanged).
  • Effect: only on a gateway with per-gateway complexity routing enabled (gateway_config.laya_routing = shadow or live), the hint lets the gateway run the self-hosted Laya classifier on the turn's user text. In live mode a turn whose hard-probability mass clears the floor is rewritten this turn only to the best eligible frontier model — intersected with data-residency and provider-allowlist enforcement ∩ the plan's model allowlist ∩ registry-proven tool-capable chat models with an adequate context window, ranked quality-first. A Local only project (or an unconfirmed project binding) has no eligible frontier model, so its turns are never upgraded. No eligible model, a below-floor signal, or an easy/medium tier → the request proceeds unchanged. In shadow mode the verdict is only logged; nothing is rewritten. The upgrade is never persisted to the conversation; a later turn routes by the conversation's own model again.
  • Disclosure: an upgraded turn reports the actually served model in the X-AIG-Model response header (X-AIG-LLM-Model on non-streamed responses), and the assistant message row is persisted with the served model.
  • Security: the target set is confined to models the caller could already select explicitly on the same gateway, so a spoofed hint cannot cross a residency, plan, or authorization boundary — at most it moves the caller's own turn to another model the caller is already entitled to use. A best-effort classifier failure (Laya unreachable) fails open: routing is unchanged.

x-aig-web-search-freshness — restrict web search to a recency window

When web search is enabled for the request (via x-aig-web-search: 1, or a gateway configured with mode: "always"), this optional header narrows the underlying search to a time window so the model grounds its answer in recent results.

  • Accepted shape: one of the discrete windows pd (past day), pw (past week), pm (past month), py (past year), or an explicit inclusive date range in the form YYYY-MM-DDtoYYYY-MM-DD (e.g. 2022-04-01to2022-07-30). Anything else — an unknown token, a partial range, wrong separators, extra query fragments, or a non-string — is rejected: the header is ignored (fail closed) and treated as absent, so an unvalidated value is never forwarded to the search provider.
  • Effect: the validated window is passed to the web-search provider so only results within that period are returned. When the header is absent or rejected, the gateway's own default_freshness applies; it is unset by default, so the search then runs with no recency filter. A valid header always wins. The filter applies to every cross-provider path that runs the gateway's own web-search backbone (buffered OpenAI-format providers and the streaming vllm/myra tool loop); providers that use their own native search (Anthropic, OpenRouter, Gemini, Mistral Agents) ignore it. Recency is a Brave-adapter feature: the EU linkup adapter (see below) currently ignores the window and searches unfiltered.
  • In the app: the chat composer's + menu exposes a Recency dropdown (Any time / Past 24 hours / Past week / Past month / Past year) whenever web search is on; picking a window sets this header for the next send. "Any time" sends no header (unfiltered).

tool_choice on a web-search turn is honored one-shot

When x-aig-web-search: 1 injects the gateway's web_search tool and the request carries a forcing tool_choice ("required", or a named function/tool), the gateway forces the model to call the tool on the first leg only, then frees it: the injected search runs, and the model is unforced on the continuation leg so it can produce a final answer. Without the one-shot drop, a forcing choice would be re-sent on every leg and the tool loop could never terminate. Non-forcing values (absent, null, "auto", "none") are untouched. (This differs deliberately from an MCP connector-references loop, which rejects a forcing tool_choice with 400 — there the tools are resolved server-side and invisible to the client, so forcing them is meaningless; a header-injected web_search, by contrast, is a tool the client explicitly opted into. Both paths share one fail-closed forcing definition.) A provider/model that does not support a forced tool choice is unaffected by web search; a forcing choice sent to such a provider follows that provider's own wire behaviour. A client-supplied forcing choice is not retried without the force when the provider rejects it (that 400 strip-and-retry covers only a choice the gateway set itself): if the model's server cannot honor it, the turn fails with that provider's error. (It is still dropped after leg 1 as described above, and with all injected tools when the model turns out not to support tools — see Auto-disable of injected tools.)

Named choice on an Anthropic model (OpenAI-format request): the gateway translates tool_choice to the Messages API's shape —

Sent (tool_choice) Sent to Anthropic
"auto" / "none" / "required" (or Anthropic's "any") {"type":"auto"} / {"type":"none"} / {"type":"any"}
{"type":"function","function":{"name":"web_search"}} {"type":"tool","name":"web_search"}
{"type":"tool","name":"web_search"} {"type":"tool","name":"web_search"}
{"type":"auto"\|"any"\|"none"} the same type

Absent and JSON null send no tool_choice. Any other value that is not one of the shapes above — a named form whose name is missing, empty or not a string, an object without a string type, an unknown string such as "Required", a number or a boolean — never reaches Anthropic: the gateway refuses it at ingress with 400 INVALID_REQUEST (see the accepted-shapes table below). It is never turned into a forced choice and never dropped to auto. Anthropic rejects any forced choice (any or a named tool) while extended thinking is on — an x-aig-thinking-budget turn, or a model that always thinks — so do not send a forcing tool_choice on such a turn.

tool_choice — accepted shapes (untrusted input). A client tool_choice is forwarded to the provider, so the gateway accepts only the documented shapes and refuses everything else before any provider sees it:

tool_choice Result
absent or null the provider's default
"auto", "none", "required", "any" accepted
{"type":"function","function":{"name":"…"}} — exactly these keys, a name of 1–256 bytes accepted (OpenAI named function)
{"type":"auto"}, {"type":"any"}, {"type":"none"}, {"type":"tool","name":"…"} (name 1–256 bytes), each with an optional boolean disable_parallel_tool_use accepted (the native /v1/messages forms)
anything else — another string, a number, an array, an unknown type (e.g. allowed_tools), an extra key, a missing / empty / non-string / over-long name, a non-boolean disable_parallel_tool_use 400 INVALID_REQUEST naming the problem; nothing is sent upstream

One tool call per turn — parallel_tool_calls: false. OpenAI's top-level parallel_tool_calls is accepted on every OpenAI-format request and must be a JSON boolean:

parallel_tool_calls Result
absent or null the provider's default (parallel tool calls allowed)
true the same — nothing is added
false on an Anthropic model: "disable_parallel_tool_use": true is added to the translated tool_choice (see below); other providers receive parallel_tool_calls: false as before
anything else ("false", 0, 1, "", an object or array) 400 INVALID_REQUEST — 'parallel_tool_calls' must be a boolean. A wrong-typed value is never read as absent, so it can never silently allow parallel calls the client meant to forbid

Anthropic has no top-level switch; "at most one tool call" rides inside tool_choice. With parallel_tool_calls: false and at least one tool offered on the turn (your tools, or a tool the gateway adds such as web search):

Sent (tool_choice) Sent to Anthropic
absent / null / "auto" {"type":"auto","disable_parallel_tool_use":true}
"required" / "any" {"type":"any","disable_parallel_tool_use":true}
a named function or tool {"type":"tool","name":"…","disable_parallel_tool_use":true}
"none" {"type":"none"} — no tool can be called, so there is nothing to limit

With no tools on the turn, no tool_choice is added (Anthropic rejects a tool_choice without tools). A client that already sends Anthropic's own {"type":"auto"|"any"|"tool", "disable_parallel_tool_use":…} inside tool_choice gets that value forwarded as sent; when it and parallel_tool_calls: false disagree, the restrictive one wins (true). A non-boolean value there (null counts as absent) is rejected with 400 INVALID_REQUEST — 'tool_choice.disable_parallel_tool_use' must be a boolean.

Web-search direct answer relays tool_calls and labels the terminal reason

When x-aig-web-search is on but the model answers directly on leg 1 (it does not call web_search), the gateway returns that leg as the response. (This is the two-leg path, which runs only for a request the gateway tool loop does not handle — see Web search — Supported providers; on every other turn web search is one of the tool loop's tools.) On the compat (OpenAI) egress:

  • if the model made its own tool call on that leg (a client-provided tool), those tool_calls are relayed on choices[0].message.tool_calls (with finish_reason tool_calls) — the turn is not collapsed to an empty completion; and
  • otherwise the terminal finish_reason is routed through the gateway's single stop-reason authority: a length-capped answer surfaces as length (so a truncated web-search answer is labelled incomplete, matching the non-web-search paths) rather than a clean stop; every other terminal reads as stop.

(An empty tool_calls array or a non-array value is not relayed. On a PII gateway the relayed tool-call arguments are token-restored with the correct depth-2 escaping.)

If the provider answers that first leg with 200 and a body the gateway cannot read (an event stream, non-JSON text, an empty body, a JSON array or any other non-object, or an error object on a 200), the request ends with one 502 upstream_error after a single provider call; the gateway does not dial the provider again.

If the web-search direct answer instead comes back with zero visible content (no text and no tool call — e.g. a reasoning-only turn), it is classified through the same shared empty-response path as the non-web-search buffered egress: the turn is counted as an EmptyResponse in the gateway's telemetry, and the compat egress delivers a short fallback bubble (a "produced internal reasoning but no visible answer" or "returned an empty response" note) instead of a blank message — so a web-search direct answer is never a silently empty turn, matching the other egress paths.

Web-search provider selection and EU residency

The gateway's own web-search backbone is provider-pluggable, selected per gateway by web_search.provider in the gateway configuration:

  • brave (default) — Brave Search (US). Used for every gateway that does not set the field.
  • linkup — linkup.so (EU, France; GDPR Art. 28 DPA, zero data retention). The EU-sovereign backend for tenants that must keep the model-generated search query in the EU.

The per-gateway search API key stays in the existing web_search.api_key field (it holds the key for whichever provider is selected). Web search is turned off per gateway with web_search.enabled: false.

Platform Linkup key injection at read

Every new production gateway — the pay-first default gateway, both trial gateways (internal and external), and a gateway created by an administrator via POST /admin/v1/tenants/{id}/gateways — is provisioned with web search on via Linkup — web_search: { enabled: true, provider: "linkup", max_results: 5 } — so a fresh organisation can search immediately with no manual setup (before it, only trial gateways were seeded). The block is seeded only when the gateway has no web_search block at all: an explicit web_search.enabled: false, a block with its own api_key (BYOK), another provider, or any existing value is a deliberate choice and is never overridden. Gateways created with purpose test, benchmark or archived (E2E fixtures, rigs) are not seeded. Existing trial gateways were backfilled the same way (migration 0302); existing non-trial gateways that have no web_search block are not backfilled (a separate decision).

The Linkup api_key for these gateways is not stored in the gateway config. It is a shared Myra platform key held in the database settings row trial_linkup_api_key (the historical name — it applies to every plan) — a super-admin sets it live from the admin console (Feature flags & settings), taking effect within about a minute. It is injected into the effective config at read time, for any tenant plan, gated only on the block being enabled, the provider resolving to linkup, and the block carrying no api_key of its own. It is a low-value search key, not a credential: a plain setting — the settings GET returns it verbatim and it is admin-editable live (see Global settings API). Consequences:

  • The stored gateway config (and therefore the admin GET/list responses and the tenant config export) contains the web_search block but never the platform api_key — the shared key is injected only at read time and is not written into per-gateway config or exports. This holds for every plan, including callers holding GATEWAYS_MANAGE.
  • If trial_linkup_api_key is unset (or empty), new gateways are still seeded with the keyless block (so a later key set lights them up with no backfill), but they have no web search until then: they report web_search_setup_pending: true, the /easy composer shows a visible "not set up" notice, the Health dashboard flag web_search_platform_key_missing is true, the gateway logs ERR every 10 minutes and a [platform_alert] fires (at most every 6 h). Signup and gateway creation never fail because of it. Set it to a dedicated, rotatable Linkup key from the admin console.
  • A trial → paid conversion changes nothing for web search: the injection is plan-agnostic, so the converted organisation keeps searching. A customer who wants their own Linkup or Brave account sets web_search.api_key (and provider) on the gateway — an explicit key always takes precedence over the platform key.
  • max_results is honored by the Brave adapter but ignored by Linkup (kept for shape parity).

Regardless of plan, the server-computed web_search_configured boolean the gateways endpoint returns (and the composer's Web search switch reads) reflects the effective config — so a keyless Linkup gateway reports web search as configured via the injected key, without the key ever reaching the client.

  • Fail-closed EU gate. When a gateway (or its tenant) enforces EU residency (eu_region_routing, including the inherited tenant_eu_region_routing floor), the model-generated search query may egress only to an EU-vouched search provider. A non-EU provider — including the brave default a sovereign gateway forgot to switch — is blocked: the query is never sent, and the model is told the search was withheld. A sovereign tenant can therefore turn web search off, but can never silently fall back to Brave (US). This also neutralizes the buffered path's wttr.in weather side-channel (which would otherwise embed the raw query in a URL to a US host). The query PII scrub (see guardrails.md) runs on top of this on every provider path.
  • The linkup response is untrusted third-party content and is validated fail-closed (principle 11): a non-2xx status, a non-JSON / non-object body, or a body with no results array yields a classified failure and zero results (never a partial or fabricated answer); every result url must be an absolute http(s) URL or it is dropped (a javascript:/data:/scheme-relative/empty URL can never become a citation or link). linkup's results[].{name,url,content} are normalized to the internal {title,url,snippet} shape at the single dispatch point, so downstream formatting/citation code is provider-agnostic.

Inline numbered citations

When the gateway's own web-search backbone runs (the cross-provider vllm/myra path — not a provider's native search), each search returns a numbered source list to the model, and the model is instructed to mark the claims it grounds with inline [1], [2] … references. The answer ends with a numbered Sources: footer (German: Quellen:) listing those URLs in the same order, so [N] in the prose maps to source N in the footer. The footer's wording follows the conversation language: the language detected for the conversation turn (chat conversations and agent runs; a bare API request without an x-aig-conv-id header skips this detection), else the account's interface language, else English. English conversations get Sources and German ones Quellen; any other language gets the English wording. The footer appears exactly once per answer, at its end — also when the gateway continues or re-drives the turn after the model's first answer part (a length-cap continuation, the broken-promise nudge, the file-claim steer or re-dial, a tool call the gateway recovered from the text): the footer then follows the last part, never sits between two parts. When such a follow-up call fails, the answer is cut off, or the tool loop stops early, the footer follows the turn's last text — after the gateway's own "interrupted" / "no visible answer" note — and, where the gateway closes the stream itself (a failed follow-up call, a cut-off answer), precedes that closing error frame and finish chunk. (When the tool loop stops on a limit, its stop note comes last, after the footer of the answer written so far.) A turn in which no part produced a visible answer gets no footer (no list of sources under an "empty response" notice or a tool-call hint alone); text the model wrote next to a tool call ("I'll look that up") counts as the answer only when the turn then ends normally. A turn the client cancelled gets no footer either. In the chat UI this footer is rendered as a collapsed-by-default disclosure ("Sources (N)" / "Quellen (N)") so a long source list does not flood the answer; the inline [N] markers remain direct links to the source, so a source is still one click away without expanding the list.

The footer in a replayed conversation. The footer is part of the stored answer, so a client that sends the conversation back as history sends it back with the footer. The model would copy that format into its next answer and the gateway would then add its own footer: two source lists. On the composed chat path (requests that carry an x-aig-conv-id header; a bare API request without it is replayed verbatim, as before) the gateway therefore removes the footer from each earlier assistant message before the model sees the history. The URLs are not lost: they reach the model in one gateway note appended to the newest user message, so a follow-up such as "what does source 3 say?" still works.

The note is one bracketed block in the conversation language, for example [Gateway note: sources the gateway showed under earlier answers (not part of this message): followed by one line per answer, Answer 2: [1] URL · [2] Title — URL (+K more)] (German: [Gateway-Hinweis: Quellen, die das Gateway unter früheren Antworten angezeigt hat (nicht Teil dieser Nachricht):, Antwort N:, (+K weitere)). The numbers are the footer's own numbers, so [N] in an earlier answer still maps to source N. The note covers at most the last 10 answers that carried a footer and is capped at 4096 bytes; a source title is cut to 120 bytes. Answers that do not fit (older than the last 10, or dropped by the byte cap) are not lost silently: the note ends with a count line, (+K earlier answers omitted) (German: (+K frühere Antworten ausgelassen)). If one answer carried two footers, they are merged into one Answer N line; an entry that appears twice is listed once, and when two footers give the same number a different URL, the later one wins. When a recovery re-send has to drop history, the sources stay as one flat, unlabelled list. The language follows the user's own words in the newest message, then the interface language, else English. The note is PII-masked like the other text the gateway injects, is never part of what the conversation record or the tools read as the user's request, and is not stored.

Only a footer in exactly the gateway's own format is removed (heading Sources: or Quellen:, consecutive numbering from 1, valid http(s) URLs, at most 100 lines, optional "hidden sources" line); anything else in an assistant message, and every user, system and tool message, reaches the model unchanged and is never rejected. The stored message is not modified, and the request that is recorded for a replay keeps the client's original text. Files the model writes are not affected; a file that uses search or fetch results keeps its own Sources section.

Citations inside a written file. The [N] markers belong to the chat answer only — a file produced with write_file has no footer to resolve them, so a document that carried them showed bare [1], [3]. The model is therefore instructed (in the write_file tool description, the file-tool rules of the composed system prompt and the file-first system notice — one shared rule, emitted only on turns where write_file is actually offered) not to use inline [N] markers inside a file. A source is a URL that appeared in a search or fetch result in the conversation, that the user wrote, that the instructions give (such as the product docs) or that a gateway note in the conversation lists, or a file the user gave. When the file's content comes from such a source, the model is instructed to list those sources in a final Sources / Quellen section (one line per source with title and URL or file name), whether or not sources were asked for. The model is told that its own knowledge is not a source: it must not list remembered textbooks, statutes, standards or URLs there (naming a law or standard in the text itself is fine). When the user explicitly asked for sources but the content has none (for example, it was written from the model's own knowledge), it is instructed to write one plain line saying the file has no external sources instead; for a clean document without sources it omits both. A file that is not built from a source and for which the user did not explicitly ask for sources (the instructions alone never trigger the line) gets neither section nor line. The ban is on a Sources section or reference list at the end of the file: a list the user asked for as the file's content (such as a reading list) is fine. This is an instruction to the model, not a check by the gateway. The gateway does check the links in a file the model writes: a link it cannot trace to a source of the conversation is labelled, see Unverified links in files the model writes. Apart from that label the gateway does not rewrite file content.

  • Source URLs are untrusted third-party content. They are validated at two boundaries and fail closed. A result URL is accepted only as a string with a lower-case http:// or https:// scheme, at most 2048 bytes, without ASCII whitespace or control characters and without < or >, and valid UTF-8; anything else (e.g. javascript:/data:, a URL with an embedded line break) is dropped when the provider (Brave or linkup) response is parsed and again when the footer is rendered (so Anthropic-native citations, which don't pass through the search path, are covered). Source titles are stripped of markdown-link metacharacters. The SPA re-validates every URL scheme before rendering a link.
  • Best-effort per claim. Inline [N] anchoring depends on the model following the instruction (as with Perplexity/ChatGPT Search). The numbered source footer is the guaranteed floor; models that don't emit [N] still get the footer, and an out-of-range or hostile-scheme [N] is left as plain text. Providers with native search cite in their own style and are unaffected.

Auto-disable of injected tools on a non-tool-calling model

Some routed models (for example the Perplexity Sonar family) expose no upstream endpoint that accepts a function-tools array; injecting the gateway's own function tools (web search, URL fetch, file access, knowledge, code, connectors) would make the provider reject the whole request (OpenRouter returns 404 "No endpoints found that support tool use").

For a model the gateway knows cannot do function calling (recorded in its capability registry), the gateway now proactively strips its injected function tools before the upstream call and lets the run proceed as a plain answer — instead of relaying the opaque 404.

The notice has a second, reactive trigger. The proactive strip only fires for a model the gateway has explicitly curated as non-tool, which cannot keep up with a catalog that grows (an OpenRouter image model, openai/o1-pro, whatever is added next). So when a model the gateway did not recognise as non-tool refuses the injected tools at the upstream — OpenRouter answers 404 "No endpoints found that support tool use" — the gateway now strips its own injected set, rebuilds the system prompt so it no longer offers tools the model cannot call, and re-sends the turn once as a plain answer. Same notice, same category tokens; the only difference is that the strip was learned from the refusal rather than known in advance. At most one extra upstream call per turn, and only for tools the gateway injected. A caller that named its own tools gets its provider's error passed through verbatim — both a plain tools array (the client is driving its own agentic loop, and silently removing its tools would leave it waiting for tool_calls that never come) and an array of {"type":"mcp"} connector references (those were explicitly requested, and the typed error names the actual lever: remove the references or pick a tool-capable model).

Scope, stated plainly: the retry is triggered by the upstream saying it cannot accept tools, so it covers the refusal phrasings the gateway recognises — OpenRouter's "No endpoints found that support tool use", and the "does not support tools / tool use is not supported / function calling is not supported" family. A backend that refuses tools in wording the gateway does not recognise still surfaces the typed error. That is a shorter and slower-moving list than one entry per model (openai/o1-pro is not an image model, which is why per-model curation could not keep up), but it is a list.

The client is told which tool categories were skipped:

  • Streaming (chat / playground): an additive SSE status event {"aig_status": "tools_skipped", "tools": ["web_search", "url_fetch", ...]} just before [DONE]. The SPA renders an informational notice on the assistant message. tools is a deduped list of coarse category tokens (web_search, url_fetch, files, knowledge, image, code, connectors, connectors_policy, or a generic tools). connectors means a connector was unavailable (transient — a retry may help); connectors_policy means the project forbids external egress, so the connectors could never have run (permanent for that conversation, and nothing is broken). When a dropped connector can be identified, the same event also carries an optional connectors array — [{"id","name","reason"}] — naming each dropped connector so the SPA can name it (instead of the bare connectors word) and, for a credential-class reason (credential_required / credential_expired), offer a Connect/Reconnect deep link to /connectors?focus=<id>. The coarse tools categories still cover nameless drops (policy / discovery-deadline). The gateway also injects a turn-scoped system note telling the model the named connector exists but is unavailable this turn (so it asks the user to reconnect rather than claiming the connector does not exist).
  • Buffered agent /invoke: a tools_skipped trace step (visible via the run's X-AIG-Trace-Id / run-detail) records the skipped categories, the model, and the provider.

Provider-native web search (OpenRouter plugins, Gemini grounding, Anthropic's native search) needs no function-calling capability and is injected in the provider's request build, so it intentionally survives this strip and is not listed as skipped — and that is true of the reactive strip too: the notice enumerates only what the gateway actually removed, so a turn whose OpenRouter web plugin still runs is never told it has no web search. A tool-incapable model the gateway does not recognize up front is not stripped here (this section describes the proactive strip, which fires only for a curated non-tool model) — it is stripped reactively instead, once the upstream refuses the injected tools, as described above. model_capability_mismatch (see error codes) remains for the case where that stripped retry ALSO fails, or where the refusal names a capability stripping cannot fix (an image, a document).

EU-residency exception. Auto-disable + proceed applies only on a non-EU gateway. On an EU-residency-enforced gateway (eu_region_routing), a definitively-non-tool online model (e.g. a Perplexity Sonar model) is not auto-disabled — it stays fail-closed. Such a model's intrinsic web search egresses outside the EU and cannot be stripped by the gateway, so proceeding would breach the tenant's data residency; rejecting is the safe outcome. In practice today's such models (Perplexity Sonar via OpenRouter, a non-EU provider) are refused by the residency dispatch gate with data_residency_blocked before any upstream call; skipping the auto-disable here simply avoids emitting a misleading tools_skipped notice ahead of that block. (A future definitively-non-tool model on an EU-vouched provider whose intrinsic search still egressed would instead be rejected with model_capability_mismatch.)

Web search enabled but not used / no results / failed

When web search is enabled for a turn the gateway keeps tool_choice: "auto" — it never forces the model to search (that would burn a turn on greetings, rewrites, and context-answerable follow-ups). A consequence: a weaker model may answer from its own training, or ask "should I search?", without running a live search — and a search that the model does run can still fail or return nothing. In all three cases the answer used to look normal with no signal that no trustworthy live search happened.

The gateway now emits an additive side-channel status event so the SPA can render a distinct chip on the assistant bubble:

data: {"aig_status":"web_search_notice","reason":"not_used"}
reason Meaning Chip
not_used Web search was enabled but the model answered without calling it (replied from training / asked whether to search). "Answered without web search"
no_results The search ran but returned zero hits. "Web search returned no results"
failed The search provider errored (quota / auth / network). "Web search failed"
not_run Web search was requested but could not run for this request (see X-AIG-Web-Search-Notice). The frame also carries cause, one of the reasons listed under When a requested search cannot run. The same turn also carries the response header X-AIG-Web-Search-Notice: not_run. cause-specific text, for example "Web search did not run: no search provider is set up for this gateway."

reason is required; cause is optional and read only on not_run. The SPA renders a chip for not_used / no_results / failed / not_run; any unknown reason is ignored (no chip; the boundary rejects unknown values rather than rendering a raw slug). An unknown or missing cause shows the generic not_run text. The not_run frame is sent once per response, on the streamed terminal and on a re-emitted buffered answer; a native /v1/messages passthrough carries no frame. The event is additive — an older client ignores the unknown aig_status (no schema bump) — and is delivered only to a client that opted into the aig_* side channel. It is emitted on the two-leg web-search engine (not_used at the buffered leg-1 direct answer, re-emitted on the buffered→SSE tail; no_results/failed inline on the streaming leg-2 wire) and on the tool-loop web-search path. It is a notice, not an error — the turn proceeds and the answer is still delivered; the chip only tells the user the answer is not backed by a fresh search. Live-session only — like the tools_skipped and pii_masked notices, it is not persisted, so a reloaded conversation carries no chip.

Declining all tools with tool_choice: "none"

A request that carries tool_choice: "none" (the string, or {"type": "none"}) is a declaration that the model will call no tool this turn. On such a request the gateway injects no built-in tools — not web search, URL fetch, file access, knowledge, image generation, nor code interpreter — and strips the now tools-less tool_choice from the upstream body (a tool_choice with no tools array is rejected by several providers). This is honored uniformly across every provider, including the pass-through providers that have no gateway tool loop (Gemini, Vertex, Bedrock, Perplexity).

  • Only an explicit "none" opts out. Absent, null, and "auto" are not a decline — they receive the normal offered tool set. A forcing value ("required", a named tool, {"type":"any"}, …) is not a decline either (and is separately rejected on the MCP path — see the connector table above).
  • MCP connector references are the one exception: a request that ALSO carries tools:[{"type":"mcp", …}] still resolves those connectors and runs the loop with tool_choice:"none" (the model declines to call), exactly as the connector table above documents — a client that named connectors asked for that loop. The built-in-tool suppression above applies to the plain (no-refs) request. On a provider with no gateway tool loop (Gemini, Vertex, Bedrock, Perplexity) such a refs request is therefore rejected with model_capability_mismatch, tool_choice:"none" notwithstanding.
  • The client is never the authorization boundary: tool_choice:"none" can only reduce the offered tools, never widen them.
  • The decline is snapshotted from the client's request before any gateway middleware mutates the body, so a gateway-internal tool_choice:"none" set on a later leg (e.g. the web-search two-leg synthesis leg) is never mistaken for a client decline.

This is how the /easy surface's post-turn utility completions (auto-title, follow-up suggestions) stay pure text: they send tool_choice:"none" so a code-interpreter-enabled gateway does not run the sandbox for a completion the user never sees.

Inline tool-call recovery (self-hosted vllm/myra models)

A self-hosted model (our qwen/vLLM fleet) occasionally emits a tool call — most commonly web_search — as inline text in the assistant content instead of a structured tool_calls field, when the serving-side tool parser fails to extract it. The gateway recovers these so the tool still runs. Recognised dialects:

  • the wrapped XML form <tool_call><function=web_search><parameter=query>…</parameter></function></tool_call>;
  • a whole-content JSON object {"name":"web_search","arguments":{"query":"…"}} (also accepted inside a <tool_call>…</tool_call> block, and when arguments is a JSON-encoded string);
  • a whole-content pseudo-call web_search(query="…") / {web_search(query="…")}.

The recovered call is untrusted model output and is validated fail-closed at this boundary — a call is recovered only when ALL hold, otherwise the text is left as-is (no tool runs):

  • Accepted: the JSON/pseudo call is the whole trimmed message OR the sole content of a <tool_call>…</tool_call> block (the wrapper is itself an anchor, so a wrapped call is honoured even with surrounding prose — consistent with the existing <function=…> behaviour); its name is a string on the request's resolved/allow-listed tool set; and its arguments is a JSON object with at least one string key.
  • Rejected (rendered as plain text, no dispatch): an un-wrapped JSON/pseudo tool call embedded in surrounding prose (a documentation example, a pasted snippet, "what does this JSON look like"); an unknown / non-allow-listed / hallucinated tool name; missing / empty / non-object arguments (incl. a JSON array); malformed or truncated JSON. write_file/read_file are never synthesized from this ambiguous channel (a mutating write is only dispatched from an unambiguous marker). When a write_file/read_file IS emitted as a bare-JSON/pseudo call and therefore not dispatched, the gateway does not lose it silently — it records a fail-loud silent_write_file_drop / silent_tool_call_drop trace step and an ERR log (so a new serving dialect is caught and patched), rather than letting the reply falsely claim success.
  • Recognised tool tag the visible stream removed but nothing synthesized: when the model's entire visible output is an inline tool tag the gateway strips from the bubble (a <tool_call> / <invoke> / <function_calls> wrapper, or a <write_file> with no parseable filename) but no dialect/allow-listed call is recovered, the assistant turn used to render as a silent empty bubble — the user had to send a bare ? for the model to produce the answer on the next turn. It now surfaces a short retry hint ("I tried to call a tool but the call wasn't in a format the gateway could parse. Please ask me to continue…", in the request's language, German or English, by the same rule as the tool-loop note) instead. On an unattended run (scheduled and webhook-fired agent runs, scheduled prompt tasks, workflow agent steps, and any service-token call that sends X-AIG-Unattended: 1; see Round limit stop note) the hint does not ask the reader to continue, because the mail, webhook or chat message that carries it has nobody to answer: it says the call was not run and, if the result is missing, to run the task again (if it repeats, simplify the task or use a different model). The gateway also records an EmptySuppressedNoTool (gateway_fault) signal so the unrecognised dialect is caught and patched. (A <memory> tag stripped from an otherwise-empty turn is not a tool call and gets neither this hint nor the empty-response fallback — see Empty responses above; a whitespace-only turn does get the fallback, tools offered or not.) The same applies to the bracket dialect [tool_call id=…] / [tool_result id=…] some models emit: it is removed from the visible stream, and each occurrence is logged ([pseudo_tool_markers]). When it is all a closing no-tools leg produced, that leg counts as blank and the tool-free recovery leg answers instead of the retry hint.
  • Unwrapped <write_file> / <read_file> block bounding: in the gemma/qwen inline-XML channel the next tool opener is a hard wall for every block: a block ends at its own close tag when that lies before the wall, otherwise at the earliest of a Hermes terminator (</function> / </tool_call>), the wall, or the end of the message. A close tag beyond the wall belongs to that later block and never ends the earlier one, so two <write_file> blocks where the first was left unclosed yield TWO calls — the first marked torn (the dead-leg diagnosis reads it as such), the second whole — instead of one call for the first file with the second file's markup embedded and the second file silently never written. An open tag whose > lies past the next opener is unparseable and skipped — no call is yielded for it (the next opener is parsed on its own). Bounding is dialect-free (the block's own close tag before the wall ends any block; otherwise the earliest of a Hermes terminator, the wall, or the end of the message); whether a block counts as closed follows its dialect: the attribute form (<write_file filename="…">) closes only with its own </write_file> — a </function> / </tool_call> inside it is quoted content, which bounds the block (the two are indistinguishable on the wire) but leaves it torn; the parameter forms (<write_file> / <function=write_file> with <parameter=…> children) close with the Hermes terminators or their own </write_file>. A body in the attribute form that quotes a Hermes terminator keeps it when its own close tag arrives before the wall. The scan is linear in the message on every axis (blocks, body bytes, repeated <parameter=…> openers): every literal lookup is a plain find, memoised. The wall's inherent trade-off: a body that quotes another tool opener (a write documenting a tool call) is split at that opener — a nested quote and an interleaved torn block are indistinguishable without a depth model — so the quoting block comes out torn and the quoted call is dispatched.
  • web_search query typing: on the buffered path a non-string query is not recovered (left as plain text); on the streaming path the call is dispatched and the tool returns an "Error: query required (must be a string)" result (it never crashes).

Degraded write_file sentinel recovery + file-claim honesty guard (streaming)

A weaker model sometimes announces a file instead of calling write_file: it prints a pseudo-sentinel like DATEI_ERSTELLT:report.html, a bare write_file token, or narrates "the file is saved — click the file card" while the turn produced zero write_file artifacts. Previously nothing recovered, stripped, or corrected these — the sentinel leaked into the visible answer, no download card existed, and the user was stranded retrying. On streaming tool-loop legs the gateway now:

  • Sentinel recovery (whole-content anchored, like the JSON/pseudo dialects above). Accepted: the entire trimmed message is a single IDENT:<filename> line (IDENT all-caps, ≥4 chars; the filename a single token with a 1–8-char alphanumeric extension; at most one space after the colon — e.g. DATEI_ERSTELLT:Report_Q2.html, FILE_CREATED: notes.md), a bare write_file / write_file() token, or a contentless pseudo-call write_file(filename="…"). The blob is suppressed from the visible answer and ONE contentless write_file call is dispatched instead — the tool rejects it deterministically (content required …, before any persistence or cap tick, so the dispatch is provably side-effect-free) and the error text steers the model into a real write_file call on the next leg. Rejected (left as plain text / loud-guarded only): a sentinel embedded in prose or spanning multiple lines; lowercase or short identifiers; a post-colon token without an extension (WICHTIG: Bitte …); a pseudo-call with a content key (a mutating write is never synthesized from this ambiguous channel — it stays with the fail-loud guards); any sentinel when write_file is not among the resolved tools (fail-closed); a sentinel co-occurring with a structured tool call (silent_write_file_drop fires with file provenance instead of dispatching).
  • File-claim honesty guard (once per turn). When the visible text claims a produced file but the turn delivered no downloadable artifact, the gateway sends one contentless steering write_file call so the model either writes the file or answers honestly; the file-claim check note covers what remains.

  • Observability: file_sentinel_recovery / file_claim_no_artifact WARN logs + trace steps (filenames gated by the trace content gate, see Tracing).

Self-repeat guard (streaming and buffered)

Some models write their whole answer twice inside one completion, separated by a gap of three or more line breaks (X, a seam, then X again). The gateway removes the second copy on the way out, before it is sent or recorded, so the stream, the saved message and the stream: false body stay identical.

  • What counts as a copy. Text that follows a seam (a run of spaces, tabs, carriage returns and line breaks holding at least 3 line breaks) and is a verbatim, byte-for-byte copy of everything the leg showed before the seam (leading and trailing whitespace of that text ignored). A copy that differs, is cut short or continues past the original is shown unchanged. Three copies give one. This also applies when the user asked for the repetition: an answer repeated verbatim with two or more blank lines between the copies is reduced to one copy.
  • Per leg. Every model leg is judged on its own, on streaming (SSE) egress and on buffered stream: false egress. A repeat that spans two legs is not a self-repeat.
  • Never dropped at the end. Text still held when a leg ended by the length cap, died before its finish event or errored releases whatever is held, byte for byte.
  • Limits. Text longer than 262144 bytes passes through unjudged. A whitespace run over 4096 bytes is never held.
  • Minimum content. A copy is only dropped when the original holds at least 4 word bytes (ASCII letters or digits, or any non-ASCII byte) and no code-fence marker (three or more identical ` or ~ in a row). A short greeting such as "Hello!" qualifies; "-", "1." or fenced code never does.
  • Restart counters. Dropped bytes are not added to the restart-dropped fields of the restarted-preamble guard.
  • Block repeats. A model may also repeat only the block it just wrote: a first paragraph, then the main text, then the main text again (P1, X, X, then new text). The guard drops the second copy of X when all of these hold:

    • X starts at the first or second paragraph of the leg and spans at least 256 bytes from its first to its last non-whitespace character (whitespace inside it counts);
    • the copy is byte-for-byte identical and is followed by a gap of two or more line breaks and more text (or ends the completed leg);
    • the word and code-fence minimums above hold for the text the leg has shown so far, not just for X, so any code fence earlier in the leg switches the block check off.

    Kept unchanged: a block that starts at the third paragraph or later; a copy followed by a single line break or by spaces only before more text; and a near-copy (any differing byte). If a paragraph equal to the leg's first (or second) paragraph comes back later, that candidate is switched off for the rest of the leg, because the text is then a loop rather than a copy. The guard removes whole separator-plus-copy segments and never edits a byte. This check runs before the whole-answer check and is identical on stream and body. A block copy followed by a blank line and more text is dropped as soon as it is recognised, on every leg, including one that later ends by the length cap or dies; only a copy still held when such a leg ends is released byte for byte.

  • Paragraph loops. A paragraph of at least 8 words and at most 8192 bytes (C3_MAX_BYTES: a paragraph is never held longer than this, so the held text and the per-chunk comparison work stay bounded; 8192 is twice the 4096-byte unit limit of the whole-answer stage and above any normal prose paragraph) that the model writes again directly after itself (the last complete paragraph, at any size) is dropped as a back-to-back duplicate. When the same paragraph comes a 4th time after two dropped copies, the gateway also stops the generation (the leg is recorded with error_class text_loop_stop, status 200, partial 0 and estimated usage) and the answer keeps one copy. A paragraph under 64 bytes is only judged a loop once its 4th occurrence is complete (followed by a blank line); a 4th occurrence that continues on the same line is shown. The stop does not depend on how the text was cut into chunks. When the provider's own finish reason is a length cap, the stopped leg ends as a plain stop (no length continuation or recovery is requested for a loop that was cut); every other provider finish (content_filter, tool_calls, stop) is reported unchanged, whether the loop was recognised in the finish chunk or at the end of the stream. Known residual: once a paragraph has been dropped twice, a following paragraph that shares at least 64 bytes with it and then differs is cut as well (its shared start is taken for the 4th copy); a paragraph that shares less is kept. Paragraphs shorter than 8 words (list items, short lines) keep the earlier behaviour and are never cut. The stop is not applied once the reply has started a tool call (copies are still dropped, and the call is kept), and it applies to streaming (SSE) and buffered reads alike.

  • Block cycles. A block of 2 to 16 paragraphs that the model writes 3 times in a row and then starts a 4th time inside one leg (a cycle of paragraphs, for example A B C A B C A B C A, that starts after the first paragraphs of the answer) also stops the generation, with the same leg record as a paragraph loop (text_loop_stop, status 200, partial 0, estimated usage). The stop is recognised once the first paragraph of the 4th copy is complete and the next paragraph has started: the client sees the block shown 3 times plus the first paragraph of a 4th copy, the separator is not shown. A block that is shown exactly 3 times and followed by different content (for example a closing paragraph) is never cut. A paragraph that completes inside text the gateway had been holding back and then released is checked at the next paragraph break, so the stop can then come one paragraph later: the paragraph that follows it is shown, then the generation stops (a leg that ends before that paragraph break is not cut and reports no loop). The block must hold at least 8 words in total and must not itself be a shorter repeating block (a single repeated paragraph is the paragraph-loop case above). Paragraphs over 8192 bytes, cut paragraphs and paragraphs that contain or sit inside a code fence never count toward a cycle, and a period above 16 paragraphs is not stopped. A white-space run of more than 4096 bytes between two paragraphs ends cycle detection for that leg (a bounded, deterministic limit; the text is shown). The comparison looks only at the words of each paragraph (ASCII letters and digits; bytes of 0x80 and above count as word bytes), so it ignores ASCII letter case, white space and ASCII punctuation and signs. It applies on every model and every compat leg, text-only like the paragraph stop. Trade-off: a block that the user explicitly asked to be written 4 or more times is shown 3 times plus its first paragraph and then the generation is stopped. When the block-repeat guard applies to a block that starts at the first or second paragraph (it spans at least 256 bytes and its copies are byte-identical), the later copies are dropped and the first paragraph of a 4th copy (with anything held) is dropped too and stops the generation, so the client sees the block once (plus the paragraphs of the 4th copy written before the text went on with something else, when that copy is not written in full); otherwise the rule above applies (3 copies plus the first paragraph of the 4th). A block written at most 3 times followed by other text keeps that text.

  • Observability. A self_repeat_dropped trace step (copies, bytes, block_copies), a [self_repeat] NOTICE log line, and ctx.meta.self_repeat_dropped (dropped bytes) per affected leg.

Restarted-preamble guard (streaming, after a re-driven leg or a tool round)

Some models, when the gateway re-drives a turn (the broken-promise steer, the file-claim steer or the file-claim re-dial), start over and re-emit the opening paragraphs they already showed. Without a guard the user sees the same preamble two or three times in one reply and it is persisted that way. Once a turn has been re-driven, the gateway therefore drops a paragraph that repeats text of the same turn the user already sees, before it is sent or recorded, so the stream and the saved message stay identical.

A call the gateway starts after such a re-drive begins on a new paragraph (a blank line is added unless the shown text already ends in one), so the guard's first kept paragraph never fuses with the text before it.

  • When it applies. On legs that start after a re-drive (full judging), and on the first leg after a tool round (leading repeats only, see below), and only on a tool-active turn, on streaming (SSE) egress only. A turn that was never re-driven and had no tool round (including a plain length-cap continuation) is byte-identical to before. A buffered response (stream: false, the playground, a PII or schema forced buffered re-emit) is never touched: its body is the last leg's text only, so dropping a "repeat" of text an earlier leg showed would remove content the client never received.
  • Restated opening sentence. On the first leg after a tool round, a paragraph that restates only the opening sentence(s) of a shown paragraph and then continues differently ("I have checked both documents. Now I create the file:" followed, after the tool, by "I have checked both documents. The document is ready:") loses the restated sentence(s); the rest of the paragraph is kept. A sentence ends at ., ! or ? followed by whitespace or the end of the text, after a word of at least 3 letters that is not a number, and before a capital letter, so "17.", "z. B." and "vs. PY" are not sentence ends. The removed text is a byte-for-byte copy of the start of a shown paragraph, has at least 3 words, holds no line break and none of * _ ` ~ | < >, and has balanced parentheses and brackets; otherwise nothing is removed.
  • What is dropped. The leg's text is judged paragraph by paragraph (a blank line is the boundary: a line break, optionally preceded by a carriage return, then only spaces, tabs or carriage returns, then a second line break, so \r\n\r\n is a boundary too; one definition is used for the comparison and for the leg index, and a dropped paragraph takes its own CRLF separator with it, never leaving a stray \r). A paragraph is a repeat when its words (case-insensitive for ASCII, punctuation ignored) are identical to a paragraph already shown (at least 3 words for the leading paragraphs of the leg, at least 6 words further into the leg), or — for the leading paragraphs of the leg only, a reworded restart — when it has at least 8 distinct words and its set of distinct words is similar enough to one shown paragraph. Two modes decide "similar enough":

    • Every leg after a re-drive until a tool result is produced (any kind: success, error, denied, deferred; a length-cap continuation of the nudged leg stays in this mode; the model was nudged and restarts) compares by containment: at least 70% of the candidate's distinct words occur in the shown paragraph, and the candidate has at least half as many distinct words as the shown paragraph (it is not a small slice of a much larger one). A restart that expands the content (it is much longer than the part it shares with the shown paragraph) is shown: the restart is kept from its first novel paragraph on.
    • Every other guarded leg (for example the leg after a tool result) compares by symmetric Jaccard similarity of at least 80% (shared words divided by all words of both). A completion that only re-uses the vocabulary of an earlier promise ("I will now create X", then "I have created X") is kept.

    Paragraphs further into the leg are only compared by the exact rule. Every earlier leg of the turn is split into paragraphs on its own: the end of a leg counts as a paragraph boundary even when the leg stopped without a blank line, so the last paragraph of one leg and the first of the next are never merged into one. Only the first 256 shown paragraphs and 512 words per paragraph are compared; a paragraph longer than 512 words is never treated as a repeat (neither as shown nor as new text), because its tail is not compared. After dropped paragraphs the guard is a pure filter: the text that is sent is the leg's text with whole repeated paragraphs removed, each together with the separator (blank line) that stood before it, and nothing else. No byte is inserted, moved or altered, so no join is created: when a repeat is removed the following paragraph keeps its own separator, and a separator that follows the last paragraph of the leg is kept. Leading blank lines of the leg stay in front of the first paragraph that is kept. One exception, also only a removal: when the leg's leading paragraphs were dropped and the text the client already has ends in a blank line (for example the blank line the gateway puts between a tool round and the next leg), the blank lines in front of the first kept text are removed too, so a drop never leaves two blank lines in a row. Indentation on the first kept line is kept. This applies only when the shown text ends in a blank line; a blank line followed by dangling spaces, tabs or carriage returns does not count (the line break in front of the kept text stays).

  • Code-fence markers stop the comparison. A marker is a run of three or more identical characters, all ` or all ~, at any position (also mid-line, in a longer run such as a row of four backticks (````), or split across stream deltas or legs). In a re-driven leg the guard judges only the complete paragraphs that end before the leg's first marker; from that marker on, everything is sent unjudged, byte for byte. A leg is not compared at all once the turn already showed a marker in an earlier leg. Comparing stops for good at the first marker or at the first unit (separator, paragraph and the separator after it) larger than 4096 bytes, whichever comes first; nothing later in that leg is judged, however the text was split into stream chunks. The guard never removes or alters a byte at or after the first marker of a leg, nor any byte of a leg whose record already had a marker. Consequence: a repeated code block, and prose after it, may appear twice. A last paragraph that ends in a one- or two-character run of ` or ~ at the end of a leg is released unjudged. The last paragraph of a leg that stopped at the length cap is released unjudged too, and comparing stops there: it is cut, not complete, and the continuation may turn it into a different paragraph.

  • What is never dropped. New content, short paragraphs (under 3 words), a paragraph that is only a markdown heading line, text with a different vocabulary, and text that runs past 4096 bytes without a paragraph boundary (it passes through unjudged, and so does everything after it in that leg). The cross-language case is not detected: a restart in another language than the shown text is kept. Text shown before a tool-approval (human-in-the-loop) pause is not compared either: a resumed turn is a new request.
  • After a tool round (leading repeats only). The first leg after every tool round that streams model text is guarded too, even if the turn was never re-driven: some models re-narrate the same plan paragraphs before their answer on each leg of a tool turn. (A leg that failed before its first text byte does not count, so a retried leg is still guarded.) On that leg only a paragraph at the start of the leg is dropped, and only when its text is identical to a paragraph already shown (at least 3 words): runs of whitespace count as one space and * emphasis markers are ignored, everything else counts, including upper/lower case, digits, signs, operators and decimal separators. So a restatement that changes a value ("-5" to "5", "a < b" to "a > b", "1,376" to "1.376") is shown; no fuzzy matching is applied. Comparing stops at the first paragraph that is kept, so later paragraphs, a length-cap continuation leg and text after the first kept paragraph are never touched. A turn without a tool round is byte-identical to before. Cost: until its first paragraph is complete (its blank line arrives) that leg's text is held, so a first paragraph without a blank line (a long table or list) reaches the client only when it ends or after 4096 bytes, when the guard releases it unjudged; from then on the leg streams token by token as before.
  • Claim checks read the dropped text. The file-claim and image-claim checks judge what the model said on the leg, shown text plus the text the guard dropped, so a claim that the guard removed as a repeat is still seen by the check. The shown stream and the saved message are unchanged by this.
  • A leg that is dropped entirely counts as visible text: no empty-response fallback or apology is added and it is not tool progress (so it does not re-license a steer or re-dial). Tool calls on the leg run as usual. For the length-cap auto-continue the model's progress is what it produced on the leg, shown text plus dropped text, so a leg cut at the length cap while it was restating shown paragraphs is still continued (with the usual limits).
  • Observability. A restart_dedup trace step (dropped, dropped_chars) and a NOTICE log line when anything was dropped; the text itself is never logged. A degenerate-output check (paragraph_loop, observability only) flags an answer in which one paragraph of at least 8 words occurs 3 or more times and at least twice directly after the same preceding paragraph (a back-to-back copy counts as following itself; headings and short lines are never counted but still serve as the preceding paragraph). A status line that a report template reuses under different headings is therefore not flagged. Known residuals: a blockquote question repeated before the same template is still flagged, because the quote is blanked before the check; a template that repeats the same sub-heading (for example ### Bewertung in a per-server report) before the same status line 3 or more times is still flagged, because the shared sub-heading is the same preceding paragraph each time. It never changes the reply.

Errors

Inference errors use a structured JSON envelope and set the X-AIG-Error response header to the error code:

{
  "error": {
    "code": "invalid_request",
    "message": "Human-readable detail about what went wrong"
  }
}

A stream: false request that is cut off mid-answer gets the typed error status (with X-AIG-Error = the code), never a 200 with the partial. Should a 2xx ever carry X-AIG-Error, treat it as a failed, interrupted run — see Interrupted answers.

Branch logic on the stable code, never on the human-readable message. The full list of codes (HTTP status, cause, and the rate_limited / quota_exceeded / guardrail_blocked specifics) is in Error codes.

An error raised after the stream has already opened

On a gateway with a PII detector, a streaming turn's response is committed early — the gateway emits a {"aig_status":"scanning_pii"} progress event before it starts scanning, so the client sees HTTP 200 and Content-Type: text/event-stream immediately.

If the request is refused after that point but before the model is called, a fresh HTTP status is no longer possible. The gateway therefore delivers the error over the open stream and ends it normally:

data: {"aig_status":"scanning_pii"}

data: {"aig_status":"provider_error","error_class":"forbidden","message":"…","user_message":{"body":"…"}}

data: [DONE]

So on a PII gateway a refusal that would otherwise be 403/413 arrives as HTTP 200 plus a terminal provider_error frame. Clients must treat a provider_error event as an error regardless of the HTTP status; error_class carries the same stable code the JSON envelope would have used.

The response status is not the whole story for such a turn, so the gateway records the logical outcome separately: the request log's status column carries the real typed status (e.g. 403), not the 200 seen on the wire, and meta.aig_stream_error holds the error code. Previously nothing was recorded at all and these turns were indistinguishable from successful ones.


Running a non-streamed request in the background (Prefer: respond-async)

A request that waits for its whole answer (stream absent or false) is cut by the gateway's time budget: 360 s of waiting for a tool-using turn. If you send Prefer: respond-async (RFC 7240), the gateway accepts the request at once and keeps working on it after your connection is gone. The turn then gets up to 900 s (15 minutes), and you read the result later.

POST /v1/{tenant}/{gateway}/compat/chat/completions
Authorization: Bearer <API key>
Content-Type: application/json
Prefer: respond-async

{ "model": "...", "messages": [ ... ] }

The same header works on POST /v1/{tenant}/{gateway}/anthropic/v1/messages and on an agent invoke, POST /v1/{tenant}/{gateway}/agents/{slug}/invoke (see Running an invoke in the background). The answer is 202:

Header Meaning
Location: /v1/{tenant}/{gateway}/async/{id} Where the result will be. Poll this URL with the same API key.
Preference-Applied: respond-async The preference was honoured.
Retry-After: 5 Seconds to wait before the first poll.
Cache-Control: no-store Do not cache.
Connection: close The connection ends after the answer.

Read the result with Fetching an asynchronous result: 202 while it is being processed, then the stored final response (the original status, body, content type, x-should-retry and x-aig-* headers). A failed turn is a stored failure with its own status, not a 202. Keep the Location, poll it, and do not send the request again: a second POST starts a second turn, which is billed and logged as its own request. The turn is logged as one request.

When the header is honoured. The request must be a non-streamed POST (stream absent, null or false; any other method answers synchronously) to one of the routes above, carry a JSON object body, and be made with a gateway API key. Only gateway API keys create asynchronous results. Web-app session tokens, device sign-in tokens and MCP OAuth tokens are answered synchronously, as is a key that expires within about 21 minutes (it could not read its result for the full wait), and a request to a gateway that requires no API key. If any of this does not hold, the header is ignored and the request is answered synchronously with the normal 360 s budget. A Prefer header with other preferences (for example wait=5) is also ignored. A streamed request (stream: true) is never accepted this way. A held agent run can finish with a stored 202 that has no Retry-After header: that is the finished response (held for review), whereas a run still being processed answers 202 with Retry-After.

A malformed Prefer header. On a request that would otherwise be accepted, a Prefer header the gateway cannot parse (for example respond-async=1, respond_async, an unterminated quoted string, a list with no preference at all such as ,,, or a value over 1 KiB) is refused with 400 invalid_prefer_header; the request is not run. Fix the header; there is no silent fallback.

Connection handling. A request carrying any Prefer header is answered with Connection: close, also when it is not accepted as asynchronous. Do not reuse the connection. A client that is behind a proxy or CDN that cuts long requests needs nothing else: the cut does not affect the turn.

A browser page can send the header across origins: Prefer is allowed on the preflight, and Location and Preference-Applied are readable.


Fetching an asynchronous result

GET /v1/{tenant}/{gateway}/async/{id}
Authorization: Bearer <the API key that made the request>

This is the result resource of an asynchronous request. {id} is the 32-character lowercase hexadecimal id returned when the request was accepted (see Running a non-streamed request in the background).

Who may read it. Only the API key that made the request. Another key of the same workspace and gateway receives 404 async_result_not_found, exactly as for an id that does not exist, so the answer never reveals whether an id is real. A key of another gateway or workspace, or a missing or invalid key, is refused by authentication (401) before the id is looked at. Results belong to the API key: when the key is revoked or deleted its results are deleted with it, an expired key can no longer read them, and web-app session tokens, device sign-in tokens and MCP OAuth tokens cannot own results (a request with one of them is answered synchronously). A key that expires within about 21 minutes is answered synchronously too. A gateway that does not require an API key answers 403 async_auth_required.

What you get back.

Situation Answer
Still being processed 202 with Retry-After: 5. Poll again after that many seconds.
Finished The stored final response: the original status code, body, content type, x-should-retry and x-aig-* response headers. An interrupted agent answer keeps x-should-retry: false (do not retry it); Retry-After is not stored.
Accepted but never finished, and its processing window has passed 500 async_result_lost. Submit the request again.
Unknown, expired, or owned by another key of the gateway 404 async_result_not_found
Missing or invalid API key, or a key of another gateway or workspace 401
{id} is not exactly 32 lowercase hex characters 400 invalid_async_id
OPTIONS Answered as the CORS preflight (204)
Any other method than GET 405 with Allow: GET

Every answer from the gateway carries Cache-Control: no-store (a request that is rejected as malformed HTTP before it reaches the gateway, for example one with a NUL byte in the path, gets a plain 400 without it). The poll accepts no request body (anything over 1 KiB is refused with 413). A result is kept for 24 hours after the request was accepted, then removed.

The poll can itself be rate limited (429 rate_limited). Its x-request-id identifies the poll, not the original request.


See also