Commit Graph
253 Commits
Author SHA1 Message Date
Susana Ferreira 3f1973f45c docs: document AI Gateway cost controls (#27643)
### Description

Adds documentation for AI Governance Cost Control, including how
administrators configure budgets, how effective groups are resolved, how
enforcement works, and where spend reporting is available.

### Changes

- Replace the placeholder cost control page with a full admin guide
- Document deployment settings, group budgets, user overrides, and
effective group resolution
- Explain estimated spend, unpriced models, notifications, enforcement,
and spend reporting
- Add migration guidance for Coder Agents Cost Control
- Add screenshots for group budgets and user overrides

Closes
[AIGOV-476](https://linear.app/codercom/issue/AIGOV-476/add-documentation-for-ai-bridge-cost-controls).

> [!NOTE]
> Initially generated by Coder Agents, modified and reviewed by
@ssncferreira
2026-07-30 15:04:39 +00:00
3f3fd1c4d7 feat: show network request summary on AI session detail card (#27418)
Frontend for the AI session network summary. Adds Network calls, Blocked
network requests, and Top domains rows to the Session summary card on
the individual AI session detail page, driven by the network fields on
the session threads response.

Renders "Disabled" when network monitoring was not active and "No
activity" when there were no calls. Covered by Storybook stories for
each state.

### PR map (merge strictly bottom-up)

This change is a 4-PR stack. Each PR depends on all the ones below it,
so merge in this exact order:

1. #27417 — backend network summary
2. #27418 — frontend summary rows
3. #27425 — backend per-call list `network_call_logs`
4. #27426 — frontend network-calls panel

Refs AIGOV-463

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Cian Johnston <cian@coder.com>
2026-07-30 13:23:51 +02:00
Jaayden Halko 54d5eb7ec2 feat: add hourly hb_agent_runtime_v1 usage events for Coder Agent runtime (#27312)
closes CODAGT-839
closes CODAGT-843
closes CODAGT-773

## Summary

Adds a new heartbeat usage event type, `hb_agent_runtime_v1`, measuring
the total agent-loop runtime of Coder Agents (chats) per UTC hour, plus
a reconciler that generates one event per hour with self-healing
backfill over a trailing 7-day window. Events flow to Tallyman through
the existing publisher unchanged. This measures the new Coder Agents
(the `chats` tables), not the deprecated Tasks counted by
`dc_managed_agents_v1`.

Independent of #27508, which fixes the dead ai-seats cron registration.
Both PRs carry the identical `usage_event` create permission hunk for
the usage-publisher subject (this feature's generator and the ai-seats
cron each need it for heartbeat inserts), so they can land in either
order and the overlap merges cleanly.

> [!WARNING]
> **Do not include this in a release until Tallyman accepts
`hb_agent_runtime_v1`.** The publisher marks permanently rejected events
as done-forever, and the generator then sees those buckets as complete
locally, so their usage would be silently and permanently lost.

## Details

Each event's payload is `{"runtime_ms": N}`: the sum of
`chat_messages.runtime_ms` for messages created in the hour bucket `[H,
H+1)`, across all chats (sub-agents, API-created, archived, and
soft-deleted messages included). Events use deterministic IDs
(`hb_agent_runtime_v1:<bucket start>`) with `created_at` set to the
bucket start, so concurrent replicas race safely via `ON CONFLICT (id)
DO NOTHING` without locking, and daily rollups attribute backfilled
hours to the correct day. Idle hours produce zero-valued events. A
bucket becomes eligible 5 minutes after it closes; hours missing for
longer than the 7-day window are forfeited, which can only undercount.

Note that this makes `usage_events.created_at` explicitly the *event
occurrence time* rather than the row insertion time; the two only
diverge for backfilled events. It already behaved as the occurrence
timestamp (it drives the daily rollup day and is shipped to
Tallyman/Metronome as the event timestamp), and the migration now
documents this with a `COMMENT ON COLUMN`, which also surfaces as a Go
doc comment on `UsageEvent.CreatedAt`.

The new `usage.Generator` runs unconditionally in enterprise builds; the
`publish_usage_data` license flag continues to gate egress only, so
air-gapped deployments still fill their local ledger. The
`aggregate_usage_event()` trigger sums `runtime_ms` per day into
`usage_events_daily` (unlike `hb_ai_seats_v1`, which takes the daily
max).

`InsertHeartbeatUsageEvent` now takes an explicit `createdAt` so
generators can backfill historical buckets; the cron passes
`clock.Now()` to preserve its existing behavior.

## Tallyman follow-up

<details>
<summary>Prompt for the Tallyman-repo agent</summary>

> **Task**: Add support for the new Coder usage event type
`hb_agent_runtime_v1` so Tallyman accepts, validates, and forwards it to
Metronome.
>
> **Background**: coder/coder PR (this PR) adds hourly heartbeat events
measuring Coder Agent runtime. Events arrive via the existing
`/api/v1/events/ingest` endpoint with: `event_type:
"hb_agent_runtime_v1"`, `event_data: {"runtime_ms": <int64 >= 0>}`,
deterministic `id` of the form `hb_agent_runtime_v1:2026-07-15_14:00:00`
(UTC hour bucket start), and `created_at` set to the bucket start (may
be up to ~8 days in the past due to backfill; within Metronome's 34-day
dedup window). Zero-value events are normal (idle hours).
>
> **Work**:
> 1. Update Tallyman's vendored/imported `coderd/usage/usagetypes` (or
equivalent) to the coder/coder commit that adds
`UsageEventTypeHBAgentRuntimeV1` and `HBAgentRuntime`.
> 2. Ensure ingestion validation accepts the type (`Valid()` switches)
and rejects negative `runtime_ms`.
> 3. Ensure Metronome forwarding maps the event with transaction ID
derived from the event `id` as for existing types, passing `runtime_ms`
through as the property for a SUM-aggregated billable metric ("Coder
Agent Hours" = `SUM(runtime_ms) / 3,600,000`).
> 4. Do NOT permanently reject unknown-but-well-formed future `hb_*`
types if avoidable; at minimum confirm current behavior for unknown
types (temporary vs permanent rejection) and report it.
> 5. Tests: ingest accept/validate, dedup by ID, Metronome payload
mapping.
>
> **Constraint**: this must be deployed to tallyman-prod **before** any
coder/coder release containing the event generator; coderd treats
permanent rejections as terminal per event.

</details>
2026-07-30 08:37:45 +01:00
Paweł BanaszewskiandCian Johnston 18128b7b52 docs: add standalone AI Gateway docs (#27592)
Documents standalone AI Gateway deployment, Gateway key authentication,
monitoring, and the updated embedded vs standalone topology in the AI
Gateway docs.

---------

Co-authored-by: Cian Johnston <cian@coder.com>
2026-07-29 19:38:22 +02:00
Matt Vollmer 4987afada7 docs: present AI Governance as included with Premium (#27545)
## Summary

AI Governance is now included with Premium licenses instead of being
sold as a separate per-user add-on. This updates `docs/` to describe the
new packaging, removes "Add-On" from AI Governance references, and
refreshes the editions architecture diagram.

## Changes

- **`docs/ai-coder/ai-governance.md`**: title is now "AI Governance";
rewrote the licensing statements (previously "a separate, per-user
license... not included with a Premium subscription and must be
purchased separately") to state it is included with Premium. The
usage-pool section now attributes the shared Agent Workspace Build pool
to Premium deployments.
- **Repeated admonition (28 files under `ai-coder/agent-firewall/` and
`ai-coder/ai-gateway/`)**: replaced "requires the AI Governance Add-On /
as of Coder v2.32, deployments without the add-on..." with "is part of
AI Governance, which is included with a Premium license." The v2.32
add-on gate no longer applies; the gate is now Premium vs. Community.
- **`docs/ai-coder/index.md`, `security.md`, `tasks.md`,
`usage-data-reporting.md`, `admin/licensing/index.md`,
`install/releases/esr-2.29-2.34-upgrade.md`,
`ai-gateway/ai-gateway-proxy/setup.md`,
`ai-gateway/clients/claude-code.md`**: reworded add-on references to
Premium inclusion.
- **`docs/manifest.json`**: nav title "AI Governance Add-On" → "AI
Governance", updated two descriptions, and swapped the 25 `"state": ["ai
governance add-on"]` badges to `["premium"]` so the sidebar badge reads
"Premium" instead of "AI Governance Add-On".
- **`docs/images/single-region-architecture.png`**: refreshed the
diagram in the **Community and Premium editions** tab on
[Architecture](https://coder.com/docs/admin/infrastructure/architecture).
Also deleted the unreferenced `single-region-architecture.svg` copy.

## Follow-ups outside this PR

- The `"ai governance add-on"` doc-state badge is defined in
`coder/coder.com` (`src/utils/docs/state.ts`). After this merges, no
manifest entry uses that key, so it becomes dead config and can be
removed there.
- `enterprise/coderd/license/license.go:564-572` still warns admins that
"The AI Governance add-on is required to use AI Gateway." That backend
string will contradict these docs once shipped.

## Verification

- `pnpm run lint-docs`: 0 errors across 504 files
- `make lint/emdash`: clean
- Vale on the changed Markdown files: 0 errors; remaining warnings are
pre-existing gerund headings on untouched lines
- `docs/manifest.json` validated as JSON
- Confirmed the deleted SVG had no references anywhere in the repo

---

PR generated with Coder Agents on behalf of @mattvollmer.
2026-07-29 08:45:20 -04:00
Susana Ferreira e96e7cfec2 docs(docs): add AI Gateway cost controls placeholder page (#27570)
## Summary

Adds a placeholder "Cost Controls" page under AI Gateway in the docs,
plus its `manifest.json` navigation entry. This is a stub with a title
only; the full content will be written in a follow-up.

Relates to
[AIGOV-476](https://linear.app/codercom/issue/AIGOV-476/add-documentation-for-ai-bridge-cost-controls).

Related to [internal slack
thread](https://codercom.slack.com/archives/C096PFVBZKN/p1785150528587409).

## Changes

- Add `docs/ai-coder/ai-gateway/cost-controls.md` placeholder page
- Register the page in `docs/manifest.json` under AI Gateway (after
Monitoring)

---
> [!NOTE]
> This PR was generated with Coder Agents.
2026-07-28 10:05:18 +00:00
TJ bfcfb71860 fix: show 'Unset' for missing providers in AI models list (#27400)
## Summary

Frontend-only fixes for the `/ai/settings/models` page:

1. **Provider column displays "Unset"** with an info tooltip when a
model's provider has been deleted, instead of "N/A".
2. **Models without a usable provider display as "Disabled"** in the
list, regardless of the stored `enabled` flag. Covers both missing
(soft-deleted) and disabled providers.
3. **Save button re-enabled when only the provider changes** on the edit
page (previously the button stayed disabled because provider changes
lived outside the formik state).

## Scope

Frontend only. The DB constraint
`chat_model_configs_ai_provider_required_when_active` already prevents a
non-deleted model from having a NULL `ai_provider_id`; CODAGT-709
addresses the server-side cascade when a provider is deleted.

## Changes

- `ModelsPageView.tsx`: two `useMemo` maps (`hasProviderByModelId`,
`providerEnabledByModelId`) passed to `ModelRow`.
- `ModelRow.tsx`: `isEffectivelyEnabled = model.enabled && hasProvider
&& providerEnabled`. When `hasProvider` is false, renders "Unset" with a
standard `InfoIcon` tooltip.
- `ModelForm.tsx`: `canSubmit` OR's in `hasProviderChange` so the save
button enables when only the provider dropdown changes.
- `ModelRow.stories.tsx`: four stories covering baseline,
missing-provider (with tooltip assertion), disabled-provider, and
disabled-model paths.
- `ModelsPageView.stories.tsx`: `OrphanedModelShowsUnset` feeds an
orphaned model through the real derivation (map-miss + `?? false`),
matching the production shape produced by `deriveProviderStates`.
`DisabledProviderModelsStillListed` now asserts the "Disabled" badge.
- `ModelForm.stories.tsx`: `EditUpdateEnabledOnProviderChange` asserts
the save button is enabled when the selected provider differs from the
model's stored provider.
- `testFixtures.ts`: `mockOrphanedModel` fixture representing the
deleted-provider case.

Diff: 7 files, 240 insertions, 9 deletions.

> 🤖 This PR was updated with Coder Agents.
2026-07-28 00:17:45 -07:00
Susana Ferreira dba45cede7 fix: remove 403 from key failover and cooldown on 401 (#27419)
## Problem

When a key returned 401 or 403, the pool marked it permanently
unavailable for the lifetime of that in-memory pool. This is bad UX: a
transient auth failure or a briefly-misconfigured key could take a key
out of rotation until the operator either restarted Coder or
reconfigured the key (even re-saving the same working value).

## Changes

- **403 removed from key failover**: it's a per-request authorization
failure, not a key-level problem, so it's surfaced to the caller as-is
without marking the key or failing over.
- **401 now applies a temporary cooldown** (like 429) so the key
recovers on its own instead of staying blocked.
- When every key is in an auth-failure cooldown, the pool reports a
`502` with no `Retry-After`, but the keys still recover automatically
once the cooldown elapses.

Closes
https://linear.app/codercom/issue/AIGOV-421/ai-gateway-a-quarantined-centralized-key-never-recovers-without-a
Closes
https://linear.app/codercom/issue/AIGOV-533/403s-misclassifying-keys-as-permanently-down-in-ai-gateway

> [!NOTE]
> Initially generated by Claude Opus 4.7, modified and reviewed by
@ssncferreira
2026-07-27 12:06:01 +01:00
Michael Suchacz 02fd1cc691 feat: allow spawn_agent model and reasoning effort override (#27385) 2026-07-22 18:43:22 +02:00
Sas SwartandClaude Opus 4.8 f17d488479 feat: add network call badges to AI sessions table (#27341)
Surface the total and blocked Agent Firewall network calls on the AI
sessions list. Sessions that did not pass through Agent Firewall show as
"Disabled".

<img width="2842" height="1366" alt="image"
src="https://github.com/user-attachments/assets/2a68b4a9-4d93-454d-a06e-5f0d0b734a33"
/>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 14:16:31 +02:00
Nick Vigilante f55be09bfc docs(docs/ai-coder/ai-gateway): fix bmcp_ described as suffix instead of prefix (#27392)
The Tool Injection section of the AI Gateway MCP doc called `bmcp_` a
suffix, directly contradicting the correct description one section
earlier on the same page and the `aibridge` implementation, where
`injectedToolPrefix` is prepended to every bridged MCP tool name
(`aibridge/mcp/tool.go`).

Reported by a customer who read the suffix wording and assumed `bmcp` in
a tool name like `bmcp_github_list_gists` was a typo.

---
🤖 Built with AI assistance.
2026-07-21 11:59:30 -05:00
Michael Suchacz 3227cac217 feat: add manual chat compaction via /compact (#27081)
Adds a user-triggered `/compact` action for Coder Agents chats: typing
`/compact` in the composer (or picking it from the `/` trigger menu)
summarizes the conversation so far to free up context window space.

## How it works

- New `POST /api/experimental/chats/{chat}/compact` endpoint
(owner-only, RBAC `ActionUpdate`, excluded from the public API reference
via `x-apidocgen skip`). It marks the chat with a durable one-shot
`chats.compaction_requested_at` signal and moves it `waiting -> running`
via a new `RequestCompaction` state transition; no message row is
inserted. AI Gateway attribution needs no per-request key: generation
preparation resolves the owner's synthetic API key (#27170) like any
other turn.
- `RequestCompaction` hands off chat ownership (clears
`worker_id`/`runner_id`) so a worker acquisition hint is published;
since the transition changes no history, the previous runner could
otherwise miss the request under reordered pubsub delivery.
- The background chat worker picks the chat up like any other turn. A
pending manual request takes precedence over turn completion in the
generation decision, and forces compaction even below the automatic
threshold (and when compaction is disabled via threshold=100). The
commit step consumes the request marker in the same transaction; any
transition that ends the turn clears stale markers.
- The summary triplet reuses the automatic-compaction path, now tagged
with a `source` (`automatic` | `manual`) that is plumbed through
streamed progress parts, persisted tool JSON, and the UI label
("Summarized (manual)").
- Validation order: busy chats reject with 409 (state-machine conflict),
empty/already-compacted chats with 409 "nothing to compact", archived
chats with 400; the owner usage-limit check runs last so no-op requests
surface the specific conflict instead of a limit error.
- Web UI: the `/` trigger menu now has a built-in "Commands" group
listing `/compact`; submit intercepts exactly `/compact` and calls the
endpoint instead of sending a message. A personal or workspace skill
named `compact` takes precedence over the built-in command; while skill
collisions are still resolving, an exact `/compact` submission is
blocked with a retryable hint instead of leaking as message text.
History and queued-message edits are never intercepted. After
compaction, the context usage indicator resets to its unknown state
until the next assistant response reports fresh usage, instead of
showing the stale pre-compaction number.
- codersdk: `ExperimentalClient.CompactChat`.

Worker-path execution (rather than compacting synchronously in the
handler) reuses the existing lock fencing, live "Summarizing..."
streaming, retry accounting, restart resilience, and debug-run
observability. Rationale documented in `coderd/x/chatd/ARCHITECTURE.md`.

## Testing

- State machine: transition-matrix coverage for `RequestCompaction`,
marker lifecycle tests (carried by lease renewals/queue appends, cleared
by terminal transitions, consumed by commit), ownership handoff +
acquisition hint assertions.
- Worker: decision-ordering and forced-compaction unit tests;
active-server end-to-end test (manual compact below threshold produces a
`source=manual` summary, returns to `waiting`, no assistant follow-up;
busy chat rejected).
- API: success, archived, non-owner, RBAC-denied, empty-chat, no-daemon
cases; usage-limit ordering (at-limit owners still get
state/nothing-to-compact conflicts for no-op requests, with marker
rollback).
- Frontend: Storybook play tests for the Commands menu group, submit
intercept, skill-name collision, queued-edit passthrough, and
manual/automatic tool rendering; unit tests for command availability
resolution and the post-compaction context usage reset.

> This PR was created by Mux, an AI coding agent, working on Mike's
behalf.
2026-07-21 10:58:08 +02:00
Michael Suchacz 9f4ddea571 feat: revoke MCP server OAuth grants at the provider on disconnect (#27300)
Closes
[CODAGT-805](https://linear.app/codercom/issue/CODAGT-805/revoke-oauth-grants-at-the-source-for-mcp-servers).

The experimental MCP server OAuth2 disconnect endpoint previously
deleted only the stored token row, leaving the grant active at the OAuth
provider. This PR adds provider-side token revocation while keeping
local disconnect independent of provider availability.

## Changes

- Add `mcp_server_configs.oauth2_revocation_url` in migration `000547`.
The value can be configured manually, discovered from RFC 8414 metadata,
and managed through the MCP server settings UI. Non-admin responses
redact it with the other OAuth2 fields.
- Revoke the refresh token first through the RFC 7009 endpoint, then
fall back to the access token only for `unsupported_token_type`. Public
clients send `client_id`; confidential clients use
`client_secret_basic`.
- Delete the local token transactionally before best-effort provider
revocation. Callers without a token receive the same response for hidden
and nonexistent config IDs, and provider failures return a generic
warning without exposing provider response bodies.
- Require HTTPS revocation endpoints except for HTTP loopback URLs.
Redirects must preserve the POST and remain on the configured origin.
Redirect errors omit provider-controlled paths and query strings so
reflected token material cannot enter logs.
- Treat `200 OK` and `204 No Content` as completed revocations. `202
Accepted` remains a failure because it does not confirm completion.
- Prevent an in-flight refresh from recreating a token deleted by
disconnect. Refresh persistence now uses an optimistic update keyed by
token ID and `updated_at`; only the OAuth callback can create a token
row. Refresh conflicts reload the current row or clear in-memory auth
when disconnect deleted it.
- Return `{token_revoked, token_revocation_error}` from disconnect,
while retaining SDK compatibility with the legacy `204` response. The UI
surfaces provider revocation failures as warning toasts.
- Document revocation endpoint discovery, HTTPS requirements, and
best-effort disconnect behavior.

No token or no configured revocation URL returns `token_revoked: false`
without an error, so disconnect remains idempotent.

> Updated by Mux, an AI coding agent, on Mike's behalf.
2026-07-20 00:14:03 +02:00
Michael Suchacz 1ac106255b feat: add Anthropic 1M context window toggle for Agents model configs (#27257) 2026-07-17 13:04:13 +02:00
Yevhenii Shcherbina 1453b4b1fc docs: document Bedrock mantle protocol (#27296)
Implements:
https://linear.app/codercom/issue/AIGOV-518/add-docs-for-bedrock-mantle
Follow-up to: https://github.com/coder/coder/pull/26745
2026-07-16 14:58:09 -04:00
Nick Vigilante c84aa564ba docs: normalize code-fence languages for Shiki compatibility (#27161)
Normalizes non-standard code-fence language tags across `docs/**` so a
strict highlighter (Shiki, used by Fumadocs) won't fail the build on an
unrecognized language, and unifies redundant synonym tags onto one
canonical form per language. The current renderer (Speed-Highlight)
detects the language from the code content, not the fence label, so this
drift wasn't visible until now.

## Changes

- `hcl` -> `tf` (199 fences, including indented ones nested in
numbered/bulleted lists). Shiki ships `hcl` and `terraform` as two
distinct grammars (not aliases); every `hcl`-tagged fence in `docs/**`
is actually Terraform resource/data/provider syntax, so the more
specific `terraform` grammar is correct for all of them. `tf` is Shiki's
own alias for that grammar, and it's also what GitHub's own markdown
renderer resolves to the same HCL/Terraform highlighting.
- `pwsh`/`powershell` -> `ps1`. Both `ps` and `ps1` are registered
PowerShell aliases in Shiki, but on GitHub's renderer only `.ps1` is a
registered file extension (`.ps` isn't), so `ps1` renders identically to
`powershell` there today while bare `ps` would silently lose
highlighting.
- `env` -> `dotenv` (a dedicated Shiki grammar for `KEY=VALUE` files)
- `text`/`output`/`none`/`url` -> `txt`. Same built-in plain-text
fallback either way, just shorter.
- `Dockerfile` -> `dockerfile` (lowercase)
- `bash`/`shell` -> `sh` (732 fences). Shiki and GitHub both alias all
three to a single shell grammar; this was already the style guide's
stated preference, just not enforced across the existing corpus until
now.
- `markdown` -> `md` (4 fences). Alias of the same grammar in both Shiki
and GitHub.
- `jsonc` -> `json` (1 fence). The block has no comments or trailing
commas, so it doesn't need the comments-capable grammar.
- `ts` -> `tsx` (2 fences, `docs/about/contributing/frontend.md`).
Verified the actual content tokenizes identically under both grammars,
and a sibling block in the same file already needs `tsx` for real JSX,
so unifying to one tag is safe for this file. Documented a caveat: `tsx`
mis-tokenizes the legacy angle-bracket type-assertion syntax
(`<Type>value`), which is invalid in real `.tsx` files anyway, so use
`value as Type` instead.
- `yml` -> `yaml` (1 fence)
- Updated `docs/.style/style-guide/formatting.md` to document all
canonical tags

`promql` (2 fences) and `caddyfile` (2 fences) are left as-is. Shiki
doesn't bundle a grammar for either, so they need a custom grammar
registration when the site adopts Shiki, rather than degrading to `txt`.
Tracked as follow-up work under DOCS-118 and
[DOCS-544](https://linear.app/codercom/issue/DOCS-544/vendor-a-local-promql-grammar-for-shiki-syntax-highlighting)
(promql).

Does not touch `offlinedocs/`.

Linear:
[DOCS-476](https://linear.app/codercom/issue/DOCS-476/normalize-docs-code-fence-languages-de-risk-shikifumadocs)

<details>
<summary>How the fence tags were verified</summary>

Each tag was tested against a real `shiki@latest` highlighter instance
(`codeToHtml`/`codeToTokens`) and cross-checked against GitHub's
`@wooorm/starry-night` grammar sources (the renderer that actually
displays these `.md` files today, in repo browsing and PR diffs), since
that's what determines whether brevity is safe before Shiki adoption:

```text
FAIL  env        -- Language `env` is not included in this bundle.
FAIL  Dockerfile -- Language `Dockerfile` is not included in this bundle.
FAIL  promql     -- Language `promql` is not included in this bundle.
FAIL  caddyfile  -- Language `caddyfile` is not included in this bundle.
FAIL  pwsh       -- Language `pwsh` is not included in this bundle.
FAIL  output     -- Language `output` is not included in this bundle.
```

`hcl` doesn't error in Shiki, since it's a real grammar, but that's
exactly the trap: it was silently rendering every fence with the generic
HCL grammar instead of the Terraform-specific one. Every `hcl`-tagged
fence in `docs/**` was manually checked against `origin/main` and is
genuinely Terraform content.

For `ts`/`tsx`, tokenizing the actual doc content confirmed identical
output under both grammars; a synthetic test with the legacy
angle-bracket cast syntax confirmed `tsx` degrades on that specific
construct, which the style guide now calls out.

The first normalization pass only matched fence tags at column 0
(`^```tag$`), missing tags indented inside numbered/bulleted lists. A
follow-up pass caught the remaining occurrences at any indentation
level.

</details>


---

*This PR description and the underlying changes were prepared with Coder
Agents assistance.*
2026-07-15 14:07:09 -04:00
Paweł Banaszewski 3126306598 feat: add --aigateway-proxy-target flag (#27122)
Adds `--aigateway-proxy-target` option to
`deploymentGroupAIGatewayProxy` that defines URL to which intercepted
requests should be forwarded to.
Forward URL used to be hardcoded to `coderAPI.AccessURL` pointing to
embedded Gateway. With addition of standalone AI Gateway this needs to
be configurable.

Renamed `aibridgeproxyd.Server.coderAccessURL` and `coderAccessPort` ->
`gatewayURL` and `gatewayPort` + option to better reflect reality.
2026-07-14 16:40:22 +00:00
Michael Suchacz 55b06f14a3 feat: allow overriding advisor reasoning effort (#27196) 2026-07-14 11:01:51 +02:00
Michael Suchacz 6f6d7539c8 feat: remove unused chat statuses pending, paused, and completed (#27064)
The chatd state machine only recognizes `waiting`, `running`, `error`,
`requires_action`, and `interrupting`. Remove the unused `pending`,
`paused`, and `completed` values from the database enum, backend, SDK,
frontend, generated queries, and API docs.

Migration `000543_chat_status_remove_unused` remaps existing `pending`
rows to `running`, remaps `paused` and `completed` rows to `waiting`,
drops the obsolete `idx_chats_pending` index, and recreates
`chats_expanded` around the enum swap. It also removes the dead
`AcquireChats` query and all remaining query literals for the deleted
statuses.

**NOTE**: The enum swap can break chat queries from older replicas
during a mixed-version rollout because they still reference
`'pending'::chat_status`. Chats are experimental, so this PR accepts
that limited rollout window instead of adding a two-release expand and
contract sequence.

> This PR was authored by Mux (AI agent) on Mike's behalf.
2026-07-13 20:28:28 +02:00
Nick Vigilante 199b5936c1 fix(docs): replace invalid </br> tags and format swallowed placeholder URL (#27174)
## Summary

Fixes two classes of invalid/broken HTML in hand-written docs. Both are
visible problems in today's rendered docs, independent of any
docs-engine work.

1. **`</br>` is not a real HTML tag.** `br` is a void element with no
closing form; browsers error-correct `</br>`, but it is invalid HTML.
Replaced all 15 usages with `<br />` across:
   - `docs/admin/templates/extending-templates/dynamic-parameters.md`
   - `docs/admin/users/idp-sync.md`
   - `docs/tutorials/best-practices/organizations.md`
2. **Browser-swallowed placeholder URL.** In
`docs/ai-coder/github-to-tasks.md`,
`https://<your-coder-url>/settings/external-auth` was unformatted, so
HTML renderers parse `<your-coder-url>` as an unknown tag and drop it.
The live docs currently render the broken text `re-authenticate at
https:///settings/external-auth`. Wrapped in backticks, matching every
other instance in the same file.

Table realignment noise in the diff is from `fmt/markdown` (`<br />` is
one character wider than `</br>`).

A repo-wide grep confirms no remaining `</br>` and no other unformatted
`https://<placeholder>` URLs in prose (other hits are inside code fences
or already backticked). The equivalent placeholder issues in
**generated** reference docs (CLI help strings, swagger annotations) are
intentionally out of scope and tracked separately in
[DOCS-551](https://linear.app/codercom/issue/DOCS-551/backtick-placeholder-syntax-in-generated-reference-docs-cli-help).

Tracking issue:
[DOCS-550](https://linear.app/codercom/issue/DOCS-550/fix-invalid-br-tags-and-browser-swallowed-placeholder-url-in-hand)

---

Created by Coder Agents on behalf of @nickvigilante.
2026-07-13 10:41:38 -04:00
Thomas Kosiewski 9af3d31036 fix: relabel advisor max uses setting from per run to per turn (#27046) 2026-07-10 09:36:12 +02:00
Cian Johnston 14767dfa8e feat: explain missing POSIX sh on Windows workspaces (#27048)
When a workspace has no POSIX sh on PATH (typical for fresh Windows workspaces), the execute tool fails with a raw `exec: "sh": executable file not found in %PATH%` error the model cannot act on. 

This change:
- Enriches the above error in chattool with remediation steps and a docs link.
- Documents the requirement in the Coder Agents architecture page.

> This PR was generated by Coder Agents on behalf of @johnstcn
2026-07-07 21:32:27 +00:00
Danielle Maywood 7c78698a6d feat: notify users when chats are shared (#26914) 2026-07-06 13:15:58 +01:00
Yevhenii Shcherbina 121107f151 docs: document the Bedrock external ID for role assumption (#26973)
Document the Bedrock external ID for role assumption.
2026-07-02 19:06:16 +00:00
Danny Kopping e3ac65aa5f docs: add AI Gateway rebranding migration guide (#26854)
## Summary

Adds an operator-facing migration guide for the AI Bridge to AI Gateway
rebrand, as a new docs page under **AI Coder > AI Gateway** (last child
in the section).

The guide documents:

- **Config aliases** (env vars, CLI flags, YAML group keys): old
`aibridge` names still work as hidden, deprecated aliases; new
`ai_gateway` names are canonical. Includes full env-var mapping tables
and the mechanical substitution rules.
- **HTTP API**: canonical path is now `/api/v2/ai-gateway`; legacy
`/api/v2/aibridge` routes retained.
- **Metrics**: prefixes renamed `coder_aibridged_*` ->
`coder_ai_gateway_*` and `coder_aibridgeproxyd_*` ->
`coder_ai_gateway_proxy_*`. Both old and new names are emitted today, so
dashboards keep working; guidance to migrate before the old names are
removed, plus an optional `metric_relabel_configs` drop snippet.
- **No database changes** and no required config changes to upgrade.

Implements the docs/release-notes portion of
[AIGOV-240](https://linear.app/codercom/issue/AIGOV-240) (parent:
[AIGOV-207](https://linear.app/codercom/issue/AIGOV-207)).

## Notes

- Content reflects what actually shipped in the codebase (metrics are
*aliased*, not hard-renamed), which differs from the original RFC that
assumed a hard rename.
- Registered in `docs/manifest.json` with `state: ["ai governance
add-on"]` to match sibling pages.


---

*This PR was produced by opencode (agent) using the
`anthropic/claude-opus-4-8` model, under human direction and review.*

---------

Signed-off-by: Danny Kopping <danny@coder.com>
2026-07-01 10:54:19 +02:00
Danielle Maywood 6b8c38b5a4 fix: gate chat advisor and virtual desktop behind experiments, delete experiments page (#26809) 2026-06-30 21:57:40 +01:00
Mathias Fredriksson 2fd5ae4323 fix: stop Agents dead-ending on unsupported providers (#26841)
Configuring only a GitHub Copilot provider left the Agents page stuck on
"set up a provider then add a model", even with a provider and models
configured. The catalog dropped any provider type that NormalizeProvider
did not recognize, so a Copilot-only deployment looked identical to an
empty one and never unlocked the page.

The Agents harness cannot use Copilot: it needs a per-request token only
an official Copilot client can mint, and the harness is not one. Instead
of dropping such providers, the catalog now reports them as unsupported
so the UI can explain the dead end and point elsewhere, rather than ask
for setup that already happened. The providers stay usable through the
AI Gateway proxy.

Support is derived from the provider type, not stored, so there is no
migration. codersdk.IsAgentsUnsupportedProviderType is the single source
of truth, consulted by the chatd catalog and, through the generated
AgentsUnsupportedProviderTypes list, the frontend.

The diff also carries unrelated modernization of nearby db2sdk and
chatprovider helpers (slices.SortFunc, strings.Cut, range-over-int).

Closes CODAGT-627
Refs CODAGT-256
Refs CODAGT-682
2026-06-30 18:49:50 +03:00
Nick Vigilante 89b0a66079 docs: add top-level Get started section and move the Quickstart (#26821)
Add a top-level "Get started" docs section to the nav and move the Quickstart to /docs/get-started, with inbound link updates and the install page TIP pointing to the Quickstart.

Filed via Coder Agents on Nick's behalf.
2026-06-29 16:07:10 -04:00
TJ 5f42bbcdbf feat(site/src): nest agent pages under a Coder Agents subsection in AI nav (#26667)
Groups the agent-related AI settings pages under a new **Coder Agents**
parent in the sidebar, with a continuous left rule connecting the
children and an active-segment indicator that lights up the rule where
the current sub-item sits.

The new nav order:

- AI Governance
- AI Gateway keys
- Providers
- Coder Agents
  - Models
  - MCP servers
  - Templates
  - Spend
  - Instructions
  - Lifecycle

All target pages already exist on main (Danielle's recent migrations of
Models, MCP servers, Templates, Instructions, Lifecycle, Spend, and
Coder Agents into AI Settings). This PR only changes the sidebar visual
structure: the children move into an indented group with a `border-l
border-l-border` rule, and the active child paints a
`border-l-content-primary` segment over that rule via `-ml-px` so the
rule and indicator share a column instead of stacking.

<details>
<summary>Design notes</summary>

Concept 1 from the earlier exploration: always-expanded with indents,
the parent is its own page. Chosen because it adds no expand/collapse
state, no "which child is the default" question, and no animation work;
the parent reuses the existing nav-item, and the children sit in a
wrapper `div` with a left rule. The site bundle ships without Tailwind's
preflight, so the wrapper and sub-item borders are paired with
`border-solid` to actually paint, matching the pattern already in
`Sidebar.tsx`.

</details>

---

_This PR was prepared by Coder Agents on behalf of @tracyjohnsonux._
2026-06-29 13:46:09 +00:00
Ben Potter 73cd34cc5f fix: correct MCP registry remote URL in server.json (#26755)
The MCP Registry rejects our `server.json` remote because the URL uses
`{coder_url}` as the entire base. Registry validation requires remote
URLs to literally begin with `https://`, and template variables are only
allowed after the scheme/host. The previous value
(`{coder_url}/api/experimental/mcp/http`) fails both the JSON schema
`^https?://[^\s]+$` pattern and the semantic remote-URL check.

## Changes

- Use `https://{coder_hostname}/api/experimental/mcp/http` with a
`coder_hostname` variable (users now enter a hostname like
`coder.example.com` instead of a full URL).
- Update the VS Code registry instructions in
`docs/ai-coder/mcp-server.md` to ask for the deployment hostname.

Verified with `mcp-publisher validate` against
`registry.modelcontextprotocol.io`:

```
Validating against https://registry.modelcontextprotocol.io...
 server.json is valid
```

This was caught by running the `Publish to MCP Registry` workflow in
validate-only mode (`publish: false`) before any real publish, so
nothing broken reached the public registry.

<details>
<summary>Root cause detail</summary>

The registry validator (`internal/validators`) substitutes known
template variables, then parses the URL. Because `{coder_url}` replaces
the whole scheme+host, the parsed URL has no scheme and is rejected as
an invalid remote URL. Hard-coding `https://` and scoping the variable
to the host satisfies both the schema pattern and `IsValidRemoteURL`
(which also requires `https`). The registry mandates `https` for remotes
regardless, so there is no loss of functionality.

</details>

---
_Generated with Coder Agents._
2026-06-26 16:32:32 +00:00
Atif AliandBen Potter 18efcb6c41 feat: publish Coder MCP server to official MCP Registry (#21673)
## Summary

This adds the necessary configuration to publish Coder's remote MCP
server to the official MCP Registry at registry.modelcontextprotocol.io.

## Changes

- **`server.json`**: MCP server metadata for registry discovery
- **`.github/workflows/publish-mcp-registry.yaml`**: GitHub Actions
workflow to automatically publish on release

## How it works

1. When a new Coder release is published, the workflow automatically
publishes to the MCP Registry
2. MCP clients (Claude, ChatGPT, VS Code, etc.) can discover Coder via
the registry
3. Users just need to provide their Coder deployment URL - OAuth handles
authentication automatically via RFC 7591 Dynamic Client Registration

## MCP Registry Entry

The server will be listed as `io.github.coder/coder` with:
- **Transport**: `streamable-http` 
- **Endpoint**: `{coder_url}/api/experimental/mcp/http`
- **Auth**: OAuth2 (automatic via
`/.well-known/oauth-authorization-server`)

## Testing

After merge and next release, verify at:
```bash
curl "https://registry.modelcontextprotocol.io/v0.1/servers?q=io.github.coder"
```

Closes #21275

---
_Generated with `mux` • Model: `anthropic:claude-opus-4-5` • Thinking:
`medium`_

---------

Co-authored-by: Ben Potter <me@bpmct.net>
2026-06-26 11:20:45 -05:00
Mathias Fredriksson 59fcc9c0ad feat: improve sub-agent orchestration tools (#26673)
Tool errors caused orchestrators to abandon spawned agents. Bare error
responses and the close_agent name framed delegation as one-shot: one
transient failure or timeout ended the work, and the orchestrator had no
way to recover or reuse agents.

Renames close_agent to interrupt_agent with a hidden backward-compatible
alias. wait_agent and message_agent return structured payloads instead
of bare errors, so the orchestrator can retry after a timeout, recover
from an error status, or redirect an idle agent. Adds list_agents so
orchestrators can rediscover spawned agents. Adds root-only
orchestration guidance for error recovery.
2026-06-26 13:41:43 +03:00
Kyle Carberry 48fd0ef4bc feat: return workspace skill directory from read_skill (#26713)
Workspace skills live on the workspace filesystem, and the agent's read_file
and execute tools already operate there. read_skill now returns "dir", the
absolute skill directory, for workspace skills, so the agent can read or run
bundled supporting files (for example a scripts/ helper) with the workspace
tools. The field is omitted for personal skills, which are database-backed and
have no files. read_skill_file is unchanged.

Generated with Coder Agents on behalf of @kylecarbs.
2026-06-25 12:05:54 -06:00
Susana Ferreira a1921b6bc0 docs: update AI Gateway URLs from /aibridge to /ai-gateway (#26664)
## Description

Updates documentation to use the new `/api/v2/ai-gateway/` URLs and
`/ai-gateway/` UI paths, following the backend rename in #26475 and
frontend route rename in #26569.

## Changes

- Update URL references across documentation files from
`/api/v2/aibridge/` to `/api/v2/ai-gateway/`
- Update UI path reference from `/aibridge/sessions` to
`/ai-gateway/sessions`
- Update route path references in client setup guides
- Covers client setup guides, authentication, monitoring, proxy setup,
and provider configuration

Addresses
https://github.com/coder/coder/pull/26475#issuecomment-4768351217

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

> Generated with the assistance of Coder Agents (@ssncferreira)
2026-06-25 19:02:39 +01:00
Yevhenii ShcherbinaandClaude Opus 4.8 7d60cbf09b docs: document Bedrock IAM role assumption (#26703)
Document the optional Role ARN field on Bedrock providers, which has the
gateway assume an IAM role via STS before calling Bedrock. Covers the
permissions the assumed role requires and the trust policy.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 16:23:58 +00:00
Danielle Maywood 1ae96fcf8a fix!: prevent AI provider name collision with static settings routes (#26688)
Move the providers routes into a dedicated providers sub-tree: `/ai/settings/providers`, `/ai/settings/providers/add`, and `/ai/settings/providers/:providerId`.

The old `/ai/settings/:providerId` and `/ai/settings/add` URLs are
removed without backward-compatibility redirects. Bookmarked or shared
links to these paths now return a 404. Creating a provider with id `models` (although unlikely) made it impossible to edit it due to a conflict with the static models route.
2026-06-25 11:09:58 +01:00
Cian Johnston 2d28c1b396 feat: surface template README to agent template tools (#26334)
Fixes CODAGT-447.

Alternative implementation of https://github.com/coder/coder/pull/26212
and https://github.com/coder/coder/pull/25978

- Adds up to the first 1000 characters of `README.md` (with leading
frontmatter stripped) to `chattool.list_templates` output
- Adds up to 800 characters of `README.md` to `chattool.read_template`.

**Note:** skipping `toolsdk` versions to keep scope small.

> 🤖 Generated by Coder Agents
2026-06-24 12:32:46 +01:00
Danielle Maywood 85652554f9 feat: move MCP servers to AI settings (#26642) 2026-06-24 12:30:15 +01:00
Danielle Maywood 3133a8b9c6 feat: move instructions to AI settings (#26624) 2026-06-24 12:29:58 +01:00
Danielle Maywood ecfff8a7db feat: move model settings page to ai settings 2026-06-23 12:33:28 +01:00
Susana Ferreira 970bd73691 feat: add /api/v2/ai-gateway API route aliases (#26475)
## Description

Registers `/api/v2/ai-gateway/*` as the new API path for AI Gateway, replacing `/api/v2/aibridge/*`. Both prefixes share the same route builder (`aiBridgeRoutes`) backed by a single in-memory handler, so existing `/aibridge` endpoints continue to work. New endpoints must be registered on the enterprise API handler under `/api/v2/ai-gateway` only.

Swagger annotations now point to `/api/v2/ai-gateway` paths with a backward-compatibility note referencing `/aibridge`. The legacy `/aibridge` routes are skipped in the swagger documentation test.

## Changes

- Store one raw handler (`aiGatewayHandler`) instead of two prefix-stripped handlers
- Register `/ai-gateway` and `/ai-gateway/proxy` route aliases alongside legacy `/aibridge` routes
- Move `/aibridge/keys` to `/ai-gateway/keys`
- Update in-process transport to use `/api/v2/ai-gateway` prefix
- Update SDK client URLs and proxy forwarding URL
- Swap `@Router` and `@Tags` annotations from `aibridge`/`AI Bridge` to `ai-gateway`/`AI Gateway`
- Rename user-facing error messages from "AI Bridge" to "AI Gateway"
- Define consts for route prefixes (`AIGatewayRootPath`, `AIBridgeRootPath`)
- Update tests and comments to use new paths

Note: the following will be addressed in follow-up PRs:
- Frontend API URLs
- Frontend routes and redirects
- Dogfood main.tf updates
- Hand-written documentation URL updates
- aibridge internal comments and nits
- Scale tests path updates

Refs https://linear.app/coder/issue/AIGOV-230

> Generated with the assistance of Coder Agents (@ssncferreira)
2026-06-23 12:15:10 +01:00
Danny KoppingandNick Vigilante bd893a4504 docs: restore Bedrock static credentials walkthrough (#26563)
## Summary

Restores the step-by-step "Obtaining static Bedrock credentials"
walkthrough that was present on the v2.32.6 `ai-bridge/setup` page but
missing from the current `ai-gateway/providers` page.

The current page mentions static credentials in a single line but no
longer explains how to create the IAM user and access key in the AWS
console. This PR brings back that walkthrough, adapted to the current
database/dashboard-managed provider flow.

## Changes

- Add an `#### Obtaining static Bedrock credentials` subsection under
the Amazon Bedrock provider section in
`docs/ai-coder/ai-gateway/providers.md`.
- Keep the AWS console steps (choose region, generate API keys, create
access key) from v2.32.6.
- Replace the deprecated `CODER_AIBRIDGE_BEDROCK_*` environment-variable
configuration step with guidance to enter the credentials when
adding/editing the provider via the dashboard or AI Providers API,
matching the post-v2.34 database-managed model.

<details>
<summary>Context and decisions</summary>

- Source: [`docs/ai-coder/ai-bridge/setup.md` at
v2.32.6](https://coder.com/docs/@v2.32.6/ai-coder/ai-bridge/setup)
"Obtaining Bedrock credentials" section.
- The old flow set provider config via environment variables, which are
deprecated since v2.34 (providers are now stored in the database and
managed via dashboard/API). The restored content keeps the AWS-side
credential-creation steps but routes the final configuration step
through the current provider management flow rather than env vars.
- Open questions from
[AIGOV-432](https://linear.app/codercom/issue/AIGOV-432/restore-bedrock-static-credentials-docs-from-v2326)
(whether other pages also need this, and whether the content needs
further accuracy updates) are left for review.

</details>

Closes
[AIGOV-432](https://linear.app/codercom/issue/AIGOV-432/restore-bedrock-static-credentials-docs-from-v2326).

> [!NOTE]
> This PR was generated by Coder Agents on behalf of @dannykopping.

---------

Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-06-22 15:51:18 +00:00
Nick Vigilante e458692cb8 refactor(docs): convert absolute coder/coder blob/tree/main links to relative (DOCS-351) (#26341)
Closes [DOCS-351](https://linear.app/codercom/issue/DOCS-351).

> [!WARNING]
> **DO NOT MERGE** until
[DOCS-349](https://linear.app/codercom/issue/DOCS-349)
([coder.com#877](https://github.com/coder/coder.com/pull/877)) has
shipped to production and baked for at least one Vercel cycle.
>
> Without DOCS-349, the relative links in this PR resolve to broken
docs-route URLs (`/docs/helm/coder/values.yaml` -> 404) instead of
GitHub URLs tagged with the displayed docs version. DOCS-349 fixes the
rewriter to classify these as GitHub blob/tree URLs with the page's
resolved ref.

## TL;DR

Converts 121 absolute
`https://github.com/coder/coder/(blob|tree)/main/<path>` links across 39
docs markdown files to relative paths. After this lands AND DOCS-349
deploys, every one of these links will follow the displayed docs version
(mainline tag on bare URLs, explicit tag on `/@vX.Y.Z/`, `main` on
`/@main/`) instead of always pointing to `main`.

## Why

Today a reader on `/docs/@v2.30.0/install/docker` follows a
`compose.yaml` link and arrives at `main`'s `compose.yaml`, which
doesn't necessarily match what the docs page describes. Helm values,
Terraform templates, and source-code references in particular drift
across versions. The fix is to let the coder.com rewriter substitute the
page's resolved ref into the URL; that only works on relative links.

## Example payoff (post-DOCS-349)

| URL | Today (absolute, always `main`) | After (relative + rewriter) |
|---|---|---|
| `/docs/install/docker` |
`https://github.com/coder/coder/blob/main/compose.yaml` |
`https://github.com/coder/coder/blob/v2.34.1/compose.yaml` (today's
mainline) |
| `/docs/@v2.30.0/install/docker` | same as above |
`https://github.com/coder/coder/blob/v2.30.0/compose.yaml` |
| `/docs/@main/install/docker` | same as above |
`https://github.com/coder/coder/blob/main/compose.yaml` |

## Scope

- **121 conversions** across **39 files**.
- Verb breakdown: `tree/main` (directories) and `blob/main` (files),
both flipped to relative paths.
- Line anchors (`#L23-L24`) and query strings preserved verbatim.
- Conversion is mechanical: relative path computed from the doc file's
directory to the target via `os.path.relpath`. Any path starting at the
same directory or below gets a `./` prefix; otherwise `../` chains.

## Rebased on main

The branch was rebased onto `main` after the DOCS-350 hotfix
([#26339](https://github.com/coder/coder/pull/26339)) merged. The hotfix
repointed 3 `docs-backend-contrib-guide` refs in `backend.md` to `main`,
which then needed the same `main` -> relative conversion this PR is
doing for the other 121 links. The conflict was resolved by reapplying
the mechanical conversion to `backend.md` after taking the hotfix's
content. Net result: those 3 links land here as relative, same as
everything else. New HEAD `3f501cb622`.

## Inline fix folded in: dead `nix` link

- `docs/about/contributing/CONTRIBUTING.md:7` -> `../../../nix`

The original absolute URL `https://github.com/coder/coder/tree/main/nix`
already returned 404 today. Repointed to `flake.nix` (modern Nix
entrypoint, what the prose "Nix environment" semantically refers to).
Closes [DOCS-357](https://linear.app/codercom/issue/DOCS-357) here since
the `check-docs` Linkspector job surfaced it during rebase; cheaper to
fix inline than in a separate single-line PR.

## Out of scope (filed separately)

- [DOCS-350](https://linear.app/codercom/issue/DOCS-350): 3 dead
`docs-backend-contrib-guide` branch refs in `backend.md`
([#26339](https://github.com/coder/coder/pull/26339), merged).
- [DOCS-352](https://linear.app/codercom/issue/DOCS-352): 10 SHA-pinned
`(blob|tree)/<sha>` links pending intent review.
- [DOCS-355](https://linear.app/codercom/issue/DOCS-355): code-server
analog (4 absolute `(blob|tree)/main` links in `coder/code-server`).
- [DOCS-356](https://linear.app/codercom/issue/DOCS-356): 2 upstream
content bugs in `coder/code-server/docs/CONTRIBUTING.md` (independent of
this PR).


## Not triggering `/coder-agents-review`

Docs-only edit; per `AGENTS.md` the bot review is reserved for
product/CI changes.

## Pre-mortem

| Concern | Mitigation |
|---|---|
| Merging before DOCS-349 deploys regresses ~120 currently-working links
into 404s on coder.com | Clear DO-NOT-MERGE banner; tracked as blocker
in Linear. |
| Relative path computed incorrectly (off-by-one `..`) | Verified all
114 newly-relative non-md/non-image paths resolve to existing files in
the repo (only exception is the pre-existing dead `nix` link above). |
| Line anchors stripped during conversion | Preserved by the
substitution regex; verified `#L<n>-L<m>` cases in `airgap.md` and
`speed-up-templates.md`. |
| Future code reorgs change file locations | Relative links will start
pointing to nothing. Same failure mode as absolute links pointing to
renamed files; can be caught with a future link-checker job. |

## Validation

```
$ grep -rE 'github\.com/coder/coder/(blob|tree)/main' docs --include="*.md" | wc -l
0
$ git diff --stat origin/main | tail -1
39 files changed, 118 insertions(+), 118 deletions(-)
```

114 newly-relative paths verified to resolve to existing repo files
(Python `os.path.exists` check on each computed target).

<details>
<summary>Decision log + planning context</summary>

**Why relative over `(blob|tree)/{{currentDocsVersion}}/...`
templating**: relative paths require zero markdown-system support and
zero upstream churn beyond this one PR. Templating would require a
preprocessor on `coder.com` side AND a convention upstream authors have
to remember; relative paths just work in a plain editor and
`github.com`'s own renderer too.

**Why `./` prefix on same-directory targets**: makes the conversion
grep-able later (`grep -E '\((\.\./|\./)'`).

**Why preserve `#L<n>-L<m>` anchors verbatim**: the anchor is meaningful
to the linked file's content, not to the URL form; keeping it as-is
preserves authorial intent. If the file later changes such that the line
range drifts, that's a different problem the SHA-pin audit
([DOCS-352](https://linear.app/codercom/issue/DOCS-352)) will surface.

</details>

---

*Generated by Coder Agents on @nickvigilante's behalf.*





## Drive-by external link fix folded in

`docs/about/contributing/CONTRIBUTING.md:296` cited
`https://reflectoring.io/meaningful-commit-messages/` which is returning
HTTP 503 (the host appears to be down site-wide right now). `check-docs`
Linkspector flagged it after the rebase. Replaced with
`https://cbea.ms/git-commit/` (Chris Beams' canonical "If applied, this
commit will..." article, confirmed 200), which is the original source of
the rule the prose recites anyway.
2026-06-22 11:39:12 -04:00
Danny Kopping 4f8acfaeff docs: add Codex WebSocket fallback troubleshooting (#26565)
## Summary

Adds a Troubleshooting section to the Codex CLI AI Gateway client docs
covering the WebSocket-to-HTTPS transport fallback.

Recent Codex CLI versions default to the WebSocket runtime for the
Responses API. AI Gateway does not support WebSocket transport, so each
request attempts a WebSocket connection, fails, and falls back to HTTPS,
surfacing:

```text
Falling back from WebSockets to HTTPS transport.
```

The doc explains the cause and the fix: set `supports_websockets =
false` in the `[model_providers.ai_gateway]` block in
`~/.codex/config.toml` to force HTTPS directly and remove the fallback
delay.

Closes
[AIGOV-453](https://linear.app/codercom/issue/AIGOV-453/document-codex-cli-websocket-fallback-workaround).

<details>
<summary>Note on the config value</summary>

The original request and the Linear issue referenced enabling websocket
support / `support_websockets = false`. The authoritative Codex CLI
[config reference](https://developers.openai.com/codex/config-reference)
confirms:

- The key is `supports_websockets` (trailing "s").
- It declares whether a provider supports the Responses API WebSocket
transport.
- Setting it to `false` is the documented workaround to force HTTPS and
stop the fallback attempts.

Since AI Gateway does not support WebSockets, `supports_websockets =
false` is the correct value. `= true` would assert support that does not
exist and keep the fallback happening.

</details>

---

This PR was generated by Coder Agents on behalf of @dannykopping.
2026-06-22 11:56:58 +02:00
Jaayden Halko bc44cdda75 feat: rank chat workspace templates (#25037)
closes CODAGT-203

## Summary

`list_templates` now returns a ranked shortlist with a recommendation,
so the chat agent can pick the right template the way a colleague would:
prefer what matches the request, what the user already uses, and what
the rest of the organization uses. Instead of teaching the model an enum
protocol in prompts, every result carries a fixed `next_step`
instruction telling the agent what to do.

## How list_templates works

1. **Fetch**: active, non-deprecated templates in the chat's
organization, filtered by the admin template allowlist, authorized as
the chat owner (no system escalation).
2. **Query relevance** (optional `query` argument): each template
receives the highest tier any of its fields matches, and a higher tier
always outranks a lower one regardless of usage:

   | Tier | Match |
   |------|-------|
   | 4 | name or display name equals the query |
   | 3 | name or display name starts with the query |
   | 2 | name or display name contains the query |
| 1 | description contains the query (checked only when no name field
matched) |
   | 0 | no match; the template is excluded |

Matching is case-insensitive and ignores spaces/hyphens/underscores
(`python gpu` matches `python-gpu`).
3. **Usage signals**: a new `GetTemplateRankingSignalsByOwnerID` query
returns, per template, the owner's active and recently-deleted workspace
counts within a 60-day window, the last in-window usage, and the count
of distinct developers with an active workspace (unclaimed prebuilds
excluded).
4. **Affinity score** (computed in Go, per template, from that
template's signals only):

   ```text
affinity = 10 x (active + 0.5 x deleted) x 0.5^(days_since_last_use /
14)
            + ln(1 + active_developers)
   ```

`active`/`deleted` are the owner's in-window workspace counts,
`days_since_last_use` is measured from the most recent in-window usage
(the personal term is zero without in-window usage), and
`active_developers` is the org-wide count. Personal usage carries 10x
the weight of org popularity; the confidence floor is the score of two
active developers (`ln 3`) and the required lead over the runner-up is
`ln 3 - ln 2`.
5. **Rank**: query tier first (when a query is present), then affinity
score, then name/ID for determinism. Results paginate 10 per page with
`next_page` present only when more exist.

## Recommendation contract

The result tells the agent what to do next instead of describing
confidence levels:

- `recommended_template_id` is present only when the top template is a
clear winner: the only available template, a decisive query match, or an
affinity score that clears a floor and leads the runner-up by a derived
margin.
- `next_step` is always present and is one of four fixed sentences: use
the recommendation, ask the user to choose, retry a query that matched
nothing, or report that no templates are available.

Per-template items carry raw evidence (`active_developers`,
`your_workspace_count`, `last_used_by_you`) rather than derived labels.
When signals fail to load, the tool logs and degrades to asking the user
unless the query alone is decisive.

Prompts and the `create_workspace`/`read_template` descriptions
reference the field through the `chattool.NextStepField` constant, so
the instruction lives in one place and cannot drift. `create_workspace`
remains idempotent and allowlist-enforced.

## Authorization

The signals query runs with the chat owner's permissions: reading the
owner's own workspaces plus a template-metadata read for the cross-user
popularity count. dbauthz rejects the call if any requested template is
not readable by the owner (covered by allow and deny method tests).

## Docs

Adds `docs/ai-coder/agents/tools/` explaining how agent tool calls work,
with `list_templates` ranking and the `next_step` contract as the first
documented tools.
2026-06-18 06:41:47 +01:00
Paweł Banaszewski d00958d464 chore: improve AI Gateway Proxy documentation (#26269)
Adds

diagram showing how AI Bridge Proxy works in tunnel and MITM modes.
diagram showing how AI Bridge Proxy integrates with upstream proxies.
Extends Troubleshooting section.
Adds a registry link for the AI Bridge Proxy module for Coder
workspaces.
2026-06-17 15:39:36 +00:00
Paweł Banaszewski f1ce1013c4 chore: export AI Gateway metrics under new branding + keep old as alias (#26413)
> AI Tools where used in this request.

Registers `coder_aibridged_*` and `coder_aibridgeproxyd_*` metrics under
new prefixes: `coder_ai_gateway_*` and `coder_ai_gateway_proxy_*`.
Old prefix is still exported. Will be removed in later release.

Also updated the `metricsdocgen` static fixture. Added 4
previously-undocumented metrics `key_pool_state`,
`key_pool_state_transitions_total`, `key_pool_exhaustions_total`,
`key_pool_failover_attempts` added the `client` label to the existing
interception, prompt, and token counter samples.

Updated AI Gateway documentation.
2026-06-17 13:10:53 +02:00
35C4n0randAtif Ali 28e83471b3 docs(docs/ai-coder/agent-firewall): fix firewall examples for claude-code v5.x (#26373)
The Agent Firewall docs had a Terraform example using `enable_boundary =
true` on the `claude-code` module at v5.2.0. That input was removed in
the v5.x refactor.

Update the getting-started and configuration examples to use the
standalone `agent-firewall` module
(`registry.coder.com/coder/agent-firewall/coder`), which is the correct
integration point for v5.x. The config is now passed via
`agent_firewall_config` (inline YAML or `file()` reference) instead of a
manual `coder_script` that base64-decoded a file into
`~/.config/coder_boundary/`.

Closes:
[REG-13](https://linear.app/codercom/issue/REG-13/docs-example-uses-nonexistent-enable-boundary-input)

> Generated by Coder Agents

---------

Co-authored-by: Atif Ali <atif@coder.com>
2026-06-15 18:28:11 +05:30
Ben Potter ba776a61e5 docs(docs/ai-coder/ai-gateway): document ChatGPT provider setup for Codex BYOK (#26348)
Following the BYOK (ChatGPT Subscription) instructions in `codex.md` on
a deployment without a ChatGPT provider fails with `404 route not
supported: POST /chatgpt/v1/responses`. The
`/api/v2/aibridge/chatgpt/v1` route only exists when an admin has
created a provider named `chatgpt`, and that requirement wasn't
documented anywhere.

## Changes

- `providers.md`: new **ChatGPT** subsection alongside the other
per-provider sections: type `openai`, name must be exactly `chatgpt`,
base URL `https://chatgpt.com/backend-api/codex`, no API keys (auth
comes from each user's ChatGPT OAuth token via BYOK)
- `codex.md`:
- prerequisite admonition in the ChatGPT Subscription section linking to
the provider setup, with the 404 symptom for troubleshooting
- template recipe for the ChatGPT subscription flow (`base_config_toml`
+ `coder_env` injecting `CODER_API_TOKEN`), since the existing recipe
only covers the centralized API key flow
  - bump the codex module pin from `~> 4.1` to `~> 5.0` (latest is 5.1)

## Verification

- All three gaps were hit and the documented configuration verified
end-to-end on a live deployment: provider created via the AI Providers
API, Codex CLI 0.139.0 authenticated with ChatGPT login, sessions
visible in the AI Sessions UI
- `pnpm run format-docs` and `pnpm run lint-docs` clean (0 errors),
`pre-commit-light` hooks passed

Linear: [DOCS-354](https://linear.app/codercom/issue/DOCS-354)

🤖 Generated with Coder Agents on behalf of @bpmct
2026-06-12 12:39:16 -05:00
Danielle Maywood 79a28bad72 feat(site): group shared agents in sidebar (#26328) 2026-06-12 12:39:53 +01:00