Skip to content

feat: expose the workspace template to agent commands - #31606

Merged
mafredri merged 8 commits into
mainfrom
mafredri/agent-template-env
Nov 3, 2026
Merged

mafredri merged 8 commits into
mainfrom
mafredri/agent-template-env

Conversation

@mafredri

@mafredri mafredri commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

The agent now sets CODER_WORKSPACE_TEMPLATE_ID and CODER_WORKSPACE_TEMPLATE_NAME for every command it runs, alongside CODER_WORKSPACE_NAME and CODER_WORKSPACE_BUILD_ID. Templates run different scripts in different orders, so a user's own script (for example a personalize script) needs to know which template it runs under to coordinate with that template's scripts.

coderd sends the values in two new manifest fields, template_id and template_name, read from the workspace row.

The Agent API goes to v2.16. release/2.39 shipped v2.15, so these fields start a new minor version. No new RPCs.

CODER_WORKSPACE_BUILD_ID loses its nil checks from #30388, in the agent and in ManifestFromProto. An agent only connects to a server that supports its API version, and every such server sends the build ID, so the checks never fired.

The environment variables page now lists the variables the agent sets, and the personalize script docs link to it with an example.

Decision log
  • The template variables are set unconditionally, like CODER_WORKSPACE_ID. workspaces.template_id is NOT NULL and workspaces_expanded inner-joins templates, so both values are always present.
  • ManifestFromProto parses the build and template IDs with uuid.FromBytes, as it does for every required ID (agent_id, workspace_id, script and devcontainer IDs). Only IDs some agents lack, such as parent_id, are optional in the proto and parsed behind a nil check.
  • TestAgent_CoderEnvVars now checks exact values for every variable it covers and absorbs the separate build ID test. Its Unset case only covered the removed nil check.
  • Not added to the variables passed to devcontainer.json (agent/agentcontainers/api.go). Those exist to build URLs such as the Zed ${localEnv:...} link, and the template does not appear in one. Dev container sub-agents still get both variables for their commands, because they fetch their manifest from the same endpoint.
  • No CODER_WORKSPACE_TEMPLATE_VERSION. The version name is usually a generated name, which scripts cannot act on.
  • The docs list only the variables that describe the workspace. Variables the agent sets for its own tooling, such as CODER_AGENT_TOKEN and GIT_SSH_COMMAND, are left out.

🤖 This PR was created with the help of Coder Agents.

@mafredri
mafredri force-pushed the mafredri/agent-template-env branch from 5c03d66 to 530e035 Compare November 1, 2026 13:08
@mafredri

This comment has been minimized.

@coder-agents-review

coder-agents-review Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Chat: Review posted | View chat
Requested: 2026-11-02 11:49 UTC by @mafredri
Spend: $6.20 / $100.00

Review history
  • R1 (2026-11-02): 9 reviewers, 1 Nit, 1 P3, 1 P4, COMMENT. Review

deep-review v0.13.0 | Round 1 | 67e216b..530e035

Last posted: Round 1, 3 findings (1 P3, 1 P4, 1 Nit), COMMENT. Review

Finding inventory

Finding inventory: PR #31606

Findings

# Sev Status Location Summary Round Reviewer Posted
CRF-1 P4 Open codersdk/agentsdk/convert.go:55 Missing template_id becomes uuid.Nil and is exported as the nil UUID; build ID guard is now stale R1 Netero Yes
CRF-2 P3 Open agent/agent.go:1550 No docs for the new template env vars (name vs display name, rename, per-org uniqueness) R1 Leorio P3, Gon Note, Pariston Note, Ryosuke Note, Mafuuu Note Yes
CRF-3 Nit Open codersdk/agentsdk/agentsdk.go:126 TemplateName field has no doc comment saying name, not display name R1 Leorio Yes
CRF-4 Note Dropped by orchestrator (comment unchanged; block already held identity vars before the PR, so its accuracy is unchanged) agent/agent.go:1542 "Set env vars indicating we're inside a Coder workspace" comment restates keys R1 Gon P2 No
CRF-5 OOS Out of scope (body) agent/agent.go:1017 Comment above connect call describes ConnectRPC, a different method R1 Gon P2 No
CRF-6 OOS Out of scope (body) agent/agent.go:1570 "current env overrides" comment contradicts loop that only adds missing keys R1 Ryosuke, Mafuuu, Zoro No
CRF-7 OOS Out of scope (body) agent/agent_test.go:1826 TestAgent_CoderEnvVars does not check CODER_WORKSPACE_ID R1 Netero, Bisky No
CRF-8 Note Dropped by orchestrator (claim disproved: agenttest serves the manifest through ProtoFromManifest at agenttest/client.go:75, so TestAgent_CoderEnvVars round-trips and asserts the build ID) codersdk/agentsdk/convert_test.go:22 TestManifest does not round-trip WorkspaceBuildID R1 Bisky No
CRF-9 OOS Out of scope (body) coderd/workspaceagents_test.go:2494 Real-database manifest test does not check template fields R1 Bisky No
CRF-10 OOS Out of scope (body) tailnet/proto/version.go:107 No version entry records workspace_build_id R1 Leorio No
CRF-11 OOS Out of scope (body) agent/agent.go:1572 strings.SplitN plus length check could be strings.Cut R1 Ging-Go No
CRF-12 OOS Out of scope (body) docs/ No page lists CODER_WORKSPACE_ID or CODER_WORKSPACE_BUILD_ID R1 Ryosuke, Gon No
CRF-13 Note Dropped by orchestrator (confirmation, asks no change) agent/agent.go:1548 Proto, SDK, env var, and client interface pairings match R1 Melody No
CRF-14 Note Dropped by orchestrator (confirmation, asks no change) agent/agent.go:1549 Variable names and sources match the Terraform provisioner R1 Gon, Zoro No
CRF-15 Note Dropped by orchestrator (confirmation, asks no change) tailnet/proto/version.go:113 v2.16 changelog entry follows sibling format R1 Leorio No

Contested and acknowledged

Law analysis

Not run. Effective additions 95 (threshold 1000). Head 530e035.

Round log

Round 1

Round type: round 1, full panel. Netero first pass: 1 P4 (CRF-1), no gate. Panel: ging-go, ryosuke, melody (specialists: Go files, Go API and package boundaries, proto/SDK serialization chain); pariston, mafuuu (core); bisky (tests changed), gon, leorio (once-per-PR floor); zoro (wildcard, random draw). Focused size 8 plus wildcard. Results: 1 P3, 1 P4, 1 Nit posted; Gon P2 on agent.go:1017 moved to out of scope (comment line unchanged and already inaccurate); Gon P2 on agent.go:1542 dropped (keep-argument: new entries sit under a comment that describes a different purpose; drop reason: the block already held CODER_WORKSPACE_ID and name variables, so the diff does not change the comment's accuracy). Bisky convert_test OOS item dropped as disproved. Name-mutability notes from Ryosuke, Pariston, Mafuuu merged into CRF-2. Reviewed against 67e216b..530e035.

About deep-review

CRF = Coder Review Finding (P0-P4, Nit, Note)

Reviewer Focus
Bisky tests
Chopper ops/errors
Churn-guard change verification
Ging language modernization
Gon naming
Hisoka edge cases
Killua perf
Kite change integrity
Knov contracts
Knuckle SQL
Komugi flake/determinism
Kurapika security
Law decomposition
Leorio docs
Luffy product
Mafu-san process
Mafuuu contracts
Melody dispatch/pairing
Meruem structural
Nami frontend
Netero mechanical checks
Pariston premise testing
Pen-botter product gaps
Razor verification
Robin duplication
Ryosuke Go arch
Takumi concurrency
Zoro shape

🤖 Managed by Coder Agents.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-02T11:50:48.276933Z 530e035 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

This comment has been minimized.

coder-agents-review[bot]

This comment was marked as outdated.

@mafredri
mafredri force-pushed the mafredri/agent-template-env branch from 530e035 to b0b4c1a Compare November 2, 2026 13:19
@mafredri

This comment was marked as outdated.

@mafredri

mafredri commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

Squash message:

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.

@mafredri
mafredri marked this pull request as ready for review November 2, 2026 14:11
@mafredri
mafredri requested a review from spikecurtis as a code owner November 2, 2026 14:11
@mafredri
mafredri requested a review from BobbyHo November 2, 2026 14:11

@spikecurtis spikecurtis left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Proto looks ok

@BobbyHo
BobbyHo requested a review from Emyrk November 2, 2026 21:28

@BobbyHo BobbyHo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm. Just left a minor (non-blocking) doc comment.

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. Scripts that depend on
template-specific scripts, such as a personalize script calling
coder exp sync wait, can now tell which template they run under.

Like CODER_WORKSPACE_BUILD_ID, both are left unset when the server
predates the fields.
release/2.39 shipped v2.15, so the template_id and template_name
manifest fields belong to a new minor version. The agent dials v2.16.
The agent dials an Agent API version that only servers sending these
manifest fields accept, so the nil checks for an older server never
fire, and Coder does not support older servers. The template ID and
name are always set: workspaces.template_id is NOT NULL and
workspaces_expanded inner-joins templates.

TestAgent_CoderEnvVars now checks exact values for every variable,
which replaces the separate build ID and template tests and their
Unset cases.
ManifestFromProto parses required IDs with uuid.FromBytes, as it does
for agent_id, workspace_id, and the script and devcontainer IDs. The
len > 0 guard on workspace_build_id existed for servers older than the
field, which an agent at this API version cannot connect to, so a
missing value now fails conversion instead of becoming uuid.Nil.
TestAgent_CoderEnvVars checked every predefined identity variable except
CODER_WORKSPACE_ID. TestWorkspaceAgent_Metadata now checks the template
fields against a manifest built from a real database, which the mocked
TestGetManifest cannot show.
No page listed the CODER_WORKSPACE_* variables, so script authors had to
read agent code to find them. The personalize section links to the list
with one example.
The agent fetches the manifest once per connection to Coder, so a
template, workspace, or user rename reaches new commands only after the
agent reconnects. Scripts in a long-running workspace can otherwise
expect the new name.
A running command keeps the environment it started with, and only new
commands pick up a new name after the agent reconnects.
@mafredri
mafredri force-pushed the mafredri/agent-template-env branch from b0b4c1a to 88fa5fe Compare November 3, 2026 09:30

@coderagents coderagents Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documentation Check

Blocking

  • docs/admin/templates/extending-templates/environment-variables.md (open) - The new "Variables the agent sets" section serves the end-user script author on a page that targets the template author.

Design notes

  • The agent-set environment variable table, the rename caveat, and the rename-timing paragraph all describe what an in-workspace script reads, which is the end user's concern. They live on the template-author environment-variables.md page.

Automated review via Coder Agents. Reply to a finding's thread with the reason if the finding is wrong.


## Variables the agent sets

The Coder agent sets these environment variables for every command it runs, including scripts and SSH sessions:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: The new "Variables the agent sets" table describes values an end user's in-workspace script reads, so it serves the end user (Dave) on a page that otherwise targets the template author (Perry), whose task here is writing coder_env resources. (Reader Advocate)

Evidence: the page's opening targets the template author ("Use the coder_env resource to inject environment variables into your workspace agents"); the table's value column is read by a script running inside the workspace.

To identify a template reliably, this belongs on the page the script author reads, docs/user-guides/workspace-dotfiles.md.

Suggested change
The Coder agent sets these environment variables for every command it runs, including scripts and SSH sessions:
Move the agent-set environment variable table to the workspace-dotfiles.md "Personalize script" section and cross-link from there. On this admin page, keep only the note that a `coder_env` resource or the agent's `env` block overrides these values, which is the one piece relevant to writing `coder_env`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The template author reads these too. Every coder_script runs with them, including cron scripts that run long after Terraform rendered the template. A portable shell script can't use data.coder_workspace, and an interpolated value is fixed at build time. The table stays with the template's environment variables, and the dotfiles guide links to it for end users.

🤖 Posted using /amend-review skill via Coder Agents.

| `CODER_WORKSPACE_TEMPLATE_ID` | ID of the workspace's template |
| `CODER_WORKSPACE_TEMPLATE_NAME` | Name of the workspace's template |

Template names are unique only within an organization, and a template can be renamed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: "Template names are unique only within an organization, and a template can be renamed" only changes what a reader does if that reader branches on the template name in a script, which is the end user (Dave) on docs/user-guides/workspace-dotfiles.md, not the template author this page targets. (Reader Advocate)

Evidence: the page's task is writing coder_env resources; the caution matters only to the script author who compares CODER_WORKSPACE_TEMPLATE_NAME.

Suggested change
Template names are unique only within an organization, and a template can be renamed.
Move this sentence to workspace-dotfiles.md next to the branch-on-template-name example (line 41), reframed for the script author. The related rename-timing paragraph you added ("commands that are already running keep the old name") is the same audience and should move with it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same reason: a template's script that reads CODER_WORKSPACE_TEMPLATE_NAME, for example a cron script or one shared across templates, depends on both the uniqueness and the rename timing, so the notes stay with the table.

🤖 Posted using /amend-review skill via Coder Agents.

| `CODER_WORKSPACE_ID` | ID of the workspace |
| `CODER_WORKSPACE_BUILD_ID` | ID of the workspace build that created the agent |
| `CODER_WORKSPACE_TEMPLATE_ID` | ID of the workspace's template |
| `CODER_WORKSPACE_TEMPLATE_NAME` | Name of the workspace's template |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The table says the value is the "Name of the workspace's template", so a reader does not learn that it is the template's internal name field, not its display name, and cannot know what string to compare against when adapting a script. (Newcomer)

Evidence: the value comes from templates.name (not display_name) via workspaces_expanded.

Suggested change
| `CODER_WORKSPACE_TEMPLATE_NAME` | Name of the workspace's template |
Use "The template's `name` field (not its display name)" for the value of `CODER_WORKSPACE_TEMPLATE_NAME`, so a script author knows to compare against `templates.name`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coder calls these the template's name and its display name: codersdk.Template has Name and DisplayName, the template settings form labels them "Name" and "Display name", and coder templates edit has --name and --display-name.

🤖 Posted using /amend-review skill via Coder Agents.

@coderagents

coderagents Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Documentation Check

Blocking

  • docs/admin/templates/extending-templates/environment-variables.md (open) - The new "Variables the agent sets" section serves the end-user script author on a page that targets the template author.

Design notes

  • The agent-set environment variable table, the rename caveat, and the rename-timing paragraph all describe what an in-workspace script reads, which is the end user's concern. They live on the template-author environment-variables.md page.

    The same variable CODER_WORKSPACE_AGENT_NAME is "Name of the agent" here but "Name of the dev container agent" on the devcontainers page; each is accurate for its own surface.

Findings for agents
- id: audience-1
  persona: audience
  class: rule
  blocking: true
  file: docs/admin/templates/extending-templates/environment-variables.md
  line: 134
  quote: "The Coder agent sets these environment variables for every command it runs, including scripts and SSH sessions:"
  evidence:
    - docs/user-guides/workspace-dotfiles.md:36
  rule: docs/.style/style-guide/audience-and-scope.md#pick-one-audience-per-page
  problem: The new "Variables the agent sets" table lists values an end user's in-workspace script reads, so it serves the end user on a page that targets the template author writing coder_env resources.
  fix: Move the agent-set environment variable table to the workspace-dotfiles.md "Personalize script" section and cross-link from there; on this admin page keep only the override caveat a template author acts on.
  verified: true
- id: audience-2
  persona: audience
  class: rule
  blocking: true
  file: docs/admin/templates/extending-templates/environment-variables.md
  line: 147
  quote: "Template names are unique only within an organization, and a template can be renamed."
  evidence:
    - docs/user-guides/workspace-dotfiles.md:41
  rule: docs/.style/style-guide/audience-and-scope.md#give-the-audience-only-what-it-needs
  problem: This product-behavior caveat only changes what a reader does if they branch on the template name in a script, which is the end user on workspace-dotfiles.md, not the template author this page targets.
  fix: Cut the sentence and its rename-timing follow-up from this admin page and place them on workspace-dotfiles.md next to the branch-on-template-name example.
  verified: true
- id: learner-1
  persona: learner
  class: suggestion
  blocking: false
  file: docs/admin/templates/extending-templates/environment-variables.md
  line: 145
  quote: "| `CODER_WORKSPACE_TEMPLATE_NAME` | Name of the workspace's template |"
  evidence:
    - agent/agent.go:1540-1552
  rule: null
  problem: The table says the value is the "Name of the workspace's template", so a reader does not learn that it is the template's internal name field, not its display name, and cannot know what string to compare against in a script.
  fix: Use "The template's `name` field (not its display name)" for the value of `CODER_WORKSPACE_TEMPLATE_NAME`.
  verified: true

Automated review via Coder Agents. Reply to a finding's thread with the reason if the finding is wrong.

@mafredri
mafredri merged commit 540552f into main Nov 3, 2026
31 of 32 checks passed
@mafredri
mafredri deleted the mafredri/agent-template-env branch November 3, 2026 10:34
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 3, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants