跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

agent-vm.setup.sh

729 行 · 32.8 KB历史下载
1#!/usr/bin/env bash
2#
3# agent-vm.setup.sh: Package installation script that runs inside the base VM
4# Part of https://www.agent-vm.org/
5#
6# This script is executed inside the VM during "agent-vm setup".
7#
8
9set -euo pipefail
10
11export DEBIAN_FRONTEND=noninteractive
12
13# apt under sudo, with the noninteractive frontend actually reaching it.
14#
15# The export above does not survive sudo: `Defaults env_reset` drops every
16# variable that is not in env_keep, so each `sudo apt-get install` started
17# debconf's Dialog frontend, failed to load it, fell back to Readline, failed
18# again, and printed that warning block, once per install step.
19#
20# `sudo env VAR=value` rather than `sudo -E` or `sudo VAR=value cmd`: both of
21# those need the sudoers policy to allow setting the environment, while
22# passing the variable to `env` is just a command with arguments.
23#
24# </dev/null: this script reaches bash on its stdin, so a command reading
25# stdin (dpkg asking about a changed config file, an npm install script)
26# would swallow the lines after it, which then never run.
27apt_get() {
28 local status before='' retries=3 timeout=60
29 if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then
30 before="$(awk '$1 == "oom_kill" {print $2}' /proc/vmstat)"
31 retries=1
32 timeout=15
33 fi
34 if sudo env DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries="$retries" -o Acquire::http::Timeout="$timeout" -o Acquire::https::Timeout="$timeout" "$@" </dev/null; then
35 return 0
36 else
37 status=$?
38 fi
39 if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then
40 printf 'APT failed (exit %s); guest memory evidence follows. oom_kill before=%s\n' "$status" "$before" >&2
41 apt-get --version | head -n 1 >&2 || true
42 awk '/^(MemTotal|MemAvailable|SwapTotal|SwapFree):/' /proc/meminfo >&2 || true
43 awk '$1 == "oom_kill" {print "oom_kill after=" $2}' /proc/vmstat >&2 || true
44 ps -eo pid,rss,comm --sort=-rss | head -n 12 >&2 || true
45 sudo timeout 5 journalctl -k -b --no-pager -n 40 --grep='Out of memory|Killed process|oom-kill' >&2 || true
46 printf 'Retry preserves the build VM and package cache. Export diagnostics if installation fails again.\n' >&2
47 fi
48 return "$status"
49}
50
51# Download completely before replacing a repository key. A failed request must
52# leave the previously trusted key usable on the next setup attempt.
53install_repository_key() (
54 set -euo pipefail
55 local url="$1" target="$2" stage replacement='' attempt status=1
56 stage="$(mktemp)"
57 trap 'rm -f "$stage"; if [ -n "$replacement" ]; then sudo rm -f "$replacement"; fi' EXIT
58 if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then
59 for attempt in 1 2 3 4; do
60 if cage_curl_download "$stage" --proto '=https' --proto-redir '=https' --tlsv1.2 --fail --location --show-error --silent \
61 --connect-timeout 15 "$url" -o "$stage" </dev/null; then
62 status=0
63 break
64 else
65 status=$?
66 fi
67 if [ "$attempt" != 4 ]; then sleep "$attempt"; fi
68 done
69 [ "$status" = 0 ] || return "$status"
70 else
71 curl --proto '=https' --proto-redir '=https' --tlsv1.2 --fail --location --show-error --silent \
72 --retry 3 --retry-all-errors --retry-max-time 120 --connect-timeout 15 --max-time 30 "$url" -o "$stage" </dev/null
73 fi
74 test -s "$stage"
75 if [[ "$target" == *.asc ]]; then
76 grep -q '^-----BEGIN PGP PUBLIC KEY BLOCK-----' "$stage"
77 grep -q '^-----END PGP PUBLIC KEY BLOCK-----' "$stage"
78 fi
79 replacement="$(sudo mktemp "${target}.XXXXXX")"
80 sudo install -m 0644 -o root -g root "$stage" "$replacement"
81 sudo mv -f "$replacement" "$target"
82 replacement=''
83)
84
85# Component toggles. The host wizard prepends `export` lines for these before
86# piping the script in. Members of the default install set (everything except
87# Ruby/Rust/Go/Pi/Playwright MCP/code-server and its extensions) default to 1 so running this
88# script standalone (without the wizard) produces the same install you'd get from
89# `agent-vm setup --preinstall=default`.
90INSTALL_PYTHON="${AGENT_VM_INSTALL_PYTHON:-1}"
91INSTALL_NODE="${AGENT_VM_INSTALL_NODE:-1}"
92INSTALL_RUBY="${AGENT_VM_INSTALL_RUBY:-0}"
93INSTALL_RUST="${AGENT_VM_INSTALL_RUST:-0}"
94INSTALL_GOLANG="${AGENT_VM_INSTALL_GOLANG:-0}"
95INSTALL_DOCKER="${AGENT_VM_INSTALL_DOCKER:-1}"
96INSTALL_CHROMIUM="${AGENT_VM_INSTALL_CHROMIUM:-1}"
97INSTALL_GH="${AGENT_VM_INSTALL_GH:-1}"
98INSTALL_CLAUDE="${AGENT_VM_INSTALL_CLAUDE:-1}"
99INSTALL_OPENCODE="${AGENT_VM_INSTALL_OPENCODE:-1}"
100INSTALL_CODEX="${AGENT_VM_INSTALL_CODEX:-1}"
101INSTALL_VIBE="${AGENT_VM_INSTALL_VIBE:-1}"
102INSTALL_PI="${AGENT_VM_INSTALL_PI:-0}"
103INSTALL_CODE_SERVER="${AGENT_VM_INSTALL_CODE_SERVER:-0}"
104# Each agent's code-server extension, which brings its own copy of the agent.
105INSTALL_CODE_CLAUDE="${AGENT_VM_INSTALL_CODE_CLAUDE:-0}"
106INSTALL_CODE_OPENCODE="${AGENT_VM_INSTALL_CODE_OPENCODE:-0}"
107INSTALL_CODE_CODEX="${AGENT_VM_INSTALL_CODE_CODEX:-0}"
108INSTALL_CODE_VIBE="${AGENT_VM_INSTALL_CODE_VIBE:-0}"
109# An extension needs the editor: `agent-vm setup` says so already, a run of
110# this script on its own may not.
111if [[ "$INSTALL_CODE_CLAUDE$INSTALL_CODE_OPENCODE$INSTALL_CODE_CODEX$INSTALL_CODE_VIBE" == *1* ]]; then
112 INSTALL_CODE_SERVER=1
113fi
114# MCP servers wired into every installed agent's config (see `agent-vm setup --help`).
115INSTALL_MCP_CHROME="${AGENT_VM_INSTALL_MCP_CHROME:-1}"
116INSTALL_MCP_PLAYWRIGHT="${AGENT_VM_INSTALL_MCP_PLAYWRIGHT:-0}"
117
118# An agent there in either form: its command line and its extension read the
119# same config, which is written for both.
120HAS_CLAUDE=0 HAS_OPENCODE=0 HAS_CODEX=0 HAS_VIBE=0
121[[ "$INSTALL_CLAUDE$INSTALL_CODE_CLAUDE" == *1* ]] && HAS_CLAUDE=1
122[[ "$INSTALL_OPENCODE$INSTALL_CODE_OPENCODE" == *1* ]] && HAS_OPENCODE=1
123[[ "$INSTALL_CODEX$INSTALL_CODE_CODEX" == *1* ]] && HAS_CODEX=1
124[[ "$INSTALL_VIBE$INSTALL_CODE_VIBE" == *1* ]] && HAS_VIBE=1
125
126# For this session too: installers (Claude Code, Vibe) warn when ~/.local/bin
127# is not on PATH, which ~/.zshenv only sets for the next ones.
128export PATH="$HOME/.local/bin:$PATH"
129
130# Behind a proxy: Lima copies the host's proxy settings into /etc/environment,
131# which ssh sessions (this script, `agent-vm shell`) load. sudo drops them
132# (env_reset), and Debian's sudo does not read that file, so every `sudo
133# apt-get` below went out without the proxy and failed (#25). Keeping them
134# through sudo covers this script and every VM cloned from this base. Checked
135# with visudo before it is installed: a broken sudoers file breaks sudo.
136printf 'Defaults env_keep += "http_proxy https_proxy ftp_proxy no_proxy HTTP_PROXY HTTPS_PROXY FTP_PROXY NO_PROXY"\n' \
137 > /tmp/agent-vm-proxy.sudoers
138sudo visudo -cqf /tmp/agent-vm-proxy.sudoers
139sudo install -m 0440 -o root -g root /tmp/agent-vm-proxy.sudoers /etc/sudoers.d/10-agent-vm-proxy
140rm -f /tmp/agent-vm-proxy.sudoers
141
142# Disable needrestart's interactive prompts
143sudo mkdir -p /etc/needrestart/conf.d
144echo '$nrconf{restart} = '"'"'a'"'"';' | sudo tee /etc/needrestart/conf.d/no-prompt.conf > /dev/null
145
146# Base packages always installed: core CLI tools plus the dev libraries needed
147# to compile Ruby/Python/Node versions via mise (kept here so that toggling a
148# language off doesn't strip the libs the user may still want to build with).
149# sshfs: the project VMs use Lima's reverse-sshfs when it can keep .git
150# read-only. Lima would install it on each clone's first boot otherwise.
151#
152# Every install passes --no-install-recommends. Recommends pulled in hundreds
153# of MB nobody uses here (Chromium alone brought printer config, Samba,
154# avahi-daemon, upower, Vulkan drivers), some of them running daemons. The
155# recommended packages that are used are listed by name instead.
156echo "Installing base packages..."
157if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then
158 # This runs in the guest, through its configured DNS and proxy-only route.
159 package_host=$(. /etc/os-release; if [ "$ID" = ubuntu ]; then printf '%s' archive.ubuntu.com; else printf '%s' deb.debian.org; fi)
160 echo "Checking guest DNS for system packages..."
161 if ! timeout 15 getent ahostsv4 mirrors.nju.edu.cn >/dev/null &&
162 ! timeout 15 getent ahostsv4 mirrors.ustc.edu.cn >/dev/null &&
163 ! timeout 15 getent ahostsv4 "$package_host" >/dev/null; then
164 echo 'Guest DNS could not resolve the system download sources. Check Cage Network & Proxy / DNS settings, apply and retry.' >&2
165 exit 1
166 fi
167fi
168apt_get update
169apt_get install -y --no-install-recommends \
170 git curl jq zsh \
171 wget build-essential pkgconf patch \
172 ripgrep fd-find htop \
173 unzip zip \
174 ca-certificates sshfs \
175 libssl-dev libreadline-dev zlib1g-dev libyaml-dev libffi-dev
176
177# Cage's download inactivity monitor needs Python even when an optional
178# language preinstall is disabled. Keep standalone agent-vm choices intact.
179if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then
180 apt_get install -y --no-install-recommends python3
181fi
182
183# sshfs 3.7.6 (and Debian's 3.7.3-1.2~deb13u1) refuses symlinks whose target
184# is absolute or contains "..", with EPERM: contain_symlinks, on by default
185# (CVE-2026-47187). That breaks every node_modules/.bin link in a share. It
186# protects a client from a rogue SFTP server; here the server is the user's
187# own host, and a link followed in the VM only reaches the VM's files. Lima
188# runs `sshfs` from PATH and takes no extra option, so the wrapper adds it.
189sudo tee /usr/local/bin/sshfs > /dev/null <<'EOF'
190#!/bin/sh
191# Installed by agent-vm: see agent-vm.setup.sh.
192if /usr/bin/sshfs -h 2>&1 | grep -q no_contain_symlinks; then
193 exec /usr/bin/sshfs "$@" -o no_contain_symlinks
194fi
195exec /usr/bin/sshfs "$@"
196EOF
197sudo chmod 755 /usr/local/bin/sshfs
198
199if [[ "$INSTALL_PYTHON" == "1" ]]; then
200 echo "Installing Python 3..."
201 # python3-dev: headers for pip builds of C extensions.
202 apt_get install -y --no-install-recommends python3 python3-pip python3-venv python3-dev
203fi
204
205if [[ "$INSTALL_RUBY" == "1" ]]; then
206 echo "Installing Ruby..."
207 apt_get install -y --no-install-recommends ruby-full
208fi
209
210if [[ "$INSTALL_GOLANG" == "1" ]]; then
211 echo "Installing Go..."
212 apt_get install -y --no-install-recommends golang-go
213fi
214
215if [[ "$INSTALL_RUST" == "1" ]]; then
216 # Rustup is the canonical Rust installer. --no-modify-path keeps it from
217 # editing ~/.profile/~/.bashrc: ~/.cargo/bin goes on zsh's PATH below.
218 echo "Installing Rust..."
219 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path --default-toolchain stable
220 echo 'export PATH=$HOME/.cargo/bin:$PATH' >> ~/.zshenv
221fi
222
223# Set zsh as default shell
224sudo chsh -s /usr/bin/zsh "$(whoami)"
225
226# Always set the VM prompt and put ~/.local/bin on PATH (mise installs there;
227# Vibe's installer puts `vibe`/`vibe-acp` there too).
228#
229# PATH additions go in ~/.zshenv only: every zsh reads it, and nothing in
230# Debian 13's /etc/zsh/{zprofile,zshrc} resets PATH afterwards.
231echo 'export PS1="vm:%1~%% "' >> ~/.zshrc
232
233# Shell history, kept across sessions and restarts: zsh saves none unless told
234# where (#20). It lives on the VM's disk, where the agent can read it, like
235# everything else there. A command started with a space is left out of it.
236cat >> ~/.zshrc <<'ZSHRC'
237HISTFILE=~/.zsh_history
238HISTSIZE=10000
239SAVEHIST=10000
240setopt INC_APPEND_HISTORY HIST_IGNORE_DUPS HIST_IGNORE_SPACE
241ZSHRC
242echo 'export PATH=$HOME/.local/bin:$PATH' >> ~/.zshenv
243
244# Auto-source ~/.agent-vm.env if present. The host pushes ~/.agent-vm/env into
245# this path on every `agent-vm` invocation (see _agent_vm_ensure_running), so
246# tokens/API keys defined there propagate to every shell in the VM. `set -a`
247# auto-exports each KEY=value line, so the file content stays a plain dotenv.
248echo '[ -f "$HOME/.agent-vm.env" ] && { set -a; . "$HOME/.agent-vm.env"; set +a; }' >> ~/.zshenv
249
250# Install mise (polyglot version manager for Ruby, Python, Node, etc.).
251# Always installed so users can `mise install ruby@latest`, etc., even when
252# they've opted out of preinstalled Node.
253echo "Installing mise..."
254if [[ "${CLAUDE_CAGE:-}" == "1" ]]; then
255 cage_install_tool mise
256else
257 curl -fsSL https://mise.run | sh
258fi
259echo 'eval "$(~/.local/bin/mise activate zsh)"' >> ~/.zshenv
260
261if [[ "$INSTALL_DOCKER" == "1" ]]; then
262 # Install Docker from official repo (includes docker compose)
263 echo "Installing Docker..."
264 sudo install -m 0755 -d /etc/apt/keyrings
265 docker_distribution=$(. /etc/os-release && printf '%s' "$ID")
266 case "$docker_distribution" in debian|ubuntu) ;; *) echo "Unsupported Docker distribution: $docker_distribution" >&2; exit 1;; esac
267 install_repository_key "https://download.docker.com/linux/$docker_distribution/gpg" /etc/apt/keyrings/docker.asc
268 sudo chmod a+r /etc/apt/keyrings/docker.asc
269 echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$docker_distribution $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
270 apt_get update
271 # buildx and pigz are Recommends: `docker build` needs buildx, pigz speeds
272 # up layer decompression. docker-ce-rootless-extras is left out: the user is
273 # in the docker group of the rootful daemon.
274 apt_get install -y --no-install-recommends docker-ce docker-ce-cli containerd.io \
275 docker-compose-plugin docker-buildx-plugin pigz
276 sudo usermod -aG docker "$(whoami)"
277fi
278
279if [[ "$INSTALL_NODE" == "1" ]]; then
280 # Install Node.js 24 LTS (needed for MCP servers and Codex CLI)
281 # The NodeSource repo is set up by hand, as their setup_24.x script does,
282 # rather than piping that script to a root shell: it also installs gnupg
283 # just to dearmor the key, while apt reads an armored .asc key as is. The pin
284 # keeps apt on NodeSource's nodejs over Debian's older one.
285 echo "Installing Node.js 24..."
286 sudo install -m 0755 -d /etc/apt/keyrings
287 install_repository_key https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key /etc/apt/keyrings/nodesource.asc
288 sudo chmod a+r /etc/apt/keyrings/nodesource.asc
289 echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.com/node_24.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list > /dev/null
290 printf 'Package: nodejs\nPin: origin deb.nodesource.com\nPin-Priority: 600\n' | sudo tee /etc/apt/preferences.d/nodejs > /dev/null
291 apt_get update
292 apt_get install -y --no-install-recommends nodejs
293fi
294
295if [[ "$INSTALL_CHROMIUM" == "1" ]]; then
296 # Install Chromium and dependencies for headless browsing
297 echo "Installing Chromium..."
298 # xauth: xvfb-run needs it, and it is only a Recommends of xvfb.
299 # fonts-dejavu-core: with Liberation alone, fontconfig resolves the generic
300 # sans-serif and serif to Liberation Mono.
301 # Disposable browser contexts use the application locale's language defaults.
302 # Debian ships the non-English locale resources in this separate package.
303 if [[ "${CLAUDE_CAGE:-}" == 1 ]] && cage_is_ubuntu; then
304 cage_install_chromium
305 else
306 chromium_packages=(chromium chromium-l10n fonts-liberation fonts-dejavu-core xvfb xauth)
307 if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then
308 cage_cache_chromium --no-install-recommends "${chromium_packages[@]}"
309 fi
310 apt_get install -y --no-install-recommends "${chromium_packages[@]}"
311 fi
312 sudo ln -sf /usr/bin/chromium /usr/bin/google-chrome
313 sudo ln -sf /usr/bin/chromium /usr/bin/google-chrome-stable
314 sudo mkdir -p /opt/google/chrome
315 sudo ln -sf /usr/bin/chromium /opt/google/chrome/chrome
316fi
317
318if [[ "$INSTALL_GH" == "1" ]]; then
319 # Install GitHub CLI from official repo
320 echo "Installing GitHub CLI..."
321 sudo mkdir -p -m 755 /etc/apt/keyrings
322 install_repository_key https://cli.github.com/packages/githubcli-archive-keyring.gpg /etc/apt/keyrings/githubcli-archive-keyring.gpg
323 sudo chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg
324 echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
325 apt_get update
326 apt_get install -y --no-install-recommends gh
327fi
328
329if [[ "$INSTALL_CLAUDE" == "1" ]]; then
330 echo "Installing Claude Code..."
331 if [[ "${CLAUDE_CAGE:-}" == "1" ]]; then
332 # Official npm distribution; lock the first cage release to a known version.
333 # npm retries interrupted package transfers and verifies registry integrity.
334 cage_install_tool claude
335 else
336 curl -fsSL https://claude.ai/install.sh | bash
337 fi
338 echo 'export PATH=$HOME/.claude/local/bin:$PATH' >> ~/.zshenv
339fi
340
341if [[ "$HAS_CLAUDE" == "1" ]]; then
342 # Enforce full autonomy via *managed* settings (highest precedence), not the
343 # user's ~/.claude/. A user can bind-mount or overwrite their own ~/.claude/
344 # dir freely; this system-level policy is untouched and always wins.
345 #
346 # Why not just rely on the `claude --dangerously-skip-permissions` launch flag:
347 # Claude Code relaunches itself in-process on self-update and on the first-run
348 # fullscreen-TUI opt-in, and the relaunched process drops the CLI flag (see
349 # https://github.com/anthropics/claude-code/issues/72479), reverting to the
350 # "ask" permission mode. Settings are re-read on every (re)launch, so encoding
351 # the policy here makes it survive those relaunches. `tui: fullscreen` also
352 # pins fullscreen from the first launch, so the opt-in relaunch never fires.
353 # The extension's own copy of Claude Code reads it too.
354 echo "Configuring Claude managed settings (bypass permissions + fullscreen)..."
355 sudo mkdir -p /etc/claude-code
356 cat << 'JSON' | sudo tee /etc/claude-code/managed-settings.json > /dev/null
357{
358 "permissions": { "defaultMode": "bypassPermissions" },
359 "tui": "fullscreen",
360 "channelsEnabled": true
361}
362JSON
363fi
364
365if [[ "$INSTALL_OPENCODE" == "1" || "$INSTALL_CODE_OPENCODE" == "1" ]]; then
366 echo "Installing OpenCode..."
367 curl -fsSL https://opencode.ai/install | bash
368 echo 'export PATH=$HOME/.opencode/bin:$PATH' >> ~/.zshenv
369fi
370
371if [[ "$INSTALL_CODEX" == "1" ]]; then
372 if [[ "$INSTALL_NODE" != "1" ]]; then
373 echo "Skipping Codex CLI: requires Node.js (re-run setup with Node.js enabled)." >&2
374 else
375 echo "Installing Codex CLI..."
376 sudo npm i -g @openai/codex </dev/null
377 fi
378fi
379
380if [[ "$INSTALL_VIBE" == "1" ]]; then
381 # Vibe installs `uv` and the `vibe`/`vibe-acp` commands into ~/.local/bin.
382 # PATH was already exported at the top of this script so the installer
383 # doesn't abort on its own PATH check.
384 echo "Installing Mistral Vibe..."
385 curl -LsSf https://mistral.ai/vibe/install.sh | bash
386fi
387
388if [[ "$INSTALL_PI" == "1" ]]; then
389 if [[ "$INSTALL_NODE" != "1" ]]; then
390 echo "Skipping Pi: requires Node.js (re-run setup with Node.js enabled)." >&2
391 else
392 # @earendil-works is the maintained scope; @mariozechner/pi-coding-agent is
393 # deprecated and misses security fixes. --ignore-scripts as Pi's docs say.
394 echo "Installing Pi..."
395 sudo npm i -g --ignore-scripts @earendil-works/pi-coding-agent </dev/null
396 # Pi never asks before running tools. Its one gate is trust for a project's
397 # .pi/ extensions and skills, which the VM makes moot and which `pi -p`
398 # silently skips. Telemetry covers the install ping and the attribution
399 # headers Pi adds to some providers' requests.
400 mkdir -p "$HOME/.pi/agent"
401 cat > "$HOME/.pi/agent/settings.json" << 'JSON'
402{
403 "defaultProjectTrust": "always",
404 "enableInstallTelemetry": false
405}
406JSON
407 fi
408fi
409
410# A top-level TOML key as the first line of <file>, where the tables the MCP
411# config appends later cannot capture it. Skipped when the key is there.
412toml_prepend() {
413 local file="$1" key="$2" value="$3"
414 mkdir -p "$(dirname "$file")"
415 if [[ -f "$file" ]] && grep -q "^$key *=" "$file"; then
416 return 0
417 fi
418 { printf '%s = %s\n' "$key" "$value"; [[ ! -f "$file" ]] || cat "$file"; } > "$file.tmp"
419 mv "$file.tmp" "$file"
420}
421
422# The URL <ref> points to from the http(s) URL <base>, fragments dropped:
423# absolute, scheme-relative, absolute-path or relative, its . and ..
424# segments resolved (RFC 3986). Fails for another scheme (vscode://..., the
425# editor's own schemas).
426schema_url_resolve() {
427 local base="${1%%#*}" ref="${2%%#*}" scheme rest host path seg
428 local -a segs=() kept=()
429 case "$ref" in
430 http://*|https://*) base="$ref" ref="" ;;
431 *://*) return 1 ;;
432 esac
433 scheme="${base%%://*}"
434 rest="${base#*://}"
435 host="${rest%%/*}"
436 path=/
437 [[ "$rest" != */* ]] || path="/${rest#*/}"
438 case "$ref" in
439 "") ;;
440 //*)
441 host="${ref#//}"
442 path=/
443 if [[ "$host" == */* ]]; then path="/${host#*/}"; host="${host%%/*}"; fi ;;
444 /*) path="$ref" ;;
445 *) path="${path%/*}/$ref" ;;
446 esac
447 IFS=/ read -ra segs <<< "$path"
448 for seg in ${segs[@]+"${segs[@]}"}; do
449 case "$seg" in
450 ""|.) ;;
451 ..) [[ ${#kept[@]} -eq 0 ]] || unset 'kept[-1]' ;;
452 *) kept+=("$seg") ;;
453 esac
454 done
455 local IFS=/
456 printf '%s://%s/%s\n' "$scheme" "$host" "${kept[*]}"
457}
458
459# Write to <out> code-server's machine settings with every JSON schema its
460# built-in extensions (in <ext-dir>) name by URL, and every schema those refer
461# to, downloaded now, a level of references at a time, in parallel. A
462# json.schemas entry with a URL and its content makes the editor use the
463# content instead of fetching the URL, so with downloads off (the user
464# settings) opening a file sends no request. A failed download only leaves
465# its files unvalidated.
466# The editor resolves a schema's relative references against its $id when it
467# has one (www.schemastore.org/package says json.schemastore.org/package.json),
468# else against the URL it loaded it from: so are they here, for each to be
469# stored under the URL the editor asks for.
470# These are the machine settings: a json.schemas of the user settings would
471# be replaced by this one, not added to (VS Code merges objects across
472# settings, not arrays). A schema of your own goes in a workspace's settings.
473code_server_schemas() {
474 local ext_dir="$1" out="$2" dir u f r base i n=0
475 local -a level next fetch
476 local -A seen urls
477 dir="$(mktemp -d)"
478 : > "$dir/entries"
479 mapfile -t level < <(jq -r '.contributes.jsonValidation[]?.url | select(test("^https?://"))' \
480 "$ext_dir"/*/package.json | sort -u)
481 while [[ ${#level[@]} -gt 0 ]]; do
482 fetch=() urls=() next=()
483 for u in "${level[@]}"; do
484 u="${u%%#*}"
485 [[ -z "${seen[$u]:-}" ]] || continue
486 seen[$u]=1
487 n=$((n + 1))
488 urls[$n]="$u"
489 # Fetched where json.schemastore.org redirects to, stored under the URL
490 # the editor asks for.
491 fetch+=(-o "$dir/$n.json" "${u/#https:\/\/json.schemastore.org\//https://www.schemastore.org/}")
492 done
493 # Each file checked below: one failed download fails curl as a whole.
494 [[ ${#fetch[@]} -eq 0 ]] || curl -fsSL --max-time 30 --parallel --parallel-max 8 "${fetch[@]}" </dev/null || true
495 for i in "${!urls[@]}"; do
496 u="${urls[$i]}"
497 f="$dir/$i.json"
498 if ! jq -c --arg u "$u" '{url: $u, schema: .}' "$f" > "$f.entry" 2>/dev/null; then
499 echo "Warning: could not download the JSON schema $u: files using it are not validated." >&2
500 continue
501 fi
502 cat "$f.entry" >> "$dir/entries"
503 # A schema may be true or false, which has no $id to read.
504 base="$(jq -r 'objects | (."$id" // .id // empty) | strings | select(test("^https?://"))' "$f")"
505 [[ -n "$base" ]] || base="$u"
506 while IFS= read -r r; do
507 r="$(schema_url_resolve "$base" "$r")" && next+=("$r")
508 done < <(jq -r '[.. | objects | ."$ref"? | strings | select(startswith("#") | not)] | unique[]' "$f")
509 done
510 level=(${next[@]+"${next[@]}"})
511 done
512 mkdir -p "$(dirname "$out")"
513 jq -sc '{"json.schemas": .}' "$dir/entries" > "$out"
514 rm -rf "$dir"
515}
516
517if [[ "$INSTALL_CODE_SERVER" == "1" ]]; then
518 # The editor of `agent-vm code` (internal/cli/code.go). No password here: every VM
519 # is a copy of this disk, so each one makes its own on first use.
520 echo "Installing code-server..."
521 if [[ "${CLAUDE_CAGE:-}" == "1" ]]; then
522 cage_install_tool code-server
523 else
524 curl -fsSL https://code-server.dev/install.sh | sh
525 fi
526 extensions=()
527 [[ "$INSTALL_CODE_CLAUDE" == "1" ]] && extensions+=(--install-extension anthropic.claude-code)
528 [[ "$INSTALL_CODE_OPENCODE" == "1" ]] && extensions+=(--install-extension sst-dev.opencode)
529 [[ "$INSTALL_CODE_CODEX" == "1" ]] && extensions+=(--install-extension openai.chatgpt)
530 [[ "$INSTALL_CODE_VIBE" == "1" ]] && extensions+=(--install-extension mistralai.mistral-vibe-code)
531 if [[ ${#extensions[@]} -gt 0 ]]; then
532 echo "Installing the agents' extensions..."
533 code-server "${extensions[@]}" </dev/null
534 fi
535 # chat.disableAIFeatures turns off the GitHub Copilot chat and completions
536 # that code-server ships (code.go also disables the extension), and
537 # chat.mcp.gallery.enabled its MCP gallery. telemetry.*: code-server's
538 # --disable-telemetry leaves the built-in extensions sending telemetry. The
539 # editor downloads no JSON schema: setup does, once, into the machine
540 # settings (code_server_schemas). remote.autoForwardPorts: Lima forwards
541 # the VM's ports already. update.*: setup installs code-server, the editor
542 # does not update itself. The rest is the look (dark theme, no secondary
543 # side bar), the welcome page, tips, recommendations, experiments, online
544 # settings search, and Claude's onboarding checklist.
545 mkdir -p "$HOME/.local/share/code-server/User"
546 jq -n --arg claude "$INSTALL_CODE_CLAUDE" '
547 {
548 "workbench.colorTheme": "Dark 2026",
549 "chat.disableAIFeatures": true,
550 "chat.mcp.gallery.enabled": false,
551 "telemetry.telemetryLevel": "off",
552 "telemetry.feedback.enabled": false,
553 "json.schemaDownload.enable": false,
554 "workbench.enableExperiments": false,
555 "workbench.settings.enableNaturalLanguageSearch": false,
556 "workbench.settings.showAISearchToggle": false,
557 "extensions.ignoreRecommendations": true,
558 "workbench.startupEditor": "none",
559 "workbench.tips.enabled": false,
560 "workbench.welcomePage.walkthroughs.openOnInstall": false,
561 "workbench.secondarySideBar.defaultVisibility": "hidden",
562 "remote.autoForwardPorts": false,
563 "update.mode": "none",
564 "update.showReleaseNotes": false
565 } + if $claude == "1" then {
566 "claudeCode.hideOnboarding": true
567 } else {} end' > "$HOME/.local/share/code-server/User/settings.json"
568 # The .deb's /usr/bin/code-server is a script running /usr/lib/code-server;
569 # a standalone install is a link into its own directory.
570 cs_root=/usr/lib/code-server
571 if [[ ! -d "$cs_root/lib/vscode/extensions" ]]; then
572 cs_root="$(dirname "$(dirname "$(readlink -f "$(command -v code-server)")")")"
573 fi
574 echo "Downloading the JSON schemas the editor uses..."
575 cs_machine="$HOME/.local/share/code-server/Machine/settings.json"
576 code_server_schemas "$cs_root/lib/vscode/extensions" "$cs_machine"
577 # Claude's conversations start in bypass mode, as the managed settings above
578 # do for the CLI. These keys are machine-scoped: code-server ignores them in
579 # the user settings.
580 if [[ "$INSTALL_CODE_CLAUDE" == "1" ]]; then
581 jq -c '. + {
582 "claudeCode.allowDangerouslySkipPermissions": true,
583 "claudeCode.initialPermissionMode": "bypassPermissions"
584 }' "$cs_machine" > "$cs_machine.tmp"
585 mv "$cs_machine.tmp" "$cs_machine"
586 fi
587 # Codex and Vibe have no setting for it: their extensions start in the mode
588 # the agent's own config names. These match the flags the command line gets
589 # (agents in internal/cli/commands.go).
590 if [[ "$INSTALL_CODE_CODEX" == "1" ]]; then
591 toml_prepend "$HOME/.codex/config.toml" sandbox_mode '"danger-full-access"'
592 toml_prepend "$HOME/.codex/config.toml" approval_policy '"never"'
593 fi
594 if [[ "$INSTALL_CODE_VIBE" == "1" ]]; then
595 toml_prepend "$HOME/.vibe/config.toml" default_agent '"auto-approve"'
596 fi
597 # OpenCode's extension runs `opencode` in a terminal, without the --auto of
598 # `agent-vm opencode`: its config allows everything instead.
599 if [[ "$INSTALL_CODE_OPENCODE" == "1" ]]; then
600 mkdir -p "$HOME/.config/opencode"
601 oc_config="$HOME/.config/opencode/opencode.json"
602 [ -f "$oc_config" ] || echo '{"$schema": "https://opencode.ai/config.json"}' > "$oc_config"
603 jq '.permission = "allow"' "$oc_config" > "$oc_config.tmp" && mv "$oc_config.tmp" "$oc_config"
604 fi
605 # Written by code-server on its first run, with a password of its own.
606 rm -rf "$HOME/.config/code-server"
607fi
608
609# Wire one stdio MCP server into every installed agent's config. Each agent
610# stores MCP servers in its own format, so that mapping is written once here
611# instead of being copy-pasted per server.
612#
613# Usage: configure_mcp <server-name> <command> [arg...]
614# configure_mcp chrome-devtools npx -y chrome-devtools-mcp@latest --headless=true
615#
616# Passing a command (rather than assuming npx) is what lets a server be
617# launched through `env VAR=value npx ...`: every one of the four formats below
618# runs a command with arguments, but only some support a separate env block.
619#
620# The args are rendered once as a JSON array; a JSON array of strings is also a
621# valid TOML array, so the same value serves all four formats.
622configure_mcp() {
623 # Not named `command`: that is a shell builtin, and shadowing its name in a
624 # file that uses `command -v` elsewhere invites a double-take.
625 local name="$1" cmd="$2"
626 shift 2
627 # One arg per line into jq -R, so an argument containing a newline would be
628 # split. None of the callers pass one.
629 local args_json
630 args_json="$(printf '%s\n' "$@" | jq -R . | jq -sc .)"
631
632 if [[ "$HAS_CLAUDE" == "1" ]]; then
633 echo "Configuring $name MCP server for Claude..."
634 local config="$HOME/.claude.json"
635 [ -f "$config" ] || echo '{}' > "$config"
636 # Guarded: `a && b` is exempt from `set -e`, and this is not the last
637 # statement of the function, so a jq failure (invalid JSON in an existing
638 # config, full disk) would otherwise leave a stray .tmp behind and let setup
639 # finish "successfully" without the MCP server.
640 if ! { jq --arg n "$name" --arg c "$cmd" --argjson a "$args_json" \
641 '.mcpServers[$n] = {"command": $c, "args": $a}' \
642 "$config" > "$config.tmp" && mv "$config.tmp" "$config"; }; then
643 rm -f "$config.tmp"
644 echo "Error: failed to write '$name' into $config" >&2
645 return 1
646 fi
647 fi
648
649 if [[ "$HAS_OPENCODE" == "1" ]]; then
650 echo "Configuring $name MCP server for OpenCode..."
651 mkdir -p "$HOME/.config/opencode"
652 local config="$HOME/.config/opencode/opencode.json"
653 [ -f "$config" ] || echo '{"$schema": "https://opencode.ai/config.json"}' > "$config"
654 if ! { jq --arg n "$name" --arg c "$cmd" --argjson a "$args_json" \
655 '.mcp[$n] = {"type": "local", "command": ([$c] + $a), "enabled": true}' \
656 "$config" > "$config.tmp" && mv "$config.tmp" "$config"; }; then
657 rm -f "$config.tmp"
658 echo "Error: failed to write '$name' into $config" >&2
659 return 1
660 fi
661 fi
662
663 if [[ "$HAS_VIBE" == "1" ]]; then
664 # Vibe uses TOML; append an array-of-tables entry (valid even if the wizard
665 # later writes to the same file). Guard against duplicates on repeated runs.
666 echo "Configuring $name MCP server for Vibe..."
667 mkdir -p "$HOME/.vibe"
668 local config="$HOME/.vibe/config.toml"
669 if ! grep -qF "name = \"$name\"" "$config" 2>/dev/null; then
670 {
671 printf '\n[[mcp_servers]]\n'
672 printf 'name = "%s"\n' "$name"
673 printf 'transport = "stdio"\n'
674 printf 'command = "%s"\n' "$cmd"
675 printf 'args = %s\n' "$args_json"
676 } >> "$config"
677 fi
678 fi
679
680 if [[ "$HAS_CODEX" == "1" ]]; then
681 # Codex CLI uses TOML at ~/.codex/config.toml with [mcp_servers.NAME]
682 # tables. Guard against duplicates on repeated setup runs.
683 echo "Configuring $name MCP server for Codex..."
684 mkdir -p "$HOME/.codex"
685 local config="$HOME/.codex/config.toml"
686 if ! grep -qF "[mcp_servers.$name]" "$config" 2>/dev/null; then
687 {
688 printf '\n[mcp_servers.%s]\n' "$name"
689 printf 'command = "%s"\n' "$cmd"
690 printf 'args = %s\n' "$args_json"
691 } >> "$config"
692 fi
693 fi
694}
695
696# True when at least one agent is installed: nothing to configure otherwise,
697# and no reason to print a "skipping" notice either.
698any_agent_installed() {
699 [[ "$HAS_CLAUDE" == "1" || "$HAS_OPENCODE" == "1" \
700 || "$HAS_CODEX" == "1" || "$HAS_VIBE" == "1" ]]
701}
702
703# Chrome DevTools MCP runs via `npx` and drives the Chromium installed above,
704# so it needs both dependencies plus at least one target agent.
705if [[ "$INSTALL_MCP_CHROME" == "1" ]] && any_agent_installed; then
706 if [[ "$INSTALL_NODE" == "1" && "$INSTALL_CHROMIUM" == "1" ]]; then
707 configure_mcp chrome-devtools npx -y chrome-devtools-mcp@latest --headless=true --isolated=true
708 else
709 echo "Skipping Chrome MCP config: requires Node.js and Chromium." >&2
710 fi
711fi
712
713# Playwright MCP drives the Chromium installed above (--executable-path), not
714# a browser of its own: PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD, on this command only,
715# skips the several hundred MB of browsers the `playwright` package downloads
716# on install, while a project's own `npx playwright test` still gets them. A
717# distro Chromium can drift from what playwright-core expects:
718# `npx playwright install chromium` here if that ever bites.
719if [[ "$INSTALL_MCP_PLAYWRIGHT" == "1" ]] && any_agent_installed; then
720 if [[ "$INSTALL_NODE" == "1" && "$INSTALL_CHROMIUM" == "1" ]]; then
721 configure_mcp playwright env PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \
722 npx -y @playwright/mcp@latest --headless --isolated \
723 --executable-path /usr/bin/chromium
724 else
725 echo "Skipping Playwright MCP config: requires Node.js and Chromium." >&2
726 fi
727fi
728
729echo "VM setup complete."