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"
"io"
"os"
"os/exec"
"path/filepath"
"slices"
"sort"
"strings"
)
@@ -23,8 +25,9 @@ type profile struct {
Extensions []string
}
type agent struct {
Package string
Paths []string
Package string
Extension string
Paths []string
}
type mount struct {
Type string `json:"type"`
@@ -78,7 +81,7 @@ func selectAgents(selection, home string) ([]string, error) {
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]
if !ok {
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})
}
}
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
if home != "/home/vscode" {
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" {
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{
"name": filepath.Base(project) + " — " + language,
"build": map[string]string{"dockerfile": "Dockerfile"},
"remoteUser": "vscode", "updateRemoteUserUID": true,
"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 {
packages := []string{}
@@ -178,9 +213,6 @@ func generate(project, language, home string, selected []string, force bool) (st
packages = append(packages, quote(agents[name].Package))
}
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 {
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)
}
// 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 {
flags := flag.NewFlagSet("devcontainer", flag.ContinueOnError)
flags.SetOutput(stderr)
@@ -264,7 +319,8 @@ func run(args []string, home string, out, stderr io.Writer) error {
if err != nil {
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 {
return err
}
@@ -273,6 +329,9 @@ func run(args []string, home string, out, stderr io.Writer) error {
names = "none"
}
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.")
return nil
}

View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"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) {
for name := range profiles {
t.Run(name, func(t *testing.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 {
t.Fatal(err)
}
@@ -56,6 +74,11 @@ func TestProfiles(t *testing.T) {
if _, ok := config["postCreateCommand"]; ok {
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"))
if !strings.HasPrefix(dockerfile, "FROM "+profiles[name].Image+"\n") || !strings.HasSuffix(dockerfile, "USER vscode\n") {
t.Fatal("wrong Dockerfile")
@@ -67,7 +90,7 @@ func TestSharedConfig(t *testing.T) {
home, project := setup(t)
put(t, filepath.Join(home, ".codex/auth.json"), "secret-value")
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 {
t.Fatal(err)
}
@@ -79,7 +102,6 @@ func TestSharedConfig(t *testing.T) {
var config struct {
Mounts []mount
PostCreateCommand string
Features map[string]any
}
if err := json.Unmarshal([]byte(configText), &config); err != nil {
t.Fatal(err)
@@ -96,18 +118,66 @@ func TestSharedConfig(t *testing.T) {
if !foundGit || !foundAgent || !strings.Contains(dockerfile, "include.path /run/host-gitconfig") {
t.Fatal("incorrect sharing")
}
if !strings.Contains(config.PostCreateCommand, "@openai/codex") || len(config.Features) == 0 {
t.Fatal("missing CLI or Node feature")
if !strings.Contains(config.PostCreateCommand, "@openai/codex") || !strings.Contains(dockerfile, "COPY --from=node /usr/local/bin/node") {
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) {
home, project := setup(t)
target, err := generate(project, "go", home, nil, false)
target, err := generate(project, "go", home, nil, nil, false)
if err != nil {
t.Fatal(err)
}
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")
}
path := filepath.Join(target, "devcontainer.json")
@@ -119,7 +189,7 @@ func TestOverwriteAndSymlinks(t *testing.T) {
if err := os.Symlink(victim, path); err != nil {
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")
}
if read(t, victim) != "keep" || read(t, filepath.Join(target, "Dockerfile")) != before {
@@ -146,7 +216,7 @@ func TestInvalidInputs(t *testing.T) {
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")
}
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"}},
}
var agents = map[string]agent{
"codex": {Package: "@openai/codex", Paths: []string{".codex"}},
"cline": {Package: "cline", Paths: []string{".cline", ".agents"}},
"opencode": {Package: "opencode-ai", Paths: []string{".config/opencode", ".local/share/opencode", ".local/state/opencode"}},
"claude": {Package: "@anthropic-ai/claude-code@2.1.312", Paths: []string{".claude"}},
"gemini": {Package: "@google/gemini-cli", Paths: []string{".gemini"}},
"codex": {Package: "@openai/codex", Extension: "openai.chatgpt", Paths: []string{".codex"}},
"cline": {Package: "cline", Extension: "saoudrizwan.claude-dev", Paths: []string{".cline", ".agents"}},
"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", Extension: "anthropic.claude-code", Paths: []string{".claude"}},
"gemini": {Package: "@google/gemini-cli", Extension: "Google.geminicodeassist", Paths: []string{".gemini"}},
}