Install agent CLIs and VS Code extensions in generated devcontainers

The nvm-based node feature put npm outside sudo secure_path and broke the postCreateCommand, so containers with agents now copy Node from the official docker.io/library/node image into /usr/local in every profile. Each selected agent also adds its official VS Code extension to the customizations and the generator captures every extension installed in the local VS Code through code --list-extensions, deduplicated case-insensitively and sorted at generation time.
This commit is contained in:
2026-11-19 00:39:17 +01:00
parent 47acda71b6
commit 012cb3534b
4 changed files with 194 additions and 27 deletions

View File

@@ -10,7 +10,9 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"os/exec"
"path/filepath" "path/filepath"
"slices"
"sort" "sort"
"strings" "strings"
) )
@@ -24,6 +26,7 @@ type profile struct {
} }
type agent struct { type agent struct {
Package string Package string
Extension string
Paths []string Paths []string
} }
type mount struct { type mount struct {
@@ -78,7 +81,7 @@ func selectAgents(selection, home string) ([]string, error) {
return result, nil return result, nil
} }
func generate(project, language, home string, selected []string, force bool) (string, error) { func generate(project, language, home string, selected []string, local []string, force bool) (string, error) {
p, ok := profiles[language] p, ok := profiles[language]
if !ok { if !ok {
return "", fmt.Errorf("unknown language %q", language) return "", fmt.Errorf("unknown language %q", language)
@@ -151,7 +154,21 @@ func generate(project, language, home string, selected []string, force bool) (st
mounts = append(mounts, mount{"bind", "${localEnv:HOME}/" + item.path, destination, item.readonly}) mounts = append(mounts, mount{"bind", "${localEnv:HOME}/" + item.path, destination, item.readonly})
} }
} }
dockerfile := fmt.Sprintf("FROM %s\nUSER root\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client ripgrep zoxide %s \\\n && rm -rf /var/lib/apt/lists/*\n", p.Image, p.Packages) // The devcontainers node feature ships an nvm-based Node outside sudo's
// secure_path, which broke the postCreateCommand npm install. Copy the
// official Node image binaries into /usr/local instead, exactly like the
// ecaas and cdp devcontainers, so sudo npm works in every profile.
needsNode := len(selected) > 0
dockerfile := ""
if needsNode {
dockerfile += "FROM docker.io/library/node:22-bookworm-slim AS node\n"
}
dockerfile += fmt.Sprintf("FROM %s\nUSER root\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client ripgrep zoxide %s \\\n && rm -rf /var/lib/apt/lists/*\n", p.Image, p.Packages)
if needsNode {
dockerfile += "COPY --from=node /usr/local/bin/node /usr/local/bin/node\n"
dockerfile += "COPY --from=node /usr/local/lib/node_modules/npm/ /usr/local/lib/node_modules/npm/\n"
dockerfile += "RUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \\\n && ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \\\n && node --version && npm --version\n"
}
dockerfile += deltaDockerfile dockerfile += deltaDockerfile
if home != "/home/vscode" { if home != "/home/vscode" {
dockerfile += "RUN usermod --home " + quote(home) + " --move-home vscode\n" dockerfile += "RUN usermod --home " + quote(home) + " --move-home vscode\n"
@@ -165,12 +182,30 @@ func generate(project, language, home string, selected []string, force bool) (st
if language == "infra" { if language == "infra" {
dockerfile += "RUN python -m pip install --no-cache-dir ansible-core ansible-lint yamllint\n" dockerfile += "RUN python -m pip install --no-cache-dir ansible-core ansible-lint yamllint\n"
} }
// The container installs the profile extensions, the VS Code extension of
// every selected agent and the extensions currently installed in the local
// VS Code, captured at generation time. Regenerate to refresh the local set.
extensions := append([]string{}, p.Extensions...)
addExtension := func(id string) {
if !slices.ContainsFunc(extensions, func(e string) bool { return strings.EqualFold(e, id) }) {
extensions = append(extensions, id)
}
}
for _, name := range selected {
if id := agents[name].Extension; id != "" {
addExtension(id)
}
}
for _, id := range local {
addExtension(strings.TrimSpace(id))
}
slices.Sort(extensions)
config := map[string]any{ config := map[string]any{
"name": filepath.Base(project) + " — " + language, "name": filepath.Base(project) + " — " + language,
"build": map[string]string{"dockerfile": "Dockerfile"}, "build": map[string]string{"dockerfile": "Dockerfile"},
"remoteUser": "vscode", "updateRemoteUserUID": true, "remoteUser": "vscode", "updateRemoteUserUID": true,
"containerEnv": map[string]string{"HOME": home}, "mounts": mounts, "containerEnv": map[string]string{"HOME": home}, "mounts": mounts,
"customizations": map[string]any{"vscode": map[string]any{"extensions": p.Extensions}}, "customizations": map[string]any{"vscode": map[string]any{"extensions": extensions}},
} }
if len(selected) > 0 { if len(selected) > 0 {
packages := []string{} packages := []string{}
@@ -178,9 +213,6 @@ func generate(project, language, home string, selected []string, force bool) (st
packages = append(packages, quote(agents[name].Package)) packages = append(packages, quote(agents[name].Package))
} }
config["postCreateCommand"] = "sudo npm install --global --no-audit --no-fund " + strings.Join(packages, " ") config["postCreateCommand"] = "sudo npm install --global --no-audit --no-fund " + strings.Join(packages, " ")
if language != "node" {
config["features"] = map[string]any{"ghcr.io/devcontainers/features/node:1": map[string]string{"version": "22"}}
}
} }
if claude { if claude {
config["remoteEnv"] = map[string]string{"ANTHROPIC_AUTH_TOKEN": "${localEnv:ANTHROPIC_AUTH_TOKEN}"} config["remoteEnv"] = map[string]string{"ANTHROPIC_AUTH_TOKEN": "${localEnv:ANTHROPIC_AUTH_TOKEN}"}
@@ -239,6 +271,29 @@ func writeAtomic(path, content string) error {
return os.Rename(file.Name(), path) return os.Rename(file.Name(), path)
} }
// discoverLocalExtensions lists the extensions installed in the local VS Code.
// A missing or failing code binary is not fatal: the generated container then
// only carries the profile and agent extensions.
func discoverLocalExtensions(stderr io.Writer) []string {
path, err := exec.LookPath("code")
if err != nil {
fmt.Fprintln(stderr, "note: no local VS Code found; skipping locally installed extensions")
return nil
}
out, err := exec.Command(path, "--list-extensions").Output()
if err != nil {
fmt.Fprintf(stderr, "warning: could not list local VS Code extensions: %v\n", err)
return nil
}
extensions := []string{}
for _, line := range strings.Split(string(out), "\n") {
if id := strings.TrimSpace(line); id != "" {
extensions = append(extensions, id)
}
}
return extensions
}
func run(args []string, home string, out, stderr io.Writer) error { func run(args []string, home string, out, stderr io.Writer) error {
flags := flag.NewFlagSet("devcontainer", flag.ContinueOnError) flags := flag.NewFlagSet("devcontainer", flag.ContinueOnError)
flags.SetOutput(stderr) flags.SetOutput(stderr)
@@ -264,7 +319,8 @@ func run(args []string, home string, out, stderr io.Writer) error {
if err != nil { if err != nil {
return err return err
} }
target, err := generate(flags.Arg(0), *language, home, selected, *force) local := discoverLocalExtensions(stderr)
target, err := generate(flags.Arg(0), *language, home, selected, local, *force)
if err != nil { if err != nil {
return err return err
} }
@@ -273,6 +329,9 @@ func run(args []string, home string, out, stderr io.Writer) error {
names = "none" names = "none"
} }
fmt.Fprintf(out, "Created %s; agents: %s\n", target, names) fmt.Fprintf(out, "Created %s; agents: %s\n", target, names)
if len(local) > 0 {
fmt.Fprintf(out, "Included %d local VS Code extensions.\n", len(local))
}
fmt.Fprintln(out, "Open the project in VS Code and choose Dev Containers: Reopen in Container.") fmt.Fprintln(out, "Open the project in VS Code and choose Dev Containers: Reopen in Container.")
return nil return nil
} }

View File

@@ -5,6 +5,7 @@ import (
"encoding/json" "encoding/json"
"os" "os"
"path/filepath" "path/filepath"
"slices"
"strings" "strings"
"testing" "testing"
) )
@@ -38,11 +39,28 @@ func put(t *testing.T, path, content string) {
} }
} }
type vscodeCustomizations struct {
Customizations struct {
Vscode struct {
Extensions []string `json:"extensions"`
} `json:"vscode"`
} `json:"customizations"`
}
func extensionsOf(t *testing.T, target string) []string {
t.Helper()
var config vscodeCustomizations
if err := json.Unmarshal([]byte(read(t, filepath.Join(target, "devcontainer.json"))), &config); err != nil {
t.Fatal(err)
}
return config.Customizations.Vscode.Extensions
}
func TestProfiles(t *testing.T) { func TestProfiles(t *testing.T) {
for name := range profiles { for name := range profiles {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
home, project := setup(t) home, project := setup(t)
target, err := generate(project, name, home, nil, false) target, err := generate(project, name, home, nil, nil, false)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -56,6 +74,11 @@ func TestProfiles(t *testing.T) {
if _, ok := config["postCreateCommand"]; ok { if _, ok := config["postCreateCommand"]; ok {
t.Fatal("unexpected agent install") t.Fatal("unexpected agent install")
} }
want := append([]string{}, profiles[name].Extensions...)
slices.Sort(want)
if got := extensionsOf(t, target); !slices.Equal(got, want) {
t.Fatalf("wrong extensions: %v", got)
}
dockerfile := read(t, filepath.Join(target, "Dockerfile")) dockerfile := read(t, filepath.Join(target, "Dockerfile"))
if !strings.HasPrefix(dockerfile, "FROM "+profiles[name].Image+"\n") || !strings.HasSuffix(dockerfile, "USER vscode\n") { if !strings.HasPrefix(dockerfile, "FROM "+profiles[name].Image+"\n") || !strings.HasSuffix(dockerfile, "USER vscode\n") {
t.Fatal("wrong Dockerfile") t.Fatal("wrong Dockerfile")
@@ -67,7 +90,7 @@ func TestSharedConfig(t *testing.T) {
home, project := setup(t) home, project := setup(t)
put(t, filepath.Join(home, ".codex/auth.json"), "secret-value") put(t, filepath.Join(home, ".codex/auth.json"), "secret-value")
put(t, filepath.Join(home, ".gitconfig"), "[user]\nname = Test\n") put(t, filepath.Join(home, ".gitconfig"), "[user]\nname = Test\n")
target, err := generate(project, "python", home, []string{"codex"}, false) target, err := generate(project, "python", home, []string{"codex"}, nil, false)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -79,7 +102,6 @@ func TestSharedConfig(t *testing.T) {
var config struct { var config struct {
Mounts []mount Mounts []mount
PostCreateCommand string PostCreateCommand string
Features map[string]any
} }
if err := json.Unmarshal([]byte(configText), &config); err != nil { if err := json.Unmarshal([]byte(configText), &config); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -96,18 +118,66 @@ func TestSharedConfig(t *testing.T) {
if !foundGit || !foundAgent || !strings.Contains(dockerfile, "include.path /run/host-gitconfig") { if !foundGit || !foundAgent || !strings.Contains(dockerfile, "include.path /run/host-gitconfig") {
t.Fatal("incorrect sharing") t.Fatal("incorrect sharing")
} }
if !strings.Contains(config.PostCreateCommand, "@openai/codex") || len(config.Features) == 0 { if !strings.Contains(config.PostCreateCommand, "@openai/codex") || !strings.Contains(dockerfile, "COPY --from=node /usr/local/bin/node") {
t.Fatal("missing CLI or Node feature") t.Fatal("missing CLI install or embedded Node")
}
if !slices.Contains(extensionsOf(t, target), "openai.chatgpt") {
t.Fatal("agent VS Code extension missing")
}
}
func TestAgentAndLocalExtensions(t *testing.T) {
home, project := setup(t)
put(t, filepath.Join(home, ".cline/state/config"), "")
put(t, filepath.Join(home, ".agents/AGENTS.md"), "")
local := []string{"github.remotehub", "SAOUDRIZWAN.claude-dev", "ms-vscode.cpptools"}
target, err := generate(project, "python", home, []string{"cline"}, local, false)
if err != nil {
t.Fatal(err)
}
want := []string{"ms-python.python", "charliermarsh.ruff", "saoudrizwan.claude-dev", "github.remotehub", "ms-vscode.cpptools"}
slices.Sort(want)
if got := extensionsOf(t, target); !slices.Equal(got, want) {
t.Fatalf("extensions mismatch: %v", got)
}
}
func TestAgentsShipNpmInsideSudoPath(t *testing.T) {
for name := range profiles {
t.Run(name, func(t *testing.T) {
home, project := setup(t)
put(t, filepath.Join(home, ".cline/state/config"), "")
put(t, filepath.Join(home, ".agents/AGENTS.md"), "")
target, err := generate(project, name, home, []string{"cline"}, nil, false)
if err != nil {
t.Fatal(err)
}
var config map[string]any
if err := json.Unmarshal([]byte(read(t, filepath.Join(target, "devcontainer.json"))), &config); err != nil {
t.Fatal(err)
}
if _, hasFeature := config["features"]; hasFeature {
t.Fatal("the nvm-based node feature breaks the sudo npm postCreateCommand")
}
post, _ := config["postCreateCommand"].(string)
if !strings.Contains(post, "sudo npm install") {
t.Fatalf("missing npm agent install: %q", post)
}
dockerfile := read(t, filepath.Join(target, "Dockerfile"))
if !strings.HasPrefix(dockerfile, "FROM docker.io/library/node:22-bookworm-slim AS node\n") ||
!strings.Contains(dockerfile, "COPY --from=node /usr/local/bin/node /usr/local/bin/node") ||
!strings.Contains(dockerfile, "ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm") {
t.Fatal("npm must be reachable inside sudo's secure_path")
}
})
} }
} }
func TestOverwriteAndSymlinks(t *testing.T) { func TestOverwriteAndSymlinks(t *testing.T) {
home, project := setup(t) home, project := setup(t)
target, err := generate(project, "go", home, nil, false) target, err := generate(project, "go", home, nil, nil, false)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
before := read(t, filepath.Join(target, "Dockerfile")) before := read(t, filepath.Join(target, "Dockerfile"))
if _, err := generate(project, "rust", home, nil, false); err == nil { if _, err := generate(project, "rust", home, nil, nil, false); err == nil {
t.Fatal("overwrote existing configuration") t.Fatal("overwrote existing configuration")
} }
path := filepath.Join(target, "devcontainer.json") path := filepath.Join(target, "devcontainer.json")
@@ -119,7 +189,7 @@ func TestOverwriteAndSymlinks(t *testing.T) {
if err := os.Symlink(victim, path); err != nil { if err := os.Symlink(victim, path); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if _, err := generate(project, "rust", home, nil, true); err == nil { if _, err := generate(project, "rust", home, nil, nil, true); err == nil {
t.Fatal("accepted symlink") t.Fatal("accepted symlink")
} }
if read(t, victim) != "keep" || read(t, filepath.Join(target, "Dockerfile")) != before { if read(t, victim) != "keep" || read(t, filepath.Join(target, "Dockerfile")) != before {
@@ -146,7 +216,7 @@ func TestInvalidInputs(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
} }
if _, err := generate(project, language, home, selected, true); err == nil { if _, err := generate(project, language, home, selected, nil, true); err == nil {
t.Fatal("invalid input accepted") t.Fatal("invalid input accepted")
} }
if exists(filepath.Join(project, ".devcontainer/Dockerfile")) { if exists(filepath.Join(project, ".devcontainer/Dockerfile")) {
@@ -188,3 +258,24 @@ func TestCLI(t *testing.T) {
}) })
} }
} }
func TestLocalExtensionDiscovery(t *testing.T) {
bin := t.TempDir()
script := filepath.Join(bin, "code")
if err := os.WriteFile(script, []byte("#!/bin/sh\necho a.b\necho c.d\n"), 0755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
home, project := setup(t)
var out bytes.Buffer
if err := run([]string{project, "--language", "go", "--agents", "none"}, home, &out, &out); err != nil {
t.Fatal(err)
}
want := []string{"a.b", "c.d", "golang.go"}
slices.Sort(want)
if got := extensionsOf(t, filepath.Join(project, ".devcontainer")); !slices.Equal(got, want) {
t.Fatalf("extensions mismatch: %v", got)
}
if !strings.Contains(out.String(), "Included 2 local VS Code extensions.") {
t.Fatal("missing local extensions summary")
}
}

View File

@@ -10,9 +10,9 @@ var profiles = map[string]profile{
"infra": {Image: "mcr.microsoft.com/devcontainers/python:3.13-bookworm", Packages: "shellcheck shfmt", Extensions: []string{"redhat.ansible", "redhat.vscode-yaml"}}, "infra": {Image: "mcr.microsoft.com/devcontainers/python:3.13-bookworm", Packages: "shellcheck shfmt", Extensions: []string{"redhat.ansible", "redhat.vscode-yaml"}},
} }
var agents = map[string]agent{ var agents = map[string]agent{
"codex": {Package: "@openai/codex", Paths: []string{".codex"}}, "codex": {Package: "@openai/codex", Extension: "openai.chatgpt", Paths: []string{".codex"}},
"cline": {Package: "cline", Paths: []string{".cline", ".agents"}}, "cline": {Package: "cline", Extension: "saoudrizwan.claude-dev", Paths: []string{".cline", ".agents"}},
"opencode": {Package: "opencode-ai", Paths: []string{".config/opencode", ".local/share/opencode", ".local/state/opencode"}}, "opencode": {Package: "opencode-ai", Extension: "sst-dev.opencode", Paths: []string{".config/opencode", ".local/share/opencode", ".local/state/opencode"}},
"claude": {Package: "@anthropic-ai/claude-code@2.1.312", Paths: []string{".claude"}}, "claude": {Package: "@anthropic-ai/claude-code@2.1.312", Extension: "anthropic.claude-code", Paths: []string{".claude"}},
"gemini": {Package: "@google/gemini-cli", Paths: []string{".gemini"}}, "gemini": {Package: "@google/gemini-cli", Extension: "Google.geminicodeassist", Paths: []string{".gemini"}},
} }

View File

@@ -40,7 +40,15 @@ ansible-playbook ansible/site.yml --limit ikaros --tags devcontainer_generator -
``` ```
Profiles: `c-cpp`, `go`, `rust`, `python`, `node`, `java`, `infra`. They generate Profiles: `c-cpp`, `go`, `rust`, `python`, `node`, `java`, `infra`. They generate
`.devcontainer/devcontainer.json` and `Dockerfile`. Open the project in local VS `.devcontainer/devcontainer.json` and `Dockerfile`. The generated
`customizations.vscode.extensions` list combines the profile extensions, the VS
Code extension of each selected agent (`cline` → `saoudrizwan.claude-dev`,
`claude` → `anthropic.claude-code`, `codex` → `openai.chatgpt`, `gemini` →
`Google.geminicodeassist`, `opencode` → `sst-dev.opencode`) and every extension
installed in the local VS Code, captured through `code --list-extensions` at
generation time; regenerate after installing or removing extensions on the
host. Without a local VS Code on PATH only the profile and agent extensions are
included. Open the project in local VS
Code (in Fedora WSL on deadalus) and choose **Reopen in Container**. The generator Code (in Fedora WSL on deadalus) and choose **Reopen in Container**. The generator
never builds or starts a container, selects a Docker context, modifies application never builds or starts a container, selects a Docker context, modifies application
sources, or removes host packages. Existing `.devcontainer` directories are refused; sources, or removes host packages. Existing `.devcontainer` directories are refused;
@@ -50,6 +58,9 @@ The definitions live centrally in the generator; generated files are standalone.
Regenerate explicitly to take updates. Profile images select a language version Regenerate explicitly to take updates. Profile images select a language version
or release family, not immutable digests; npm agents other than Claude currently or release family, not immutable digests; npm agents other than Claude currently
resolve the latest release at container creation, matching the host lifecycle. resolve the latest release at container creation, matching the host lifecycle.
Agent containers copy Node from the official `docker.io/library/node` image into
`/usr/local` instead of using the nvm-based node feature, so the
`sudo npm install` postCreateCommand works in every profile.
Rebuilds are therefore not bit-for-bit reproducible. Pin image digests and agent Rebuilds are therefore not bit-for-bit reproducible. Pin image digests and agent
versions in generated project files when a project requires that guarantee. versions in generated project files when a project requires that guarantee.
Project-specific dependencies, ports, services and build commands belong in the Project-specific dependencies, ports, services and build commands belong in the
@@ -100,9 +111,15 @@ credential contents, but do contain the host's absolute home path.
Use a local development container engine. Docker CE is currently provisioned on Use a local development container engine. Docker CE is currently provisioned on
deadalus; ikaros explicitly has Podman, while nymph's runtime needs verification. deadalus; ikaros explicitly has Podman, while nymph's runtime needs verification.
Podman requires VS Code's `dev.containers.dockerPath` and compatible rootless/UID Podman (5+) works through VS Code's `dev.containers.dockerPath: podman` per the
configuration; generation alone does not configure it. SELinux bind-mount access official Dev Containers documentation: the extension drives the container CLI
must also be validated on Fedora. Do not recursively relabel the personal home. and needs neither the `podman-docker` shim nor a daemon socket or `DOCKER_HOST`.
Never install `podman-docker` where docker-ce provides the real Docker CLI
(deadalus). Generation alone does not configure the engine; the `desktop_gnome`
profile deploys `dev.containers.dockerPath: podman` with its managed VS Code
settings, while compatible
rootless/UID configuration and SELinux bind-mount access must be validated on the
Fedora target host. Do not recursively relabel the personal home.
No engine socket is mounted inside these containers by default; add access only No engine socket is mounted inside these containers by default; add access only
for projects that need to launch sibling containers. for projects that need to launch sibling containers.