Commit Graph
197 Commits
Author SHA1 Message Date
7c7e2e73cf feat: honor disable-model-invocation in uploaded skill content (#31159)
Addresses @ethanndickson's [review comment on
#30882](https://github.com/coder/coder/pull/30882#discussion_r4344815088):
the same `SKILL.md` file could be manual-only in Claude Code and the
project dialog but automatic in Coder, because the server and the
browser each handled `disable-model-invocation` in their own way.

The server now owns the key for personal, organization, and project
skills:

- When a create or update request leaves `model_invocable` unset,
`disable-model-invocation: true` in the content turns automatic use off,
and `false` turns it back on. The key is read with the function
workspace skills use, so a file gets the same setting in both places.
Only YAML booleans count, so a quoted `"true"` is ignored.
- An explicit `model_invocable` in the request always wins.
- New content without the key leaves the setting unchanged, so editing
text never turns it back on.
- Content is stored as uploaded. Every API response returns content
whose key agrees with `model_invocable`: when the stored file says
otherwise, the server replaces the value of the key or adds the key
before the first one, and leaves every other byte alone.
- **Download** and **Export all** save the content the API returns, so
the browser no longer edits the file. `withDisabledModelInvocation` is
removed.
- An upload is rejected with a 400 when the key holds a value the server
can't replace with a boolean, such as a list. A later change to
`model_invocable` can then always reach the file.

Two edges:

- Adding the key makes the returned file about 30 bytes larger, so a
file at the 64 KB upload limit can be too large to upload again.
- A skill stored before the upload check with a value the server can't
replace is returned as stored.

Workspace skills already honor the key since #31147.

#31160, the frontend PR on top of this one, adds the switch to the
personal and organization skill editors.

> Generated by an agent on behalf of the user

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-11-18 14:04:49 +07:00
Susana Ferreira 3211ca066e feat: add organization unpriced AI models endpoint (#31753)
## Description

Adds the experimental `GET
/api/experimental/organizations/{organization}/ai/model-prices/unpriced`
endpoint behind the "N models not set up" warning on the organization AI
spend page
([Figma](https://www.figma.com/design/6TkixpkUIM5Qv6I7qhM3xZ/AI-Gov---user-spend?node-id=70-11964&t=KQwENGjcQvVT9qkh-4)).
It lists the models used in the period that still hold no price in the
organization, using the query from this stack.

## Changes

- Add the `organizationUnpricedAIModels` handler and
`ExperimentalClient.OrganizationUnpricedAIModels`:
- Reuses `aiSpendRetainedPeriod`, since token usage is subject to data
retention.
- Returns the applied period, `count`, and `models` (provider name,
display name, icon and type, model, token count), most unpriced tokens
first.
- Requires read on the organization's model prices (owners and
organization admins), so the UI only requests it for users who can set
prices.
- Add handler tests for the response, period validation, organization
scoping and role access.

Note: pagination will be added in a follow-up.

Closes AIGOV-730

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-17 15:34:04 +00:00
Jaayden Halko 4866d0fb1f feat: add display names to project skill actions (#31747)
closes CODAGT-1506

Project skill action chips show the skill's slug (`deploy-bot`,
`security-review`), because skill names must be kebab-case. This adds an
optional display name that labels the chip instead.

Project skills get a `display_name` column, set through `display_name`
on the create and update requests. It is limited to project skills (the
same rule as `action`), trimmed, single line, and at most 64 Unicode
code points. The chip, its tooltip, and the "More" menu show the display
name, sort by it, and fall back to the skill name when it is empty. When
a display name is set, the tooltip and the menu item also show the
`/name` slash command, so actions that share a display name stay
distinguishable. Clicking an action still inserts `/name`, and the `/`
menu is unchanged.

The project skill editor shows a **Display name** field under **Show as
action** only while that switch is on. Turning the switch off hides the
field but keeps its value, and saves omit `display_name` while the
action is off, so the stored value stays. The display name lives in the
database rather than SKILL.md frontmatter, so downloading and
re-importing a skill does not carry it.

To share the code-point length check with the editor, `countCharacters`
and `maxCharacters` move from `ChatProjectDialog.tsx` into
`site/src/utils/formUtils.ts`.

<img width="637" alt="Project skill editor with the Display name field
under Show as action"
src="https://raw.githubusercontent.com/coder/coder/assets/pr-skill-action-display-name/pr/edit.png"
/>

<img width="520" alt="Action chips labeled with display names, with the
tooltip open"
src="https://raw.githubusercontent.com/coder/coder/assets/pr-skill-action-display-name/pr/chips.png"
/>

Refs CODAGT-1506
2026-11-17 17:55:35 +07:00
Susana Ferreira 30abd0593c feat: add organization AI spend overview endpoint (#31709)
## Description

Adds the experimental `GET
/api/experimental/organizations/{organization}/ai/spend` endpoint that
backs the new Overview tab of the organization AI spend page ([Figma
design](https://www.figma.com/design/6TkixpkUIM5Qv6I7qhM3xZ/AI-Gov---user-spend?node-id=12-5152&t=YlCC7RGSMNrzMxVo-4)).
It returns the organization's spend summary, daily spend, and a page of
users with their per-group spend, using the queries from #31711.

## Changes

- Add the `organizationAISpend` handler and
`ExperimentalClient.OrganizationAISpend`:
- Reuses the period handling of `/ai/spend/users`: `period_start` and
`period_end` must be provided together and span at most 31 days, and the
default is the current budget period.
- Also requires both bounds at 00:00:00 UTC, since the daily spend
aggregate holds whole UTC days.
- Is not limited by the AI Gateway data retention window, since the
daily spend aggregate is not purged. `/ai/spend/users` and the export
keep the retention check, now in `aiSpendRetainedPeriod`.
- Returns `count`, `totals` (`spend_micros`, `median_spend_micros`),
`intervals` (daily spend, one interval per UTC day, zeros included), and
`users` (paginated with `limit`/`offset`, most spend first, with
per-group spend).
- Echoes the applied period, and reads every value in one read-only
repeatable-read transaction so the values agree.
- Extract `parseOrganizationAISpendPage`, shared with `/ai/spend/users`.
- Add handler tests.

Closes AIGOV-728

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-13 10:02:58 +00:00
Dean Sheather fb12d6018f fix!: redact agent environment variable values in API responses (#31932)
Workspace, build, and agent API responses (`/workspaces`,
`/workspacebuilds/{id}`, `/workspaceagents/{id}`, and so on) returned
agent environment variable values in plain text. Template authors often
pass credentials such as API tokens through `coder_env`, so anyone who
could read the workspace could read those secrets.

`db2sdk.WorkspaceAgent` now replaces every non-empty value with
`***REDACTED***` and keeps the keys. This is the same marker the support
bundle (`sanitizeEnv`) and the agent `/debug/manifest` endpoint already
use. The agent still gets the real values through its manifest
(`db2sdk.WorkspaceAgentEnvironment`), and nothing in the CLI or frontend
reads these values from the API.

Every value is redacted because neither `coder_env` nor
`coder_agent.env` in the Terraform provider has a sensitive flag, and
`proto.Env` has no field to carry one. Selective redaction would need
changes to the provider, the proto, and the database.

## For changelog

- Agent environment variable values are redacted in API responses
(#31932)

> Workspace, workspace build, workspace agent, and template version API
responses now return `***REDACTED***` for every non-empty agent
`environment_variables` value. Keys and empty values are unchanged. The
agent still receives the real values, so workspaces behave as before.
  >
> Migration: Update scripts and integrations that read agent environment
variable values from the API or from `coder list -o json`. Read the
values inside the workspace instead.

Closes ENG-1505 (coder/security#51)

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

- Confirmed the leak on `main` (e1c3a21d05): `db2sdk.WorkspaceAgent`
copied `dbAgent.EnvironmentVariables` straight into
`codersdk.WorkspaceAgent.EnvironmentVariables`. Every API path that
returns an agent goes through this function.
- Redact all non-empty values, not just some. There is no secret or
non-secret marker in `terraform-provider-coder` v2.20.0 (`coder_env` has
only `agent_id`, `name`, `value`, `merge_strategy`; `coder_agent.env` is
a plain map), and name heuristics fail in both directions.
- Use `***REDACTED***` to match the existing support bundle and
`/debug/manifest` redaction. Empty values are kept, which also matches
existing behavior.
- Redact in the SDK converter only, so the agent manifest path is
unaffected.
- Regression test `TestWorkspaceAgent/RedactsEnvironmentVariables`
covers the workspace, workspace agent, and workspace build endpoints. It
fails without the fix.

</details>

> Generated by Coder Agents on behalf of @deansheather.
2026-11-11 16:51:20 +11:00
Ethan a40ff12c8c feat!: steer chat messages by default and remove the interrupt busy behavior (#31174)
Breaking API Change for changelog:

> `POST /api/v2/chats/{chat}/messages` now steers by default. If the
chat is busy, the message is delivered before the agent's next model
call, instead of after the turn ends. `busy_behavior` accepts `steer` or
`queue`, and `interrupt` now returns a 400. To redirect the agent, just
send a message, and only call `POST /api/v2/chats/{chat}/interrupt` to
stop it. Queued messages now include their `busy_behavior`.

This is where steering becomes the default for API clients. A send
without a `busy_behavior` used to wait for the turn to end, and now it
goes in the steer lane, so the agent sees it before its next model call
and keeps going. `queue` still waits for the turn to end.

Interrupt isn't a busy behaviour any more. Since #31155 it just meant
"interrupt, then steer", so the API now returns a 400 for it, and
`codersdk.ChatBusyBehaviorInterrupt` is gone. `coder_send_chat_message`
in the MCP server gets the same default and enum. A steer message
already corrects a busy agent, and combining it with an interrupt goes
wrong in either order, so the docs and the MCP tool descriptions now say
to send a message to redirect the agent, and to interrupt only to stop
it.

Queued messages now report their `busy_behavior`, and the queue lists
the steer lane first, so clients can show which messages go in at the
next step and which wait for the turn to end. A message moved with Send
now reports `steer`.

The site doesn't send a `busy_behavior`, so its sends start steering
with this PR, but its queue UI doesn't know about the steer lane until
#31173. chatd still accepts `interrupt` internally, as `message_agent`
uses it, and #31175 removes both.

Part of CODAGT-1140
2026-11-09 15:55:17 +11:00
Mathias Fredriksson c0f7663e95 feat: support editing queued chat messages (#29215)
The owner of a chat can edit a queued message through
`PATCH /api/v2/chats/{chat}/queue/{queuedMessage}`. chatd never sends
a row under edit (`editing_since`): rows ahead of it still send in
order, and a turn that ends at it puts the chat in the new `paused`
status. Ending the head's edit, deleting it, or promoting a queued row
continues the chat. Interrupting sends still run ahead of the queue.

The chat state machine classifies a queue whose head is under edit as
its own sub-state (R1P, I1P, A1P, E1P, XE1P, P), so every path to
`paused` is in the transition matrix. A chat whose family has a paused
member cannot be archived, and auto-archive skips that family. Queue
edit and delete are owner-only, because both can send the next message
with the owner's credentials.

`ChatQueuedMessage` gains `editing_since` and `reasoning_effort`, and
`ChatStatus` gains `paused`.

Closes CODAGT-1028
Refs CODAGT-971
2026-10-30 15:52:22 +02:00
Michael Suchacz 7f6ce9c8ab test(coderd): stamp chat message fixtures with the current content version (#30996)
Chat prompt tests built most of their stored-message fixtures in the
legacy content format (`content_version` 0), so they exercised the
legacy decoder instead of the current one. This PR changes tests only:
it stamps those fixtures with `ContentVersionV1` and builds them with
`MarshalParts`, so they keep passing after the legacy decoder is removed
later in this stack. Tests of the version 0 decoder itself keep their
version 0 rows until the layers above remove that decoder.

**Why it is safe**

- `mustMarshalContent` and `mustMarshalToolResult` now build current
parts (`PartFromContent`, `ChatMessageToolResult`) and encode them with
`MarshalParts`, the production write path.
- `TestMixedFormatConversation` becomes
`TestConvertMessagesWithFiles_Conversation` and uses current-format rows
only.
- `TestParseContent_BackwardCompat` does not change. Migration 000434
stamped every existing row with version 0, so its six cases of
current-format parts in version 0 rows still cover the version 0
heuristics. #30998 moves those six cases to version 1 rows when it
removes that decoder.
- `TestProviderExecutedResult_LegacyToolRow` calls the legacy writers
(`MarshalContent`, `MarshalToolResult`) directly, so its
provider-executed tool row still goes through the legacy tool-row
decoder.
- `TestParseContent_ErrorPaths` runs its malformed-input cases on
version 1 rows, and runs the same input on version 0 rows of each role
(`v0/<role>/malformed_json`), so a version 0 parser that accepts
malformed content still fails the suite. #30998 deletes the version 0
cases with that decoder.
- I ran the 17 mutants listed below, each a `go test -overlay` edit of
the current decode and prompt-conversion code in `chatprompt.go`,
against the `chatprompt` and `db2sdk` tests on `main` and on this
branch. Every mutant `main` catches is still caught. Two more are caught
here: mutant 3, because
`TestParseContent_ErrorPaths/system/malformed_json` used to hit the
legacy system decoder, and mutant 14, by the new JSON `null` case of
`TestConvertMessagesWithFiles_NormalizesAssistantToolCallInput`. Mutants
4 and 8 survive those tests on both. The `chatd` test
`TestOrganizationSkillsFollowChatOwnerAccess` catches mutant 4, so 8 is
an existing gap.
- Mutants of the version 0 decoder fail on `main` and on this branch:
version 0 assistant or user rows always take the envelope path, their
current-format parts are dropped, legacy tool rows lose
`provider_executed`, or a version 0 parser accepts malformed JSON.
- With the version 0 case removed from `ParseContent` by an overlay,
only tests of version 0 rows fail. #30997 deletes them, except the six
`TestParseContent_BackwardCompat` cases, which #30998 moves, and the
version 0 cases of `TestParseContent_ErrorPaths`, which #30998 deletes.

<details>
<summary>The 17 mutants</summary>

1. `ParseContent` returns no parts for a V1 row.
2. V1 decoding skips NUL restoration (`decodeNulInParts`).
3. The V1 parse error says "decode" instead of "parse".
4. Tool error string extraction is off (`toolResultPartToMessagePart`).
Only a `chatd` test catches it.
5. Tool call input is dropped.
6. Tool call `ProviderExecuted` is dropped when reading.
7. Resolved file data is dropped.
8. The file media type fallback is dropped (`partsToMessageParts`).
Survives.
9. User file IDs are not collected for resolution.
10. Text provider metadata is dropped.
11. File reference text is replaced by the raw content.
12. System messages are dropped.
13. Tool call `ProviderExecuted` is dropped when writing
(`PartFromContent`).
14. `normalizeToolCallInput` keeps a JSON `null` input instead of `{}`.
Survives on `main` only.
15. Text tool result `ProviderExecuted` is dropped.
16. Tool result IDs are dropped.
17. Assistant file IDs are resolved like user file IDs.

</details>

**Review focus**

The rewritten conversation test in `chatprompt_test.go`. It checks the
same prompt shape as before, but every row is in the current format. In
the same file, `TestProviderExecutedResult_LegacyToolRow` keeps its
legacy rows, `TestParseContent_ErrorPaths` checks malformed input on
both content versions, and the input normalization table gains a JSON
`null` case. The other changed test files only switch fixtures to the
current format: `coderd/x/chatd/chatprompt/file_inline_test.go`
(+4/-16), `coderd/database/db2sdk/db2sdk_test.go` (+11/-13),
`coderd/x/chatd/message_conversion_test.go` (+3/-2) and
`coderd/x/chatd/quickgen_internal_test.go` (+1).

**Validation**

- `go test ./coderd/x/chatd/... ./coderd/database/db2sdk/ -count=1 -p 4
-parallel 4`: ok
- `go vet` on the touched packages and `golangci-lint run --fix=false
./coderd/x/chatd/chatprompt/...`: clean
- pre-commit hook: passed

**Stack**

This stack retires chatd compatibility paths for chat data that older
Coder versions stored.

1. #30996 stamp chat message fixtures with the current content version
(this PR)
2. #30997 drop tests of the legacy content codec
3. #30998 retire the V0 chat message content decoder
4. #31000 inline the model config provider identity
5. #31005 retire the `close_agent` tool alias

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-28 19:45:29 +00:00
Susana Ferreira 15a5844253 feat: add cost to AI Gateway session threads API (#30509)
## Description

Exposes cost data on the AI Gateway session threads endpoint (`GET
/api/v2/aibridge/sessions/{session_id}`), so the session page can show
cost alongside token usage. Backend only, the UI changes for AIGOV-600
will follow separately.

## Changes

- Add `cost_micros` and `has_unpriced_usage` to
`AIBridgeSessionThreadsTokenUsage`, populated for the session summary,
each thread, and each agentic action.
- Compute the session summary cost in `ListAIBridgeSessions`, next to
the existing session token sums, so tokens and cost come from the same
rows.
- Add `priced_model`, the model and per-token prices used for pricing,
to `AIBridgeThread` for the root interception (the prompt) and to each
`AIBridgeAgenticAction` for that interception, since requests in a
thread may be priced as different models. Nil when not priced.
- Update frontend mocks for the new required fields.

Related to AIGOV-600

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-10-26 10:01:50 +00:00
c4d76a4009 feat: add skill action and automatic-use settings (#30882)
Adds two per-skill settings that the project skills UI will expose next:

- `action` marks a project skill to show as an action button above
project chat composers. A `skills_action_project_only` check keeps it to
project skills; the personal and organization routes reject `action`
with 400.
- `model_invocable` (default true, every stored source) controls
automatic use. When it's false the skill is left out of
`<available-skills>` and `read_skill` reports it as not found, but a
structured skill invocation (a chip from the `/` menu or an action)
still loads it, as long as the skill is enabled and the chat owner can
read it. Workspace skills always count as model-invocable.

Migration 000625 adds both columns with defaults, so existing skills
keep today's behavior. The list, get, insert and update queries,
`codersdk.SkillMetadata` and the create/update requests carry both
fields, and the audit table tracks them.
`coderd/x/chatd/ARCHITECTURE.md` gets TODO notes for the author.

**NOTE**: the migration adds two columns with constant defaults and a
CHECK constraint to `skills`.

Stack (merge top to bottom):
- #30826
- #30827
- #30838
- #30840
- #30854
- #30855
- #30856
- #30861
- #30880
- #30881
- #30882 👈
- #30884
- #31122
- #31126

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Nick Vigilante <nickvigilante@users.noreply.github.com>
2026-10-23 19:32:08 +07:00
Garrett Delfosse 6ebefb8325 feat: add chat project sharing API (#30439)
API for chat project sharing (experiment `chat-projects`). Builds on
#30479 (merged).

Owners share a project with users, groups, or the whole organization
(the Everyone group, ID = organization ID). Chats in a shared project
stay private.

| Role    | Project and instructions | Memories   | ACL  | Delete |
|---------|--------------------------|------------|------|--------|
| `use`   | read                     | read/write | read | no     |
| `admin` | read/write               | read/write | edit | no     |

Only the owner, and administrators whose role grants delete, can delete
a project.

- **API:** `GET`/`PATCH .../chats/projects/{project}/acl`, same shapes
as `/chats/{chat}/acl`, plus SDK methods. Project responses include the
caller's `permissions` (`update`, `delete`, `share`); the UI hides edit
and delete accordingly.
- **Listing:** `GET /chats/projects` returns owned and shared projects.
Removes `GetChatProjectsByOwnerID`.
- **Chat access:** creating a chat in a project, and loading its memory
and instructions on each turn, requires the chat owner to own the
project or have an ACL grant (`chatd.ChatProjectUsableBy`). Role grants
don't count. If the grant is removed, existing chats lose memory and
instructions on their next turn.
- **Validation:** users and groups must be in the project's
organization; keys must be canonical UUIDs; callers can't change their
own role; the owner can't be added. Migration `000624` drops a user's
grants when they leave the organization, so rejoining doesn't restore
access.
- **Instructions:** readers who can't edit get 403 instead of 404, and
the UI hides editing.
- **Agent prompt:** memories are visible to and editable by sharees, so
the agent is told not to save secrets or personal details.

Known gap: project deletion still detaches chats, and a sharee's open
sidebar keeps showing them until reload. #30683 replaces this.

Not included: share notifications, `/acl/available`, sharing UI.

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

- `use` grants memory read/write over HTTP, because agents in a sharee's
chats can already write memories. Making the agent read-only for sharees
was the alternative (@f0ssel chose sharees changing memories through
use).
- An administrator with `share` can grant themselves access and then use
the project. Accepted to keep access control simple (@f0ssel).
</details>

> Generated by Coder Agents.
2026-10-19 11:32:26 +00:00
Jaayden Halko e289c6fe01 feat: add project skill API routes (#30827)
Adds experimental routes for managing a chat project's skills under
`/api/experimental/organizations/{organization}/chats/projects/{project}/skills`:
list, create, get, update (PATCH) and delete by skill name.

The handlers reuse the shared skill create and update path from the
personal and organization skill APIs. Reading needs `chat_project:read`
on the project and writing needs `chat_project:update`; callers without
access get 404, matching the project instructions routes. Duplicate
names and the 100-skill-per-project cap return 409. Writes are audited
as `chat_project_skill` with the skill name as the target. The SDK gains
the matching `ExperimentalClient` methods.

Stack (merge top to bottom):
- #30826
- #30827 👈
- #30838
- #30840
- #30854
- #30855
- #30856
- #30861
- #30880
- #30881
- #30882
- #30884
2026-10-18 13:16:23 +07:00
Steven Masley 03cba25a63 feat: list a workspace build's secrets in coder secret list (#30388)
`coder secret list` now shows the current workspace build's secrets next to your user secrets, and which user secrets they replace. Part of [RELAY-7](https://linear.app/codercom/issue/RELAY-7/agent-relay-deliver-provider-credentials-via-coder-secrets-instead-of).

**Stack** (design decisions in #30248)
1. #30248 Database schema, queries, and RBAC
2. #30249 Encryption at rest
3. #30250 Set secrets on workspace builds
4. #30251 Deliver secrets to the agent
5. #30252 Docs
6. **#30388 List a build's secrets (this PR)**
7. #30459 Audit a build's secrets

- New `GET /workspacebuilds/{workspacebuild}/secrets` lists a build's secrets (metadata only, never values) and which user secret each one replaces.
- Inside a workspace, `coder secret list` includes the current build's secrets. Outside a workspace, use `--workspace` or `--build-id`.
- The agent now exposes `CODER_WORKSPACE_BUILD_ID`, so the CLI knows which build it is running in.
- The agent manifest and the new endpoint use one shared resolver, so they always agree on which secret wins.
- The user secret API is unchanged.

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

- The manifest carries `workspace_build_id`; the agent sets it as `CODER_WORKSPACE_BUILD_ID`.
- `coderd/workspacesecrets.Resolve(user, build, policy)` decides which secret is delivered on each env var and file. The manifest no longer relies on entry order.
- `codersdk.WorkspaceSecret` embeds `UserSecret` and adds `workspace_build_id`, `ephemeral`, `cleared_at`, `env_replaces`, and `file_replaces`. Secrets whose values a later build cleared are still listed, with `cleared_at` set.
- CLI columns: `source` and `replaced by` are shown by default only when a build is included; `ephemeral` is opt-in. The CLI makes two requests: user secrets, then build secrets.
- Agents that predate the build ID fall back to `CODER_WORKSPACE_ID` and its latest build.

</details>

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

(existing decision log, unchanged)

</details>

---

*Created by Coder Agents on behalf of @Emyrk.*
2026-10-15 17:40:00 -05:00
Michael Suchacz db7f5a7703 feat: add organization skill API routes (#30610)
## Stack

Part of
[CODAGT-1341](https://linear.app/codercom/issue/CODAGT-1341/support-organization-level-skills-in-coder-agents).
This stack adds organization skills to Coder Agents: admins publish a
skill once per organization, share it with groups or members, and chats
in that organization load it next to personal and workspace skills. It
replaces the 21-PR draft stack #30584 to #30604 with five PRs, bottom to
top:

1. #30609 data model: one migration, queries, RBAC and dbauthz
2. **#30610** organization skill API routes and the scope-neutral SDK
(this PR)
3. #30611 sharing ACL routes
4. #30612 settings UI: shared skills table, admin page, member section
5. #30613 chats: chatd loading, `/` menu, docs

## What changes

This PR adds the organization skill CRUD routes and makes the skill SDK
types owner-neutral so personal and organization skills share them.

**API contract change (experimental API, personal and organization
skills):** skill list and get responses gain `enabled`, and `PATCH
.../skills/{skillName}` now takes `{content?, enabled?}`, so `content`
is optional and a toggle doesn't resend it. A PATCH with neither field
returns 400; `content`, when present, is validated as before. In the
SDK, `UserSkill`, `UserSkillMetadata`, `CreateUserSkillRequest` and
`UpdateUserSkillRequest` become `Skill`, `SkillMetadata`,
`CreateSkillRequest` and `UpdateSkillRequest` (`codersdk/userskills.go`
moves to `codersdk/skills.go`), and `UpdateSkillRequest.Content` is now
`*string`. The personal client method names are unchanged. The site
changes are the handwritten edits that rename forces (`api.ts`,
`queries/userSkills.ts`, `testHelpers/skills.ts` and three call sites),
with no UI change.

Organization routes under
`/api/experimental/organizations/{organization}/skills`, not gated by an
experiment or license, like the personal ones:

- `GET` lists with the caller's own permissions, so admins, the site
owner and org auditors see every skill and members see only skills
shared with them. `GET /{skillName}` goes through the new
`httpmw.ExtractOrganizationSkillParam` and admits only read, so a
missing skill and a denied one both return 404.
- `POST` checks `create` on the organization before reading the body,
then seeds `group_acl` with the Everyone group (whose ID is the
organization ID) so a new skill reaches every member until an admin
narrows it. The 100-skill cap and a duplicate name return 409.
- `PATCH` admits only callers who can read the skill, because its
response includes the content; `DELETE` admits callers who can read or
delete it. A reader who can't change the skill gets a write-specific 403
from the database wrapper, and everyone else gets 404. PATCH locks the
row as system, updates as the caller in the same transaction, and audits
the locked row only after the transaction commits.
- Audit: `database.AuditableOrganizationSkill` records resource type
`organization_skill` with the organization ID; personal skills keep
`user_skill`.

Personal and organization handlers share one create and update path in
`coderd/userskills.go` (`createSkill`, `updateSkill`, and a
`skillWriteErrors` table per owner and action).

## Commits

The first commit reproduces the reviewed code from the old stack; each
later commit is a labeled trim or fix.

- `49cb2c84276` feat: add organization skill API routes. Reproduction:
every file this commit changes, including the SDK layer's site edits,
equals the reviewed old `write-routes` head `aa597100f28`; the rest of
the tree differs only by #30609's migration merge and main.
- `dc893bc60d6` refactor(coderd): share the skill create and update path
across owners (production +164/-188). It keeps the organization create
check before the body read, the lock as system then update as caller
order, and audit assignment after the transaction. No swagger,
`codersdk` or `typesGenerated.ts` change; `make gen` is clean.
- `f94925425ef` test(coderd): merge duplicate personal and organization
skill tests. `TestSkillsCRUD`, `TestSkillValidationAndConflicts` and
`TestSkillAudit` are table-driven over Personal, OrgAdmin and SiteOwner,
alongside `TestOrganizationSkillAuditsDeniedWrites` and one
`ScopedAPIKeys` subtest; `TestPatchUserSkill` is deleted because none of
its blocks were unique. Coverage of `userskills.go`,
`organizationskills.go` and `httpmw/organizationskillparam.go` is 101 of
117 blocks before and after, the same block set.
- `ad0a7a37504` fix(coderd): require read access to patch an
organization skill. The organization PATCH route now admits only `read`,
because its response carries the skill's content: a key scoped to
`organization_skill:update` without read gets 404, like GET, instead of
200 with the content. Readers without update still get 403, and DELETE
is unchanged. `TestOrganizationSkillAccess/ScopedAPIKeys` asserts the
404, that the response has no content, and that the skill is unchanged;
against the old route it fails with 200.
- `69d00ded0b6` and `f67b79343ec` merge the updated #30609 layer,
including main; `69d00ded0b6` resolves a conflict in the personal skills
page with main. No other changes of their own.
- `18373ffd59e` merges the updated #30609 layer (main at `e7b76872098`)
and reapplies the `AuditableOrganizationSkill` entry in
`enterprise/audit/table.go` alongside main's new
`AuditableChatProjectInstructions` entries.

## Size

Production +838/-308, tests +733/-322, generated +801/-274; total
+2372/-904. This is above the 500-line reviewer-friendly limit on
purpose: Mike asked for 4 to 5 PRs instead of the 21 small ones this
stack replaces.

## Replaces

#30587 (scope-neutral SDK and personal enabled state), #30588 (read
routes), #30589 (write routes and audit).

## Validation

- The coverage comparison above, before and after the test merge.
- `make gen` leaves no diff after the shared create and update refactor.
- On `18373ffd59e`: `make gen` is clean; build, vet, the `coderd` and
`enterprise/coderd` skill tests, `rbac`, `httpmw`, `dbauthz` and
`enterprise/audit` pass; `pnpm check`, `pnpm lint` and `make pre-commit`
pass.
- Remote UAT round 7 through Coder Agents passed on the whole stack; see
#30613's Validation for scope and findings.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-13 16:24:45 +00:00
Michael Suchacz b67587c875 feat: add the organization skills data model (#30609)
## Stack

Part of
[CODAGT-1341](https://linear.app/codercom/issue/CODAGT-1341/support-organization-level-skills-in-coder-agents).
This stack adds organization skills to Coder Agents: admins publish a
skill once per organization, share it with groups or members, and chats
in that organization load it next to personal and workspace skills. It
replaces the 21-PR draft stack #30584 to #30604 with five PRs, bottom to
top:

1. **#30609** data model: one migration, queries, RBAC and dbauthz (this
PR)
2. #30610 organization skill API routes and the scope-neutral SDK
3. #30611 sharing ACL routes
4. #30612 settings UI: shared skills table, admin page, member section
5. #30613 chats: chatd loading, `/` menu, docs

## What changes

This PR adds the data model and authorization for organization skills.
Personal skills keep working unchanged: `git diff origin/main --
codersdk site` shows only generated RBAC and API key scope additions
(`apikey_scopes_gen.go`, `rbacresources_gen.go`,
`rbacresourcesGenerated.ts`, the RBAC and scope unions in
`typesGenerated.ts`) and `codersdk.ResourceTypeOrganizationSkill` with
its friendly string. No personal route, SDK type or site component
changes, and `coderd/userskills_test.go` changes only by mechanical
constant renames.

**One migration, `000621_skills`** (please review it closely):

- renames `user_skills` to `skills` with its constraints, index and
triggers, and recreates the cap function and
`delete_deleted_user_resources`, whose PL/pgSQL bodies name the table;
- adds `organization_id` and `project_id` (`ON DELETE CASCADE`),
`enabled` (default true), and `group_acl` / `user_acl` (`jsonb`, default
`{}`), with CHECKs for exactly one owner, ACLs that are JSON objects,
and ACLs that stay empty unless an organization owns the row, plus
partial unique name indexes per owner kind;
- replaces the cap trigger with `enforce_skills_per_owner_limit()`: 100
rows per owner, disabled rows included, locking the owner row `FOR NO
KEY UPDATE` so unrelated foreign key checks are not blocked;
- adds a `BEFORE DELETE` trigger on `organization_members` that removes
a departing member from `user_acl` on that organization's skills, so
rejoining doesn't restore a direct grant;
- adds the `organization_skill` `resource_type` and `api_key_scope` enum
values last; nothing in the migration uses them.

The down migration undoes the three old migrations in reverse order: it
drops organization and project rows and restores `user_skills`, its
names, the cap function and `user_id NOT NULL`.

Authorization: a new RBAC resource `organization_skill` (create, read,
update, delete, share). Owner and org admin get it; site and org
auditors get read; members read only through the skill's ACL, which
applies only to members of its organization. `Skill.RBACObject()`
returns the organization object with both ACLs; project rows stay denied
to everyone. New sqlc queries cover organization insert, get, list
(SQL-filtered through `GetAuthorizedOrganizationSkillMetadata` and a
`regosql` converter), update and delete, with dbauthz wrappers and the
audit table entries. No routes yet.

## Commits

The first commit reproduces the reviewed code from the old stack; each
later commit is a labeled trim or fix.

- `baa3150e3b7` feat: add the organization skills data model.
Reproduction: every non-site file this commit changes equals the
reviewed old `authz` head `1e16b3004c4`, except that the old stack's
migrations 000615, 000616 and 000617 are merged into one migration (then
`000615_skills`, now `000621_skills`) with one fixture
(`testdata/fixtures/000621_skills.up.sql`) and one migration test (now
`testMigration000621Skills`). At that commit, `dump.sql` was
byte-identical to the old head's.
- `1b84e83463a` test(coderd/database): keep only the SQL paths of the
org skill matrix. `TestOrganizationSkillAuthorization` becomes
`TestOrganizationSkillQueries` instead of being deleted, because
coverage showed it is this PR's only run of the
`GetAuthorizedOrganizationSkillMetadata` row scan (80% to 65% without
it) and of the organization update and delete queries (100% to 0%).
Swapping `group_acl` and `user_acl` in the converter makes
`GrantedMember` fail. The removed cases are decided by
`TestRolePermissions`, `TestSkillRBACObjectOrganizationACL` and the
dbauthz method suite.
- `e2931b412e9` test(coderd/database): fold the skill cap cases into
existing coverage. The user case is covered by `TestUserSkillLimit` and
`TestUserSkillLimitConcurrentCreates`; the organization case folds into
`ConcurrentOrganizationInsertsHonorCap`, which now also checks that
disabled rows count and another organization is unaffected (mutation
checked); the project case stays.
- `be62aea9021` test(coderd/rbac): drop
`TestOrganizationSkillReadScope`, covered by `TestExternalScopeNames`
and the generated scope file.
- `0c275ba37de` merges main at `454a2fcc697`, which took 000615 to
000618: it renumbers the migration to 000619 and resolves `dump.sql`,
`check_constraint.go` and the generated API docs. `8f2b4b87ee2` merges
main at `ad85646164e`, which took 000619: it renumbers the migration to
000620.
- `5248d56b64f` merges main at `e7b76872098`, which took 000620
(`000620_audit_chat_project_instructions_resource_type`): it renumbers
the migration, fixture and migration test to `000621_skills` (step
`Migration000621Skills`, version 621), and resolves
`enterprise/audit/table.go` (keeping main's
`AuditableChatProjectInstructions` entries and the `Skill` entry),
`dump.sql` and `models.go` (the `resource_type` enum gets
`chat_project_instructions`, then `organization_skill`) and the
regenerated `schemas.md`. The up and down SQL are unchanged by every
renumbering.

## Size

Production +549/-67, tests +728/-33, generated +881/-314; total
+2158/-414. This is above the 500-line reviewer-friendly limit on
purpose: Mike asked for 4 to 5 PRs instead of the 21 small ones this
stack replaces.

## Replaces

#30584 (rename `user_skills` to `skills`), #30585 (skill owners), #30586
(organization skill authorization).

## Validation

- Migration test: up keeps the existing personal row and its ID; down
restores the `user_skills` names, cap function and `NOT NULL`, and drops
organization rows; soft-deleting a user removes their skills after up,
after down, and after re-up.
- `go test` passed on `be62aea9021`, before the main merges, for
`coderd` (skill tests), `coderd/database`, `dbauthz`, `migrations`,
`gentest`, `coderd/rbac/...`, `coderd/x/chatd`, `coderd/x/skills`,
`enterprise/audit` and `enterprise/coderd`; `make lint/check-scopes`
passed; the four personal skills Vitest files pass unchanged.
- On `5248d56b64f`: build, vet, `TestMigrate`, `TestMigrationChain`, the
`migrations`, `database`, `dbauthz`, `gentest`, `rbac` and
`enterprise/audit` packages pass; `make gen` run twice is clean, and
`make pre-commit` passes.
- Remote UAT round 7 through Coder Agents passed on the whole stack; see
#30613's Validation for scope and findings.

> Xum opened this PR on behalf of @ibetitsmike.
2026-10-13 15:51:31 +00:00
97c5260adb feat: add chat project instructions API (#30368)
Adds the experimental API for chat project instructions: `GET`, `PUT`,
and `DELETE
/api/experimental/organizations/{organization}/chats/projects/{project}/instructions`,
behind the `chat-projects` experiment.

- `GET` returns 200 with empty instructions and null
`updated_by`/`updated_at` when nothing is set, so clients don't need a
404 path.
- `PUT` requires update access only (the read-back runs under a system
context, so a custom role with update but not read can save). It
sanitizes the text with `SanitizePromptText`. It rejects blank text with
400, pointing the caller to `DELETE`, and rejects text over the chat
prompt byte limit. It records the caller as `updated_by`. The upsert and
the read-back that returns the editor's profile run in one transaction.
- `DELETE` returns 204, including when nothing is set.
- Users without access to the project get 404, like the other project
routes.
- `PUT` and `DELETE` are audited as a new `chat_project_instructions`
resource (`write` and `delete`), with the project as the resource ID and
its name as the target. The diff tracks only the instruction text.
Saving unchanged text and deleting unset instructions are not audited. A
per-project advisory lock serializes reading the previous value with the
write, so concurrent edits produce accurate diffs. Migration `000615`
adds the enum value.

The codersdk client gains `ChatProjectInstructions`,
`UpdateChatProjectInstructions`, and `DeleteChatProjectInstructions`.

**What to scrutinize:** writes are last-writer-wins with no version
precondition, matching the deployment, user, and organization prompt
settings.

**Generated:** `coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`,
and `docs/reference/api/schemas.md` come from the Swagger annotations;
`site/src/api/typesGenerated.ts` comes from `codersdk`;
`docs/admin/security/audit-logs.md`, `coderd/database/dump.sql`, and
`coderd/database/models.go` come from the audit table and migration.
Together they are about 400 of this PR's lines.

**Validation:** `make gen` leaves no diff. `go test ./coderd -run
TestChatProject` and `go test ./enterprise/coderd -run
TestChatProjectInstructions` pass. `TestChatProjectInstructionsAudit`
checks the audit entries for create, update, and delete, and that no-op
saves and deletes are not audited. It covers unset GET, create, update,
blank and oversized PUT, delete, access denial, and cascade on project
delete.

---

Stack (merge top to bottom). #30377 through #29583 are f0ssel's split of
the original #29583, and this stack sits on #29583:
- #30377 data layer and project dialog (f0ssel)
- #30378 new-chat form locked to a project (f0ssel)
- #30379 project page route (f0ssel)
- #29583 sidebar folders (f0ssel), the base of this stack
- #30291 composer frame
- #30292 project chat list caches
- #30293 project page header
- #30294 project chats list
- #30367 instructions storage and prompt injection
- #30368 instructions API 👈
- #30369 instructions editor dialog
- #30370 instructions Details panel

---------

Co-authored-by: Garrett Delfosse <delfossegarrett@gmail.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 19:15:16 +07:00
Bobby Ho dae7967bd1 feat: persist script resource addresses and dependencies (#30625)
feat(coderd): persist workspace agent script dependencies

Persist Terraform resource addresses and script dependencies supplied by
the provisioner (#30451, #30491), and expose them through the SDK and
REST API.

- Add migration 000618 with `resource_address` and `dependencies`
  columns, empty defaults, and a JSON-array constraint. API responses
  always include the address and omit empty dependency lists.
- Preserve `success` and `completion` requirements, including scripts
  on devcontainer subagents. Legacy scripts and older provisioners
  remain compatible through empty defaults.
- Reject empty prerequisite addresses and unsupported requirements,
  rolling back the entire job. Invalid stored dependencies return HTTP
  500 rather than silently dropping ordering.
- Add persistence, validation, rollback, devcontainer, API, and migration
  coverage; regenerate API docs and TypeScript types.

Unordered templates retain their existing execution behavior.
Dependency lists remain empty until #30556. Agent manifest wiring and
the agent API version bump are deferred to a follow-up.

Refs PLAT-548.
2026-10-13 03:43:55 +00:00
Ehab Younes 5b060beeb1 feat: separate connection log methods from app names (#30466)
Connection logs now record how a connection was made
(`connection_method`) separately from which app made it (`app_name`).
Storage, the HTTP API, search filters, and the UI move to the new
fields. Legacy agent reports and the deprecated `type` field keep
working.

- Add `connection_method` (`ssh`, `reconnecting_pty`, `workspace_app`,
  `port_forwarding`, `tunnel`) and optional `app_name` and
  `app_display_name` to `GET /api/v2/connectionlog`. Deprecate `type`
  and make it a plain string in the API and the Go SDK.
- Add `method:` and repeatable `app:` search filters. `type:` keeps its
  old results but can't be combined with the new filters.
- Replace the Type menu with a Method menu, show the app next to the
  method in each row, and warn when a filter uses `type:`.
- Change the Active SSH connections preset to `method:ssh`, so it also
  includes SSH sessions from VS Code and JetBrains apps.
- Generate `codersdk.ConnectionLogMethod` from the database enum with
  `typegen dbenums`.
- Migration 000617 rewrites `connection_logs` under an ACCESS EXCLUSIVE
  lock, which takes about 50 seconds for 10 million rows. `vscode` and
  `jetbrains` rows become `ssh` rows with that app. Rolling back folds
  apps into the old types and loses per-app names.
- Document the new filters and how to replace each `type:` value.

Closes #27412
2026-10-12 15:56:40 +03:00
Thomas Kosiewski f923f4a525 chore!: remove the chat automations experiment (#30412)
Removes the experimental Chat Automations feature (`chat-automations` experiment) from main. This reverts the 16-PR stack that added it and adds two forward migrations that undo its schema and credential changes.

> [!WARNING]
> **Upgrade consequences**
>
> - **Automation data is deleted.** Migration 000615 drops the `chat_automations` table and deletes every queued message an automation delivered. Chats, their messages and ordinary queued messages stay. Messages lose their automation provenance (`automation_id`, `input_id`).
> - **Automation-only credentials are revoked.** Migration 000616 deletes API keys, OAuth2 codes and OAuth2 tokens whose only scopes (or allow-list entries) were `chat_automation:*`. Mixed credentials keep their other scopes. Custom roles lose their `chat_automation` permissions. OAuth2 apps that allowed only `chat_automation` scopes get the whitespace allowlist that grants nothing, as in 000595.
> - **A coordinated restart is required.** Stop all old replicas before the new version runs the migrations. Old replicas read the dropped table and columns, so a rolling deploy is not supported.
> - **Remove `--chat-max-automations-per-owner` before upgrading.** The flag, the YAML key `chat.maxAutomationsPerOwner` and the env var `CODER_CHAT_MAX_AUTOMATIONS_PER_OWNER` are removed. A deployment that still sets the flag or the YAML key will not start (`unknown flag` / `unknown option`). The env var is ignored. This includes dogfood. No release or tag contains the flag.
> - **Down migrations restore the schema only.** 000616 down and 000615 down recreate the 000611 schema with empty tables. They do not restore deleted automations, webhook secrets, provenance, queued deliveries, revoked credentials, stripped permissions or the deleted experiment rule.

## What is removed

- The `chat-automations` experiment and its stored runtime rule (`experiment_rule:chat-automations`).
- The `--chat-max-automations-per-owner` deployment option.
- The `chat_automation` RBAC resource, its member and chatd grants, and the `chat_automation:*` API key scopes.
- The automation sqlc queries, dbauthz wrappers and audit table entries.
- The management routes under `/api/experimental/organizations/{organization}/chat-automations`, and the webhook route `POST /api/experimental/chat-automations/{automation}/events` with its rate limiter.
- The chatd management service, webhook publish, schedule loop, the `manage_automations` tool, and the chatstate admission seam and queue promotion guard that only automations used.
- The Agents Automations page, editor, nav entry, chat labels, the Manage automations toggle and the API client.
- The `archived:any` chat search value that the automations "View chats" dialog added.
- `docs/ai-coder/agents/automations.md`, its manifest entry, the glossary entry and the related rows.

Reverted PRs: #30085, #30096, #30112, #30117, #30127, #30134, #30160, #30166, #30167, #30171, #30187, #30207, #30214, #30217, #30219, #30220.

## What stays, and why

- Migrations 000609, 000610 and 000611, their fixture, and the #30297 lock fix with `migration000609_test.go` stay unchanged. Deployments such as dogfood already ran them.
- New migration **000615** reverses the schema changes of 000609 and 000611 against the current schema. It uses the same short-wait lock-and-retry block as 000609, and it rebuilds `chats_expanded` from main's current definition minus the two automation columns. New migration **000616** follows the 000595 Tasks removal for credentials and recreates `api_key_scope` without the five `chat_automation:*` values. It keeps the `chat_project_memory:*` values from 000612.
- The `chat_automation` value stays in the `resource_type` enum, and `codersdk.ResourceTypeChatAutomation` stays. Old audit log rows stay readable, as with `task` after the Tasks removal.
- The 000615 delete fires the existing queue-version trigger, so `queue_version` moves to `snapshot_version` for each affected chat. `snapshot_version` is not bumped: the coordinated restart restarts every stream loop from an empty state, and the site does not read the version fields.
- `coderd/x/chatd/ARCHITECTURE.md` drops the sections the stack added and gets back its pre-stack wording, merged with the later main edits to the same file.

## Notes for reviewers

- #30379 (chat project page) merged while this PR was in progress. It passed `manageAutomationsEnabled` in `AgentCreatePage.test.tsx` and listed an `automations` route in `AgentsPageLayout.test.tsx`. Later main commits also added automation props in `ConversationTimeline.test.tsx` and `ConversationTimelineWorkingBlocks.stories.tsx`. This PR removes all of them.
- Remaining `automation` matches under `coderd`, `codersdk`, `enterprise`, `site/src` and `docs` are intended:
  - migrations 000609 to 000611, their fixture and `migration000609_test.go`;
  - the new 000615 and 000616 migrations and `migration000615_test.go`;
  - the `chat_automation` resource type in `dump.sql`, `models.go`, `codersdk/audit.go`, the generated API docs, `swagger.json` and `typesGenerated.ts`;
  - unrelated uses of the word "automation" (docs, `chatlabels_test.go`, `ratelimit.go`, `autostop.go`, `subagent_catalog.go`, `WorkspaceSharingSection.tsx`, `AgentChatPage.stories.tsx`).

Remote UAT on an isolated dev deployment passed. It upgraded a populated pre-removal database, then checked chats, queued messages, tokens, the 404 routes, the removed page and nav entry, and the experiments list.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_

![Agents sidebar after the upgrade, with no Automations entry](https://github.com/user-attachments/assets/bd446035-7fc8-4ca4-a735-3a4f36380738)
2026-10-11 19:57:49 +02:00
Danielle Maywood 49b1a2cf5d feat: expose per-ref diff statuses (#29082)
Part 2 of 6. Depends on #29081.

The API now exposes every ref a chat tracks. All API changes are
additive.

- `Chat.diff_statuses` lists every ref on the chat GET and in chat lists
(including child chats). The order is stable: refs are listed by first
report, so the list does not change order when a ref gets a new git
report.
- `Chat.diff_status` is the primary: the ref with the most recent git
report. It is the same rule as before. Use it to find the primary, not
the list position.
- `ChatDiffStatus` gains `remote_origin` and `git_branch`.
- `diff_status_change` watch events carry `changed_diff_status` (`{ref,
status}`) naming the ref that changed. If that ref's row is gone,
`status` contains only `chat_id`.
- `GET /chats/{chat}/diff` accepts optional `origin` and `branch` query
parameters. Set both or omit both (otherwise 400). A selector that
matches no stored ref returns 404. Without a selector the endpoint
returns the primary, as before. The Go SDK adds `WithChatDiffStatusRef`
for this.
- A git report without a chat ID (for example, from a terminal or an
agent older than v2.32) now refreshes only the chats that already track
that ref. It does not add the ref to other chats. Such a report can no
longer give a chat its first ref.

Generated by Coder Agents.
2026-10-06 09:32:46 +01:00
Garrett DelfosseandClaude Opus 5.5 a08ba6a70c feat: add shared project memory API for chats in a project (#29301)
- Experiment, stacked on #29242. UI is in #29583.
- Adds **project memory**: `chat_project_memories` rows with a name
(lowercase slug, unique per project), a one-line description (150
characters) and a body (8KB). Up to 200 per project, shared by every
root chat in the project. Chats outside a project and subagents have no
memory.
- Memories are immutable: they are created and deleted, never edited.
Agent tools are `read_memory`, `save_memory`, `delete_memory` and
`consolidate_memory`. Saving an existing name fails and points the agent
at `consolidate_memory` to replace it.
- **Consolidation is agent-driven, in the turn**, modeled on how Claude
Code compacts its memory index when warned it is near its limit. From
160 memories (80%), save results ask the agent to get under 140 (70%)
with `consolidate_memory`, choosing what to merge and drop. That tool
deletes and saves memories in one transaction under the per-project
advisory lock, and rolls back entirely if a delete is missing, a name is
taken, or the result exceeds 200. There is no background extraction or
consolidation.
- **The memory index reaches the model as model-only conversation
messages**, not in a tool description or the system prompt. At turn
start the chat gets a full `<project-memory-index>` snapshot when its
prompt has none (first turn, or after compaction), otherwise a
`<project-memory-index-update>` listing only what changed. Tool
definitions and the system prompt carry no memory state, so memory
writes never invalidate the provider's cached prompt prefix. Writes by
other chats, or by this chat mid-turn, reach the model at its next turn.
- REST API (create, list, get, delete) under
`/api/experimental/organizations/{organization}/chats/projects/{project}/memories`.
Memory permissions follow projects onto the `agents-access` role.
- **Every memory change is audited** as `ChatProjectMemory` create or
delete. REST changes are attributed to the caller. Tool changes
(`save_memory`, `delete_memory`, `consolidate_memory`) are attributed to
the chat owner, carry the `chat_id`, and record one entry per memory
after the change commits, so a rolled-back consolidation records
nothing.

### Examples

**What the model sees.** The system prompt gets a fixed guidance block
with no memory state:

```text
<memory>
Memory is durable context shared by every chat in the project "platform".
Save facts that will matter in future chats: … The memory index is in the conversation: a <project-memory-index> message lists every saved memory, and <project-memory-index-update> messages at the start of later turns list what changed. Changes made during a turn, including your own, appear in the next turn's update. … Memories cannot be edited: replace one that no longer holds with consolidate_memory, or delete it.
</memory>
```

On the first turn, after the user's message, the chat gets a model-only
row with the full index (hidden in the UI):

```text
<project-memory-index>
- deploy-day: Deploys happen on Tuesdays
- release-owner: Alice owns releases; ping her before tagging
</project-memory-index>
```

On a later turn where memories changed, it gets only the difference:

```text
<project-memory-index-update>
Added or changed:
- deploy-day: Deploys happen on Wednesdays (changed 2026-09-30)
- staging-url: Staging lives at staging.example.com
Removed:
- old-ci-notes
</project-memory-index-update>
```

Resulting request layout, with the provider's cached prefix unchanged by
memory writes:

```text
[tools: fixed]  [system: fixed <memory> guidance]  [turn 1 user] [index snapshot] [assistant/tools …]  [turn 2 user] [index update] [assistant …]
```

**Tool calls and results** (produced by the tools in this PR):

```text
save_memory {"name":"staging-url","description":"Staging lives at staging.example.com","body":"Staging is https://staging.example.com; deploys from main."}
→ {"count":3,"saved":"staging-url"}

save_memory {"name":"deploy-day", …}   // name already exists
→ error: a memory named "deploy-day" already exists; read it, then replace it with consolidate_memory by deleting "deploy-day" and saving the new version in one call

consolidate_memory {"delete":["deploy-day"],"save":[{"name":"deploy-day","description":"Deploys happen on Wednesdays (changed 2026-09-30)","body":"The team deploys every Wednesday since 2026-09-30."}]}
→ {"count":3,"deleted":["deploy-day"],"saved":["deploy-day"]}

read_memory {"name":"deploy-day"}
→ {"name":"deploy-day","description":"…","body":"…","created_at":"2026-09-30T15:04:05Z","created_by":"alice"}
```

Near and at the cap:

```text
save_memory … → {"count":160,"saved":"one-more","warning":"memory is 160/200, approaching the limit. Consolidate it to under 140 memories now with consolidate_memory: merge overlapping memories into one, and drop stale, wrong, or superseded ones."}

save_memory … → error: memory is full (200/200); use consolidate_memory to merge overlapping memories and drop stale ones, and include this memory in its save list
```

**REST memory object** (`GET .../chats/projects/{project}/memories`):

```json
{
  "id": "59500000-0000-4000-8000-000000000001",
  "project_id": "7c0e4a3e-5b1f-4f7d-9a51-2f3c8f6d2b10",
  "organization_id": "bb640d07-ca8a-4869-b6bc-ae61ebb2fda1",
  "name": "deploy-day",
  "description": "Deploys happen on Wednesdays (changed 2026-09-30)",
  "body": "The team deploys every Wednesday since 2026-09-30.",
  "created_by": "0ed9befc-4911-4ccf-a8e2-559bf72daa94",
  "created_by_username": "alice",
  "created_at": "2026-09-30T15:04:05Z"
}
```

Create takes `{"name", "description", "body"}` and answers 409 on a
duplicate name or at the cap.

<details>
<summary>Screenshots (predate the immutable-memory rework; tool output
shape has since changed)</summary>


![save_memory](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr2-01-chat-saves-memory-raw.png)

![read_memory](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr2-02-chat-reads-memory-raw.png)
![Agent reads every
memory](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr2-agent-lists-memories-raw.png)

</details>

---
Generated with Coder Agents on behalf of @f0ssel.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-05 12:52:10 -04:00
Thomas Kosiewski fb0951b850 feat: add the manage_automations chat tool switch and read actions (#30214)
Adds the `manage_automations` chat tool with its read and stop actions
(`list`, `get`, `disable`, `delete`), gated by an interim per-chat
switch. Tool sets have not landed, so this ships
`chats.manage_automations_enabled` as the RFC describes for that case;
tool sets later replace it and migrate its values.

Part of CODAGT-1212 (slice 12a of 3). Part of CODAGT-1135.

## What changes

- **Switch.** Migration `000611` adds `chats.manage_automations_enabled`
(default off). It is set through `POST /api/v2/chats` and `PATCH
/api/v2/chats/{chat}`. After creation only the chat owner may send the
field (403 otherwise). Turning it on returns 400 when the
`chat-automations` experiment is off for the chat owner (POST checks the
resolved `owner_id`, not the caller) or when the chat is a sub-agent
chat. Turning it off is always accepted. The audit table tracks it.
- **Offering.** The tool is offered only in root chats, outside plan
mode and explore mode, with the switch on, and with the experiment on
for the chat owner (decided once per turn, like `mcp-tool-search`). It
is not on the plan-mode or explore allowlists, and sub-agent chats are
created with the switch off.
- **Per-call recheck.** Every call reloads the chat and checks all rules
again, with a fresh experiment evaluation, before doing anything.
- **Scoping.** Owner and organization come from the chat, never from
arguments. Reads run as the owner through a new query that filters on
organization and owner. Other members' automations are "not found", even
when the chat owner is an organization admin.
- **Automation-reached turns.** Detected at call time from the full
history (compaction replays user rows without `automation_id`, so the
prompt window is not enough). In such turns only automations that target
the chat or created it (`chats.automation_id`) are visible.
- **Visibility of prompts and deletes.** `list` leaves out prompts (tool
results stay in the chat, which may be shared); `get` returns the prompt
of the automation it names. In a turn an automation reached, `delete`
only removes the triggering automation; the others can still be
disabled.
- **Audit.** `disable` and `delete` go through the management service
and write a background audit entry with `chat_id`, plus the triggering
`automation_id` and `input_id` in reached turns. Results use the API
shape and never contain a secret or secret hash.

`create`, `update`, `enable`, and `run_now` come in the next PR and
return "not available in this version" here.

Follow-up: CODAGT-1270 (bound the history read that reached-turn
detection does on each call).

## Size

About 1,380 hand-written lines: about 460 production, 680 tests, and 240
SQL that has to be there (the `chats_expanded` view rebuilt in both
migrations and the 17 inline column lists). Generated: +649/-280 (sqlc,
dbmock, dbmetrics, dump.sql, apidoc, API and audit docs,
`typesGenerated.ts`).

## Validation

- Unit and DB tests for every rule above (switch 403/400 cases, offering
rules, per-call recheck, owner/org scoping with an org-admin owner,
reached-turn detection including compaction replay, audit fields, secret
scan), plus a separate test audit. Full `make pre-push` passed before
push.
- Remote dogfood UAT passed on this slice: switch API cases, tool absent
with the switch off, in plan mode, in sub-agents and with the experiment
off for the owner (checked in the server's per-step tool lists),
list/get/disable/delete, and a secret scan of all tool output. Audit
entries are verified in Go tests only.

> [!NOTE]
> ARCHITECTURE.md prose was drafted by an agent at the user's request;
the user will review it.

## Stack

Stacked on the Automations for Coder Agents stack (30085 ... 1214b).
Next: slice 12b (write actions), then 12c (composer toggle).

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
2026-10-02 15:54:55 +00:00
Thomas Kosiewski b96f1b970c feat: label automation messages in agent chats (#30167)
Closes CODAGT-1215. Part of CODAGT-1135 (Automations for Coder Agents,
RFC step 9).

Chat messages and queued inputs delivered by a chat automation (webhook,
schedule, Run now) now show a label: `Automation run · <automation name>
· input <first 8 chars of input ID>`. A tooltip holds the full
automation and input IDs. While names load, the label omits the name
part. When the name cannot be resolved (deleted automation, a
shared-chat viewer who cannot read it, or experiment off), the label
shows the automation ID instead. Ordinary messages have no label.

## Changes

- **Backend (minimal, SDK exposure only):** `codersdk.ChatMessage` and
`codersdk.ChatQueuedMessage` gain `automation_id` and `input_id`
(omitted when unset). `db2sdk` fills them from the existing columns, so
REST messages and the stream `message` and `queue_update` events carry
them. No behavior change in the lower layers.
- **Frontend:** `API.experimental.getChatAutomations`, a
`chatAutomations` query, and `useChatAutomationNames`. The hook fetches
`GET /api/experimental/organizations/{org}/chat-automations` only when
the user-scoped `chat-automations` experiment is on and the chat holds
automation input. The `AutomationLabel` component uses the shared
`Badge` and `Tooltip`, and is wired into `ConversationTimeline`
(history) and `QueuedMessagesList` (queue). The chat store refetches
names when new automation input arrives, so automations created or
renamed after page load show their current name.
- Out of scope, per the ticket: the occurrence label and the
requested-versus-resolved effort display.

## Validation

- Vitest: the automations list is requested for the chat's organization
only when the chat holds automation input and the experiment is on;
`useChatAutomationNames` reports loading until the list resolves and
then maps IDs to names; the chat store refetches names on new live
automation input. Go: `TestChatMessageAutomationProvenance` for both
converters.
- Storybook (Pixel): `ConversationTimeline/AutomationUserMessages` and
`QueuedMessagesList/AutomationMessages` (named, deleted by ID, long name
at phone width, no label on ordinary items) and
`QueuedMessagesList/AutomationMessagesLoading` (name still loading: no
UUID flash).
- Remote dogfood UAT on a develop.sh instance with the experiment on:
PASS in round 2. It covered webhook input in an existing chat (history
and queue), a schedule, a new_chat first message, the ID fallback after
deletion, and no label on ordinary messages. Screenshots are in a
comment below. Run now was not on the base branch during UAT; it uses
the same fields and path.
- coder-frontend-review self-review: all roles PASS, after fixes on each
update.

## Known limitations (follow-ups under CODAGT-1135)

- A shared-chat viewer who does not own the automation sees its ID,
because automation RBAC has no chat ACL (CODAGT-1239).
- Copying the label text yields three lines, because the name span
truncates separately (CODAGT-1238).

## Stack

Stacked on #30085, #30096, #30112, #30117, #30127, #30134, #30160 (1211
7a) and #30166 (1211 7b). Base: `tk/codagt-1211b-automations-run-now`.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_

---------

Signed-off-by: Thomas Kosiewski <tk@coder.com>
2026-10-02 15:54:53 +00:00
Thomas Kosiewski 9316d67440 feat: add chat automations management API behind chat-automations (#30112)
Adds the management API for chat automations under
`/api/experimental/organizations/{organization}/chat-automations`,
behind the new user-scoped `chat-automations` experiment. This is the
first of two PRs for RFC step 3; nothing publishes automation messages
yet.

- **Experiment:** `chat-automations` is in `ExperimentsKnown`,
`ExperimentsUserScoped`, and the ruleguard list in `scripts/rules.go`.
Every route asks `chatd.AutomationsEnabled(ctx, api.ExperimentEvaluator,
callerID)`, which fails closed on a missing subject or evaluator; the
routes stay mounted and return 404 when the experiment is off for the
caller, so a runtime rule for one user applies on the next request
without a restart. There is no `/api/v2` alias.
- **Routes:** list, create (201), get, `PATCH`, delete (204), with
Swagger annotations and audit entries. List returns the automations in
the organization the caller can read (members see their own,
organization admins see all).
- **Service** (`coderd/x/chatd/automations.go`): create validates kind
and target shape, a non-empty prompt, a five-field cron and IANA time
zone, model access, and that an `existing_chat` target is a root chat of
the owner in the same organization. It defaults `when_busy` to `skip`
for schedules and `queue` for webhooks and computes the first schedule
cursor. `PATCH` runs the same per-field validation on each changed
field, rejects `kind` and `target_mode`, bumps `schedule_revision` on
prompt, cron, or time zone changes, and recomputes the cursor on cron or
time zone changes.
- **Owner-only:** only the owner can `PATCH` an automation, even with
organization-admin or site-owner roles (403); admins can list, read, and
delete.
- **Secrets:** a webhook's secret (`coder_automation_` prefix) is
returned once in the create response. Only its SHA-256 is stored, and it
appears in no list, get, audit, or log output.
- **Cap:** new option `--chat-max-automations-per-owner` (default 50)
caps automations per owner across all organizations; creating one more
returns 409. Creates serialize on a per-owner advisory lock.
- **Cron:** `cron.Standard(spec, timeZone)` accepts any standard
five-field expression (the existing `Weekly` rejects day-of-month and
month restrictions). Responses include the next five run times of an
enabled schedule.

PR 3b (stacked on this one) adds disable and re-enable with the queue
cutoff, makes delete run disable first, and adds secret rotation and the
schedule preview route. Until then, the queue promotion guard from
#30096 discards queued rows whose automation was deleted.

Dogfood UAT ran on a real dev instance and passed:
create/list/get/patch/delete via curl, owner-only 403s for an
organization admin and the site owner, the cap (including concurrent
creates and cross-organization counting), a runtime rule turning the
experiment off for one user without a restart, and `/api/v2` 404s.

Part of CODAGT-1209 (PR 3b closes it)
Part of CODAGT-1135
Refs CODAGT-1217

Stack: PR 3 of the Automations for Coder Agents stack, on top of #30096
(which is on top of #30085).

> This PR was written by an AI agent (xum) and reviewed by the agent's
own test audit and UAT. A human has not reviewed it yet.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_

---------

Signed-off-by: Thomas Kosiewski <tk@coder.com>
2026-10-02 15:54:49 +00:00
Mathias Fredriksson ff158c0589 feat: preserve user-supplied chat titles (#29486)
Chats created through the API or MCP couldn't be given a title, and
automatic title generation could overwrite a title the user had set,
at creation or by renaming during generation. #30254 tried to keep
renames by comparing title text, but text can't tell a user title
from a generated one that has the same text.

Chat creation over the API and MCP now accepts a title. Each chat
records where its title came from: fallback (derived from the
prompt), generated, or user. A title can only be replaced by a title
from the same source or a higher one, so automatic generation never
overwrites a user's title. Title changes no longer reorder the chat
list, and clients apply them in the order they were written. Chats
created before this change are treated as having fallback titles.

Closes CODAGT-1047
Reverts #30254
2026-10-02 12:58:53 +00:00
Garrett DelfosseandClaude Opus 5.5 7cd1b2040b feat: add chat projects API (#29242)
- Experiment, behind `chat-projects` (off by default). First of three
stacked PRs: #29301 (memory), #29583 (UI). This PR is API only; the
screenshots below are from the UI in #29583.
- CRUD under
`/api/experimental/organizations/{organization}/chats/projects/{project}`.
`GET /api/experimental/chats/projects` lists the caller's projects
across all organizations.
- `project_id` on chat create and as a chat list filter. A chat joins a
project only at creation; there is no move.
- Projects are identified by ID. Names are display labels (64
characters, description 1024) with no uniqueness constraint. An optional
`icon` URL (usually an emoji image under `/emojis`) is capped at 256
characters and audited.
- A user can own at most 100 projects across all organizations; creating
another answers 409. Creates count and insert under a per-owner advisory
lock so concurrent requests cannot overshoot.
- Projects are private to their `owner_id`. Members may only create
their own, and a chat can only be bound to a project its owner owns. An
unreadable or foreign project on chat create answers 404 so IDs cannot
be probed; a project from another organization answers 400.
- Permissions ride on the `agents-access` role next to chats (after
#30004), so whoever can use Coder Agents can use projects. Owners and
org admins reach every project.

### Examples

Create a project in an organization:

```http
POST /api/experimental/organizations/{organization}/chats/projects
{"name": "Platform", "description": "Infra and deploy work", "icon": "/emojis/1f680.png"}
```

```json
{
  "id": "7c0e4a3e-5b1f-4f7d-9a51-2f3c8f6d2b10",
  "organization_id": "bb640d07-ca8a-4869-b6bc-ae61ebb2fda1",
  "owner_id": "0ed9befc-4911-4ccf-a8e2-559bf72daa94",
  "name": "Platform",
  "description": "Infra and deploy work",
  "icon": "/emojis/1f680.png",
  "created_at": "2026-09-30T15:04:05Z",
  "updated_at": "2026-09-30T15:04:05Z"
}
```

List the caller's projects across organizations with `GET
/api/experimental/chats/projects` (an array of the object above). Update
with `PATCH .../chats/projects/{project}` and any of `name`,
`description`, `icon`; delete with `DELETE`, which detaches its chats.

Create a chat in the project, and list only its chats:

```http
POST /api/v2/chats
{"organization_id": "bb640d07-…", "project_id": "7c0e4a3e-…", "content": [{"type": "text", "text": "Plan the deploy"}]}

GET /api/v2/chats?project_id=7c0e4a3e-…
```

At the limit:

```json
409 {"message": "You can have at most 100 chat projects. Delete a project to create another."}
```

<details>
<summary>Screenshots (UI from #29583)</summary>

![Create
project](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr1-01-create-project-dialog.png)
![Sidebar
folders](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr1-02-sidebar-folders.png)
![Project
page](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr1-03-project-page.png)
![Folder
menu](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr1-05-folder-menu.png)
![Another member sees no
projects](https://raw.githubusercontent.com/coder/coder/f0ssel/chat-projects-assets/v3/pr5-member-sees-no-projects.png)

</details>

---
Generated with Coder Agents on behalf of @f0ssel.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 11:49:21 -04:00
Ethan f64ccfb836 feat: add experimental inline MCP servers (#29546)
Closes CODAGT-1131

Fifth PR in the inline MCP servers stack, on top of #29520. A chat owner
can now declare MCP servers by URL and headers on their own chat, and
chatd connects to them every turn alongside the org-configured ones.

They go in a new `inline_mcp_servers` field on `POST /api/v2/chats` and
`POST /api/v2/chats/{chat}/messages`, which replaces the whole set (omit
to keep, `[]` to remove). Root chats only. `GET /api/v2/chats/{chat}`
returns them, with the URL blanked for non-owners and header values
never returned. Subagents only get servers marked `allow_in_subagents`,
a root chat in explore mode gets none, and a root chat in plan mode gets
all of them.

URLs must be `https`, or `http` to an IP literal in
`CODER_MCP_ALLOWED_PRIVATE_CIDRS`. Header values have no minimum length,
so anything under the redactor's 8 byte floor from #29518 is accepted
but not redacted, which the docs call out. Every cap is exported from
`codersdk`.

It's behind the `chat-inline-mcp-servers` experiment, and the
`--disable-chat-caller-supplied-tools` kill switch from #29466 covers it
too. With either off, declaring servers gets a 403 and existing chats
stop connecting to theirs, but `[]` still works so a client can detach.

Load failures show up in the chat debug panel as failed connections, as
do org servers with an invalid config. Docs are hand-written in
`mcp-servers.md`.
2026-09-25 18:51:55 +10:00
Thomas Kosiewski 2de1f8b111 feat: link promoted chat messages to their queue entry (#29859)
Signed-off-by: Thomas Kosiewski <tk@coder.com>
2026-09-25 09:51:25 +02:00
Bobby Ho c95a87cea7 feat: warn before narrowing a self-registered OAuth2 app's scope allowlist (#29777)
- Warn rather than block when admins narrow a self-registered OAuth2 app's scope allowlist. Clients requesting all advertised scopes may receive `invalid_scope` on new authorizations; existing tokens retain their scopes.
- Expose `dynamically_registered` in API responses and display registration type on the app page.
- Show no warning for widening or clearing allowlists, or for admin-created apps.
- Update scope and `invalid_scope` troubleshooting docs and remove the outdated note that the UI cannot set allowlists.

Closes PLAT-664.
2026-09-24 08:03:32 -07:00
Bobby Ho 9fd0131d04 feat: accept redirect_uris on the OAuth2 app admin API and deprecate callback_url (#29502)
- Add `redirect_uris` to admin OAuth2 app responses and create/update requests.
- Deprecate `callback_url` while preserving compatibility; it maps to the first redirect URI.
- Reject empty `redirect_uris` lists instead of silently ignoring them.
- Update fixtures, tests, and docs.

Part of PLAT-619. Builds on #29440; admin UI support follows in #29603.
2026-09-22 19:12:27 +00:00
Bobby Ho b9e3de8403 fix: make redirect_uris the source of truth for OAuth2 redirect URIs (#29440)
Fix OAuth2 callback edits retaining stale redirect URIs

- Make `redirect_uris` the sole source of truth, with the first entry as primary and `callback_url` retained as a synchronized, deprecated copy.
- Backfill existing apps and unify all writers. Callback-only admin updates now replace the previous primary while preserving alternate URIs.
- Share redirect URI validation, reject fragments, and add limits of 32 URIs and 2048 bytes per URI.
- Add regression coverage for migration, callback edits, validation, and rejection of removed URIs during authorization and token exchange.

One data migration; no schema or request/response shape changes. Admin API and UI list editing follow separately.

Rollout: Drain old replicas before upgrading; callback edits handled by old code are not reflected on new replicas.

Refs PLAT-619.
2026-09-22 10:49:19 -07:00
Bobby Ho 55da502938 feat: allow admins to configure an OAuth2 app's scope allowlist (#29313)
Add backend support for scope allowlists on admin-created OAuth2 apps, previously available only through DCR.

- Add optional, space-separated `scope` to create/update requests and return canonicalized, deduplicated scopes in app responses.
- On create, omitted or empty `scope` means unrestricted. On update, `scope` replaces the allowlist; omission preserves it, and an empty string clears it to unrestricted.
- Keep scope enforcement unchanged. Add tests for scope round-trips, DCR canonicalization parity, and authorization narrowing.
- Include generated SDK and docs updates. The UI scope picker follows in a separate PR.

Part of [PLAT-475](https://linear.app/codercom/issue/PLAT-475).
2026-09-18 11:58:49 -07: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
Michael Suchacz 26e4429362 test: fold near-identical test bodies into tables across eight packages (#29463)
Folds groups of near-identical test bodies (same parent, same parallel
flag, differing only in inputs and expected values) into table-driven
tests in eight packages: `coderd/templatebuilder`, `scripts/develop`,
`agent/agentfiles`, `coderd/x/chatd/chatloop`,
`coderd/x/chatd/chatdebug`, `enterprise/aibridgeproxyd`, `cli`, and
`coderd/database/db2sdk`. One commit per package.

Every case keeps its previous subtest name, `t.Parallel()` placement is
unchanged, and the set of `=== RUN` names is identical except where
standalone `TestX_Y` funcs became `TestX/Y` subtests (chatloop: 9 funcs
into `TestExecuteLocalTools_BatchRuntime`; chatdebug: 15 funcs into two
tables). Members whose bodies differ in more than data stayed as they
were (listed per package in the commit messages). In `agent/agentfiles`
the four `TestFuzzyReplace_*` funcs were already tables, so the shared
request plumbing was hoisted into one helper instead of merging the
funcs and losing their per-rule docs. Net -1035 lines across 9 test
files; runtime is unchanged (all sub-100ms unit tests).

| Package | Diff | Funcs removed | Subtests | RUN lines |
|---|---|---|---|---|
| coderd/templatebuilder | +237 / -291 | 0 | 31 -> 31 | 33 -> 33 |
| scripts/develop | +194 / -246 | 0 | 27 -> 27 | 28 -> 28 |
| agent/agentfiles | +117 / -260 | 0 | unchanged | 58 -> 58 |
| coderd/x/chatd/chatloop | +224 / -306 | 9 | 3 -> 12 | 14 -> 15 |
| coderd/x/chatd/chatdebug | +251 / -537 | 13 | 0 -> 15 | 42 -> 44 |
| enterprise/aibridgeproxyd | +287 / -419 | 0 | 31 -> 31 | 32 -> 32 |
| cli | +143 / -326 | 0 | 15 -> 15 | 16 -> 16 |
| coderd/database/db2sdk | +130 / -233 | 0 | 9 -> 9 | 10 -> 10 |

## Validation

- Per package: `go test -count=1 -tags=testsmallbatch -parallel=8
./<pkg>/ -run <regex> -v` before and after, with the `=== RUN` name sets
diffed
- `go test -race -count=2 -shuffle=on` on each converted test: pass
- `golangci-lint run ./<pkg>/...` with a fresh cache: 0 issues in all
eight packages
- Repository pre-commit hook (including lint/go) passed on every commit

Part of the test-suite speedup series (see #29457); independent of the
other PRs.

## Remote validation

Remote run on a dogfood workspace (separate compute), chat
https://dogfood.cdr.dev/agents/5bbe73d0-866a-4841-9cc3-c5e5b4d97e44,
tested head `d7c55d6b0e8` against base `9d973372774`: all eight packages
pass on the head and under `-race -count=3 -shuffle=on`; package times
are sub-second on both sides (unchanged). `=== RUN` name sets: chatloop
15 to 16 lines with all nine `TestExecuteLocalTools_<X>` leaves
surviving as `TestExecuteLocalTools_BatchRuntime/<X>`; chatdebug 42 to
44; `aibridgeproxyd` `TestNew` 32 to 32, byte-identical sorted list. One
correction to the text above: seven chatdebug leaves are renamed, not
preserved verbatim (`TestRecordingTransport_*UnknownLength*` became
`TestRecordingTransport_UnknownLengthClose/<name without
"UnknownLength">`), so `-run` filters keyed on those old names need
updating. Endorsed verdict: PASS.


> Xum (an AI agent) authored this PR on behalf of @ibetitsmike.
2026-09-17 19:26:18 +02:00
Michael Suchacz d2e94e299a chore: delete dead functions and skip-only or duplicated tests (#29461) 2026-09-17 18:14:08 +02:00
Michael Suchacz 9d97337277 feat: list organization AI spend by user (#29129)
Third of a four-PR stack that reworks the AI spend page onto the
released organization spend export, `GET
/api/v2/organizations/{organization}/ai/spend/export`, and a sibling
per-user endpoint, `GET
/api/v2/organizations/{organization}/ai/spend/users`, instead of the
deployment-wide `/api/v2/ai-gateway/spend/*` endpoints this stack
previously proposed. Every PR in the stack was rewritten in place from
current main; the head branch name predates the rework. The export's
accounting rules are unchanged: token usage by `created_at` in
`[period_start, period_end)`, attributed to the organization through the
effective budget group, so the page reconciles with the CSV and with
daily budget accounting.

Adds `GET /api/v2/organizations/{organization}/ai/spend/users`, a
paginated per-user report beside the CSV export. It accepts the export's
period parameters and the optional `provider_name`, `model`, and
`client` filters (`client` matches after `COALESCE(client, 'Unknown')`,
as the AI Gateway sessions listing does), and it authorizes identically
through `ResourceGroupMember` in the organization. The response is
`OrganizationAISpendReport`: the applied period bounds,
`retention_start` when retention is enabled (so the page can bound its
date picker), the user count, a `totals` object over every matching
user, and one page of users (`limit` default 10, max 100; `offset` >=
0), each with cost, unpriced usage count, providers, and clients. Each
user row also lists the sorted distinct models they spent through
(e73049f, added on request after the review round).

The period rules (provided together, at most 31 days, within retention,
default narrowed to retention) are shared with the export through the
caller's query parser. As a result the export now rejects unknown query
parameters whether or not a period is given; previously the
excess-parameter check only ran in the explicit-period branch. The
export's parameters and output are otherwise unchanged; the CSV itself
is not filterable.

The JSON rows are per user while the CSV keeps its user x group x
provider x model grain. That is deliberate: the page is the only JSON
consumer, and an explicit `group_by` can be added later without changing
this contract. A page past the last user still carries the window
totals, read from the first page.

Query cost, measured on PostgreSQL 13 with 400k token usages and 200k
interceptions across 4 organizations (31-day window of about 52k usages
for the target organization): `ListOrganizationAISpendUsers` 128 ms
unfiltered and 68 ms filtered by provider. Token usage is read through
the existing partial index on `(effective_group_id, created_at)`; no new
index is needed. The provider and client aggregates were added after
this measurement.

Tests cover pagination validation (including the export rejecting page
parameters), report contents and filters against the CSV, retention
narrowing and rejection, retention disabled, and the role matrix (Owner,
User Admin, Auditor, Org Admin, Org User Admin OK; member 403; other
organization 404).

Previous revisions served this report from the export endpoint through
`Accept` negotiation and also added the dimension filters to the CSV
export (#29220, #29224); the separate endpoint replaces the former, and
the CSV filters were dropped because the page does not use them.

> Xum prepared this PR on behalf of @ibetitsmike.

Codex on e73049f: P2 on the moving `now - retention` lower bound for
clients that echo the default window while paging. Declined: it is the
released CSV export's contract, the report echoes `retention_start`, and
the page never echoes the default window; the handler and tests now use
`OrganizationAISpendPage` (8cdc127).
2026-09-17 04:32:16 +00:00
Bobby Ho 070a91c1d9 feat: hide client secrets for public OAuth2 clients (#29312)
Fix the OAuth2 app edit page for public clients by replacing the secrets table and “Generate secret” button with an explanation and skipping secrets requests, including on initial load. Expose client_type in OAuth2 app API responses and regenerate TypeScript types and API docs. Confidential client behavior remains unchanged. Fixes PLAT-504.
2026-09-15 16:40:36 +00:00
McKayla はな 2a8e390f0c refactor: replace most usage of ptr.Ref with new (#28282) 2026-08-26 11:57:56 -06:00
Susana Ferreira 276d0a8586 fix: expose effective member AI budgets (#28410)
## Description

The group members page could not distinguish an unlimited Everyone
fallback from a configured budget on the Everyone group when viewing
another group, so it incorrectly displayed `Unlimited` and `Everyone
(not allocated)` despite the configured Everyone budget.

The member spend response now includes `effective_budget` as the
canonical budget that currently applies to the user. The existing
`group_budget` field remains for backward compatibility and is
deprecated in favor of `effective_budget`.

## Changes

- Add `effective_budget` to group member AI spend responses.
- Deprecate `group_budget` in favor of `effective_budget`.
- Display budgeted Everyone as the governing group instead of
`Unlimited` and `Everyone (not allocated)`.
- Add database, API, conversion, and Storybook coverage.

Closes https://linear.app/codercom/issue/AIGOV-588

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-08-26 16:17:07 +01:00
Michael Suchacz 45f2eb48cc refactor(coderd): restore agents-access cleanup migration (#28587)
## Summary

- restore the `agents-access` data cleanup migration as `000587`
(renumbered from `000585`; main advanced past that number)
- revert the temporary RBAC tolerance for retired role names now that
the migration strips stale grants
- make the migration test discover its predecessor dynamically, since
this branch does not carry main's `000585`/`000586`

## Stack context

Stacked on #28186, which retires the `agents-access` role but
intentionally ships without a migration so it can be backported across
diverged migration numbers. This layer completes the retirement on main:
it cleans up stale role grants in `users.rbac_roles`,
`organization_members.roles`, and
`organizations.default_org_member_roles`, then reverts the interim
leniency (role expansion dropping legacy names, assignment validation
ignoring them) that existed only to keep the migration-less base safe.
`rbac.ReservedRoleName` still reserves the retired name so custom roles
cannot shadow it on rollback. Do not backport this PR alongside the base
PR.

## Rollback note

The down migration restores effective access broadly because it cannot
reconstruct which users previously held the removed role.

## Validation

- `go build ./coderd/... ./enterprise/...`
- full `coderd/database/migrations`, `coderd/rbac/...`, and
`coderd/database/dbauthz` suites
- targeted members tests in `coderd`
- repository pre-commit checks (`lint/go`, `lint/ts`, etc.)

> Mux created this pull request on Mike's behalf.
2026-08-26 15:29:26 +02:00
Michael Suchacz 845790e652 feat: enable Coder Agents for organization members (#28186)
## Summary

- make Coder Agents available to organization members without a separate
built-in role
- remove the obsolete role from backend and frontend role surfaces
- update authorization, UI, documentation, and regression coverage

## Database note

This PR intentionally ships no migration so it backports cleanly across
diverged migration numbers. Stale `agents-access` grants may remain in
user role arrays and org default member roles; the retired name is
treated as a grant of nothing (role expansion drops it, assignment
validation ignores it, and the name stays reserved). A follow-up PR will
add the data cleanup migration.

## Validation

- `make gen`
- `make lint`
- repository pre-commit checks
- targeted RBAC, migration, chat API, enterprise, site, Storybook, and
race tests
- `git diff --check`

## Rollback note

Rolling back the deployment restores the previous behavior directly: no
data changed, and older binaries still resolve any lingering
`agents-access` grants.

> Mux created this pull request on Mike's behalf.
2026-08-26 13:33:13 +02:00
Susana Ferreira 50ecd6959f feat: add a source filter to the AI model price list (#28329)
## Description

With prices from the price book and prices set through the API both in the table, `list` showed only the price in effect and gave no way to tell where it came from. There was also no way to see the price book's entry for a model that had been overridden, since the listing resolves to the custom price.

This adds a `source` column to the output and a `--source` filter for narrowing to one source, or to every row with `all`.

Note: `--source` selects rows rather than models. A model carrying both a price book price and a custom one appears under either value, so the two filtered listings do not sum to the unfiltered one. `--source all` reports both rows at once.

## Changes

- Add `Source` to `codersdk.AIModelPrice` and `AIModelPricesFilter`, and map it in `db2sdk`, which previously dropped it.
- Filter `GetAIModelPrices` by source before resolution, so the price book's row for an overridden model stays reachable.
- Accept `all` as a source, which reports every price a model holds instead of resolving to one.
- Accept a `source` query parameter on the list endpoint, rejected with a 400 when outside the enum.
- Add `--source` to the list command and a `source` column to its output.
- Document the column and the filter, and lead the price section with `coder exp ai-model-prices list`.
- Distinguish a deployment's default prices from the price book that ships with each release.

Closes https://linear.app/codercom/issue/AIGOV-593

> [!NOTE]
> Initially generated by Claude Opus 5, modified and reviewed by @ssncferreira
2026-08-20 11:56:58 +01:00
Michael Suchacz affeeaf9c8 feat: extend agent chat MCP tools for remote UAT evidence loops (#28233)
Extends the Agent-chat MCP tools so an unattended UAT evidence loop can
fetch artifacts, monitor long runs, and find prior runs without burning
model context.

## Backend

- New `chat_files_token` crypto key feature (migration 000571) with
rotator support and a dedicated signing keycache on coderd.
- `POST /api/experimental/chats/files/{file}/download-url`
(authenticated) mints a short-lived (5 min) signed URL and returns it
with `sha256`, `size_bytes`, `name`, `mime_type`, and `expires_at`.
- `GET /api/experimental/chats/files/{file}/download?token=` (no session
token) redeems the signed URL: verifies the JWS, requires the token's
`file_id` to match the path, and re-checks the minting user's RBAC
access live at redemption. Clients can `curl -o` artifacts with zero
credentials in the URL consumer.
- `ChatFileMetadata` gains `size_bytes` (via `octet_length`, no bytes
fetched).

## MCP tools (`codersdk/toolsdk`)

- `coder_download_chat_file`: by `file_id` or `chat_id`+`file_name`;
returns the signed URL plus checksum and size instead of base64.
- `coder_await_chat`: blocks (bounded `wait_secs`, 1-120) until a chat
leaves `running`/`interrupting`, using the existing watch stream with
subscribe-before-read.
- `coder_list_chats`: label, query, and limit filtering; chat
projections now include labels.
- `coder_get_chat_messages`: `after_id` forward cursor with
`next_after_id` (exact incremental reads), plus per-message `files`
metadata so artifact-bearing messages are identifiable.
- `coder_get_chat`: file listings now include `size_bytes` and
`created_at`.
- `coder_list_templates`: exposes `agents_allowed` for pre-flight
checks.

## Testing

- coderd: mint/redeem happy path with an unauthenticated client,
expired/tampered/file-mismatched tokens, auth still required on the
plain file endpoint, non-owner mint rejection.
- toolsdk: harness + integration coverage for all new/changed tools,
including signed-URL redemption with checksum verification,
forward-cursor exactness, await transition/timeout paths, and label
filtering.
- Remote dogfood UAT (dev.coder.com Coder Agent) passed all six
acceptance scenarios end to end over both MCP transports.

Note: `go test ./codersdk/toolsdk/` has a pre-existing goleak flake on
main (leaked `agentssh` non-PTY session goroutines from SSH exec tests;
reproduced 3/3 on clean `b4971bc49f1`). It is unrelated to this diff.

> Mux acted on Mike's behalf to create this PR.

<!-- mux-attribution: model=claude-sonnet-4-6 thinking=high -->
2026-08-18 19:15:30 +02:00
Michael Suchacz 119f2b1dd9 feat: limit concurrent chat agents with pooled admission (#27902)
Limits concurrent chat generation on capped deployments to 5 root chats
and 10 delegated subagent chats. The pools are deployment-wide and
independent, so delegated work can continue while root capacity is full.

The default caps live in AGPL code. Enterprise contributes only a
licensing unlock, so unlicensed deployments stay capped and cannot fail
open. Licensed deployments are uncapped while Agent Hours usage stays
below an explicit hard limit. Deployments without a hard limit remain
uncapped, and reaching the Agent Hours allocation only triggers
warnings.

Admission happens before a worker takes chat ownership. Capped
deployments serialize admission across replicas with a
transaction-scoped advisory lock and derive active and queued state from
current ownership plus fresh runner heartbeats, rather than persisted
queue markers or per-replica state. The acquisition query returns a
bounded, pool-interleaved candidate set instead of ranking the whole
backlog; a migration replaces the acquisition index with a pool-aware
one. Refused chats stay running but unowned, and interrupt requests
bypass admission so users can stop queued or over-cap chats.

The single-chat API derives `queued_for_capacity` from live pool state;
list endpoints do not report it. The UI polls that value every 5 seconds
while a chat is running and shows a callout when the chat is waiting for
capacity.

Updates the administrator documentation and deployment-wide Prometheus
gauges for active and queued agents. Replica-level values must be
aggregated with `max`, not `sum`.

> Mux updated this PR on Mike's behalf.
2026-08-18 16:55:43 +02:00
Susana Ferreira 2d9b6eda8f feat: add experimental CLI to price unpriced AI models (#27926)
## Description

AI Gateway computes the cost of an interception from `ai_model_prices`,
which is seeded on every server start from a price book embedded in the
binary. A model the price book does not cover records a NULL cost, so
its spend is invisible to cost reporting and is not enforced against
budgets. The only fix was to wait for a Coder release that added the
model.

This adds an experimental CLI, backed by an experimental HTTP endpoint,
for pricing those models. Models the price book already covers are
rejected, because the seeder re-applies the book on every start and
would overwrite an operator price. Support for custom pricing will be
handled in
https://linear.app/codercom/issue/AIGOV-589/extend-experimental-cli-command-to-set-custom-ai-model-prices.

## Commands

```
coder exp ai-model-prices list [--provider] [--model]
coder exp ai-model-prices update [file|-] [--provider] [--model] [--input-price] [--output-price] [--cache-read-price] [--cache-write-price] [--yes]
```

## Changes

- Add `GET` and `POST /api/experimental/ai/model-prices`, gated behind
the AI Bridge entitlement and the existing `ai_model_price` RBAC
resource.
- Add a `GetAIModelPrices` query with optional `provider` and `model`
filters applied in SQL.
- Validate the whole request before writing anything, so one bad entry
cannot leave the table half updated, and report every problem at once.
- Reject prices for models the embedded price book already covers,
through a new `prices.IsDefaultPriced`.
- Add the `coder exp ai-model-prices` command with `list` and `update`.
`update` accepts a JSON document or the single-model flags and prints a
plan, asking to confirm unless the document is piped in or `--yes` is
passed.
- Consolidate the supported provider list into
`coderd/aibridge/prices/providers` so the price generator and the server
share one definition.
- Add `codersdk` types and client methods for both endpoints, and bound
the request body at 1 MiB.
- Document the command in the AI Gateway cost controls page.

Closes
https://linear.app/codercom/issue/AIGOV-567/experimental-cli-command-to-set-prices-for-unpriced-ai-models

> [!NOTE]
> Initially generated by Claude Opus 5, modified and reviewed by
@ssncferreira
2026-08-13 15:00:36 +01:00
Andrew Aquino 6e07e2610f feat: add paginated API endpoint for groups (#27603)
backend-only changes from #27271; see that PR for summary of changes +
implementation details
2026-08-10 13:23:14 -07:00
Sas SwartandClaude Opus 4.8 8886a5749a feat: add network calls list to AI session threads API (#27425)
The AI session threads API returned only a network call *summary*
(total/blocked counts + top domains). This adds the per-call list so the
session detail can render individual Agent Firewall network calls.

`ListAIBridgeSessionNetworkCalls` reuses the same sequence-number
windowing as the existing summary and includes all protocols. The list
is exposed as `network_call_logs` on the threads response and is capped
server-side at 100 rows. The summary (`network_calls.total`/`blocked`)
remains authoritative for whole-session totals: the list length and its
blocked count equal the summary only when a session has at most 100
calls, and are truncated beyond that.

### 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-464

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-03 11:34:27 +02:00
841a1765f7 feat: add network calls summary to AI session threads API (#27417)
Backend for the AI session network summary. Exposes total/blocked
network calls and top destination domains on the session threads
endpoint (`GET /api/v2/ai-gateway/sessions/{id}`).

Total and blocked reuse the existing Agent Firewall aggregation from the
sessions list query, so the numbers match the sessions table. Top
domains are a new server-side aggregation
(`GetAIBridgeSessionTopDomains`) over boundary logs, using the same
interception-window correlation. There is no network-error state,
matching the current data model.

Frontend consuming these fields is in a separate stacked PR.

### 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 (base `main`)
2. #27418 — frontend summary rows (base #27417)
3. #27425 — backend per-call list `network_call_logs` (base #27418)
4. #27426 — frontend network-calls panel (base #27425)

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:09:46 +02:00
Susana Ferreira d6a5c8e9f8 refactor: make user AI budget and spend endpoints consistent (#27611)
## Description

Makes the user AI cost control endpoints consistent.

## Changes

- Replaces the flat `spend_limit_micros` and `limit_source` fields on
`GET /users/{user}/ai/spend` with a nested `effective_budget`, reusing
the type behind `group_budget`. The flat pair made it possible to encode
a limit without a source.
- Renames `AIGroupBudget` to `AIBudgetLimit`, since it also carries
`user_override` limits and is no longer group-specific. The type name is
not part of the wire format.
- Moves `/users/{user}/ai/budget` to `/users/{user}/ai/budget/override`.
The endpoint only ever managed the per-user override, which the type,
the handlers, and the operation IDs all already said; the path was the
only place that didn't.

> [!NOTE]
> Initially generated by Claude Opus 4.7, modified and reviewed by
@ssncferreira
2026-07-29 14:01:32 +01:00
Michael Suchacz c17bed25e0 feat: wire chat lifecycle hooks into chatd (#27429)
Wires chat lifecycle hooks into chatd, gated by the
`agent-lifecycle-hooks` experiment. Part of the lifecycle hooks stack
(#27401, #27428, #27430). See `docs/admin/setup/chat-lifecycle-hooks.md`
for the consumer-facing contract.

## Summary

When a hook URL is configured, chatd dispatches `session_start`,
`user_prompt_submit`, `pre_tool_use`, `post_tool_use`, `pre_compact`,
`post_compact`, and `stop` events to the consumer and applies its
responses.

## Design

- **Stateless**: Coder stores no hook dispatch or decision state.
Delivery is at least once; consumers deduplicate on stable payload
identifiers (chat ID, event type, tool-use ID) and answer duplicates
with the same decision.
- **Admission-time prompt effects**: `user_prompt_submit` dispatches
exactly once per submission (create, send, queue, edit, subagent spawn)
and folds its effects into the stored prompt as typed message parts:
original-or-overridden user parts, then model-only `hook-context`, then
a user-visible `hook-notice`. Hook context is stripped from every
client-facing conversion; hook notices are excluded from model prompts.
The server rejects hook parts in client-submitted content.
- **Tool gating**: `pre_tool_use` allow can override tool input; deny
becomes a synthetic denied tool result, with any returned model context
persisted as a model-only transcript row so it never reaches clients.
The denial text identifies an external policy (the deployment's
lifecycle hook) as the source and marks the decision as persistent, so
the model explains the denial instead of retrying it or misreporting it
as an infrastructure failure.
- **Fail closed**: a dispatch failure rejects the triggering request or
moves the chat to the error state in the same transaction as the
affected step, so a runnable state is never published with unapproved
content.
- **Admission before persistence**: `pre_tool_use` is dispatched for the
calls the model produced, before the assistant message is stored. See
"Staged tool admission" below.
- **Fresh dispatch per tool call**: every non-provider-executed tool
call is decided by its own `pre_tool_use` dispatch; Coder never reuses
an earlier decision on the consumer's behalf. Retries re-dispatch the
same logical event.

## Structure

All hook dispatch flows through one seam: entry points build a
`chathooks.Chat` (chat identity) and a `chathooks.Message` (event
details) and call `Trigger.Trigger`, the only component that talks to
the dispatcher. The integration lives in the `coderd/x/chatd/chathooks`
subpackage, split by responsibility:

- `trigger.go`: the trigger seam; builds the wire envelope per event,
normalizes deny into a typed error, and holds the package's single
enabled-check.
- `effects.go`: pure conversion of hook results into transcript rows and
prompt parts.
- `errors.go`: failure classification (dispatch error messages, denial
mapping, tool-result dispatch-failure scanning).
- `tooluse.go`: the tool-call gate (`pre_tool_use` preflight,
`post_tool_use` payloads, applying admitted input to the step).

Server-bound glue stays in `coderd/x/chatd/hook_server.go`: the
chat-parking dispatch error handlers, the step-commit row insertion
wrappers, and the dynamic post-tool-use state loader, which depends on
chatd validation types.

This PR adopts the `codersdk/x/agenthooks` and
`coderd/x/agenthooks/dispatch` import paths introduced at the tip of
#27401; intermediate commits still reference the pre-move paths and are
not individually buildable.

## Staged tool admission

`pre_tool_use` originally ran at tool execution time, which is after the
assistant message carrying the tool call was already committed. An
`input_override` therefore had to rewrite stored message content in
place. @hugodutka pointed out that chatd treats message content as
immutable, and that the rewrite was a shortcut rather than a
requirement.

It was also a correctness problem in its own right: the rewrite only
updated the database, so the transcript could show one input while a
different one had executed.

The hook now runs before the step is persisted:

```text
provider stream ends (tool calls complete, in memory)
  -> pre_tool_use dispatch per call
  -> ONE transaction: assistant row with admitted inputs, synthetic denials, hook rows
  -> execute
```

The step is inserted once, carrying the input the tool runs with.
`UpdateChatMessageContentByID` and `Tx.UpdateMessageContent` are deleted
from #27428, so message content stays immutable.

Two consequences, both intentional:

- **Clients converge rather than wait.** Tool-call parts still stream
live, so a rewritten call briefly shows the model's proposed input
before the committed message replaces it. The chat store already clears
stream state when an assistant message arrives, so the stored input wins
with no frontend change and no added latency before tool cards appear.
- **A call already in history was already admitted.** Execution consumes
the stored input instead of dispatching a second decision, which keeps
one dispatch and one set of hook effects per call. A consumer policy
change between admission and execution applies to later calls, not to
calls already admitted.

The per-chat debug endpoint still records the provider's original tool
input. Its purpose is to report provider behavior, and it requires an
explicit per-chat debug flag; the invariant here covers the transcript.

## Configuration

Adds `chat-hook-url`, `chat-hook-secret`, `chat-hook-timeout`, and
`chat-hook-enabled` deployment options with startup validation. The
flags are hidden from `coder server --help` while the feature is
experimental; the setup guide documents them.

## Tool input validation

Built-in tool arguments reach a consumer as raw JSON with key spelling
preserved, but the tools decode those bytes with Go, which matches
struct fields case-insensitively and keeps the last match. A policy
reading `path` could therefore authorize one value while the tool
executed another, and a lone case variant such as `{"PATH":"/secret"}`
was invisible to a policy checking for `path`.

Coder now rejects a built-in tool call whose input repeats a key or
spells a schema property with different capitalization, before the
`pre_tool_use` dispatch, so a consumer is never asked to authorize bytes
whose meaning depends on the reader. Rejected calls produce an error
result the model can retry; unambiguous calls in the same batch still
run. A consumer-authored `input_override` is rechecked after the
dispatch and fails the turn closed, because the model cannot correct it.
Dynamic and MCP inputs are excluded because the client and the workspace
agent execute those calls rather than coderd.

Two paths needed more than a schema check. Execution resolves a
deprecated tool name to its canonical tool, so validation resolves
aliases first. The `edit_files` decoder also reads `search` and
`replace`, which its schema does not advertise, so those aliases are now
matched exactly and their case variants ignored.

A hook denial now returns a structured 403 carrying `kind:
"hook_denied"`, mirroring the dispatch-failure response that already
carries its own kind. Without it a client cannot tell a policy decision
apart from a generic failure, and the chat UI titled a denial "Request
failed". Adding a kind needs no migration: `ChatErrorKind` is persisted
only inside the JSONB `chats.last_error` column, whose decoder accepts
unknown kinds.

The hook docs also correct the tool-input convergence window. A batch
dispatches sequentially before the assistant row commits, so the
original input stays visible for a span that scales with the number of
tool calls in the step rather than a single hook timeout.

> This PR was written by Mux, an AI coding agent, on Mike's behalf.
2026-07-29 11:39:12 +00:00