Commit Graph
137 Commits
Author SHA1 Message Date
Paweł Banaszewski a3f25a491e feat: forward bridged routes in AI Gateway proxy mode (#30226)
Enable bridged request forwarding in AI Gateway proxy mode. Responses
are captured through `TeeBuffer`.
Proxies are created per-request reusing transports.

Handle `http.ErrAbortHandler` inside the circuit-breaker wrapper so
aborted responses are classified by HTTP status before the panic is
propagated.

Generated by Coder Agents on behalf of @pawbana.
2026-11-17 18:02:24 +00:00
Roo Thorp 0b5083440f fix(aibridge): correlate Responses API tool results followed by developer messages (#32053)
When a user approves a command with "Yes, and don't ask again", a
developer message is appended after the tool result.
`correlatingToolCallID` only checked the last `input` item, so these
requests weren't correlated and the session page split the agentic loop
into a new thread with no prompt.

`correlatingToolCallID` now walks back from the end of `input`, and
skips developer/system messages and reasoning items. The request is
correlated if the first remaining item is a tool result with a
`call_id`. A user message or any other item means a new turn, so it
isn't correlated.

Fixes AIGOV-727

Generated by Coder Agents on behalf of @roothorp
2026-11-17 11:48:52 +00:00
Paweł Banaszewski ff3de6e666 feat(aibridge/x/proxy): integrate key-pool failover (#30400)
Route centralized provider requests through the existing key-pool
failover transport. Retries replay a consumed request prefix and
continue the still-open source, discard rejected attempt responses, and
preserve client bytes and headers. BYOK requests do not fall back to
pooled credentials.

Generated by Coder Agents on behalf of @pawbana.
2026-11-13 11:33:20 +00:00
Paweł Banaszewski 44bd84cf9e feat: add per-request reverse proxy for bridged routes (#30399)
Prepare `forwardingHandler` to forward bridged requests to the provider.
Nothing calls it yet.
2026-11-13 10:42:45 +00:00
Ethan 5cbf086517 feat: send tool result media to providers like user files (#31383)
Part of [CODAGT-1430](https://linear.app/codercom/issue/CODAGT-1430).
This is the first of four stacked PRs.

Today a PDF in an MCP tool result reaches no provider. On Anthropic we
strip it in chatd. On OpenAI Chat Completions fantasy swaps it for a
"cannot be displayed" note, and on Responses it sends a placeholder that
points at a user message it never sends.

coder/fantasy#73 and coder/fantasy#74 make fantasy convert tool result
media with the converter it already uses for user files: an Anthropic
document inside `tool_result`, an `input_file` inside
`function_call_output` on Responses, and a user file part straight after
the tool message on Chat Completions. Both have merged, and this PR pins
`charm.land/fantasy` to the coder_2_33 tip that has them. Chat
Completions file parts now refuse text files, as Responses already did,
so `AcceptsFilePartMediaType` follows.

The converters take a filename, so an MCP embedded resource blob is now
named after the last element of its URI path, and we store the name with
the tool result so later turns send the same one. OpenAI picks the file
type from the extension, so we append the right one when it's missing or
wrong. We drop names with control characters, as Postgres `jsonb`
rejects NUL, and we redact the name like the rest of the tool response,
since a URI like `https://host/sse/<token>` would otherwise put the
token in the chat history.

There's also a test proving aibridge's Chat Completions re-encode keeps
a user file part, as that's where these PDFs end up.

Anthropic still strips tool result PDFs until the next PR in the stack.
2026-11-11 00:06:40 +11:00
Paweł Banaszewski d430a6254f feat(aibridge/x/proxy): capture HTTP bodies for replay (#30398)
Adds HTTP body capture under `aibridge/x/proxy/replaybody`. `NewRequest`
and `NewResponse` replace the original body with an `io.ReadCloser` that
retains read bytes in the returned `TeeBuffer`.
Request retries replay the retained bytes through `r.GetBody()`.
`TeeBuffer.Wait` returns buffered bytes without reading the original
source.

Enables full duplex so Go’s HTTP/1 server can send an early upstream
response without first draining the client’s unfinished upload.

Generated by Coder Agents on behalf of @pawbana.
2026-11-09 14:05:00 +01:00
Ethan ff40ec6900 fix: pick the Anthropic computer use tool version from the model on every platform (#31657)
#31521 made computer use send `computer_toolset_20260801` to Claude 4.8
and later, but swapped it back to `computer_20251124` on Claude Platform
on AWS and Bedrock, since Anthropic's docs say neither offers the
toolset. That's wrong for Claude Platform on AWS, so computer use on
dogfood's Opus 5.5 fails with `'claude-opus-5-5' does not support tool
types: computer_20251124`.

I probed the AI gateway, and Claude Platform on AWS accepts exactly the
versions the Claude API does, e.g. the toolset for Opus 4.8 and 5.5, and
`computer_20251124` for Opus 4.6. The harnesses that get this right
(Anthropic's computer-use demo and SDK toolset helpers, the Vercel AI
SDK, LiteLLM) pick the version from the model ID alone and leave the
wire format to the platform client, so we'll do the same and drop the
override. fantasy's doc comment repeated the docs, which
coder/fantasy#83 fixed, so this bumps fantasy too.

Bedrock follows the same model table. AWS's Opus 4.8 model card only
lists `computer_20251124`, but it's just behind: Anthropic's Bedrock
docs list Opus 4.8 as taking the toolset with no beta header, and
`anthropic.claude-opus-4-8` on Bedrock (via Mantle in us-east-1)
returned a `screenshot` tool call for the toolset with no beta.
Dogfood's InvokeModel route, which runs Opus 5.5, does the same.

Bedrock was also broken on `main`, since aibridge's Bedrock beta
allowlist drops `computer-use-2025-11-24`, so `computer_20251124` never
got through validation. I've added it. On InvokeModel, Opus 4.7 returned
a `computer` tool call for `computer_20251124` once the flag reached
Bedrock, but a 400 when the flag went through dogfood's gateway, which
runs `main` and drops it. Unlike the effort and context management
flags, the flag doesn't need gating per model, as Bedrock accepts it on
models that don't support `computer_20251124`. On Bedrock InvokeModel in
us-east-2, Haiku 4.5 returned a 200 with the flag on its own and with
`computer-use-2025-01-24` and a `computer_20250124` tool, whilst a
made-up flag got a 400. Bedrock only rejects the tool type itself, and
the model table never sends `computer_20251124` to Haiku 4.5 anyway.

InvokeModel does still run the provider's `settings.model` rather than
the model the chat config names, so the version can disagree with what
actually runs if the two differ. That's the known model swap in #29511,
and it's no worse here, as `main` picked the version from the model
config too. The documented setup is one provider per model, so the two
match, and the native `bedrock-runtime` protocol will remove the swap.

I verified Claude Platform on AWS end to end, running Coder Agents from
this branch against dogfood's AWS gateway route. Computer use on Opus
5.5 and Sonnet 5.5 sent the toolset and got a 200 on every request,
across multi-step turns, an interrupted turn, a page reload, and a chat
that switched to Opus 4.6 (which sent `computer_20251124`) and back. The
same setup on `main` reproduced the 400.

I also ran the same scenarios against dogfood's Bedrock InvokeModel
route. Opus 5.5 and Haiku 5.5 got a 200 on every computer use request,
with up to 22 screenshots in the history, including a chat that switched
to Opus 4.6 on Claude Platform on AWS and back. That went through
dogfood's gateway, so it covers what Bedrock accepts from Coder Agents,
but not a Bedrock provider configured in Coder itself, which I still
haven't run end to end.
2026-11-03 16:52:56 +11:00
Sas Swart 15365c69cf feat: use the resolved organization for AI Gateway budgets and cost (1/2) (#31120)
`IsAuthorized` resolves the workspace organization, but uses it only to
reject requests; nothing downstream reads it. The budget check and cost
each resolve the group site-wide, so a user working in an org B
workspace can be billed in org A, and no interception records its
organization.

Resolve the request organization once, in `IsAuthorized`. A workspace
session token resolves to the workspace's organization (source
`workspace`). Any other request, including chatd requests until
AIGOV-713, resolves to the organization of the user's site-wide
effective group (source `effective_group`). Return the source in
`IsAuthorizedResponse`.

Have aibridged pass the organization to `IsBudgetExceeded`, which
resolves the budget inside it, and stamp the organization and source on
`RecordInterception`. Resolve cost's effective group inside the
organization stored on the interception. When there is no organization,
behave site-wide as before.

Move `resolveOrganization` and the workspace checks into
`orgresolver.go`, and leave a slot for the chat organization
(AIGOV-713). Bump the aibridged API to v1.6, adding
`IsAuthorizedResponse.organization_source` and
`IsBudgetExceededRequest.organization_id`.

aibridged checks only the shape of the organization (both fields or
neither, and a valid non-nil UUID), not the source value. That lets a
newer coderd add a source without breaking older gateways.

Behaviour changes to review:

- Spend follows the workspace's organization. A user whose budgets are
all in org A has no limit in an org B workspace if B has none.
- A database error while resolving the organization now returns 403 from
`IsAuthorized`, instead of 500 from `IsBudgetExceeded`.
- Requests without a workspace make up to three extra budget queries in
`IsAuthorized`.
- The user spend status endpoint (`GET /api/v2/users/{user}/ai/spend`)
stays site-wide, so it can disagree with where a request was charged.

The org-aware price lookup follows in #31121.

Part of AIGOV-716. Stacked on #31119.

---

*This PR was generated by Coder Agents on behalf of @SasSwart.*
2026-10-30 13:35:23 +02:00
eric-hughes-coder bb8912dc46 fix: wait for full completion before asserting in tests (#30885)
Fixes the `TestServer_Metrics/Forwarding` flake reported in
[PLAT-609](https://linear.app/codercom/issue/PLAT-609/flake-testserver-metricsforwarding)
and, in addition, other defects similar to it.

## Testing defects

### The Original

`TestServer_Metrics/Forwarding` waited for `batches_dropped_total` and
then asserted on `logs_dropped_total`. The forwarder updates those two
counters separately, on adjacent lines, so a read between them sees the
first updated and the second not. CI caught exactly that window:
expected 2, actual 0 at `proxy_test.go:780`. Each counter is atomic on
its own, so the race detector reports nothing.

### The Additional

The fallacy of the original is a _de facto_ assumption that sequential
updates are atomic as a group. The defect arose from not taking into
account that they are atomic individually. The test asserted before the
work was completed. A repo-wide sweep for related metrics written
together found similar mistakes in other tests:

- Live races: all three phases of `TestServer_Metrics/Forwarding` and
`TestServer_Metrics/BufferFull` in `agent/boundarylogproxy`, and
`TestMetadataBatcher_DropsWhenFull`, which waited for the update channel
to empty although the final flush runs after that.
- Correct only because of the current implementation's ordering:
`TestMetrics_TokenUseCount` in `aibridge`, four tests in
`coderd/agentapi/metadatabatcher`, and `TestAgentStatsSessionCounts` in
`coderd/prometheusmetrics`. These pass today but would start failing if
the code under test reordered its work.

## Fixes

All tests the sweep found were fixed. Each test now waits for every
value it asserts before asserting it. Where a value is already non-zero
from earlier work, or legitimately zero, the wait is for the final value
rather than for a change, and several tests use
`require.EventuallyWithT` so the wait and the assertion are one step.
Two Forwarding phases gain assertions on values they already waited for:
`batches_dropped_total == 1` in phase 1, and the reporter's recorded
request count in phase 2.

Two phases of `TestAgentStatsSessionCounts` assert that the counts did
not change. No wait on an unchanged value can show that the collection
cycle ran, so they keep waiting on the execution histogram, and a
comment at that wait names the dependency.

Each fix was checked by temporarily blocking or reordering the code
under test between the relevant writes: the old test failed on every run
and the new one passed.

## Documentation

As a guard against recurrence of defects of this kind, we add the
following documentation targeted mostly at agents. The material in
`TESTING.md` provides guidance about how to write such a test correctly
in the first place. That in `AGENT_FAILURES.md` describes how to
recognize the symptoms of this class of test failure, should they arise.

- `.claude/docs/TESTING.md`: new section "Wait for Full Completion
before Asserting", covering waits on one value with assertions on
another, Prometheus metrics in particular, and assertions that nothing
changed.
- `.claude/docs/AGENT_FAILURES.md`: a catalog entry for the symptom.
- `coderd/coderdtest/promhelp`: doc comments noting that each helper
call is a separate gather.

Generated with Claude Code under the direction of @eric-hughes-coder.
2026-10-28 09:17:10 -06:00
Danny Kopping e6d24ff30a fix(aibridge/intercept/messages): treat Bedrock Opus 5, Haiku 5.5, Fable 5, and Mythos 5 as adaptive-only (#30692)
Bedrock rejects `thinking.type: "enabled"` with `budget_tokens` for
Claude Opus 5, Haiku 5.5, Fable 5, and Mythos 5 ([AWS adaptive thinking
docs](https://docs.aws.amazon.com/bedrock/latest/userguide/claude-messages-adaptive-thinking.html)).
AI Gateway didn't recognize these models as adaptive-only, so it rewrote
adaptive thinking to the `enabled` shape and stripped
`output_config.effort`. That broke reasoning effort for all of them.

`bedrockModelRequiresAdaptiveThinking` now matches
`anthropic.claude-opus-5` (which also covers Opus 5.5, the same way
`anthropic.claude-sonnet-5` covers Sonnet 5.5),
`anthropic.claude-haiku-5-5`, `anthropic.claude-fable-5`, and
`anthropic.claude-mythos-5` (the last two also cover their 5.1
releases). Mythos Preview accepts both thinking modes, so it isn't
matched.

Each model group has two commits: the first adds test cases that pin the
current broken behavior, and the second applies the fix and flips the
test expectations, so the behavior change shows up in the test diff.

Fixes AIGOV-704

<details>
<summary>Decision log</summary>

- This is the same class of bug as #25335 (Opus 4.7), #26691 (Opus 4.8),
#27339 (Sonnet 5) and #29762 (Opus 5.5). Each time, a new model was
missing from the substring allowlist. This PR follows the same minimal
pattern. Moving capability detection into the model catalog is left as a
follow-up.
- Chatd's `anthropicReasoningEffort` maps effort `none` to `low` only
for Opus 5.5 and Sonnet 5.5, and is intentionally unchanged. Per the
Anthropic and AWS docs, Opus 5 and Haiku 5.5 still accept `thinking:
{type: "disabled"}` at effort `high` or below, so sending `none` (which
becomes `disabled`) is valid for them.
- Adaptive-only models also get `output_config.format` stripped. That
matches the docs: structured outputs aren't available for Haiku 5.5 on
Bedrock.

</details>

> [!NOTE]
> Generated by Coder Agents on behalf of @dannykopping.
2026-10-14 12:25:30 +02:00
Danny Kopping 71e8e526fa fix(aibridge): correlate Codex custom tool results to their AI Gateway thread (#30667)
Codex sends the results of custom (freeform) tools such as `apply_patch`
back as `custom_tool_call_output` input items.
`RequestPayload.correlatingToolCallID` only matched
`function_call_output`, so these follow-up interceptions had no
correlating tool call ID. They were not linked to the interception that
issued the tool call, which left blank AI Gateway sessions.

[Example
session](https://dogfood.cdr.dev/ai-gateway/sessions/01a1184a-08a4-7d50-8e15-a12368302a2f)

<img width="996" height="576" alt="image"
src="https://github.com/user-attachments/assets/5bce6035-963b-4438-897b-bee36ead5a47"
/>

`custom_tool_call_output` is now handled the same way as
`function_call_output`. The earlier `custom_tool_call` is already
recorded as a tool usage with its `call_id`, and
`GetAIBridgeInterceptionLineageByToolCallID` does not check the tool
type, so lineage now resolves without any other change.

Fixes AIGOV-707

<details>
<summary>Implementation notes</summary>

- **Reproduction first:** the first commit adds blocking and streaming
`custom_tool_result.txtar` fixtures. Each one is a follow-up turn that
replays a `custom_tool_call` and ends with its
`custom_tool_call_output`. `TestResponsesOutputMatchesUpstream` now
checks `CorrelatingToolCallID` on every case, and
`TestCorrelatingToolCallID` gains a `custom_tool_call_output` case plus
a case where the last item is the tool call itself rather than its
result. On that commit, both fixture cases and the unit case fail with
`nil` instead of the custom tool's call ID. The second commit makes them
pass.
- **Out of scope:** other client-executed result types
(`computer_call_output`, `shell_call_output`, `apply_patch_call_output`,
`local_shell_call_output`) are not correlated either. Codex's
`apply_patch` arrives as a custom tool, so it is covered here. Those
other types were left out to keep this change tied to the reported bug.

</details>

> Generated by Coder Agents on behalf of @dannykopping.
2026-10-13 13:36:04 +02:00
Michael Suchacz 7517301ffa chore: add golangci new-code quality gates (#30622)
Stack context: second layer of the Go lint gate stack, built on the
exclusion fix below.

Why: adds commented-out code detection and a `log/slog` ban to the main
config, plus a new-code-only pass requiring reasons on lint
suppressions, flagging ignored errors (including `_, _ = w.Write(...)`),
and banning `time.Sleep` in tests. Fixing the hits surfaced a real bug:
GitLab warnings went to the wrong logger. The new-code pass resolves
symlinked checkout paths so it does not silently report nothing.

Validation: both configs report 0 issues; each seeded violation is
caught; `make pre-commit` passed.

> Xum acted for Mike to open this PR.
2026-10-13 07:57:56 +00:00
Sas Swart a4b68acf9e test: make Responses streaming test handle CRLF SSE boundaries (#30352)
Update `TestResponsesStreamingRelaysWithoutInjectedTools` in
`aibridge/internal/integrationtest/responses_internal_test.go` to split
the fixture stream on SSE event boundaries in a line-ending-independent
way, while preserving the original `fix.Streaming()` bytes for the final
relay equality assertion. Include regression coverage or test setup that
exercises CRLF-normalized fixture bytes, and verify the targeted
integration test passes.

Added `aibridge/fixtures/** text eol=lf` to `.gitattributes`

Fixes AIGOV-675
2026-10-08 11:27:47 +02:00
Paweł Banaszewski f08bfddfa7 feat: validate AI Gateway actor and credentials in proxy mode (#30225)
Extends the AI Gateway `forwardingHandler` with actor check, provider
credential resolution, and initial interception metadata.
Missing provider credentials return 403
Credential resolution failures return 500 with details kept in logs.
AWS-signed bridged credentials remain unsupported.

Generated by Coder Agents on behalf of @pawbana.
2026-10-07 16:51:19 +00:00
Paweł Banaszewski 7cfc38d0e7 feat: wire AI Gateway proxy routing and recorder dependencies (#29725)
Adds `forwardingHandler` for "bridged" routes in proxy mode. Wires
provider snapshots to a shared mux and recorder, tracing, circuit
breakers, and the server-owned inflight gate.

Generated by Coder Agents on behalf of @pawbana.
2026-10-05 17:33:07 +00:00
Paweł Banaszewski 63d9b6b38f refactor(aibridge): export passthrough handler (#30283)
Exports the existing AI Bridge passthrough handler as
`NewPassthroughHandler`.

Generated by Coder Agents on behalf of @pawbana.
2026-10-05 14:54:35 +00:00
Paweł Banaszewski ffc7dadfe2 refactor: use typed AI Gateway actor identity (#30258)
Adds typed AI Gateway actor identity, including the API key ID used by
recording.

Recorders now read the authenticated API key ID from each call context
instead of capturing request identity at construction time. This allows
one recorder to be reused safely across sequential and concurrent
requests. Includes context helper coverage and recorder regression
tests.

Generated by Coder Agents on behalf of @pawbana.
2026-10-05 14:00:15 +00:00
Sas Swart bf3db74b83 fix: reject encoded path traversal in ai gateway before forwarding upstream (#30178)
AI Gateway passthrough forwards the client's escaped path upstream
unchanged. `http.ServeMux` only cleans literal dot segments, so a
percent-encoded dot segment (for example
`/openai/v1/models/%2e%2e/files`) matched an allowlisted passthrough
route here, while the upstream decoded it and served a different
endpoint with the centralized key attached.

This adds `xurl.ContainsEncodedPath` in `coderd/util/xurl` so other
forwarding code can reuse it. It is applied at the gateway entrypoint
(`NewRequestBridge`, via `routing.RejectInvalidForwardPath`) and in the
experimental `x/proxy.Router`, before routing. Requests get a 400
`invalid request path` if any path segment, after decoding once:

- contains a `.` or `..` element, including behind an escaped `/` or
`\`,
- still contains `%`, which only arises from multiple encoding,
- contains control characters.

Escaped separators in ordinary segments such as `/models/org%2Fmodel`
keep forwarding unchanged.

Fixes AIGOV-678

<details>
<summary>Decisions</summary>

- **Validate once at the entrypoint instead of per handler.** One check
covers every provider and route, including the reverse-proxy handler
that will mount behind `x/proxy.Router`.
- **Shared helper in `coderd/util/xurl`.** Per review, the check is a
generic `func ContainsEncodedPath(*url.URL) bool` so other proxies can
reuse a single implementation.
- **Reject rather than normalize.** Legitimate clients have no reason to
send dot segments to these APIs, and rejecting avoids authorizing a path
the upstream interprets differently.
- **Decode exactly once, and reject leftover `%`.** One decode matches
RFC 3986 section 2.4. Rejecting a remaining `%` means further decoding
by any downstream component cannot produce a dot segment.
- **Split decoded segments on `/` and `\`.** Guards against components
that decode reserved characters. `org%2Fmodel` still passes.
- **Literal `..` now returns 400** instead of the ServeMux 307 redirect,
because the check runs before the mux.
- **Out of scope:** tightening passthrough route patterns and key-pool
hardening. Both are separate follow-ups.

</details>

---

_Generated by Coder Agents on behalf of @SasSwart._
2026-10-05 12:15:42 +00:00
Michael Suchacz bb9f31d94b fix: apply Anthropic prompt caching through OpenRouter and OpenAI-compatible gateways (#29563)
Anthropic models configured through an `openrouter` provider (and, by
the same code path, `vercel` and generic `openai-compat` providers)
never got prompt caching. Two independent gaps: chatd only emitted
`cache_control` breakpoints when the fantasy client was `anthropic`, and
even when a client sent them, the AI Gateway chat-completions
interceptor rebuilt the upstream body from typed
`openai.ChatCompletionNewParams` and silently dropped the unknown key.
Dogfood UAT on main @ 77479408b4 measured 0 cached tokens on 27/27 turns
for `anthropic/claude-haiku-4.5` via OpenRouter while the direct
Anthropic provider cached 7k to 11k tokens per turn.

## Fix

**AI Gateway** (`aibridge/intercept/chatcompletions`):
`ChatCompletionNewParamsWrapper` records every message-level and
content-part-level `cache_control` from the raw request and re-applies
it at the same JSON path when the upstream body is rebuilt, before the
Google-specific patching. The blocking path now sends the raw body
whenever preserved fields exist; the streaming path already sent the
rebuilt body. Nothing is added unless the client sent it, and at most
four markers are recorded per request (Anthropic's breakpoint limit) so
the per-marker body rewrites stay bounded.

**chatd** (`coderd/x/chatd`): the caching gate becomes a small strategy
resolver keyed on the fantasy client and the model ID. `anthropic` keeps
the existing message-level breakpoints; `openrouter` and `vercel` reuse
them for Anthropic-family IDs since both clients translate them;
`openai-compat` gets content-part-level `ContentExtraFields` markers
(last text part of the last system message plus the final two
text-bearing user or assistant messages, tool messages skipped, at most
3 markers). `chatprovider.IsAnthropicFamilyModelID` recognizes
`anthropic/...`, Bedrock-style `anthropic.`/`.anthropic.` IDs, and bare
`claude` IDs. The `claude` substring match is deliberately broad; a
non-Anthropic model whose ID contains it would receive markers that
OpenAI-compatible upstreams ignore.

Docs: a short "Prompt caching" note in `docs/ai-coder/agents/models.md`.
`coderd/x/chatd/ARCHITECTURE.md` has no caching text to update.

## Dogfood UAT

Remote Coder Agents UAT on dogfood (chat:
https://dogfood.cdr.dev/agents/9f81cc40-add0-4b6f-b76c-f348b04762e4),
OpenRouter provider with real keys:

- Baseline (main @ `77479408b4`): 0 cached tokens on every OpenRouter
Haiku turn; direct Anthropic control cached normally; a hand-added
`cache_control` on the same key cached fine.
- Fix (`1d685f7e3e`, the first three commits):
`anthropic/claude-haiku-4.5` via OpenRouter now sends 2 markers on turn
1 and 3 afterwards (system last part plus the last two text-bearing
messages, never on tool messages). OpenRouter's `/generation` ground
truth reported `native_tokens_cached` 7137 to 7255 on turns 2+, equal to
Coder's `cache_read_tokens` and the AI Gateway's
`cache_read_input_tokens` on all 43 measured rows. Turn-2 prompt cost
dropped about 8x versus baseline. Agentic S3 cache reads grew from 7156
to 13993 as a 2500-line file entered the prompt. `openai/gpt-5-mini`,
`google/gemini-2.5-flash`, `deepseek/deepseek-chat-v3.1`, and
`moonshotai/kimi-k2.5` received 0 markers with unchanged request shapes;
the direct Anthropic control was unchanged. 76 upstream attempts, 0
non-200. The remote agent reported FAIL only because one acceptance
criterion I wrote asked the chat usage indicator to display cached
tokens, which the UI has never done for any provider; the runner
endorsed PASS for the fix itsel... [truncated]
- Smoke re-tests on `20ad259999b` (marker-code simplification) and on
`e31f1806748` (docs reflow plus the four-marker cap; the later head
`92b8f8ad0b8` only renames `google_openai_compat.go` to
`request_body.go` with no content change): S1 cache reads 0 / 7139 /
7161 / 7184 / 7207 equal to OpenRouter ground truth on every row,
markers 2 then 3 and never on tool messages, tool-heavy turn all 200, a
12 KB file read grew cache reads to 13548 with every request body
inspected for marker placement, `openai/gpt-5-mini` still 0 markers.

Known follow-ups surfaced by the UAT and out of scope here:
`provider_options.openrouter.*` never reach the wire on the gateway
path; OpenRouter cache writes are folded into `input_tokens` in chat
message usage (`cache_creation_tokens` stays 0) although the gateway
records them; the AI Gateway sessions UI has no cache columns and labels
every OpenAI-compatible provider "OpenAI"; attachment-only messages (no
text) fail upstream with HTTP 400 on OpenRouter (pre-existing,
reproduced without markers).

> Xum acted on behalf of @ibetitsmike for this pull request.
2026-10-04 22:55:37 +02:00
Michael Suchacz d203439495 fix(aibridge): relay streams when accumulation fails (#30119)
AI Bridge failed any Anthropic Messages stream whose events the SDK
accumulator rejected. The common case is a response that stops at
`max_tokens` inside a `tool_use` block: the tool input JSON is
truncated, the pinned SDK's `Accumulate` fails when it marshals that
input on `content_block_stop` or `message_stop`, and the interceptor
stopped relaying and sent the client an SSE `error` (`processing error:
accumulate event: ...`). The client lost the rest of the response,
including the `max_tokens` stop reason it needed to recover. Coder
Agents treats that error as non-retryable, so the chat ended in an error
state.

Relaying does not depend on a successful accumulate; only injected MCP
tools execute the accumulated input. This PR:

- Logs the first accumulate error in each iteration and keeps relaying
events.
- Clears pending injected tool calls when a `message_delta` carries a
stop reason other than `tool_use` (for example `max_tokens`), so AI
Bridge never runs an MCP tool on truncated input or sends that input
back upstream. An interim `message_delta` without a stop reason keeps
them.
- Still fails the stream when accumulation failed and injected tool
calls are pending at `message_stop`: their accumulated input cannot be
trusted, and the client never saw those calls.
- Also fails the stream when accumulation failed and the upstream closes
before `message_stop`, so the client still gets a terminal event. A
client cancel is not reported as an accumulation failure.
- Records tool usage from `block.Input`, as a string when it is not
valid JSON. After a failed accumulate, `variant.Input` holds the stale
`{}` from `content_block_start`.

Other accumulator errors, such as `invalid character '}'`, are handled
the same way.

Related: #30120 makes chatd answer the cut-off call with a tool error
that tells the model to split its input.

Follow-up, out of scope: upgrading `anthropic-sdk-go` from the pinned
v1.19.0 fork. A probe upgrade to v1.76.0 fails two existing tests
(injected-tool content block indices and the Bedrock eventstream path).

## Testing

- `TestAnthropicMessages/streaming builtin tool truncated by
max_tokens`, with and without `content_block_stop`: the client receives
every event in order through `message_stop` with no `error` event, the
interception ends without an error, and the tool usage is recorded with
the truncated input.
- `TestAnthropicMessages/streaming injected tool with invalid input`:
with `stop_reason: max_tokens` the client receives the stop reason and
`message_stop`, the MCP tool is never called, and AI Bridge makes one
upstream request. With `stop_reason: tool_use`, or when the upstream
closes before `message_stop`, the stream ends with an `accumulate event`
error instead of calling the tool.
- `TestAnthropicMessages/streaming injected tool with interim
message_delta`: a `message_delta` with a null stop reason before the
`tool_use` delta still runs the MCP tool.
- Red-green: with `streaming.go` restored to the base code, the three
truncation cases fail. The `tool_use` case passes on the base code by
design, since the old code failed every such stream; removing the new
`message_stop` guard makes the MCP tool run with the stale `{}` input.
- `go test ./aibridge/... -count=1` and `golangci-lint run
./aibridge/...` pass. Local pre-push checks were skipped per standing
preference; PR CI covers them.
- Remote UAT: not run yet.

## Review record

- Parent review (Xum) of `383dda920d6`: the remaining `message_stop`
guard had no test. Fixed in `5ea664affbf`.
- Codex round 1 on `5ea664affbf`: 1 P2, a clean upstream close after a
failed accumulate ended the response without a terminal event and
recorded success. Reproduced by the new `upstream closes before
message_stop` case (red on `5ea664affbf`) and fixed in `72bdc10e77b`.
- Codex round 2 on `72bdc10e77b`: 1 P1 and 1 P2. P1: an interim
`message_delta` without a stop reason cleared pending injected tools;
reproduced by the new interim delta case (red on `72bdc10e77b`) and
fixed in `73a7ba2a9a8`. P2: a client cancel after a failed accumulate
was promoted to a server error; confirmed by code trace (no
deterministic test for a cancel between `Next` and `Send`) and fixed in
`73a7ba2a9a8` by promoting only where the upstream stream ends.
- Codex round 3 on `73a7ba2a9a8`: no findings.

> Xum, an AI coding agent, prepared this PR on behalf of @ibetitsmike.
2026-09-30 12:33:58 +00:00
Cian Johnston fc861975bf refactor(aibridge): expose provider credentials and invocation models (#29886)
Expose provider credential resolution and request model accessors for
later Gateway authorization work. Preserve interceptor constructor
signatures, credential resolution ordering, error precedence, and
request forwarding. Bedrock accessors distinguish the configured
invocation target from the billing model.

Independent, behavior-preserving extraction from #29846. This does not
add authorization enforcement or new permissions.

Verified locally: `make pre-commit` and `go test ./aibridge/...` passed,
including the existing integration suite and accessor/credential
regression coverage.

Extracted and verified with AI assistance on behalf of @johnstcn.
2026-09-30 10:02:51 +01:00
Michael Suchacz 1e9dd0abbc feat: add Claude Sonnet 5.5 and GPT-6.1 Sol to Agents and AI Gateway (#30159)
Add Claude Sonnet 5.5 and GPT-6.1 Sol to the Agents known models
catalog, so they appear as suggestions when an admin adds a chat model,
and regenerate the AI Gateway price book from models.dev.

| Model | Added to |
|---|---|
| Claude Sonnet 5.5 | anthropic (`reasoningEffort: high`), azure,
bedrock (`global.anthropic.claude-sonnet-5-5`), openrouter, vercel |
| GPT-6.1 Sol | openai (`reasoningEffort: medium`), azure, openrouter,
vercel |

**Bedrock.** bedrock-runtime serves Sonnet 5.5 only through its global
inference profile, so the catalog curates the `global.` ID without a
bare alias: fantasy's Bedrock client prefixes a bare `anthropic.*` ID
with a regional profile (`us.`, `eu.`, `apac.`) that this model lacks.
bedrock-mantle takes the bare ID and the gateway looks prices up by
exact provider and model, so `overrides.jq` injects the bare ID as a
copy of the global price entry. The two GPT Daybreak alias injections
are gone: models.dev now lists both aliases, and their guards error out
once it does.

**Reasoning effort.** Sonnet 5.5 rejects the `thinking: {"type":
"disabled"}` that fantasy sends for effort `none`, and GPT-6.1 Sol
rejects `none` outright, both with HTTP 400. `applyReasoningEffort` now
maps `none` to `low` for Sonnet 5.5 on the Anthropic and Bedrock
providers, next to the Opus 5.5 clamp, and maps `none` and `minimal` to
`low` for GPT-6.1 Sol on OpenAI and Azure through a new
`chatopenai.IsGPT61Sol`, next to the GPT-6 Astra clamp. GPT-6 Sol
accepts `none` and stays unclamped; the test pins that. AI Gateway's
Bedrock adaptive-thinking allowlist already matched Sonnet 5.5 through
its `anthropic.claude-sonnet-5` substring; a table case now covers it.

**Price book drift.** `prices.json` includes every model of its 8
providers, so the regeneration also brings in upstream changes since the
last refresh: 28 new entries (such as Grok 4.7 on Bedrock and Mistral
Large 2512 on OpenRouter), 7 entries models.dev delisted (mostly free
variants on OpenRouter and Vercel), and 49 price changes (39 OpenRouter,
10 Vercel). Other uncurated upstream models, such as `-pro` and `-fast`
variants and `openai.*` on Bedrock, stay out of the catalog, matching
how earlier releases were curated.

The Reasoning effort section of `coderd/x/chatd/ARCHITECTURE.md`
documents only the GPT-6 Astra clamp and should gain Sonnet 5.5 and
GPT-6.1 Sol. That doc edit is left to a human author.

Validation: regenerating from a fresh models.dev fetch reproduces both
generated files byte for byte. Go tests pass for
`scripts/aibridgepricesgen`, `coderd/aibridge/prices`,
`coderd/x/chatd/chatprovider`, `coderd/x/chatd/chatopenai`, and
`aibridge/intercept/messages`. Removing either clamp with `go test
-overlay` fails the new cases on exactly the Sonnet 5.5 and GPT-6.1 Sol
inputs. Vitest passes for `src/modules/aiModels` (176 tests) and the
Models and Coder Agents settings pages (24 tests). The pre-commit hook
passed; local pre-push checks were skipped, so CI is the first full run.

Review record: no reviews yet. No remote UAT was run; the tested head is
`78abe17e69d`.

> Xum opened this PR on behalf of @ibetitsmike.
2026-09-29 18:46:41 -07:00
Cian Johnston 9fa17a12ef fix: strip client actor headers unconditionally (#30037)
Strip all client-supplied headers matching `IsActorHeader()` in
`PrepareClientHeaders`, regardless of `send_actor_headers`. This
reserves the case-insensitive `X-AI-Bridge-Actor` prefix for identity
injected by the gateway. Remove the redundant deletion of the three
standard actor headers from `BuildUpstreamHeaders`.

Generated with Coder Agents on behalf of @johnstcn.
2026-09-29 20:26:17 +01:00
Cian Johnston 8742d2484c feat: add opt-in AI Gateway actor email headers (#29930)
Add opt-in forwarding of the authenticated Coder account email through
`--ai-gateway-actor-header-meta-email`,
`CODER_AI_GATEWAY_ACTOR_HEADER_META_EMAIL`, or
`ai_gateway.actor_header_meta_email`. The option defaults to empty:
enabling `send_actor_headers` alone does not forward email. Set a
destination header explicitly to opt in; accounts without an email omit
it.

Carry authenticated email through the Gateway authorization response and
strip client-supplied standard/configured email headers before applying
trusted identity. The additive protocol field joins unreleased Gateway
API v1.3 alongside workspace attribution. Includes email configuration
precedence, authorization compatibility, captured upstream request
tests, and matching documentation.

Refs https://linear.app/codercom/issue/AIGOV-601

Generated with Coder Agents on behalf of @johnstcn.
2026-09-29 20:07:49 +01:00
Cian Johnston 05d1fa8a4c feat: configure AI Gateway actor identity headers (#29929)
Allows configuring AI Gateway actor ID and username headers independently through
`--ai-gateway-actor-header-id` and
`--ai-gateway-actor-header-username` or associated environment
variables and YAML settings. 

- Defaults to existing header name, an empty string disables that attribute. 
- Existing `send_actor_headers` gate remains off by default.
- Validates header names, case-insensitive collisions, and protected
destinations for embedded and standalone gateways.
- Strips standard and configured identity destinations before injecting authenticated values.
- Adds coverage for configuration precedence, captured upstream request, and generated help/API documentation.

Refs https://linear.app/codercom/issue/AIGOV-601

Generated with Coder Agents on behalf of @johnstcn.
2026-09-29 18:22:59 +01:00
Susana Ferreira e5a449e172 feat: record provider model on AI Gateway token usage (#30086)
## Description

Record the model reported by the upstream provider on each AI Gateway
token usage and send it to coderd as `provider_model` on
`RecordTokenUsageRequest`. The provider can report a different model
than the one requested (for example, an alias or a dated snapshot), and
pricing only by the requested model leaves those requests unpriced.

This PR only captures and transmits the model. coderd ignores it for
now, and storing it and using it for price lookup will be added upstack.

Related to https://linear.app/codercom/issue/AIGOV-650

## Changes

- Add `ProviderModel` to `recorder.TokenUsageRecord`, set from the
response `model` in the messages, chat completions, and responses
interceptors (blocking and streaming).
- Add `provider_model` to `RecordTokenUsageRequest`, as part of the
unreleased aibridged API v1.3.
- Assert the recorded provider model in the interceptor and integration
tests.

> [!NOTE]
> Generated by Claude Code on behalf of @ssncferreira.
2026-09-29 17:47:27 +01:00
Sas Swart 813b8c151f feat: make AI Gateway content recording optional (#30031)
Add `--ai-gateway-disable-content-recording`, which stops user prompts,
tool
calls and model thoughts from being stored. Cost control reads none of
those
tables, so budgets, spend accounting and enforcement are unaffected.

A dropped record is still logged, so pairing the option with
`--ai-gateway-structured-logging-source=gateway` keeps the SIEM export
for
records that are never persisted. The gateway warns at startup when
content is
dropped while coderd is the only emitter, since those records then reach
neither
the database nor a SIEM.

Covered end to end for the embedded and the standalone gateway, and
documented
alongside cost controls.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 11:48:53 +02:00
Sas Swart 23fb35d185 feat: let the AI Gateway emit the structured interception records (#30030)
coderd emitted the structured interception records as they arrived over
DRPC, so
a record the gateway never sends cannot be exported.

- Add `--ai-gateway-structured-logging-source` (`coderd`, `gateway`,
`both`) and
teach the gateway's `LogRecorder` to emit the same format where the
records
originate. Gateway lines omit `thread_parent_id` and `thread_root_id`,
which
  are resolved by a database lookup only coderd can perform.
- Reaching the serving pool required repairing the pool options: they
were
derived at construction sites and discarded, so the server always built
its
pool with the defaults. They are now derived from the deployment
configuration
in one place and passed to the pool that serves requests. The server
reports
those options, and its ownership of the `key_pool_state` collector, so a
second
  registration cannot silently reappear and panic startup.
- The standalone gateway inherits both structured logging options, since
it is
  now one of the processes that can emit.

This is the keystone of the stack: the flag, the mechanism that carries
it and
the behavior it selects land together, so
`TestAIGatewayStart_InheritedOptions`
and the gateway help output stay truthful at every commit.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 11:48:52 +02:00
Sas Swart 5be9f16b6b feat(aibridge): refuse records with an unset timestamp (#30029)
Timestamps are stamped by the gateway. A record that arrives with an
unset one is
persisted as year one, which skews budget periods, retention and the
sessions
timeline. A `timestamptz` column cannot report that, so the record is
refused
where it is produced, and the reason logged: most records are dispatched
asynchronously and their errors are discarded.

Only timestamps are checked. Every other property is left to the
database, so
this recorder cannot diverge from it; the test asserts that directly by
delegating a record with a non-UUID ID and empty initiator, provider and
model.
Deciding where the other checks belong is #30045.

## Stack

| # | PR | Change |
|---|----|--------|
| 1 | #29916 | Share the structured log format definition |
| 2 | #29917 | coderd substitutes its own time for an unset one |
| 3 | #29918 | Stamp records where they are created |
| 4 | #29919 | Fold client acquisition into `DRPCRecorder` |
| 5 | #30029 | Refuse records that cannot be recorded correctly |
| 6 | #30030 | `--ai-gateway-structured-logging-source` + gateway
emission |
| 7 | #30031 | `--ai-gateway-disable-content-recording` + record filter
|

Each PR targets the one before it. Together they are #29664, which stays
open
until the stack is merged; the tip of the stack is byte-identical to its
tree.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 10:47:23 +02:00
Sas Swart 868dcd9c75 refactor: fold AI Gateway recorder client acquisition into DRPCRecorder (#29919)
`WrappedRecorder` existed to resolve a client per record call and to
stamp
timestamps. With stamping moved to the creation sites, resolving a
client is all
it did, and `DRPCRecorder` is the only recorder that needs one.

Give `DRPCRecorder` the client function and delete `WrappedRecorder`, so
the
chain has one fewer layer and `NewRecorder` takes the recorder it
decorates.

Each PR targets the one before it. Together they are #29664, which stays
open
until the stack is merged; the tip of the stack is byte-identical to its
tree.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 10:47:22 +02:00
Sas Swart a69d89bae6 refactor(aibridge): stamp records when they are created (#29918)
Timestamps were set in `WrappedRecorder`, on the goroutine that
delivered the
record, and in local time. A record could therefore be stamped after the
interception it belongs to had ended, and the value depended on delivery
scheduling rather than on when the event happened.

Stamp each record where it is created, in UTC. `WrappedRecorder` is left
resolving clients, which is all it now does.

Each PR targets the one before it. Together they are #29664, which stays
open
until the stack is merged; the tip of the stack is byte-identical to its
tree.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 10:47:22 +02:00
Sas Swart 8a66160df9 refactor: share the AI Gateway structured log format definition (#29916)
The structured interception log format was defined by literals in
`coderd/aibridgedserver`: the log marker, the user agent metadata key,
and a
`record_type` string per record. Customer SIEM pipelines parse on those
values.

Move them to `aibridge/recorder`, beside the recorder chain, so that a
second
emitter of this format cannot drift from coderd's. The emitted values
are
unchanged.

## Stack

| # | PR | Change |
|---|----|--------|
| 1 | #29916 | Share the structured log format definition |
| 2 | #29917 | coderd substitutes its own time for an unset one |
| 3 | #29918 | Stamp records where they are created |
| 4 | #29919 | Fold client acquisition into `DRPCRecorder` |
| 5 | #30029 | Refuse records that cannot be recorded correctly |
| 6 | #30030 | `--ai-gateway-structured-logging-source` + gateway
emission |
| 7 | #30031 | `--ai-gateway-disable-content-recording` + record filter
|

Each PR targets the one before it. Together they are #29664, which stays
open
until the stack is merged; the tip of the stack is byte-identical to its
tree.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 10:47:21 +02:00
Seth ShelnuttandCian Johnston 10a22c8302 feat: support Claude Platform for AWS on the Anthropic provider (#29048)
## Summary

Adds Claude Platform for AWS as a variant of the Anthropic provider,
preserving the native Messages protocol and model IDs. Builds on the
merged SigV4 extraction in #29047. Configuration and UI follow in #29049
and #29050.

A provider-owned transport handles both bridged and passthrough
requests, sets the configured workspace header, and re-signs SDK
retries. Credential precedence is allowed BYOK, then the stored key
pool, then ambient AWS SigV4 when neither key source applies. Rejected
keys or an exhausted pool do not fall back to IAM. AWS configuration
loads lazily, so key-authenticated requests do not require working AWS
credentials.

There are no explicit authentication-mode, static AWS credential, Role
ARN, or external-ID fields for Claude Platform. Bedrock behavior and PRM
attribution remain separate. Anonymous Anthropic Messages support is out
of scope.

## Validation

- Full offline `go test -race ./aibridge/...` passed on this PR tip.
- Installed pre-commit hook passed, including generation, lint, and
build.
- Tests cover workspace-header signing, retries, key
precedence/failover, lazy credential recovery/cache, cancellation, and
stream lifetime.
- `TestClaudePlatformLive` sends a small real request through the bridge
when explicitly enabled. It was not run against AWS.

Co-authored-by: Cian Johnston <cian@coder.com>
2026-09-29 09:06:00 +01:00
Paweł Banaszewski c5a58b194a fix(aibridge/keypool): reuse request bodies during key failover (#29721)
Prepares key failover for the AI Gateway reverse proxy, which buffers
the request body before forwarding.

Generated by Coder Agents on behalf of @pawbana.
2026-09-28 18:16:23 +00:00
Paweł Banaszewski 0e8521d41e refactor(aibridge): accept a pre-read payload in GuessSessionID (#29719)
Adds `client.GuessSessionIDFromPayload(client, r, payload)` for
reverse-proxy callers.

Generated by Coder Agents on behalf of @pawbana.
2026-09-28 10:55:44 +00:00
Paweł Banaszewski 382a8763ff chore: move to be shared gateway types and helpers (#29718)
Moves client identification, credential handling, header
processing, and error categorization into shareable packages.

Generated by Coder Agents on behalf of @pawbana.
2026-09-28 09:49:56 +00:00
Garrett Delfosse b55f721f24 fix: apply user-supplied AWS Bedrock API keys instead of dropping them (#28724)
## Bug

Under `/agents/settings/api-keys`, a personal API key saved for a
Bedrock provider never took effect. AI Gateway forwarded the saved
value, but the Bedrock interceptors re-signed every request with the
deployment's AWS credentials (SigV4), overwriting the `Authorization`
header. The key was silently dropped, so users were unknowingly still
billed to the administrator's AWS account with no way to bring their own
credentials.

## Fix

Apply the user's Bedrock key instead of discarding it. AWS Bedrock API
keys are bearer tokens (`Authorization: Bearer <key>`), so when a
personal key is present AI Gateway now sends it as a bearer token and
skips SigV4 signing. This covers every Bedrock route:

- **InvokeModel** (`/v1/messages`): applies the same wire transform as
the signed path (`/model/{model}/invoke[-with-response-stream]`,
`anthropic_version`, `anthropic-beta` → body, `model`/`stream`
stripping) but sets a bearer `Authorization` header instead of signing.
- **Mantle** (`/v1/messages`, `/v1/responses`, `/v1/chat/completions`):
passthrough with a bearer `Authorization` header instead of signing.

The bearer paths resolve no deployment AWS credentials, so BYOK works
even where the deployment has none. Requests without a personal key keep
the existing SigV4 behavior.

This also reverts the earlier interim guard that hid the key field and
rejected Bedrock key upserts: the field is shown again and the API
accepts the keys, because they now work.

<details>
<summary>Implementation notes</summary>

**Gateway (`aibridge`)**
- `messages.newMessagesService` detects BYOK on a Bedrock interception
and routes it through bearer-token option builders instead of the SigV4
path.
- `withBedrockInvokeModelBYOKOptions` /
`bedrockInvokeModelBearerMiddleware` reimplement the Anthropic SDK's
`bedrock.WithConfig` wire transform without signing, because that helper
couples the transform with SigV4 and would resolve deployment
credentials a BYOK request must not depend on.
- `bedrocksig.BearerMiddleware` is shared by the Messages, Responses,
and chat-completions interceptors for the Mantle passthrough; each
installs it in place of `SignMiddleware` when the credential is BYOK.
- Streaming decoding is unchanged: the Bedrock event-stream decoder is
registered by the SDK package's `init` and selected by response
content-type, independent of `bedrock.WithConfig`.

**coderd / SDK / frontend / docs**
- Removed the interim guard and `supports_user_api_key` capability flag;
restored the API-key field for Bedrock providers.
- Docs describe the Bedrock personal key as an AWS Bedrock API key
forwarded as a bearer token for every model family Bedrock serves.

**Tests**
- Unit: bearer middleware transform + auth for InvokeModel; shared
bearer middleware; option-builder validation.
- Integration: end-to-end through the bridge for InvokeModel, Mantle
Messages, Mantle Responses, and Mantle chat completions, asserting
`Authorization: Bearer <key>`, no `X-Amz-*` headers, correct upstream
path/model, no `X-Api-Key` leak, and that InvokeModel streaming decodes
real AWS binary event-stream frames.
- coderd: Bedrock key upserts succeed.

</details>

Closes
[CODAGT-699](https://linear.app/codercom/issue/CODAGT-699/bedrock-provider-settings-for-byok-only-expose-one-api-key).

---

*This PR was generated by Coder Agents on behalf of @f0ssel.*
2026-09-25 18:15:47 -04:00
Cian Johnston 9a4cb3aebd refactor(aibridge/intercept): inject actor headers in middleware (#29839)
Move actor-header injection into the shared upstream-header middleware
for Messages, Chat Completions, and Responses. Read the authenticated
actor from the request context and remove the duplicated SDK-option
injection from blocking and streaming paths, completing the TODO from
@ssncferreira.

Preserve the existing header names and forwarding toggle. This is the
first PR in the actor-header stack: #29839 → #29840 (email forwarding) →
#29812 (configurable names).

Refs https://linear.app/codercom/issue/AIGOV-601

> 🤖 Generated by AI with human input.
2026-09-24 17:20:40 +01:00
Ethan 0e9337c215 fix: retry Anthropic thinking binding errors with drop_block (#29792)
Closes CODAGT-1141

Opus 5.5 and Fable 5.1 bind each signed thinking block to the exact
prefix it was created under. chatd rebuilds the system prompt and tools
from live state before every model call, so if that state changes
mid-turn (e.g. after `start_workspace`), the replayed block no longer
matches and Anthropic returns a 400, which we treated as non-retryable:

```
messages.1.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation...
```

To fix, we'll do what Anthropic recommends: on that 400, retry once with
`thinking.block_binding.prefix_mismatch_behavior: "drop_block"` and the
`thinking-binding-controls-2026-08-01` beta, then send both upfront for
that provider and model once the retry succeeds. That's only a hint,
since BYOK users on the same provider can have different keys, so if a
request with `drop_block` gets a 400 we retry once without it and clear
the hint. The retry wraps the model itself, so compaction and the
advisor get it too. The hint is in-memory, so a restart costs one extra
400 per model on each replica. Chats that never hit the error are
unchanged.

aibridge's InvokeModel path was stripping the beta and deleting
`block_binding`, so it now forwards both or neither, for any model. It
also renames the field to `mismatch_behavior`, since that's what Bedrock
calls it, and only some regions accept the Anthropic name.

Always sending `drop_block` would change bytes on working chats, and AWS
doesn't document Mantle support for the beta. Dropping stale thinking
client-side means guessing what the server will reject (the signature is
opaque, and enforcement depends on the model and account), so it would
still need the retry. The proper fix is an append-only prefix, but
that's a much bigger change, and it would also still need this retry.

Mantle does accept the beta, at least for Opus 5.5 on us-east-1 (see
testing below).

<details>
<summary>Testing</summary>

I tested this manually on `9c2b4d6` with `develop.sh`, using Opus 5.5 on
Bedrock Mantle us-east-1 via the dogfood AI Gateway, with a small
logging proxy in front to record the beta header and `block_binding` on
each request. The direct Anthropic API doesn't enforce the binding for
our account, so I couldn't reproduce it there.

To trigger it, I just asked the agent to reason about something, create
a workspace from the `docker` template and run a command in it, all in
one turn. On the merge base, the turn fails with the 400 above as soon
as the workspace is created. On this branch there's one 400, the
`drop_block` retry succeeds, the turn finishes with no error in the UI,
and every request after that sends `drop_block` upfront:

```
status=400 beta=""                                     block_binding=""
status=200 beta="thinking-binding-controls-2026-08-01" block_binding={"prefix_mismatch_behavior":"drop_block"}
status=200 beta="thinking-binding-controls-2026-08-01" block_binding={"prefix_mismatch_behavior":"drop_block"}
```

The chat that failed on the merge base also recovers once it's continued
on this branch, and a restart costs one extra 400 as expected. I also
had the proxy reject any request with `drop_block`, to mimic a BYOK key
without the beta, and the retry without it succeeded and cleared the
hint, so the next chat didn't send it.

I didn't test the InvokeModel path, since I don't have AWS credentials
for it.

</details>
2026-09-24 14:02:06 +10:00
Michael Suchacz 5b5432ce73 feat: add GPT-6 Sol, GPT-6 Luna, and Claude Opus 5.5 to Agents and AI Gateway (#29762)
Add the models released on 2026-09-22 (GPT-6 Sol, GPT-6 Luna, and Claude
Opus 5.5) plus Grok 4.7 to the Agents known models catalog, so they
appear as suggestions when an admin adds a chat model in `/agents`
settings, and pick up their prices in the AI Gateway price book. chatd
and AI Gateway's Bedrock path also stop producing Opus 5.5 thinking
shapes it rejects.

| Model | Added to |
|---|---|
| GPT-6 Sol, GPT-6 Luna | openai, azure, openrouter, vercel |
| Claude Opus 5.5 | anthropic, azure, bedrock (plus `global.` alias),
openrouter, vercel |
| Grok 4.7 | openrouter (`x-ai/grok-4.7`), vercel (`spacexai/grok-4.7`)
|
| Qwen3.8 Max | vercel (`alibaba/qwen3.8-max-0902`; already curated on
openrouter) |

Every model is already on models.dev, so `overrides.jq` is unchanged.
Sol and Luna use `reasoningEffort: medium` like GPT-6 Astra and the
GPT-5.6 models. Opus 5.5 uses `high` like every other Opus, Fable, and
Mythos entry, and joins the Anthropic thinking-mode pin in
`knownModelsGenerated.test.ts`. Anthropic documents `medium` as the Opus
5.5 default, but the catalog value seeds both the default and the max
effort in the admin form (`applyKnownModelDefaults.ts`), so `medium`
would also stop users from picking `high`. Gateway entries follow the
existing convention of no reasoning default and upstream display names;
Qwen3.8 Max reuses its openrouter display name. New entries sort ahead
of the models they supersede.

**chatd.** Opus 5.5 always runs adaptive thinking and rejects `thinking:
{"type": "disabled"}` with HTTP 400. The pinned fantasy fork sends
exactly that for the `none` effort on Claude 5+ models (it exempts only
Mythos and Fable), and the effort picker offers `none` whenever a model
config sets a max effort. `applyReasoningEffort` now maps `none` to
`low` for Opus 5.5 on the Anthropic and Bedrock providers, next to the
existing GPT-6 Astra clamp. The new `ClampsNoneForClaudeOpus55` subtest
fails without the fix. The Reasoning effort section of
`coderd/x/chatd/ARCHITECTURE.md` documents the Astra clamp and should
gain a line for this one; that doc edit is left to a human author.

**AI Gateway on Bedrock.** Opus 5.5 also rejects `thinking: {"type":
"enabled", "budget_tokens": N}`. On the Bedrock InvokeModel path,
`augmentRequestForBedrockInvokeModel` in
`aibridge/intercept/messages/base.go` rewrote adaptive thinking into
that legacy shape for every model outside its adaptive-only allowlist.
`bedrockModelRequiresAdaptiveThinking` now includes Opus 5.5, so
adaptive requests pass through, legacy requests (Claude Code falls back
to them behind the gateway) convert to adaptive, and
`output_config.effort` is kept. `output_config.format` is still
stripped, as for the other adaptive-only models; before this change the
whole `output_config` was dropped. Two new
`TestAugmentRequestForBedrock_AdaptiveThinking` cases fail without the
fix.

Deliberately not added: the `-pro` (openrouter) and `-fast` (vercel)
variants, matching how Astra and the GPT-5.6 models are curated;
`openai.*` models on Bedrock; regional Bedrock profiles; `~` rolling
aliases; `copilot`; `azure/grok-4.6`, which models.dev lists without
pricing; vendors not curated on the gateways (Xiaomi MiMo V2.6, Nex
N2.5, and others); and variants of curated models (GLM 5.3 FlashX,
Qwen3.8 Omni Flash). All of these that have prices are still in the
price book.

Known gaps, unchanged by this PR:

- The price book stores one flat price per model, so the long-context
tier for Sol and Luna (above 272K input tokens) is not applied, as for
Astra.
- The Bedrock adaptive-only allowlist still lacks the already curated
Opus 5, Fable 5, and Fable 5.1, plus Mythos 5 and 5.1, which also reject
`budget_tokens`, so their adaptive requests still take the legacy
conversion. They predate this PR and need the same allowlist entry.
- AI Gateway forwards a client's explicit `thinking: {"type":
"disabled"}` unchanged on every path, so Opus 5.5 answers it with its
documented 400, as the direct API does.

`knownModelsGenerated.json` and
`coderd/aibridge/prices/data/prices.json` are regenerated with `make
gen/aibridge-prices` from one models.dev snapshot. Besides the rows
above, both carry the upstream drift the weekly scheduled refresh would
produce. The catalog has nine repriced gateway rows, including vercel
`openai/gpt-5.6-sol`, which moves from $2/$10 to $4/$20 per 1M
input/output tokens and now matches OpenAI's direct price. `prices.json`
gains 41 rows (26 for the models above across every listed provider, 15
for other new upstream models), drops 4 that upstream delisted, and
reprices 30.

Validation: `go test ./scripts/aibridgepricesgen/...
./coderd/aibridge/prices/... ./coderd/x/chatd/chatprovider/...
./aibridge/...`, `pnpm test src/modules/aiModels/` (176 tests),
`golangci-lint` on `chatprovider` and `aibridge/intercept/messages`, and
`biome check` on `knownModels/` pass.

Review log (4 completed review passes):

- Codex round 1 on `03decfde855`: two P1 findings. Bedrock adaptive
thinking for Opus 5.5 was confirmed by a failing test and fixed. The
request to add a TODO to `coderd/x/chatd/ARCHITECTURE.md` was declined;
the chatd paragraph above flags that section for a human.
- Codex round 2 on `0156b3e5997`: one P2 finding, that the chatd clamp
misses opaque Bedrock application inference profile ARNs and fantasy
then sends disabled thinking. Refuted: fantasy omits the thinking field
when it cannot parse a Claude version from the model ID, so Opus 5.5
keeps its default adaptive thinking.
- Codex round 3 on `0156b3e5997`: two P1 findings. The claim that
`minimal` reaches Opus 5.5 verbatim was refuted: fantasy normalizes it
to `low`. The request to rewrite a client's explicit `disabled` thinking
for Opus 5.5 on Bedrock was declined: the gateway forwards it unchanged
on every path, before and after this PR (see Known gaps).
- Codex round 4 on `0156b3e5997`: no findings ("Didn't find any major
issues").

> Xum opened this PR on behalf of @ibetitsmike.
2026-09-23 14:10:24 +02:00
Michael Suchacz 2bf0f567d8 feat: add OpenAI Pro reasoning mode to chat model configs (#29584)
Adds `provider_options.openai.reasoning_mode` (`pro`) to chat model
configs so admins can turn on OpenAI's Pro reasoning mode for a model,
alongside the other OpenAI request options on the model form such as
`service_tier`. The field is offered for any model on an OpenAI
provider; the field description says Pro is supported from the GPT-5.6
Sol generation and that requests fail when Pro is set on a model that
does not support it. There is deliberately no supported-model list
anywhere: a newly released model that supports Pro works with no code
change, and OpenAI rejects the request when the model does not.
Validation rejects only values other than `pro`, non-OpenAI providers,
and configs that explicitly force plain sampling
(`reasoning_model=false`) or Chat Completions
(`use_responses_api=false`), including partial updates that move a
configured model onto such a provider or transport.

A configured mode implies the Responses API and reasoning-model
treatment when `openai_config` leaves those unset
(`chatprovider.effectiveOpenAIConfig`), so an alias the pinned SDK has
never seen, such as `gpt-daybreak-blue-latest`, still gets `effort` and
`summary` and drops `temperature`. The same effective config feeds the
client options and the recorded transport, so the two cannot disagree.

The pinned fantasy OpenAI provider options do not carry
`reasoning.mode`, so the mode is applied as a client-scoped `openai-go`
request option when the model client is built rather than per call. The
SDK merges pre-serialization `WithJSONSet` overlays by top-level key, so
the key is escaped (`reasoning\.mode`) to add `mode` to the existing
`reasoning` object instead of replacing `effort` and `summary`.
`TestResolveModelCallReasoningModeWire` pins the resulting request body
for streaming and non-streaming calls and checks that the fixed
computer-use model does not inherit the mode; AI Gateway forwarding of
the `reasoning` object is covered in `aibridge`. Because the option is
bound to the model client, every call made through a Pro model config
carries it, including title generation and quick generation when those
fall back to the chat's model; deployments that want cheaper auxiliary
calls should point the title generation override at another model.

Frontend: the field renders through the existing schema-driven provider
options with no hand-written field logic. Two generic changes:
`visible_for_providers` is now honored for provider fields the way it
already was for general fields (render and payload), so the
OpenAI-scoped select does not appear or serialize for Azure, which
shares the OpenAI field group; and the add/update model save toasts now
carry the server's error detail, so a rejected combination such as Pro
with Use Responses API at Off tells the admin which field to change.

Docs: `docs/ai-coder/agents/models.md` gains a Reasoning Mode row in the
OpenAI provider-specific options table (from the documentation check
comment
https://github.com/coder/coder/pull/29584#issuecomment-5752457808), and
its Azure note now says Azure OpenAI lacks that one option.

Not changed: `coderd/x/chatd/ARCHITECTURE.md`. Its OpenAI transport
selection table needs a `reasoning_mode` row (client-applied, neither
transport) to match `TestProviderOptionsTransportParity`; left for the
human author.

<details>
<summary>Delivery record</summary>

- Local validation on every pushed head: targeted Go tests (chatopenai,
chatprovider, chatd wire test, aibridge integration test, coderd DB
tests for persistence, invalid input, and partial updates), red/green on
the wire test (injection removed, and unescaped key), Vitest
(`modelConfigFormLogic`, `ModelForm`), Storybook tests for
`ModelFormProviderConfig`, biome, tsc, oxlint, golangci-lint on touched
packages, pre-commit hook.
- Codex round 1 on `e7dbaefeafc`: 3 findings (Storybook assertions,
ARCHITECTURE.md TODO, `gpt-daybreak-blue-latest` alias). Disposition:
assertions moved to Vitest and alias accepted in `8fccf111111`;
ARCHITECTURE.md left untouched by author instruction. Threads replied to
and resolved.
- Codex round 2 on `8fccf111111`: 1 finding (fixture naming, FE9),
renamed in `23449e92317`. Round 3 on `23449e92317`: 1 finding (fixture
location, FE9), moved to `testHelpers/chatModels.ts` in `c3bd5aa370f`.
Round 4 on `c3bd5aa370f`: "Didn't find any major issues"
(https://github.com/coder/coder/pull/29584#issuecomment-5735119236). All
threads resolved.
- Remote UAT round 1 (chat
https://dogfood.cdr.dev/agents/f5ed1d16-be1d-4d39-952b-126a6a829ef1)
exercised `e7dbaefeafc`: endorsed PASS. Real `gpt-5.6-sol` turns showed
`"mode": "pro"` / `"standard"` / no key in the Debug tab with effort and
summary intact; 14 POST and 6 PATCH rejections captured; UI select
visibility, persistence, reload, and clearing verified. Low,
non-blocking notes: the `gpt-5.6` alias revert in the model identifier
field is pre-existing; Pro is dropped silently when a model or transport
change makes it unsupported; Pro applies to auxiliary calls (see above).
- Remote UAT round 2 on `c3bd5aa370f` (same chat, alias and core
re-verify): core PASS, alias FAIL. With `gpt-daybreak-blue-latest` the
request carried `{"mode": "pro"}` without the configured effort and
summary and kept sending `temperature` (provider 400 then retry on quick
generation and title calls), because the SDK does not classify the alias
as a reasoning model. Fixed in `d4c338de767`: a configured mode now
implies a reasoning model unless `openai_config.reasoning_model` is set,
and a mode on a config that forces plain sampling is rejected. Alias
UI/API behavior, rejections, and known-model Pro/Default turns all
passed on `c3bd5aa370f`.
- Codex round 5 on `d4c338de767`: "Didn't find any major issues"
(https://github.com/coder/coder/pull/29584#issuecomment-5736190356).
Zero unresolved threads. CI green on `d4c338de767`.
- Remote UAT round 3 on `d4c338de767` (same chat): endorsed PASS. Alias
runs are single-attempt 200s with `{"effort", "summary", "mode": "pro"}`
and no `temperature` (quick generation and title calls no longer retry);
`reasoning_model=false` plus a mode is rejected by POST and PATCH with
the stored config unchanged; the Reasoning Model override at Off hides
the select and drops the mode on save; `gpt-5.6-sol` Pro turn unchanged.
Remaining low notes, none introduced here: rejection detail for a
non-OpenAI provider names the model rather than the provider; Pro is
dropped silently when an override makes it unsupported; `PATCH
model_config` replaces the whole object (pre-existing on main).

- coder-frontend-review on `d4c338de767` (8 role reviewers, 3 passes):
13 failing checkpoints, chiefly a TS mirror of the Go model regex, the
`json_name === "reasoning_mode"` gate duplicated in the render filter
and payload builder, a defaulted `model` parameter, and comment and type
nits. Fixed in `554c90d5fd9`: the pattern and provider scope are
generated onto the field schema, one predicate is shared by both call
sites, `buildModelConfigFromForm(provider, model, form)` requires the
model, and the ModelForm test also asserts the select disappears for an
unsupported model. Red/green: stripping `supported_models` or
`visible_for_providers` from the generated schema fails 21 and 1 Vitest
cases respectively. Declined with rationale: RO4 (move the fixture to
`ModelsPage/testFixtures.ts`; FE9 in `FRONTEND_PATTERNS.md` names
`testHelpers/chatModels.ts`, and Codex round 3 required it) and a DF5
nit to gate on the committed identifier and warn when a saved mode is
dropped (behavior change, separate follow-up). Final pass: all
checkpoints PASS or N/A.
- Remote UAT round 4 on `554c90d5fd9` (same chat, focused regression
after the frontend-review refactor): endorsed PASS. All six claims held
(Pro round trip with effort and tier intact; unsupported identifiers
hide the select and a save drops the stale mode while keeping the other
options; Azure never shows or saves it; the alias shows it only with the
Responses override On; Reasoning Model Off hides it and drops it; three
real `gpt-5.6-sol` Pro turns were single-attempt 200s with
`{"effort","summary","mode":"pro"}` and no `temperature`). Probes aimed
at the refactor also passed: `gpt-5X6-sol` is rejected (dot escaping
survived the JSON round trip), whitespace-padded identifiers still
match, the other 11 OpenAI fields and the Anthropic section still
render. Remaining low notes are carried over from round 3 plus one
naming note ("Reasoning Mode" versus "Reasoning Model"). The final head
`abb58df77d8` differs from `554c90d5fd9` only in `ModelForm.test.tsx`,
so it ships the same production code.
- Codex round 6 on `554c90d5fd9`: 1 finding
(https://github.com/coder/coder/pull/29584#pullrequestreview-5260492465):
the two `toBeInTheDocument` assertions added in the frontend-review
round violate FE1. Confirmed against `site/AGENTS.md`; removed in
`abb58df77d8` (test-only, 7 deletions; the payload assertion keeps the
behavior coverage and the `ProviderConfigOpenAI` story captures the
hidden state). Thread replied to and resolved.
- Codex round 7 on `abb58df77d8`: "Didn't find any major issues"
(https://github.com/coder/coder/pull/29584#issuecomment-5749626071).
Zero unresolved threads. CI green on `abb58df77d8` (23 success, 8
skipped, `required` pass).

- Design change on `e99152e5c57` (owner direction: no model gating;
"none or pro" for any model; tooltip states the GPT-5.6 Sol constraint
and that requests fail on unsupported models). Removed
`codersdk.ChatModelReasoningModeModels`, the generated
`supported_models`, `isFieldApplicableToModel`, the
`gpt-daybreak-blue-latest` special case, and the `standard` enum value;
`ValidateReasoningMode(provider, config)` no longer takes the model;
`effectiveOpenAIConfig` makes a mode imply Responses and reasoning-model
treatment. PR footprint went from +1130/-22 to +769/-18. Local
validation: `go test` for chatopenai, chatprovider, chatd wire test, and
the coderd API tests (persistence now covers `gpt-5.6-sol`, `gpt-4o`,
`gpt-daybreak-blue-latest`, `gpt-7-nova`; invalid input now rejects
`standard`), golangci-lint on touched packages, Vitest (187 tests across
`modules/aiModels` and `ModelsPage`), biome, tsc, pre-commit hook.
- coder-frontend-review on `e99152e5c57` (8 roles, 1 pass plus a TS and
CD confirmation pass): 9 failing checkpoints (SD4, CD1, CD3, CD4, TS3,
TS7 x2, RO3, RO5, TN4, DF5). Fixed in `e06bfbe4299`: the ModelForm test
edits `mockGPT5` so its provider matches the selected provider state,
types the update mock like the sibling story, and drops an unused route;
the story spreads `mockGPT5` with a saved mode instead of a dedicated
shared fixture (`MockGPT56Pro` removed, `testHelpers/chatModels.ts` back
to base); a `ProviderConfigAzure` story captures the panel without
`reasoning_mode`; comment nits. Left as a nit with justification: RO3
(the one-line `!hidden && isFieldVisibleForProvider` predicate now
appears in both `getVisibleProviderFields` and
`getVisibleGeneralFields`; hoisting a helper for two call sites is not
worth it). Confirmation pass: TS all PASS; CD flagged one wording nit,
fixed before commit.
- CI green on `e06bfbe4299` (23 success, 8 skipped, `required` pass).
- Codex round 8 on `e06bfbe4299`: 1 P2 finding
(https://github.com/coder/coder/pull/29584#discussion_r4057659673): the
form still offers Pro with Use Responses API or Reasoning Model at Off,
a combination the server rejects, and the failure was not actionable.
Disposition: the select stays visible by owner direction (no client-side
gating of this field beyond the provider scope; an explicit rejection is
preferred over the earlier silent drop), and `e2b43c3aee7` makes the
add/update save toasts show the server detail so the admin sees which
field to change. Thread replied to and resolved; zero unresolved
threads.
- Remote UAT round 5 on `e06bfbe4299` (same chat): endorsed PASS with
two UI issues to land before release. All seven probes passed: the
select offers only Default and Pro for `gpt-5.6-sol` and `gpt-4o` with
the tooltip text verbatim; Pro saves on `gpt-4o` and the real turn fails
visibly with the provider's "reasoning.mode is not supported with this
model" after a single 400 attempt, and works again once Pro is cleared;
`gpt-daybreak-blue-latest` with Pro and no overrides is a single 200 to
`/v1/responses` with `{effort, summary, mode: "pro"}` and no
`temperature`; the `gpt-5.6-sol` Pro turn is unchanged; POST and PATCH
reject `standard`, `PRO`, empty, Responses Off, Reasoning Model Off, and
Azure, openai-compat, and Anthropic providers with the stored config
unchanged, while a model-only PATCH to `gpt-4o` now succeeds; the Azure
form shows no Reasoning Mode; the alias with an explicit Responses
override still works. Reservations: (1) medium, the UI conflict path
only showed "Invalid model config." without the detail (fixed in
`e2b43c3aee7`, not yet UAT-exercised); (2) low-medium, a dev-DB row
still holding `standard` from round 2 renders an empty red select whose
message is the whole field description plus "has an invalid value." and
blocks saving unrelated fields (pre-existing generic behavior of
`yupTestForField` using the description as the label; no released data
can hold `standard`, so no migration); (3) low, no hint next to older
identifiers (documented design); (4) low, a chat on such a stored row
fails with a generic headline (pre-existing).
- Final head `e2b43c3aee7` differs from `e06bfbe4299` only in the two
save-toast handlers (`AddModelPage.tsx`, `UpdateModelPage.tsx`, 8
insertions). CI is green on `e2b43c3aee7` (skipped=8, success=23,
`required` success). Codex has not run on `e2b43c3aee7`.
- Remote UAT round 6 on `e2b43c3aee7` (same chat,
https://dogfood.cdr.dev/agents/f5ed1d16-be1d-4d39-952b-126a6a829ef1,
settled 2026-09-20T19:02Z): endorsed PASS on the exact final head. Build
proven by `/api/v2/buildinfo` (`v2.37.2-devel+e2b43c3aee`,
`external_url` at the full SHA) and the UI badge. The round 5 toast
issue is resolved: Add and Update saves with Pro plus Use Responses API
Off or Reasoning Model Off show "Invalid model config." with the server
detail as the description, one 400 each, nothing stored. Compact
regression of every round 5 probe held (dropdown and tooltip; Pro on
`gpt-4o` fails visibly with the provider's `reasoning.mode is not
supported with this model` and works after clearing; alias with and
without the Responses override and `gpt-5.6-sol` all send `{effort,
summary, mode: "pro"}` with no `temperature` in a single 200; POST and
PATCH rejection matrices with stored config unchanged; Azure form
without the field). Legacy `standard` row: fails closed on chat, and
re-picking Pro or Default saves. Remaining notes, none blocking: the
malformed validation copy for an invalid stored enum (pre-existing
`yupTestForField` label choice, dev-DB rows only), Pro offered for
models that cannot accept it (documented design), and a pre-existing
`quickgen` status quirk on `gpt-4o` unrelated to this field. Secret scan
clean.
- Final head `4f3c6106dfe` adds one docs-only commit on top of
`e2b43c3aee7` (`docs/ai-coder/agents/models.md`, 9 insertions, 8
deletions, no code). Remote UAT round 6 exercised `e2b43c3aee7`; the
docs commit is not UAT-relevant. Validated with
`markdown-table-formatter`, `markdownlint-cli2`, and the pre-commit hook
(`fmt/markdown`, `lint/markdown`, `lint/emdash`, `lint/typos`). CI is
green on `4f3c6106dfe` (success=24, skipped=7, `required` success) and
the documentation check re-run marked its item addressed
(https://github.com/coder/coder/pull/29584#issuecomment-5752457808).
- Review tally for this PR: Codex 8 completed rounds;
coder-frontend-review 34 role passes (24 on `d4c338de767`, 10 on
`e99152e5c57`); remote UAT 5 rounds; no human review yet. This is far
past the six-review guardrail, so no further Codex or agent review has
been requested. Whether to spend another Codex pass on `e2b43c3aee7` is
an owner decision; human review is still required before merge.

</details>

> Xum acted on behalf of @ibetitsmike.
2026-09-21 15:58:18 +02:00
Paweł Banaszewski 44eb71f922 chore: move aibridge proxy code and helpers to separate packages (#29573)
Move the stateless AI Gateway router into `aibridge/x/proxy`.
Extract shared routing helpers into `aibridge/routing` and move provider
and recorder helpers to their owning packages. Update callers and tests
without changing behavior.

Generated by Coder Agents.
2026-09-21 12:26:09 +02:00
Michael Suchacz a698b026fe fix(aibridge): relay Responses SSE events unless tools are injected (#29580) 2026-09-19 09:02:55 +02:00
Paweł Banaszewski c47eb47393 feat: add stateless AI Gateway proxy mode (#29349)
Adds proxy mode to the AI Gateway. No AI provider is supported in this
mode yet.
2026-09-18 16:47:16 +02:00
Cian Johnston 19076beb8d feat: attribute AI Gateway usage to workspaces (#29235)
- Adds nullable `workspace_id` to AI Gateway interceptions without a
foreign key or index.
- Derives direct attribution from strictly parsed server-minted workspace
session-token names, excluding user-created tokens and validating the
embedded owner.
- Derives delegated Coder Agents attribution from the persisted chat
workspace ID.
- Records `workspace_id` through the additive v1.3 gateway protocol and
structured interception logs.
- Exposes attribution in session details through
`interception_attributions`, including tool-less interceptions and null
values for unknown attribution.

Closes AIGOV-637

Generated by Coder Agents.
2026-09-18 15:22:02 +01:00
Seth ShelnuttandCian Johnston 621cbf681e refactor(aibridge): generalize AWS SigV4 signing beyond Bedrock (#29047)
Behavior-neutral refactor. First of four PRs adding Claude Platform for
AWS as an authentication method on the existing `anthropic` provider
type, rather than as a new provider type.

## Why

`aibridge/intercept/bedrocksig` already SigV4-signs native Messages
requests, but was shaped around Bedrock Mantle: the service name was
hardcoded, and the Bedrock revenue-attribution user-agent was baked into
the signing middleware. Nothing about SigV4 signing is Bedrock-specific,
so a second AWS-signed Anthropic upstream can reuse the entire path once
these two things are parameterized.

Doing this first means the follow-up feature needs no new signing code,
no new AWS credential-chain code, and no dependency bump.

## Changes

- Rename package `bedrocksig` to `awssig`. It already documented itself
as SDK-agnostic and had a single production importer.
- `SignMiddleware` takes the signing service as a parameter instead of
hardcoding `bedrock-mantle`, which survives as
`awssig.ServiceBedrockMantle`. Error messages name the service rather
than saying "mantle".
- Move the PRM attribution user-agent out of `SignMiddleware` into the
Bedrock option builders. It is Coder's AWS Partner Revenue Measurement
marker for **Bedrock** traffic, so other AWS-signed endpoints must not
inherit it without their own attribution agreement.
- Extract `withAWSSignedMessagesOptions`, which routes and signs a
native Messages request for any AWS service with optional
endpoint-specific headers. `withBedrockMantleOptions` becomes a thin
caller that adds PRM attribution.
- Split `buildBedrockCredentials` into `buildAWSCredentials`, taking an
`awsCredentialSpec` (region, static keys, role ARN, external ID) rather
than Bedrock settings. The static-keys / default-chain / AssumeRole
logic and its credentials cache are unchanged.
- Rename `intercept.Bedrock` to `intercept.AWSSigV4` and
`hintBedrockChainKey` to `hintAWSChainKey`. Hint **values** are
unchanged.

## Notes for review

- **The region-or-base-URL check stayed with the Bedrock caller** rather
than becoming a `requireRegionOrEndpoint bool` on the shared function.
That is Bedrock's endpoint policy, and revive correctly flagged the
parameter as control coupling.
- **The hint constant block now records the `VARCHAR(15)` bound** that
`aibridge_interceptions.credential_hint` imposes. Values are unchanged,
so there is no risk here, but the next credential type added will need
it.

## Testing

The existing Bedrock mantle and invoke-model tests are the regression
suite: they assert the signed service scope and the PRM user-agent on
the real upstream request.

I verified that suite actually constrains the PRM relocation by
temporarily removing the new PRM middleware from
`withBedrockMantleOptions`.
`TestAWSBedrockIntegration/mantle/v1/messages` fails with
`"Go-http-client/1.1" does not contain "sdk-ua-app-id/..."`, then passes
again once restored.

New `awssig` unit tests cover the parameterized service (asserting the
credential scope for both `bedrock-mantle` and
`aws-external-anthropic`), body restoration after hashing, and that
signing alone never adds the PRM marker.

`go test ./aibridge/... -count=1` green, `-race` green, `golangci-lint
run aibridge/...` reports 0 issues, full `make pre-commit` passed.

<details>
<summary>Coder Agents disclosure</summary>

This pull request was generated by Coder Agents on behalf of @Shelnutt2.

</details>

---------

Co-authored-by: Cian Johnston <cian@coder.com>
2026-09-18 14:40:51 +01:00
Michael Suchacz d2e94e299a chore: delete dead functions and skip-only or duplicated tests (#29461) 2026-09-17 18:14:08 +02:00
Paweł Banaszewski 3e95ae3278 refactor(aibridge): share request admission and shutdown middleware (#29348)
- Share request admission, context cancellation, and drain accounting
through `InflightGate` middleware.
- Migrate interception to the shared middleware while preserving request
body limits.
- Reject new requests during shutdown with 503 and cancel on deadline
without waiting indefinitely for handlers that ignore cancellation.
- Add admission and shutdown regression coverage.

Generated by Coder Agents on behalf of @pawbana.
2026-09-17 16:22:51 +02:00
Paweł Banaszewski 263f2c207e feat: register AI Gateway proxy experiment and share provider helpers (#29347)
- Add `ai-gateway-reverse-proxy` experiment and update generated API
types and documentation. The experiment has no runtime effect yet.
- Extract shared (will be used by next PRs in stack) provider routing
and key-pool enumeration helpers.
- Log unsupported routes at Debug level.
2026-09-17 10:27:48 +02:00
Sas Swart 98bf16098e feat: add a LogRecorder for AI Gateway (#29136)
Write middleware for the Recorder interface that are responsible for the logging and
tracing of all calls to a Recorder.

Simplify existing Recorders by removing logging and tracing that is now
done by the new Decorators.

Ensures consistent logging coverage for the entire interface.
Reduce local code complexity in other implementations of the Recorder.

Given the ensured logging coverage, this allows us to implement the
feature flag to drop persistence of this information to the Coder
control plane database
2026-09-15 17:35:29 +02:00