Linear:
[CODAGT-1101](https://linear.app/codercom/issue/CODAGT-1101/agent-plugins-read-only-support-behind-the-agent-plugins-experiment)
**tl;dr:** Adds the `agent-plugins` experiment and the Agent API v2.17
messages that carry Agent Plugins data from the agent to coderd. First
of eight stacked PRs adding read-only [Agent
Plugins](https://agent-plugins.org/) v1.0.0 support.
A plugin is a directory with a `plugin.json` manifest, skills under
`skills/`, and an optional `mcp.json`. Across the stack, the agent
discovers plugins in `plugins/` and `.agents/plugins/` under its scan
roots (for example `~/.coder/plugins/<name>`), chatd lists their skills
with plugin attribution, the agent runs the MCP servers of plugins in
the workspace working directory, and the Agents page shows plugin
attribution in the chat context. Hooks, commands, agents, install flows,
and org-managed plugins are out of scope. Background:
[research/agent-plugins-standard.md](https://github.com/coder/scott-misc/blob/main/research/agent-plugins-standard.md)
(internal).
This PR adds `codersdk.ExperimentAgentPlugins` and a `PluginBody` oneof
variant on `ContextResource` (tag 18) that carries the validated
manifest fields and nests the plugin's skills and MCP servers.
`Manifest` gains `agent_plugins_enabled` (field 23), which coderd sets
when the experiment is enabled; the agent discovers plugins only then.
coderd stores each nested resource as its own row with the plugin's name
in a new `plugin_name` column (migration 000642), which the hydrate, MCP
sync, and re-pin queries copy. With the experiment off,
`PushContextState` drops plugin resources and everything nested in them.
Otherwise it rejects pushes with plugin names that fail
`workspacesdk.ValidatePluginName` (the spec's name grammar, shared by
agent and coderd), OK plugins without a name or with a duplicate name, a
non-OK plugin that nests resources, nested entries of the wrong kind,
plugin skill sources outside `<plugin source>/skills/`, and plugin MCP
servers with an empty `server_name` or a source other than `<plugin
name>/<server_name>`. Nested resources count toward the 1000-resource
cap.
Agents now dial v2.17, so a new agent needs a coderd that supports it,
as with every Agent API minor. Turning the experiment off does not
remove plugin data already pinned to existing chats.
<!-- pr-map:start -->
<details><summary>PR map</summary>
`main..4b0cfc9657`
| Category | Files | + | - |
|---|---:|---:|---:|
| prod (backend) | 15 | 342 | 78 |
| test (backend) | 9 | 534 | 3 |
| migrations | 2 | 14 | 0 |
| generated (backend) | 7 | 1216 | 1027 |
| generated (frontend) | 1 | 2 | 0 |
| **Total** | 34 | 2108 | 1108 |
1. `coderd/agentapi/context.go` (+211/-51, API): drops plugin resources
when the experiment is off; otherwise validates plugin names and
nesting, and stores each nested skill and MCP server as its own row with
the plugin's name.
2. `agent/proto/agent.proto` (+39/-9, API): `PluginBody` with nested
`skills` and `mcp_servers`, and `Manifest.agent_plugins_enabled`.
3. `codersdk/workspacesdk/frontmatter.go` (+31/-0): `ValidatePluginName`
and `MaxPluginNameLength` (manifest name grammar).
4. `coderd/database/queries/chats.sql`, `workspaceagentcontext.sql`,
migration 000642 (+28/-7, DB): the `plugin_name` column on both context
resource tables, copied by the hydrate, MCP sync, and re-pin queries.
5. `codersdk/agentsdk/agentsdk.go`, `agent/agent.go` (+18/-4, API):
`Manifest.AgentPluginsEnabled` and `ConnectRPC217WithRole`; the agent
dials v2.17.
6. `coderd/agentapi/api.go`, `manifest.go` (+4): the manifest flag
follows the experiment.
7. `tailnet/proto/version.go` (+8/-1, API): Agent API v2.17.
8. `codersdk/deployment.go` (+4, API): the `agent-plugins` experiment.
</details>
<!-- pr-map:end -->
---
This PR was generated by Coder Agents on behalf of @jscottmiller.
Co-authored-by: Garrett Delfosse <delfossegarrett@gmail.com>
The agent now sets CODER_WORKSPACE_TEMPLATE_ID and
CODER_WORKSPACE_TEMPLATE_NAME for every command it runs, from new
template_id and template_name manifest fields. Templates run different
scripts in different orders, so a user's own script needs to know which
template it runs under to coordinate with that template's scripts.
The Agent API goes to v2.16 because release/2.39 shipped v2.15.
CODER_WORKSPACE_BUILD_ID loses its nil checks: an agent only connects
to servers that support its API version, and those always send the
build ID. The environment variables docs now list the variables the
agent sets.
Fixes the `TestServer_Metrics/Forwarding` flake reported in
[PLAT-609](https://linear.app/codercom/issue/PLAT-609/flake-testserver-metricsforwarding)
and, in addition, other defects similar to it.
## Testing defects
### The Original
`TestServer_Metrics/Forwarding` waited for `batches_dropped_total` and
then asserted on `logs_dropped_total`. The forwarder updates those two
counters separately, on adjacent lines, so a read between them sees the
first updated and the second not. CI caught exactly that window:
expected 2, actual 0 at `proxy_test.go:780`. Each counter is atomic on
its own, so the race detector reports nothing.
### The Additional
The fallacy of the original is a _de facto_ assumption that sequential
updates are atomic as a group. The defect arose from not taking into
account that they are atomic individually. The test asserted before the
work was completed. A repo-wide sweep for related metrics written
together found similar mistakes in other tests:
- Live races: all three phases of `TestServer_Metrics/Forwarding` and
`TestServer_Metrics/BufferFull` in `agent/boundarylogproxy`, and
`TestMetadataBatcher_DropsWhenFull`, which waited for the update channel
to empty although the final flush runs after that.
- Correct only because of the current implementation's ordering:
`TestMetrics_TokenUseCount` in `aibridge`, four tests in
`coderd/agentapi/metadatabatcher`, and `TestAgentStatsSessionCounts` in
`coderd/prometheusmetrics`. These pass today but would start failing if
the code under test reordered its work.
## Fixes
All tests the sweep found were fixed. Each test now waits for every
value it asserts before asserting it. Where a value is already non-zero
from earlier work, or legitimately zero, the wait is for the final value
rather than for a change, and several tests use
`require.EventuallyWithT` so the wait and the assertion are one step.
Two Forwarding phases gain assertions on values they already waited for:
`batches_dropped_total == 1` in phase 1, and the reporter's recorded
request count in phase 2.
Two phases of `TestAgentStatsSessionCounts` assert that the counts did
not change. No wait on an unchanged value can show that the collection
cycle ran, so they keep waiting on the execution histogram, and a
comment at that wait names the dependency.
Each fix was checked by temporarily blocking or reordering the code
under test between the relevant writes: the old test failed on every run
and the new one passed.
## Documentation
As a guard against recurrence of defects of this kind, we add the
following documentation targeted mostly at agents. The material in
`TESTING.md` provides guidance about how to write such a test correctly
in the first place. That in `AGENT_FAILURES.md` describes how to
recognize the symptoms of this class of test failure, should they arise.
- `.claude/docs/TESTING.md`: new section "Wait for Full Completion
before Asserting", covering waits on one value with assertions on
another, Prometheus metrics in particular, and assertions that nothing
changed.
- `.claude/docs/AGENT_FAILURES.md`: a catalog entry for the symptom.
- `coderd/coderdtest/promhelp`: doc comments noting that each helper
call is a separate gather.
Generated with Claude Code under the direction of @eric-hughes-coder.
- Reject external app URLs with javascript, vbscript, data, blob, file,
or filesystem schemes, or control characters, for template and
sub-agent apps.
- Skip invalid sub-agent apps and log the reason; the dev container
still starts.
- Strip the $SESSION_TOKEN placeholder from sub-agent app URLs.
- Drop app status URIs that aren't http, https, or file.
Ingest, the template insights API, and the Prometheus metric now use one rule to fold apps and one rule to derive each app's connection method. The method is derived from the app name, not stored. Every current reporter's app name implies its method.
- Add codersdk.SessionAppMethod: reconnecting_pty and port_forwarding keep their own method, and every other app name is ssh. It replaces the private helper in coderd/insights.go.
- Add codersdk.FoldUnregisteredSessionApps, the fold rule that GetTemplateInsights already applies in SQL. Registered apps, unknown, and overflow keep their entries, and so do the 64 busiest other apps. Ties break by app name in byte order, and the rest add up under overflow.
- Ingest uses the shared rule instead of capSessionCounts. Registered apps and unknown no longer fold, and at most 64 unregistered app names keep their entries.
Refs #31012, CLIENT-1062
Expose discovered ACP harnesses in the chat context resource inventory
when the `chat-acp-subagents` experiment is enabled, including
configuration paths and resource status. Persist ACP harness resources
from agent context snapshots and update the SDK and generated API types.
Generated with Codex, carefully reviewed by Hugo.
Workspace stops and deletes closed active SSH connections with generic
shutdown or process-exit reasons. This obscured the workspace action
that ended a connection and made related logs harder to correlate.
The agent’s SSH tracking and logging now identify connections closed by
the SSH server as server_shutdown, while preserving earlier client or
network disconnects. The agent includes the client session ID when
available for ordinary sessions and connections used only for port
forwarding.
Coderd now enriches shutdown reasons when it processes connection
reports. It translates server_shutdown into workspace_stopped when the
latest build is a running or successful stop or delete requested before
the connection closed. Coderd persists the enriched reason and logs the
build reason, transition, and build ID alongside the client session ID.
Unavailable or unrelated build state retains the generic shutdown
reason.
The CLI now logs shutdown context once per stop or delete build through
its existing workspace watcher. This includes the client session ID when
available and preserves the existing graceful SSH shutdown behavior.
Regarding the PTY connections, when the agent shut down, the
reconnecting PTY server closed each PTY
and its attached connections, and the connection handler then returned
without an error. The server therefore logged and reported those
connections as graceful closes. Its fallback for a forced shutdown
reported a free-form reason that coderd did not recognize, so coderd
never refined either case into a workspace shutdown.
We change the reconnecting PTY server so that it reports any connection
that ends after the agent begins shutting down as a server shutdown
initiated by the agent, and its log keeps the client session ID. The
forced shutdown fallback now reports the same standard reason, which
lets coderd translate it into a workspace stop or delete in the
connection log, as it already does for SSH. A client that closes its
connection before the shutdown still keeps its graceful reason.
Regression tests cover shutdown attribution, fallback behavior, CLI
logging, and PostgreSQL persistence with and without a client session
ID. The test logging helper also synchronizes with cleanup to prevent
logging after a test completes
- resolves
https://linear.app/codercom/issue/CLIENT-665/close-workspace-tunnel-with-a-reason
<!--
If you have used AI to produce some or all of this PR, please ensure you
have read our [AI Contribution
guidelines](https://github.com/coder/coder/blob/main/contributing/AI_CONTRIBUTING.md)
before submitting.
-->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
feat: expose skipped and canceled script outcomes
Add `skipped` and `canceled` statuses across the Agent API, database,
SDK, and Build Timeline for startup scripts.
- Store and return both outcomes, preserving zero-duration timings,
and reject unknown statuses. Rollbacks rewrite the new outcomes to
`exit_failure` with exit code 255.
- Add typed legends, outcome-specific tooltips, and keyboard-accessible
bars. Fix timeline crashes for `timed_out` and `pipes_left_open`.
- Bump the Agent API to v2.15 while agents continue using v2.14.
Add API, migration, and Storybook coverage.
First of two PRs for PLAT-550. Agents do not emit the new statuses yet;
a follow-up after #30765 enables reporting. Shutdown scripts remain
outside the timeline, and agent health and badge rules are unchanged.
Refs: https://linear.app/codercom/issue/PLAT-550/phase-3-expose-skipped-and-canceled-script-outcomes
`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.*
feat(agent): enforce lifecycle script ordering
Honor `coder_script_order` dependencies for startup and shutdown scripts
using the existing outcome-aware unit manager. Cron, legacy scripts,
and scripts without dependencies retain their existing behavior.
- Wait for all prerequisites before running. `success` requires a
successful prerequisite; `completion` also accepts failure, timeout,
or skip. Skip dependents as soon as a required success becomes
impossible, preserving the original failure as the lifecycle error.
- Reject invalid dependency graphs before any scripts start and write
the reason to every selected script's log.
- Log unmet dependencies every 30 seconds and explain skips. Populate
display names in the manifest so skip messages use readable names,
falling back to Terraform addresses.
- Exclude dependency waits from script timeouts, record an outcome on
every exit, and use fresh state per execution. Cancellation stops
waiters without starting dependents or emitting skip messages.
Add regression coverage for ordering, skip propagation, timeouts,
cancellation, invalid graphs, and unchanged unordered execution.
Refs https://linear.app/codercom/issue/PLAT-549/phase-3-enforce-lifecycle-script-ordering
Delivers workspace secrets to the agent, so they show up as env vars and files in the workspace. 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 (this PR)**
5. #30252 Docs
6. #30388 List a build's secrets
7. #30459 Audit a build's secrets
- The agent receives the secrets of the build that created it, alongside the owner's user secrets.
- A workspace secret wins over a user secret on the same env var or file path.
- An agent from an older build gets no workspace secrets.
- The agent itself needs no changes.
<details>
<summary>Implementation details</summary>
- `GetManifest` finds the agent's build through its resource and provisioner job, then lists that build's live secrets as `AsWorkspaceSecretManager`.
- In this PR, precedence comes from order: user secrets are emitted first and workspace secrets after, so the agent applies the workspace value last. #30388 replaces this with `workspacesecrets.Resolve`, which decides one winner per target and is shared with the build secrets API.
- The deployment's file path policy applies to both kinds of secret. When file delivery is blocked, a file-only secret is dropped.
</details>
---
*Created by Coder Agents on behalf of @Emyrk.*
feat: include script dependencies in agent manifests
Send persisted script Terraform addresses and dependency lists on every
manifest request, preserving them across agent restarts, reconnects, and
shutdown without rebuilding the workspace.
- Add `resource_address` and `dependencies` to the agent proto, with
`SUCCESS` and `COMPLETION` requirements.
- Reuse shared database-to-SDK validation and add bidirectional SDK/proto
conversion. Reject empty prerequisite addresses and invalid requirements
rather than accepting partial lists.
- Bump the agent API to v2.13 and update the agent's RPC connection.
Older agents ignore the new fields; older servers return empty fields.
- Test manifest delivery, subagent isolation, round trips, invalid
dependencies, and unchanged encoding when the new fields are unset.
Script execution is unchanged; ordering enforcement follows in PLAT-549.
Production dependency lists remain empty until #30556 merges.
Stacked on #30625. Refs PLAT-548.
Agents now report how a connection was made and which app made it, so
the connection log records the method and the client app separately.
- Bump the Agent API to v2.13. `Connection` gains `connection_method`
and `app_name`, and `type` is deprecated.
- SSH and reconnecting PTY handlers set the method themselves, so a
client-supplied app name can't change it.
- SSH sessions report the app from `CODER_SSH_SESSION_TYPE`. Sessions
without one count as SSH but report no app.
- Disconnect reports repeat the connect report's method, app, and
client session ID.
- Coderd logs the reported method and normalized app name. For agents
older than v2.13, it maps `type` as before.
- Coderd rejects unknown methods instead of logging them as SSH.
Closes CLIENT-1037
Stack context: second layer of the Go lint gate stack, built on the
exclusion fix below.
Why: adds commented-out code detection and a `log/slog` ban to the main
config, plus a new-code-only pass requiring reasons on lint
suppressions, flagging ignored errors (including `_, _ = w.Write(...)`),
and banning `time.Sleep` in tests. Fixing the hits surfaced a real bug:
GitLab warnings went to the wrong logger. The new-code pass resolves
symlinked checkout paths so it does not silently report nothing.
Validation: both configs report 0 issues; each seeded violation is
caught; `make pre-commit` passed.
> Xum acted for Mike to open this PR.
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
The client session ID is not populated yet; this just adds the ability
for agents to send a client session ID with the rest of the connection
data, once it gets piped through.
Track individual applications across deployment statistics, Prometheus, telemetry, and the dashboard instead of exposing only fixed family totals. Preserve existing fields and gauges so current consumers can migrate without breaking.
- Add per-app counts with normalized identifiers and registry-backed display names, families, and bundled icons. Unrecognized apps retain their identifiers.
- Limit each statistics report to 64 distinct app names, combining excess names into an explicit overflow bucket.
- Group dashboard connections by family, including an Other category, with alphabetical per-app tooltips and distinct loading and empty states.
- Export app-keyed Prometheus counts separately from current family metadata, allowing queries to enrich historical counts without rewriting stored samples.
- Document family queries with unknown fallback, deployment isolation, and replica handling, alongside collection behavior and migration guidance.
- Include per-app counts in telemetry, update API schemas and documentation, and add regression coverage across collection, metrics, and dashboard behavior.
Closes#27411
Report session counts as a dynamic app-name map from the agent, the SSH CLI, and the workspace usage API, so a new IDE flows end to end without a schema, proto, or server change.
- Report through `Stats.session_counts` on Agent API v2.11. Older agents keep reporting through the deprecated count fields.
- Accept arbitrary names from `coder ssh --usage-app` and the workspace usage API. A name the registry does not recognize keeps its identity and is attributed to the `unknown` family.
- Add reconnecting PTY counts to the map without overwriting the counts SSH reported.
- Normalize and merge names before applying the deterministic 64-name cap, ordered by known apps, then count, then name. Overflow sums into `unknown`, and non-positive counts cannot cancel valid activity.
- Strip control characters, treat whitespace-only HTTP app names as absent, and require the exact environment variable prefix when you extract an SSH session type.
- Count overflow entries in `coderd_agentstats_session_counts_overflow_total` and keep raw payloads out of logs.
- Change the usage API's `app_name` to a string, and update the SDK types and API reference.
closes#27410
Reject `UpdateLifecycle`, `UpdateStartup`, and `BatchUpdateMetadata`
requests with a missing sub-message using `InvalidArgument` instead of
panicking. The whole metadata batch is validated before any value is
trimmed or queued.
Adds tests for each handler, a mixed metadata batch, and one DRPC
round-trip confirming the code propagates and the connection stays
usable.
Refs PLAT-596
Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder.
Removes the Tasks API and task orchestration from coderd and codersdk:
the `/api/v2/tasks` handlers, task middleware and search filters, task
name generation, autobuild pause/resume logic, task notification
enqueues, telemetry, and the codersdk task types. Regenerates apidoc,
the API reference docs, and `typesGenerated.ts`.
**Breaking change:** the Tasks API is removed; requests to
`/api/v2/tasks` fail. Tasks was deprecated in v2.34.
**Stack context:** Coder Tasks removal stack (CODAGT-642): #28743
frontend → #28788 CLI → #28789 API → #28790 provisioner → #29084
notifications → #29085 build reasons → #29086 tables → #28750
permissions. The last four PRs replace the single data-drop migration
that used to live in #28750; each carries one concern and its own
migration number.
**Why:** with the UI (#28743) and CLI (#28788) gone, this deletes the
server surface. Database tables, RBAC, and notification templates stay
until the top of the stack so every layer builds and migrates
independently.
**What to scrutinize:**
- The `enable-ai-tasks` option is removed outright (review feedback):
configs still carrying `enableAITasks` fail to parse until the key is
deleted.
- provisionerdserver now writes `HasAITask: false` on template/build
flags; the column and these lines are dropped in #29085.
- `codersdk.ResourceTypeTask` stays so audit logs recorded before the
removal keep rendering.
**Validation:** `go build ./...`, `go vet ./...`, `go test
./codersdk/...`, site biome and tsc, CLI goldens regenerated, pre-commit
hooks.
**Size:** +242/-10,792 over 76 files; additions are regenerated
docs/goldens and test fixture updates.
> Created by Xum (AI agent) on behalf of @ibetitsmike.
Workspace agents could call RefreshResumeToken and WorkspaceUpdates,
even though agent connections do not configure the providers those RPCs
require. The resulting nil dereference panicked a DRPC handler and
crashed coderd.
Limit the agent Tailnet surface to its supported RPCs, return
`Unimplemented` when optional providers are absent, and recover panics
in Coder-owned DRPC servers so they return an internal error instead of
crashing the process.
Refs: https://linear.app/codercom/issue/PLAT-464
When `DisableUserSecretFilePath` is set, coderd strips file targets
while building the agent manifest: env-only secrets are unchanged,
dual-target secrets keep the env var with an empty file path, and
file-only secrets are omitted so their plaintext never crosses DRPC.
Stored paths stay in the database and reappear on the next manifest
fetch once the option is cleared. Agents converge on reconnect; no
protobuf, provisioner, or agent-side changes are needed, and files
already written to workspace disks are left alone.
Also exposes the positive capability as the
`user-secret-file-path-enabled` embedded metadata tag, which the next PR
in the stack consumes in the dashboard. Builds on #28518. Refs #27488.
Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder.
Phase 2 of the Scalable Approach for Adding New IDE Session Types RFC,
tracked in #27410.
Adds a session_counts map to Stats on the Agent API, so an agent can report
a count per app name instead of the four fixed fields, which are now marked
deprecated. Bumps the API to v2.11.
- coderd normalizes names on ingest, caps distinct entries, and sums the
overflow under unknown, so an arbitrary client name cannot blow up
cardinality.
- Agents predating v2.11 set the fixed fields instead, never both, and the
ingest path falls back to them.
Nothing sends session_counts yet. The agent starts populating it in #28338.
Users can now disable a secret to stop it from being injected into
workspaces without deleting it, and re-enable it later. Disabled secrets
stay visible and editable everywhere they already appear.
An enabled secret must have at least one injection target; a secret with
no target can be stored only while disabled. Existing target-less secrets
are migrated to disabled to preserve current behavior.
Support spans the REST API, SDK, CLI, dashboard, and audit log.
## Overview
Part of the **boundary correlation** feature. Fixes lazy creation of
`boundary_sessions` rows so it works within the agent's RBAC
constraints, and consumes the new `ConfinedProcessName` field reported
by boundary.
Pairs with coder/boundary#206, which adds `ConfinedProcessName` to
`ReportBoundaryLogsRequest`. This branch bumps the
`github.com/coder/boundary` module to pick up that work.
## Problem
`ensureSession` did a pre-insert existence check via
`GetBoundarySessionByID`. Agents are **not permitted to read boundary
sessions**, so that read path is not viable when the session is created
from an agent-reported log batch.
## Changes
- **Remove the pre-insert read.** `ensureSession` now inserts directly
and treats a primary-key unique violation as success, covering sessions
already created by a prior batch, a reconnection, or another coderd
replica — without requiring read access.
- **Per-connection guard.** Add a mutex-protected `ensuredSessions` set
so repeated log batches on the same connection skip the existence check
and insert entirely, touching the database only for the logs. On a
transient insert failure the session is left unmarked so the next batch
retries.
- **Consume `ConfinedProcessName`.** Pass `req.GetConfinedProcessName()`
through to the session insert.
- **Bump boundary module** from `v0.9.0` to
`v0.9.1-0.20260706095856-35ba90f9e8b2`.
- **Tests.**
- Add `TestReportBoundaryLogsAgentRBAC`
(`coderd/boundary_logs_test.go`), an integration test that connects as a
real workspace agent, verifies the session and log are persisted under
agent RBAC, and asserts the agent subject cannot read boundary sessions
— guarding against reintroducing a pre-insert read.
- Add `TestReportBoundaryLogsSessionGuard` (session inserted once across
two batches, logs inserted per batch) and
`TestReportBoundaryLogsSessionRetriedOnError` (insert retried after a
transient error).
- Regenerate `agent-firewall` CLI docs/golden files and adjust the
clidocgen template to render the YAML path when a flag has no long name.
> 🤖 This PR was opened by Coder Agents on behalf of @SasSwart.
Add a GET endpoint at `/api/v2/agent-firewall/sessions/{id}` that
returns agent firewall session metadata (`id`, `workspace_id`,
`owner_id`, `confined_process`, `started_at`). The handler authorizes
against the `boundary_log` resource with `ActionRead` via dbauthz.
The endpoint is enterprise-only, gated behind the `FeatureBoundary`
entitlement.
The `GetBoundarySessionByID` SQL query JOINs through `workspace_agents`
→ `workspace_resources` → `workspace_builds` → `workspaces` to return
`workspace_id` and `workspace_owner_id` directly, avoiding a separate
query.
Also adds an `owner_id` column to the `boundary_logs` table (migration
000526) with a FK to `users(id)` and a backfill from
`boundary_sessions`. This enables user-scoped RBAC authorization for
`InsertBoundaryLogs` via `.WithOwner()`, ensuring workspace agents can
only insert logs for their own owner.
Depends on #24810
**RBAC behaviour:**
| Role | Result |
|---------|--------|
| Owner | read |
| Auditor | read |
| Member | 404 |
> [!NOTE]
> This PR was authored by Coder Agents.
Makes the chat context foundation from #26385 live. That PR added the
storage columns, writer queries, and a dormant
`agentapi.ContextDirtyMarker` trigger with no production callers; this
PR wires them together end to end.
When a workspace agent pushes a context snapshot, bound chats now
hydrate to that snapshot's hash, and a later push with a different hash
flips already-pinned chats to dirty (emitting a `context_dirty` watch
event after the transaction commits). Chat creation pins the agent's
latest snapshot when one already exists. The experimental chat API
exposes this as `Chat.Context` (`*ChatContext` with `dirty`,
`dirty_since`, `error`), and a new `PUT
/api/experimental/chats/{chat}/context` endpoint re-pins the agent's
latest snapshot and clears the dirty marker.
`context_dirty_resources` stays NULL (the resource-level diff is
deferred to the UI phase) and the live per-turn context pull is
unchanged.
The end-to-end test provisions a workspace agent via the echo
provisioner, connects it over the Agent API v2.10, and exercises the
full path: an initial push hydrates a bound chat (clean), a second push
with a different hash marks it dirty, the API reports the dirty state,
and the refresh endpoint clears it.
<details>
<summary>Decision log</summary>
- **API shape — sub-struct.** Dirty state is surfaced as
`codersdk.Chat.Context *ChatContext { Dirty bool; DirtySince *time.Time;
Error string }` rather than flat fields, matching the RFC's named
`ChatContext` type and leaving room for future fields (resource diff,
sources). `db2sdk.Chat` populates it when the chat is context-tracked
(`len(ContextAggregateHash) > 0`), dirty, or carries a snapshot error,
and leaves it nil (`omitempty`) otherwise. `Dirty` mirrors
`context_dirty_since` being set.
- **Marker wiring.** The chat daemon is injected directly as the
`agentapi.ContextDirtyMarker`. It is unconditionally constructed (only
its background worker is gated), so the marker is always non-nil and the
wiring matches every other `api.chatDaemon` call site. `agentapi` still
treats a nil marker as "chatd absent", so `PushContextState` stays a
pure write path for any future caller that does not wire chatd in.
- **Refresh is atomic.** `RefreshChatContext` reads the agent's latest
snapshot and re-pins the chat in one repeatable-read transaction, so a
concurrent push cannot land between the read and the write and leave the
chat pinned to a stale hash with the dirty marker cleared.
- **Hydrate + dirty run inside the push transaction.** The fan-out
shares the push's transaction so a concurrent refresh cannot interleave
with the version gate; `context_dirty` watch events publish only after
commit. The pinned hash on dirtied chats is intentionally left unchanged
— the refresh endpoint re-pins it.
- **Dirtied chats keep their pinned hash.** Drift is advisory: a dirty
chat stays usable, and refreshing is the only path that advances the
pinned hash.
- **Test binds `chats.agent_id` directly.** In production the binding is
set lazily during a chat turn (`chatd.persistBuildAgentBinding`); the
test sets it via `dbgen` so it exercises the context flow rather than
turn resolution.
Plan: `coderd/x/chatd` context integration + E2E (sub-struct API,
create-time + push-time hydration, refresh endpoint;
`context_dirty_resources` and the per-turn pull untouched).
</details>
🤖 Generated by Coder Agents on behalf of @kylecarbs
Foundation for the Workspace Context Sources RFC (phase 3). The agent
push (#25983) and coderd snapshot storage (#26145) already persist
per-agent context snapshots; this PR lands the **chat-side storage**
plus the **`agentapi` push trigger** that a follow-up will use to read
them. It does **not** touch `chatd` and changes no behavior — nothing
wires an implementation yet.
## What changed
- Adds four nullable columns to `chats` — `context_aggregate_hash`,
`context_dirty_since`, `context_dirty_resources`, and `context_error` —
and rebuilds the `chats_expanded` view.
- Adds three queries — `SetChatContextSnapshot`,
`HydrateAgentChatsContext`, `MarkChatsContextDirtyByAgent` — with
`dbauthz` wrappers and `audit` entries. They are store-interface methods
covered by a Postgres test (`TestChatContextHydration`).
- Adds the `agentapi.ContextDirtyMarker` interface and invokes it inside
the `PushContextState` transaction, publishing collected events only
after commit.
## Intentionally inert
There are **no production callers** of the three queries and **no
implementation** wired for `ContextDirtyMarker`, so the push trigger is
dormant. This is deliberate: the PR is the durable storage/query
foundation only.
The actual integration — the `chatd` implementation that
hydrates/dirties chats and backs a refresh endpoint, consuming the
pinned context in prompt building, the rich SDK types + UI, and retiring
the live per-turn pull — lands as a single follow-up PR. Splitting this
way keeps the schema/query layer reviewable on its own and keeps the
integration whole in one place.
Refs #25983, #26145.
<details>
<summary>Decision log</summary>
- **Columns over a side table.** The four `chats` columns are the
durable model (accepting the one-time `chats_expanded` view/CTE churn).
`last_injected_context` is deliberately left untouched — it is
load-bearing for the live per-turn context pull.
- **Keep `agentapi`, drop `chatd`.** The earlier revision wired the
hydrate/dirty implementation through `chatd` and added a `PUT
/chats/{chat}/context` refresh endpoint. Those were removed so this PR
is pure foundation; `agentapi` defines the trigger + interface (it does
not import `chatd`), and the `chatd` implementation arrives with the
full integration.
- **No new experiment flag.** The columns are dark and unread by prompt
building.
- **Authz.** The new query wrappers authorize chat updates under the
chat RBAC object / `ResourceChat`, consistent with the existing system
chat mutators.
</details>
---
🤖 Generated by Coder Agents on behalf of @kylecarbs.
Replaces the v2.10 `PushContextState` stub with a real coderd write
path. Phase 1 of the chat-side persistence story; nothing reads these
rows yet.
Follows [#25983](https://github.com/coder/coder/pull/25983) and unblocks
[CODAGT-569](https://linear.app/codercom/issue/CODAGT-569/enable-agent-api-v210-pushcontextstate-bump-currentminor-wire-coderd).
## What ships
### Schema (`000517_workspace_agent_context.{up,down}.sql`)
Two new tables plus `api_key_scope` enum extensions:
- `workspace_agent_context_snapshots` (PK `workspace_agent_id` to
`workspace_agents(id) ON DELETE CASCADE`): one row per agent,
overwritten per push. Holds `version`, `schema_version`,
`aggregate_hash`, `snapshot_error`, `received_at`.
- `workspace_agent_context_resources` (PK `(workspace_agent_id,
source)`): per-resource state. `body_kind` and `status` are `TEXT` +
`CHECK` so adding new wire kinds (the RFC's reserved
PLUGIN/HOOK/SUBAGENT/COMMAND) is a one-line CHECK update plus a Go
switch case.
### SQLC queries (`coderd/database/queries/workspaceagentcontext.sql`)
- `UpsertWorkspaceAgentContextSnapshot`
- `UpsertWorkspaceAgentContextResource`
- `DeleteStaleWorkspaceAgentContextResources`
(delete-where-source-not-in)
- `GetLatestWorkspaceAgentContextSnapshot`
- `ListWorkspaceAgentContextResources`
### Handler (`coderd/agentapi/context.go`)
`ContextAPI` is a new sub-API. `PushContextState`:
1. Rejects `schema_version > 1` with a non-`Unimplemented` error so a
forward-incompatible agent fails loudly during rollout instead of
slipping into the permanent fallback path the `Unimplemented`
translation reserves for old coderd deployments.
2. Validates resources: no empty/duplicate sources, every variant maps
to a known body kind, every status maps to a known enum value, the
`Body` oneof is set (even when status is non-OK, mirroring the wire
guarantee so coderd can attribute failures to a known kind).
3. Inside `Database.InTx`, reads the existing snapshot. If the push is
not `initial` and `version` is not strictly greater, returns `accepted =
false` and leaves stored state untouched. Otherwise upserts the snapshot
row, upserts each resource, then runs the stale-source prune so the
snapshot and resource rows always agree.
4. Returns `accepted = true` on success.
Resource bodies are stored as `protojson(body oneof variant)` in `body
JSONB` with `body_kind` as the discriminator. Adding a new field to an
existing variant is zero work since `protojson` tolerates new fields;
adding a new variant is a CHECK + switch case.
### RBAC + dbauthz
- New `ResourceWorkspaceAgentContext` (Create/Read/Update/Delete).
- New `SubjectTypeAgentContext` plus `subjectAgentContext` system role
and `dbauthz.AsAgentContext` helper. The push handler elevates to this
subject; the agent's own role does not get direct write access to the
table.
- New `workspace_agent_context:*` API key scopes registered in the enum
migration; internal-only (not added to `externalLowLevel`).
### Audit
These rows are agent-pushed state, not user-authored. They are
intentionally not added to `AuditActionMap` and not enumerated in
`enterprise/audit/table.go`, matching `boundary_logs`,
`workspace_agent_memory_resource_monitor`, etc. `enterprise/audit` tests
pass unchanged.
## Tests
- `coderd/agentapi/context_test.go`: 12 subtests covering
accepts/rejects (schema version, empty/duplicate source, unknown status,
missing body), version semantics (stale dropped, same-version replay
dropped, `initial=true` overwrites lower version), variant coverage,
non-OK status persistence, and the empty-active-set prune case.
- `coderd/database/dbauthz/dbauthz_test.go`: 5 `MethodTestSuite` cases
covering the new queries.
- `coderd/rbac/roles_test.go`: `WorkspaceAgentContext` permission row
asserting no human role currently has access.
-
`coderd/database/migrations/testdata/fixtures/000517_workspace_agent_context.up.sql`:
one snapshot + one resource per known body kind plus a non-OK status, so
the migration test suite never lands with these tables empty.
## Out of scope (later phases)
- Chat hydration (`chats.context_aggregate_hash`,
`last_injected_context`).
- Dirty-bit fan-out and `PUT /chats/{id}/context`.
- Agent-side `POST /api/v0/context/resync` barrier and the `coder exp
chat context` CLI.
- `codersdk` chat-context wire types and the dashboard Sources drawer.
- Removal of the chatd per-turn pull fallback.
## Compat property
This is a pure write path. If anything here returns errors the agent's
`RunPush` loop backs off, no chat behavior changes, and the workspace
keeps behaving exactly like it did before v2.10.
<details>
<summary>Implementation plan and decision log</summary>
Key design calls:
1. **Concurrency**: Accept iff `req.Initial || req.Version >
existing.Version`. The strict RFC reading ("version comparison is
authoritative") locks restarted agents out because their per-process
counter resets to 1; honoring `initial=true` reflects the real reboot
reality while still rejecting steady-state replays/out-of-order pushes.
2. **Body encoding**: `protojson` over the oneof variant body proto,
stored in JSONB with `body_kind` discriminator. Structured at the API/Go
layer, schema-tolerant at the storage layer, and Phase 2 readers
round-trip back via `protojson.Unmarshal`.
3. **Schema version rejection**: returns a normal error, not
`Unimplemented`. The agent's `RunPush` loop only short-circuits on
`Unimplemented`; that escape hatch is reserved for old coderd
deployments. A forward-incompatible agent should retry-and-back-off, not
flip the connection into permanent fallback.
4. **Validation strictness**: empty sources, duplicate sources,
`STATUS_UNSPECIFIED`, and missing `Body` oneof variants are rejected
before any write so a misbehaving agent cannot poison the snapshot
table. Phase 2 readers can trust every row maps to a known proto
variant.
</details>
_This PR was authored by Coder Agents on Kyle Carberry's behalf._
Add database persistence to `ReportBoundaryLogs`. On first log for a
session, the handler lazy-creates a `boundary_sessions` row, then
batch-inserts all `BoundaryLog` entries into `boundary_logs`. Structured
logging and usage tracking are preserved. Old boundary clients (no
`session_id`) fall back to log-only mode.
> [!NOTE]
> This PR was authored by Coder Agents.
Adds the agent half of the workspace context sources RFC. The agent now
resolves instruction files, skills, and MCP configs into a typed
`Snapshot`, watches the relevant paths recursively, exposes the source
list over a workspace-agent HTTP API, and pushes each `Snapshot` to
coderd over a new `PushContextState` RPC on Agent API v2.10.
The coderd-side handler is a stub returning `Unimplemented` for now.
Real persistence to `workspace_agent_context`, chatd hydration on dirty
events, and the `KindMCPServer` MCP provider are tracked by
[CODAGT-569](https://linear.app/codercom/issue/CODAGT-569/enable-agent-api-v210-pushcontextstate-bump-currentminor-wire-coderd).
This matches the pattern used for v2.7 `ReportBoundaryLogs` in
[#21293](https://github.com/coder/coder/pull/21293), which bumped the
version and shipped a stub server so the wire and client could iterate
before the persistence layer landed.
## What ships
### agent/agentcontext (new package)
- `Source`, `Resource` (kinds `instruction_file`, `skill`, `mcp_config`,
`mcp_server` plus reserved `plugin`/`hook`/`subagent`/`command`),
`ResourceStatus`, `Snapshot`, `ComputeAggregateHash`.
- `Manager` owns the in-memory source list, performs the initial resolve
synchronously in `NewManager`, runs a re-resolve/watcher loop in `Run`,
exposes
`AddSource`/`RemoveSource`/`Sources`/`HasSource`/`Snapshot`/`SubscribeChanges`/`Resync`/`SeedSources`/`Close`.
- `Resolver` walks scan roots, classifies recognized files, enforces 64
KiB per-resource, 2 MiB aggregate, and 500-resource caps with
`StatusOversize`/`StatusExcluded`/`StatusUnreadable`/`StatusInvalid`
outcomes, skips `node_modules`/`vendor`/etc., validates symlink targets
stay inside the scan root, stamps `SourcePath` on user-derived
resources, and optionally pulls MCP server tool lists via an
`MCPProvider` interface. MCP config resources ship metadata only (size,
hash) so secrets in env blocks never leave the agent.
- `Watcher` is a recursive `fsnotify` wrapper with a 250 ms debounce,
dynamic arming of newly created directories, and an ENOSPC-tolerant
degraded mode that no-ops further syncs until the manager resyncs
explicitly.
- HTTP API for `GET/POST /sources`, `GET/DELETE /sources/{path}`, `POST
/resync` mounted at `/api/v0/context`.
- `Pusher` interface plus `RunPush` goroutine with exponential backoff
capped at 30 s. `DRPCPusher` adapts the generated `DRPCAgentClient210`
to `Pusher` and translates `drpcerr.Unimplemented` to
`ErrPushUnimplemented` so the push loop exits cleanly when talking to
coderd deployments that have not enabled the real handler.
### agent/proto (v2.10)
- New messages `ContextResource`, `PushContextStateRequest`,
`PushContextStateResponse` and the `PushContextState` RPC on `service
Agent`.
- Generated `DRPCAgentClient210` interface and
`codersdk/agentsdk.Client.ConnectRPC210` / `ConnectRPC210WithRole`.
- `tailnet/proto.CurrentMinor` bumped from `9` to `10`.
### Agent wiring
- `agent.Options.Client` declares both v2.9 and v2.10 connectors;
`run()` dials with `ConnectRPC210WithRole`.
- `apiConnRoutineManager` holds a `DRPCAgentClient210`. Existing v2.8
routines keep their narrower `DRPCAgentClient28` signature thanks to
interface embedding.
- `startAgentAPI210` is the v2.10 counterpart to `startAgentAPI` for
routines that need the new client. The push context state routine uses
it.
- A `contextManager` is constructed in `agent.init()`, seeded from the
existing `CODER_AGENT_EXP_*_DIRS` env vars, started in its own goroutine
under `gracefulCtx`, and closed in `agent.Close`.
- `handleManifest` calls `Manager.SeedSources` for sources rooted at the
manifest directory, then `Resync` after `manifest.Swap`, so the snapshot
reflects the workspace working directory immediately instead of waiting
for the next filesystem event.
- HTTP routes mounted at `/api/v0/context` when the manager is up.
### Coderd stub
`coderd/agentapi/context.go` returns `drpcerr.Unimplemented` for
`PushContextState`. The real handler that persists
`workspace_agent_context` rows, hydrates chats, and emits dirty events
lives in CODAGT-569.
## Tests
24 tests across `agent/agentcontext` cover types, paths, resolver
behavior with file caps, skill containers, MCP secret omission, symlink
target validation, the recursive watcher firing on real fsnotify events,
manager source CRUD / `Resync` / `SeedSources` / `Run` lifetime, the
HTTP API, the DRPC adapter, and the push retry / initial-flag /
unimplemented paths. Passes `go test -race -count=2`.
`TestAgent_ContextStatePushed` boots a full agent against
`agenttest.FakeAgentAPI` (which now records `PushContextState` traffic)
and asserts the seeded `AGENTS.md` appears in a snapshot push with
`schema_version = 1`.
<details>
<summary>Notes for reviewers</summary>
- Source CRUD is workspace-agent-token only; coderd is not in the path
for source mutation.
- Per-resource cap 64 KiB, aggregate 2 MiB, count cap 500; resources
past the cap ship with `StatusExcluded` and an empty payload so the
aggregate hash still detects content edits. MCP-emitted resources
enforce both a per-provider count cap and the aggregate byte cap.
- Symlinks inside the scan root are followed; symlinks pointing outside
(or broken) are rejected with `StatusExcluded` so credentials reachable
via a stray symlink stay off the wire.
- The initial push gates `lifecycle = ready` in the eventual full
design. For this PR the `SeedSources` plus `handleManifest`-driven
`Resync` keeps the snapshot fresh; the live push loop ships now and
DRPCPusher translates the coderd `Unimplemented` stub into a clean exit.
- The `PLUGIN`/`HOOK`/`SUBAGENT`/`COMMAND` kinds are reserved in proto
and Go enums but unused; the Claude Code plugin resolver ships in a
follow-up that does not need a schema migration.
- Two follow-ups remain, both tracked by
[CODAGT-569](https://linear.app/codercom/issue/CODAGT-569/enable-agent-api-v210-pushcontextstate-bump-currentminor-wire-coderd):
(1) the chatd-side handler that persists snapshots and dirties chats;
(2) the `coder exp chat context` CLI command set for
`list`/`show`/`add`/`remove`/`refresh`.
</details>
_This PR was authored by Coder Agents on Kyle Carberry's behalf._
Fixes an issue where sub-agent apps created via CreateSubAgent would
bypass the check for the template's max port sharing level:
- Clamps dynamically inserted `workspace_apps` to the template max
sharing level in `coderd.agentapi.SubAgentAPI`.
- Emits a warning when clamping occurs.
- Adds unit test coverage for the max sharing level matrix.
- Adds an integration-ish test through the devcontainer sub-agent client
path.
> 🤖 Generated by Coder Agents with guidance from a human.
Use typed atomics (atomic.Int64, atomic.Int32, etc.) in test files to prevent
mixing atomic and non-atomic access on the same value, guarantee 64-bit
alignment on 32-bit platforms, and provide a cleaner API.
Injects user secrets into workspace agents at runtime via the agent
manifest. Secrets with an environment variable name are set as
environment variables in every agent session and startup script. Secrets
with a file path are written to disk before startup scripts run.
- Fetch user secrets in GetManifest and convert to proto
- Defensively strip secrets from manifests received by the agent to
avoid accidental leakage
- Add WorkspaceSecret type and proto conversion helpers to agentsdk
- Write secret files eagerly on manifest fetch (0600 perms, 0700 dirs)
- Inject secret env vars per-session in updateCommandEnv
- Expand ~/paths using caller-resolved home directory
- Log file write errors without blocking workspace startup
> This PR was authored by Mux on behalf of Mike.
## Summary
Adds support for multiple peer root workspace agents sharing the same
`auth_instance_id`, so AWS, Azure, and GCP instance-identity auth can
issue the correct session token for a selected agent instead of assuming
a
single root agent per instance.
## Problem
When a Terraform template attaches two or more `coder_agent` resources
(with `auth = "aws-instance-identity"`) to a single compute instance,
every agent shares the same cloud instance ID. The existing singular
lookup picks whichever agent was created most recently, silently
ignoring
the others.
## Solution
Introduce an optional pre-auth agent selector (`CODER_AGENT_NAME`) and
make the server-side lookup ambiguity-aware.
**Database layer:**
- `GetWorkspaceAgentsByInstanceID` (`:many`): returns all matching root
agents for an instance ID.
- `GetWorkspaceAgentByInstanceIDAndName` (`:one`): returns the named
root
agent for disambiguation.
**SDK and CLI:**
- `agent_name` field added to AWS, Azure, and GCP request structs
(`omitempty` for backward compatibility).
- `CODER_AGENT_NAME` env var and `--agent-name` flag wired into the
agent
bootstrap before instance-identity auth runs.
**Server handler (`handleAuthInstanceID`):**
- When `agent_name` is present: direct lookup by (instance ID, name).
- When absent: legacy lookup, then resource-scoped ambiguity check.
Returns 409 with available agent names if multiple root agents match.
- Whitespace-only names are trimmed and treated as unspecified.
- Sub-agents remain excluded (`parent_id IS NULL` filter).
**Verification template:**
- `examples/templates/aws-multi-agent/` provisions one EC2 instance with
two agents (`main` and `dev`), both using instance-identity auth with
`CODER_AGENT_NAME` set in the cloud-init user data.
## Backward compatibility
Existing single-agent deployments work unchanged. The `agent_name` field
is optional with `omitempty`, and the unnamed path preserves today's
behavior when only one root agent matches.
When a devcontainer subagent is terraform-managed, the provisioner sets
its directory to the host-side `workspace_folder` path at build time. At
runtime, the agent injection code determines the correct
container-internal
path from `devcontainer read-configuration` and sends it via
`CreateSubAgent`.
However, the `CreateSubAgent` handler only updated `display_apps` for
pre-existing agents, ignoring the `Directory` field. This caused
SSH/terminal
sessions to land in `~` instead of the workspace folder (e.g.
`/workspaces/foo`).
Add `UpdateWorkspaceAgentDirectoryByID` query and call it in the
terraform-managed subagent update path to also persist the directory.
Fixes PLAT-118
<details><summary>Root cause analysis</summary>
Two code paths set the subagent `Directory` field:
1. **Provisioner (build time):** `insertDevcontainerSubagent` in
`provisionerdserver.go`
stores `dc.GetWorkspaceFolder()` — the **host-side** path from the
`coder_devcontainer` Terraform resource (e.g. `/home/coder/project`).
2. **Agent injection (runtime):**
`maybeInjectSubAgentIntoContainerLocked` in
`api.go` reads the devcontainer config and gets the correct
**container-internal**
path (e.g. `/workspaces/project`), then calls `client.Create(ctx,
subAgentConfig)`.
For terraform-managed subagents (those with `req.Id != nil`),
`CreateSubAgent`
in `coderd/agentapi/subagent.go` recognized the pre-existing agent and
entered
the update path — but only called `UpdateWorkspaceAgentDisplayAppsByID`,
discarding the `Directory` field from the request. The agent kept the
stale
host-side path, which doesn't exist inside the container, causing
`expandPathToAbs` to fall back to `~`.
</details>
> [!NOTE]
> Generated by Coder Agents
Workspace agent logs could still fail after the earlier invalid UTF-8
fix because NUL bytes are valid Go/protobuf strings but are rejected by
Postgres text columns. The legacy HTTP log upload path also bypassed the
old sanitization entirely, and both server insert paths computed
logs_length from the unsanitized input.
Add a shared log-output sanitizer in agentsdk, use it in the protobuf
conversion path and both server-side insert paths, and compute
OutputLength from the sanitized string so overflow accounting matches
what is actually stored. This keeps the old invalid UTF-8 behavior while
also handling embedded NUL bytes consistently across DRPC and HTTP log
ingestion.
Refs [#23292 ](https://github.com/coder/coder/issues/23292)
Refs [#13433 ](https://github.com/coder/coder/issues/13433)
- Trim leading/trailing whitespace from metadata `value` and `error`
fields before storage
- Trimming happens before length validation so whitespace-padded values
are handled correctly
- Add `TrimWhitespace` test covering spaces, tabs, newlines, and
preserved inner whitespace
- No backfill needed (unlogged table, stores only latest value)
> 🤖 Created by a Coder Agent, reviewed by me.
## Changes
- **Commit 1**: Remove 17 unnecessary `//nolint` directives:
- `//nolint:varnamelen` — linter not active
- `//nolint:unused` on exported `SlimUnsupported`
- `//nolint:govet` in `coderd/httpmw/csrf` — no longer fires
- `//nolint:revive` on functions refactored since the nolint was added
- `//nolint:paralleltest` citing Go 1.22 loop variable capture
(obsolete)
- Bare `//nolint` narrowed to specific `//nolint:gocritic` with
justification
- **Commit 2**: Fix root causes behind 5 dangerous nolint suppressions:
- Add `MinVersion: tls.VersionTLS12` to TLS client config (removes
`gosec` G402)
- Delete trivial unexported wrappers `apiKey()`/`normalizeProvider()` in
chatprovider (removes `revive` confusing-naming)
- Add doc comments to `StartWithAssert` and `Router` (removes `revive`
exported)
- Rename unused parameters to `_` in integration test helpers
> 🤖 This PR was created using Coder Agents and reviewed by me.
We currently call GetWorkspaceAgentByID millions of times at scale
unnecessarily. This PR embeds immutable fields into the relevant
services instead of fetching for them every time.
resolves https://github.com/coder/scaletest/issues/84
Confirmed with a 10k scaletest that this changeset takes the query from
10M+ queries down to 39k
The `flush` method sets `start := b.clock.Now()` but later computes
duration with `time.Since(start)` instead of `b.clock.Since(start)` for
the `FlushDuration` metric and the debug log. Line 352 already uses
`b.clock.Since(start)` correctly — this makes the rest consistent.
Test output before fix:
```
flush complete count=100 elapsed=19166h12m30.265728663s reason=scheduled
```
After fix:
```
flush complete count=100 elapsed=0s reason=scheduled
```