跳到主要内容

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

提交记录

use feedbacks from albert-code to facilitate integrations (#24)

A shell function isn't inherited by child processes, so agent-vm couldn't be driven from another tool. install.sh now puts it on PATH as a symlink. Sourcing still works as before — existing installs need nothing. New commands: version, name, info (key=value state), env (set/get/has/unset/ list), and mcp-chrome / mcp-playwright in --preinstall. Fixed: no "Stop the VM?" prompt when resources haven't changed; --disk alone no longer hangs in $EDITOR; safe to source under set -u and pipefail; CDPATH no longer redirects path resolution; a jq failure writing an MCP config is no longer silent. Heads-up: an explicit --preinstall list no longer wires the Chrome MCP unless mcp-chrome is named. default, all and the wizard are unaffected.

作者
Sylvain Zimmer
时间
2026/09/15 20:01
提交
3c4a4a2
上一个
b4c5d97
这个版本的全部文件
新增.github/workflows/test.yml+36 −0看文件
@@ -0,0 +1,36 @@
1新增:name: test
2新增:
3新增:on:
4新增: push:
5新增: pull_request:
6新增:
7新增:jobs:
8新增: test:
9新增: runs-on: ubuntu-latest
10新增: steps:
11新增: - uses: actions/checkout@v4
12新增: with:
13新增: # The steps below run test.sh from the PR branch. Leaving the checkout
14新增: # token in .git/config would put it within reach of that code.
15新增: persist-credentials: false
16新增:
17新增: - name: Syntax check
18新增: run: |
19新增: for f in agent-vm.sh agent-vm.setup.sh runtime.example.sh test.sh; do
20新增: echo "bash -n $f"
21新增: bash -n "$f"
22新增: done
23新增:
24新增: - name: Test suite
25新增: run: ./test.sh
26新增:
27新增: # agent-vm is sourced into whatever shell the user runs, and macOS still
28新增: # ships bash 3.2 — which errors on empty array expansion under `set -u`.
29新增: # Modern bash does not, so a 3.2 run is the only way to catch it in CI.
30新增: - name: Test suite on bash 3.2 (what macOS ships)
31新增: run: docker run --rm -v "$PWD:/w" -w /w bash:3.2 ./test.sh
32新增:
33新增: - name: Test suite under zsh (the usual way it is sourced)
34新增: run: |
35新增: sudo apt-get update && sudo apt-get install -y zsh
36新增: zsh ./test.sh
修改README.md+102 −5看文件
@@ -21,8 +21,22 @@ Feedback welcome!
2121```bash
2222git clone https://github.com/sylvinus/agent-vm.git
2323cd agent-vm
24新增:./install.sh
25新增:```
26新增:
27新增:`install.sh` puts `agent-vm` on your `PATH` as a symlink to `agent-vm.sh` in the
28新增:clone, then offers to also define it as a shell function. Being a symlink, a
29新增:`git pull` updates the command — there is nothing to reinstall.
30新增:
31新增:**Already installed by sourcing?** Nothing breaks: sourcing is still fully
32新增:supported and is what defines the shell function. Run `./install.sh` once if you
33新增:want the command on your `PATH` too — other tools need that, because a shell
34新增:function is not inherited by child processes. `./install.sh --uninstall` removes
35新增:the link.
36新增:
37新增:Sourcing by hand still works if you prefer it:
2438
25删除:# Add to your shell config
39新增:```bash
2640echo "source $(pwd)/agent-vm.sh" >> ~/.zshrc # zsh
2741echo "source $(pwd)/agent-vm.sh" >> ~/.bashrc # or bash
2842```
@@ -48,13 +62,17 @@ Options:
4862| `--cpus N` | Number of CPUs | 1 |
4963| `--preinstall=LIST` | Preinstall only this comma-separated subset in the base image (skips the wizard) | — |
5064
51删除:Names are lowercase: `python`, `node`, `ruby`, `rust`, `golang`, `docker`, `chromium`, `gh`, `claude`, `opencode`, `codex`, `vibe`. Use `default` for the default set (everything except Ruby/Rust/Go), `all` for everything, or `none` for nothing. Selecting `codex`, or `chromium` with any AI agent, also installs `node` because those paths require `npm`/`npx`.
65新增:Names are lowercase: `python`, `node`, `ruby`, `rust`, `golang`, `docker`, `chromium`, `gh`, `claude`, `opencode`, `codex`, `vibe`, `mcp-chrome`, `mcp-playwright`. Use `default` for the default set (everything except Ruby/Rust/Go and `mcp-playwright`), `all` for everything, or `none` for nothing. Selecting `codex`, or `chromium` with any AI agent, also installs `node` because those paths require `npm`/`npx`.
66新增:
67新增:The `mcp-*` names wire an MCP server into every installed agent's config. Both current ones drive the preinstalled Chromium, so both need `node` and `chromium` and are skipped with a notice without them. Omit them to leave the agents' MCP config untouched — useful when MCP servers are managed per project rather than baked into the base image.
5268
5369```bash
5470agent-vm setup # Interactive wizard
5571agent-vm setup --preinstall=default # Default set, no prompts
5672agent-vm setup --preinstall=default,rust # Default set plus Rust
73新增:agent-vm setup --preinstall=default,mcp-playwright # Default set plus Playwright MCP
5774agent-vm setup --preinstall=python,docker,claude # Minimal Claude-only setup
75新增:agent-vm setup --preinstall=node,chromium,opencode # OpenCode, no MCP wired in
5876agent-vm setup --disk 50 --memory 16 --cpus 8 # Larger VM for heavy workloads
5977```
6078
@@ -105,6 +123,42 @@ agent-vm rm # Stop and permanently delete the VM
105123agent-vm destroy-all # Stop and delete all agent-vm VMs
106124```
107125
126新增:### Scripting against agent-vm
127新增:
128新增:Wrapping agent-vm from another tool? Use these instead of parsing human-facing
129新增:output or reading `~/.agent-vm` internals — VM naming, the template name and the
130新增:state files are implementation details.
131新增:
132新增:```bash
133新增:agent-vm version # 0.1.0 — gate on this; a build without it predates the command
134新增:agent-vm name [dir] # VM name for a directory (default: cwd)
135新增:agent-vm info [dir] # machine-readable state, one key=value per line
136新增:agent-vm env set K V # store a secret for every VM (see below)
137新增:agent-vm env get K # read it back
138新增:agent-vm env has K # exit 0 if stored, 1 otherwise, no output
139新增:agent-vm env unset K
140新增:agent-vm env list # key NAMES only, never values
141新增:```
142新增:
143新增:Use `agent-vm env` rather than writing `~/.agent-vm/env` yourself: that file is
144新增:*sourced* by a shell, so a single mis-escaped quote costs every secret in it, not
145新增:just the mis-quoted one. `get`/`has` answer about the file, never about the
146新增:ambient environment — which matters because callers often run inside a VM that
147新增:already exports those very variables.
148新增:
149新增:`info` prints `version`, `template`, `state_dir`, `dir`, `vm_name`,
150新增:`base_exists`, `vm_exists`, `vm_running` and `vm_stale`. Booleans are `1`/`0`;
151新增:anything that cannot be determined is `unknown` rather than a guess — including
152新增:`vm_stale` when no base version has been recorded to compare against.
153新增:`version`, `name`, `info` and `env` all work without Lima installed (the
154新增:Lima-dependent keys of `info` read `unknown`).
155新增:
156新增:Call the command rather than sourcing the file: a shell function is not
157新增:inherited by child processes, so a tool that spawns a shell cannot see one.
158新增:`agent-vm.sh` does remain safe to `source` from a script running under `set -u`
159新增:and `set -o pipefail`; it is *not* written for the caller's `set -e`, since like
160新增:most shell libraries it uses `test && action` internally.
161新增:
108162To automatically destroy a VM after the agent exits (like `docker run --rm`):
109163
110164```bash
@@ -143,7 +197,16 @@ agent-vm --offline --readonly claude # Both
143197
144198### Sharing tokens across VMs: `~/.agent-vm/env`
145199
146删除:Put environment variables (API tokens, secrets, etc.) in this file as plain `KEY=value` lines — no `export` prefix, `#` for comments. They're auto-loaded into every shell in every VM:
200新增:Put environment variables (API tokens, secrets, etc.) in this file as plain `KEY=value` lines — no `export` prefix, `#` for comments. They're auto-loaded into every shell in every VM.
201新增:
202新增:Edit it by hand, or let agent-vm handle the quoting for you:
203新增:
204新增:```bash
205新增:agent-vm env set GH_TOKEN github_pat_xxxx
206新增:agent-vm env list # names only, never values
207新增:```
208新增:
209新增:Scripts should always use `agent-vm env` — the file is *sourced* by a shell, so one mis-escaped quote breaks every secret in it, not just that one.
147210
148211```bash
149212# ~/.agent-vm/env
@@ -157,6 +220,16 @@ These are picked up automatically by the tools that look for them: `gh` reads `G
157220
158221For subscription-based auth (where you've already run `claude login` / `gh auth login` on the host), share the host's credentials directory via [`~/.agent-vm/volumes`](#extra-host-mounts-agent-vmvolumes) instead.
159222
223新增:**What the sandbox does and does not protect here.** Anything in this file is
224新增:readable by *everything* running in the VM — the agent, its dependencies, any
225新增:code it fetches. The VM keeps those secrets away from your host, but it does not
226新增:keep them from the agent, and an agent that has been prompt-injected or a
227新增:dependency that has been tampered with can send them out over the network. So:
228新增:put a **dedicated, revocable, narrowly-scoped** token here rather than your main
229新增:one, and reach for `--offline` on sessions that don't need outbound internet.
230新增:`--offline` limits where a secret can go; it does not stop code in the VM from
231新增:reading it.
232新增:
160233### Extra host mounts: `~/.agent-vm/volumes`
161234
162235List host files or directories to mount inside every VM. One path per line, `~` is expanded, `#` starts a comment. Uses Docker Compose-style `source[:destination][:mode]` syntax, where `mode` is `ro` (default) or `rw`:
@@ -258,7 +331,9 @@ bundle install
258331
259332### MCP servers
260333
261删除:The base VM comes with [Chrome DevTools MCP](https://github.com/ChromeDevTools/chrome-devtools-mcp) pre-configured for Claude, giving the agent headless browser access.
334新增:The base VM comes with [Chrome DevTools MCP](https://github.com/ChromeDevTools/chrome-devtools-mcp) pre-configured for every installed agent, giving it headless browser access. [Playwright MCP](https://github.com/microsoft/playwright-mcp) is available too via `--preinstall=...,mcp-playwright`; it is pointed at the same Chromium with `--executable-path` and launched through `env PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1` so it does not pull its own copies of Chromium, Firefox and WebKit into every VM. To drive another engine, edit its entry (drop `--executable-path`, add e.g. `--browser firefox`) and run `npx playwright install firefox` inside the VM.
335新增:
336新增:Drop either one with `--preinstall`: the names are opt-in like any other component, so `--preinstall=node,chromium,opencode` installs OpenCode with no MCP server wired in. That is the switch to use when MCP servers are managed per project instead.
262337
263338To add more MCP servers, add them to `~/.claude.json` in your `~/.agent-vm/setup.sh`, or edit the file directly inside a VM via `agent-vm shell`. Add entries to the `mcpServers` object:
264339
@@ -286,12 +361,33 @@ To add more MCP servers, add them to `~/.claude.json` in your `~/.agent-vm/setup
286361
287362Each VM is fully isolated — agents must authenticate independently inside their VM (e.g. `claude login`). Credentials persist within the VM across restarts but are not shared between VMs or with the host.
288363
364新增:## Tests
365新增:
366新增:```bash
367新增:./test.sh
368新增:```
369新增:
370新增:Runs against a stub `limactl` in a throwaway `HOME`: no VM is created, started or
371新增:deleted, your real `~/.agent-vm` is untouched, and no network is needed. It covers
372新增:VM naming, resource comparison, staleness, the `info`/`version`/`name` surface,
373新增:the `--preinstall` parser and the MCP config writer.
374新增:
375新增:Worth running under bash 3.2 as well — it is what macOS ships, and it is stricter
376新增:about empty array expansion under `set -u`, which modern bash forgives:
377新增:
378新增:```bash
379新增:docker run --rm -v "$PWD:/w" -w /w bash:3.2 ./test.sh
380新增:zsh ./test.sh
381新增:```
382新增:
289383## Project structure
290384
291385| File | Description |
292386|------|-------------|
293387| `agent-vm.sh` | Main script — source this in your shell config |
294388| `agent-vm.setup.sh` | Package installation script that runs inside the base VM during setup |
389新增:| `install.sh` | Installer — puts `agent-vm` on your PATH, `--uninstall` removes it |
390新增:| `test.sh` | Test suite — runs against a stub `limactl`, creates no VMs |
295391
296392## What's in the VM
297393
@@ -311,7 +407,8 @@ The wizard's "default install" and `--preinstall=default` produce the same set:
311407| Browser | Chromium (headless), xvfb | `chromium` | yes |
312408| Containers | Docker Engine, Docker Compose | `docker` | yes |
313409| AI agents | Claude Code, OpenCode, Codex CLI, Mistral Vibe | `claude`, `opencode`, `codex`, `vibe` | yes |
314删除:| MCP | Chrome DevTools MCP (Claude/OpenCode/Codex/Vibe) | — | auto, when Node.js + Chromium + agent installed |
410新增:| MCP | Chrome DevTools MCP (Claude/OpenCode/Codex/Vibe) | `mcp-chrome` | yes, when Node.js + Chromium + an agent are installed |
411新增:| MCP | Playwright MCP, reusing the Chromium above | `mcp-playwright` | no |
315412
316413## Security model
317414
修改agent-vm.setup.sh+123 −72看文件
@@ -26,6 +26,14 @@ INSTALL_CLAUDE="${AGENT_VM_INSTALL_CLAUDE:-1}"
2626INSTALL_OPENCODE="${AGENT_VM_INSTALL_OPENCODE:-1}"
2727INSTALL_CODEX="${AGENT_VM_INSTALL_CODEX:-1}"
2828INSTALL_VIBE="${AGENT_VM_INSTALL_VIBE:-1}"
29新增:# MCP servers wired into every installed agent's config. Only servers with a
30新增:# dependency worth baking into the image get a toggle; remote MCP servers are
31新增:# a URL (and often a secret) and belong in per-project config, not in an image
32新增:# every VM is cloned from. mcp-playwright is opt-in: a second browser-driving
33新增:# MCP alongside mcp-chrome is redundant for most users, and every wired server
34新增:# costs tool definitions in the agent's context.
35新增:INSTALL_MCP_CHROME="${AGENT_VM_INSTALL_MCP_CHROME:-1}"
36新增:INSTALL_MCP_PLAYWRIGHT="${AGENT_VM_INSTALL_MCP_PLAYWRIGHT:-0}"
2937
3038# Several installers (Claude Code, Vibe, …) check PATH at install time and
3139# print a "~/.local/bin is not in your PATH" warning otherwise. The persistent
@@ -190,96 +198,139 @@ if [[ "$INSTALL_VIBE" == "1" ]]; then
190198 curl -LsSf https://mistral.ai/vibe/install.sh | bash
191199fi
192200
193删除:# Chrome DevTools MCP runs via `npx` and controls the local Chromium binary, so
194删除:# only configure it when both dependencies and at least one target agent exist.
195删除:if [[ "$INSTALL_NODE" == "1" && "$INSTALL_CHROMIUM" == "1" ]]; then
201新增:# Wire one stdio MCP server into every installed agent's config. Each agent
202新增:# stores MCP servers in its own format, so that mapping is written once here
203新增:# instead of being copy-pasted per server.
204新增:#
205新增:# Usage: configure_mcp <server-name> <command> [arg...]
206新增:# configure_mcp chrome-devtools npx -y chrome-devtools-mcp@latest --headless=true
207新增:#
208新增:# Passing a command (rather than assuming npx) is what lets a server be
209新增:# launched through `env VAR=value npx ...`: every one of the four formats below
210新增:# runs a command with arguments, but only some support a separate env block.
211新增:#
212新增:# The args are rendered once as a JSON array; a JSON array of strings is also a
213新增:# valid TOML array, so the same value serves all four formats.
214新增:configure_mcp() {
215新增: # Not named `command`: that is a shell builtin, and shadowing its name in a
216新增: # file that uses `command -v` elsewhere invites a double-take.
217新增: local name="$1" cmd="$2"
218新增: shift 2
219新增: # One arg per line into jq -R, so an argument containing a newline would be
220新增: # split. None of the callers pass one.
221新增: local args_json
222新增: args_json="$(printf '%s\n' "$@" | jq -R . | jq -sc .)"
223新增:
196224 if [[ "$INSTALL_CLAUDE" == "1" ]]; then
197删除: echo "Configuring Chrome MCP server for Claude..."
198删除: CONFIG="$HOME/.claude.json"
199删除: if [ -f "$CONFIG" ]; then
200删除: jq '.mcpServers["chrome-devtools"] = {
201删除: "command": "npx",
202删除: "args": ["-y", "chrome-devtools-mcp@latest", "--headless=true", "--isolated=true"]
203删除: }' "$CONFIG" > "$CONFIG.tmp" && mv "$CONFIG.tmp" "$CONFIG"
204删除: else
205删除: cat > "$CONFIG" << 'JSON'
206删除:{
207删除: "mcpServers": {
208删除: "chrome-devtools": {
209删除: "command": "npx",
210删除: "args": ["-y", "chrome-devtools-mcp@latest", "--headless=true", "--isolated=true"]
211删除: }
212删除: }
213删除:}
214删除:JSON
225新增: echo "Configuring $name MCP server for Claude..."
226新增: local config="$HOME/.claude.json"
227新增: [ -f "$config" ] || echo '{}' > "$config"
228新增: # Guarded: `a && b` is exempt from `set -e`, and this is not the last
229新增: # statement of the function, so a jq failure (invalid JSON in an existing
230新增: # config, full disk) would otherwise leave a stray .tmp behind and let setup
231新增: # finish "successfully" without the MCP server.
232新增: if ! { jq --arg n "$name" --arg c "$cmd" --argjson a "$args_json" \
233新增: '.mcpServers[$n] = {"command": $c, "args": $a}' \
234新增: "$config" > "$config.tmp" && mv "$config.tmp" "$config"; }; then
235新增: rm -f "$config.tmp"
236新增: echo "Error: failed to write '$name' into $config" >&2
237新增: return 1
215238 fi
216239 fi
217240
218241 if [[ "$INSTALL_OPENCODE" == "1" ]]; then
219删除: echo "Configuring Chrome MCP server for OpenCode..."
220删除: OPENCODE_CONFIG_DIR="$HOME/.config/opencode"
221删除: mkdir -p "$OPENCODE_CONFIG_DIR"
222删除: OPENCODE_CONFIG="$OPENCODE_CONFIG_DIR/opencode.json"
223删除: if [ -f "$OPENCODE_CONFIG" ]; then
224删除: jq '.mcp["chrome-devtools"] = {
225删除: "type": "local",
226删除: "command": ["npx", "-y", "chrome-devtools-mcp@latest", "--headless=true", "--isolated=true"],
227删除: "enabled": true
228删除: }' "$OPENCODE_CONFIG" > "$OPENCODE_CONFIG.tmp" && mv "$OPENCODE_CONFIG.tmp" "$OPENCODE_CONFIG"
229删除: else
230删除: cat > "$OPENCODE_CONFIG" << 'JSON'
231删除:{
232删除: "$schema": "https://opencode.ai/config.json",
233删除: "mcp": {
234删除: "chrome-devtools": {
235删除: "type": "local",
236删除: "command": ["npx", "-y", "chrome-devtools-mcp@latest", "--headless=true", "--isolated=true"],
237删除: "enabled": true
238删除: }
239删除: }
240删除:}
241删除:JSON
242新增: echo "Configuring $name MCP server for OpenCode..."
243新增: mkdir -p "$HOME/.config/opencode"
244新增: local config="$HOME/.config/opencode/opencode.json"
245新增: [ -f "$config" ] || echo '{"$schema": "https://opencode.ai/config.json"}' > "$config"
246新增: if ! { jq --arg n "$name" --arg c "$cmd" --argjson a "$args_json" \
247新增: '.mcp[$n] = {"type": "local", "command": ([$c] + $a), "enabled": true}' \
248新增: "$config" > "$config.tmp" && mv "$config.tmp" "$config"; }; then
249新增: rm -f "$config.tmp"
250新增: echo "Error: failed to write '$name' into $config" >&2
251新增: return 1
242252 fi
243253 fi
244254
245255 if [[ "$INSTALL_VIBE" == "1" ]]; then
246256 # Vibe uses TOML; append an array-of-tables entry (valid even if the wizard
247257 # later writes to the same file). Guard against duplicates on repeated runs.
248删除: echo "Configuring Chrome MCP server for Vibe..."
249删除: VIBE_CONFIG_DIR="$HOME/.vibe"
250删除: mkdir -p "$VIBE_CONFIG_DIR"
251删除: VIBE_CONFIG="$VIBE_CONFIG_DIR/config.toml"
252删除: if ! grep -q 'name = "chrome-devtools"' "$VIBE_CONFIG" 2>/dev/null; then
253删除: cat >> "$VIBE_CONFIG" << 'TOML'
254删除:
255删除:[[mcp_servers]]
256删除:name = "chrome-devtools"
257删除:transport = "stdio"
258删除:command = "npx"
259删除:args = ["-y", "chrome-devtools-mcp@latest", "--headless=true", "--isolated=true"]
260删除:TOML
258新增: echo "Configuring $name MCP server for Vibe..."
259新增: mkdir -p "$HOME/.vibe"
260新增: local config="$HOME/.vibe/config.toml"
261新增: if ! grep -qF "name = \"$name\"" "$config" 2>/dev/null; then
262新增: {
263新增: printf '\n[[mcp_servers]]\n'
264新增: printf 'name = "%s"\n' "$name"
265新增: printf 'transport = "stdio"\n'
266新增: printf 'command = "%s"\n' "$cmd"
267新增: printf 'args = %s\n' "$args_json"
268新增: } >> "$config"
261269 fi
262270 fi
263271
264272 if [[ "$INSTALL_CODEX" == "1" ]]; then
265273 # Codex CLI uses TOML at ~/.codex/config.toml with [mcp_servers.NAME]
266删除: # tables. Append the chrome-devtools entry; guard against duplicates on
267删除: # repeated setup runs.
268删除: echo "Configuring Chrome MCP server for Codex..."
269删除: CODEX_CONFIG_DIR="$HOME/.codex"
270删除: mkdir -p "$CODEX_CONFIG_DIR"
271删除: CODEX_CONFIG="$CODEX_CONFIG_DIR/config.toml"
272删除: if ! grep -q '\[mcp_servers\.chrome-devtools\]' "$CODEX_CONFIG" 2>/dev/null; then
273删除: cat >> "$CODEX_CONFIG" << 'TOML'
274删除:
275删除:[mcp_servers.chrome-devtools]
276删除:command = "npx"
277删除:args = ["-y", "chrome-devtools-mcp@latest", "--headless=true", "--isolated=true"]
278删除:TOML
274新增: # tables. Guard against duplicates on repeated setup runs.
275新增: echo "Configuring $name MCP server for Codex..."
276新增: mkdir -p "$HOME/.codex"
277新增: local config="$HOME/.codex/config.toml"
278新增: if ! grep -qF "[mcp_servers.$name]" "$config" 2>/dev/null; then
279新增: {
280新增: printf '\n[mcp_servers.%s]\n' "$name"
281新增: printf 'command = "%s"\n' "$cmd"
282新增: printf 'args = %s\n' "$args_json"
283新增: } >> "$config"
279284 fi
280285 fi
281删除:elif [[ "$INSTALL_CLAUDE" == "1" || "$INSTALL_OPENCODE" == "1" || "$INSTALL_CODEX" == "1" || "$INSTALL_VIBE" == "1" ]]; then
282删除: echo "Skipping Chrome MCP config: requires Node.js and Chromium." >&2
286新增:}
287新增:
288新增:# True when at least one agent is installed — nothing to configure otherwise,
289新增:# and no reason to print a "skipping" notice either.
290新增:any_agent_installed() {
291新增: [[ "$INSTALL_CLAUDE" == "1" || "$INSTALL_OPENCODE" == "1" \
292新增: || "$INSTALL_CODEX" == "1" || "$INSTALL_VIBE" == "1" ]]
293新增:}
294新增:
295新增:# Chrome DevTools MCP runs via `npx` and drives the Chromium installed above,
296新增:# so it needs both dependencies plus at least one target agent.
297新增:if [[ "$INSTALL_MCP_CHROME" == "1" ]] && any_agent_installed; then
298新增: if [[ "$INSTALL_NODE" == "1" && "$INSTALL_CHROMIUM" == "1" ]]; then
299新增: configure_mcp chrome-devtools npx -y chrome-devtools-mcp@latest --headless=true --isolated=true
300新增: else
301新增: echo "Skipping Chrome MCP config: requires Node.js and Chromium." >&2
302新增: fi
303新增:fi
304新增:
305新增:# Playwright MCP drives the Chromium installed above instead of pulling its own
306新增:# browser build, so it needs the same two dependencies as the Chrome MCP.
307新增:#
308新增:# Two things are needed for that reuse, and --executable-path alone is not
309新增:# enough: @playwright/mcp depends on the `playwright` package, whose postinstall
310新增:# downloads every browser marked installByDefault in playwright-core's
311新增:# browsers.json — chromium, chromium-headless-shell, firefox, webkit and ffmpeg,
312新增:# several hundred MB — regardless of which binary ends up being launched.
313新增:# PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD suppresses that. It is set through `env` on
314新增:# this one command rather than in the VM's ~/.zshenv, so a user's own
315新增:# `npx playwright test` in a project still downloads the browsers it expects.
316新增:#
317新增:# Consequence to know: this server is pinned to Chromium. Pointing it at another
318新增:# engine means editing the MCP entry (drop --executable-path, add e.g.
319新增:# --browser firefox), and the first launch then fails with Playwright's usual
320新增:# "run npx playwright install" message — which works inside the VM and lands the
321新增:# download in that project VM rather than in the base image.
322新增:#
323新增:# The trade-off: Playwright pins and tests against its own browser build, so a
324新增:# distro Chromium can drift from what playwright-core expects. Re-add
325新增:# `npx playwright install chromium` here if that ever bites.
326新增:if [[ "$INSTALL_MCP_PLAYWRIGHT" == "1" ]] && any_agent_installed; then
327新增: if [[ "$INSTALL_NODE" == "1" && "$INSTALL_CHROMIUM" == "1" ]]; then
328新增: configure_mcp playwright env PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \
329新增: npx -y @playwright/mcp@latest --headless --isolated \
330新增: --executable-path /usr/bin/chromium
331新增: else
332新增: echo "Skipping Playwright MCP config: requires Node.js and Chromium." >&2
333新增: fi
283334fi
284335
285336echo "VM setup complete."
修改agent-vm.sh+481 −53看文件
@@ -18,12 +18,47 @@
1818# agent-vm rm - Stop and delete the VM for cwd
1919# agent-vm list - List all agent-vm VMs
2020# agent-vm status - Show status of all VMs (current dir marked with >)
21新增:# agent-vm name - Print the VM name for cwd
22新增:# agent-vm info - Print machine-readable state (key=value)
23新增:# agent-vm version - Print the agent-vm version
2124# agent-vm help - Show help
2225#
2326
27新增:# Semantic version of this file. Bumped by hand on release. Integrators gate on
28新增:# it via `agent-vm version`; a build with no `version` command predates it.
29新增:AGENT_VM_VERSION="0.1.0"
30新增:
2431AGENT_VM_TEMPLATE="agent-vm-base"
2532AGENT_VM_STATE_DIR="${HOME}/.agent-vm"
26删除:AGENT_VM_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
33新增:
34新增:# Directory holding the real agent-vm.sh, symlinks followed.
35新增:#
36新增:# ./install.sh puts a symlink on PATH (~/.local/bin/agent-vm -> <repo>/agent-vm.sh)
37新增:# so `agent-vm` works as an ordinary command. Without resolving the link, this
38新增:# would point at ~/.local/bin and `agent-vm setup` would fail to find
39新增:# agent-vm.setup.sh, which lives next to the real file.
40新增:#
41新增:# `readlink -f` would do it in one call but is GNU-only — macOS ships a readlink
42新增:# without it — so walk the chain by hand.
43新增:#
44新增:# `CDPATH=` because `dirname` can yield a bare relative path (running
45新增:# `bash sub/agent-vm.sh`). With CDPATH set, `cd <relative>` searches it before
46新增:# the current directory and prints where it landed, so without clearing it this
47新增:# would resolve the wrong directory and capture a stray line — leaving
48新增:# `agent-vm setup` unable to find agent-vm.setup.sh next to the real file.
49新增:_agent_vm_script_dir() {
50新增: local src="${BASH_SOURCE[0]:-$0}" dir
51新增: while [ -L "$src" ]; do
52新增: dir="$(CDPATH= cd -P -- "$(dirname "$src")" >/dev/null && pwd)"
53新增: src="$(readlink "$src")"
54新增: case "$src" in
55新增: /*) ;; # absolute: use as-is
56新增: *) src="$dir/$src" ;; # relative: to the link's directory
57新增: esac
58新增: done
59新增: (CDPATH= cd -P -- "$(dirname "$src")" >/dev/null && pwd)
60新增:}
61新增:AGENT_VM_SCRIPT_DIR="$(_agent_vm_script_dir)"
2762
2863# Prompt for a value with a default. Reads from /dev/tty so this still works
2964# when called inside command substitution. Writes the prompt to stderr and the
@@ -106,7 +141,9 @@ _agent_vm_check_linux_prereqs() {
106141 errs=1
107142 elif [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then
108143 echo "Error: /dev/kvm exists but you don't have read/write access." >&2
109删除: if ! id -nG 2>/dev/null | grep -qw kvm; then
144新增: local groups
145新增: groups="$(id -nG 2>/dev/null || true)"
146新增: if [[ " $groups " != *" kvm "* ]]; then
110147 echo " Fix: sudo usermod -aG kvm \"\$USER\"" >&2
111148 echo " Then log out and back in (or run 'newgrp kvm') so the new" >&2
112149 echo " group membership takes effect." >&2
@@ -133,6 +170,33 @@ _agent_vm_clean_partial_state() {
133170 fi
134171}
135172
173新增:# Resolve a user-supplied directory argument to the same absolute form the
174新增:# VM-running commands use.
175新增:#
176新增:# Those commands all derive the name from `$(pwd)`, so they never see a relative
177新增:# or trailing-slash path. `name` and `info` do take a directory argument, and the
178新增:# name is a hash of that *string*: without this, `agent-vm name /tmp` and
179新增:# `agent-vm name /tmp/` return two different VMs for one directory, and neither
180新增:# need match what `cd /tmp && agent-vm opencode` produces.
181新增:#
182新增:# Logical pwd (no `-P`), to agree with the `$(pwd)` the other commands use.
183新增:# A directory that does not exist is rejected rather than hashed: a name derived
184新增:# from an unresolvable path is wrong in a way nothing downstream would catch.
185新增:#
186新增:# `CDPATH=` is not cosmetic. With CDPATH set in the environment, `cd <relative>`
187新增:# searches it *before* the current directory and prints where it landed — so
188新增:# this would both emit a stray line into the captured value and resolve a
189新增:# DIFFERENT directory than the `-d` test above just validated. Clearing it keeps
190新增:# the argument meaning "relative to cwd", like every other path-taking tool.
191新增:_agent_vm_abs_dir() {
192新增: local dir="${1:-$(pwd)}"
193新增: if [[ ! -d "$dir" ]]; then
194新增: echo "Error: no such directory: $dir" >&2
195新增: return 1
196新增: fi
197新增: (CDPATH= cd -- "$dir" >/dev/null && pwd)
198新增:}
199新增:
136200# Generate a deterministic VM name for a directory
137201_agent_vm_name() {
138202 local dir="${1:-$(pwd)}"
@@ -143,14 +207,71 @@ _agent_vm_name() {
143207 echo "agent-vm-${base}-${hash}"
144208}
145209
146删除:# Check if a VM exists (any state)
210新增:# Exact-line match against an already-captured string, with no pipe.
211新增:#
212新增:# `cmd | grep -q needle` is unsafe for anyone who sources this file from a
213新增:# script running under `set -o pipefail`: grep -q closes the pipe as soon as it
214新增:# matches, limactl takes a SIGPIPE and exits 141, and pipefail fails the whole
215新增:# pipeline. The result is an intermittent false negative that depends on how
216新增:# much limactl still had to write — it looks like "the VM doesn't exist". So
217新增:# capture the output first, then match it in the shell.
218新增:_agent_vm_has_line() {
219新增: case $'\n'"$1"$'\n' in
220新增: *$'\n'"$2"$'\n'*) return 0 ;;
221新增: *) return 1 ;;
222新增: esac
223新增:}
224新增:
225新增:# Check if a VM exists (any state).
226新增:# 0 = yes · 1 = no · 2 = could not ask (limactl itself failed).
227新增:# The third status matters: an empty answer from a failed query is otherwise
228新增:# indistinguishable from "no such VM", and `info` would report a confident 0.
147229_agent_vm_exists() {
148删除: limactl list -q 2>/dev/null | grep -q "^${1}$"
230新增: local list
231新增: list="$(limactl list -q 2>/dev/null)" || return 2
232新增: _agent_vm_has_line "$list" "$1"
149233}
150234
151删除:# Check if a VM is running
235新增:# Check if a VM is running. Same three statuses as _agent_vm_exists.
152236_agent_vm_running() {
153删除: limactl list --format '{{.Name}} {{.Status}}' 2>/dev/null | grep -q "^${1} Running$"
237新增: local list
238新增: list="$(limactl list --format '{{.Name}} {{.Status}}' 2>/dev/null)" || return 2
239新增: _agent_vm_has_line "$list" "$1 Running"
240新增:}
241新增:
242新增:# Check if the base VM template exists. Kept as a named helper so integrators
243新增:# don't have to hardcode the template name to answer "do I need to run setup?".
244新增:# Same three statuses as _agent_vm_exists.
245新增:_agent_vm_base_exists() {
246新增: _agent_vm_exists "$AGENT_VM_TEMPLATE"
247新增:}
248新增:
249新增:# Turn one of those exit statuses into the value `info` publishes.
250新增:_agent_vm_tristate() {
251新增: case "$1" in
252新增: 0) echo 1 ;;
253新增: 1) echo 0 ;;
254新增: *) echo unknown ;;
255新增: esac
256新增:}
257新增:
258新增:# Was <vm_name> cloned from an older base than the current one?
259新增:# Prints 1 (stale), 0 (up to date), or "unknown" when there is nothing recorded
260新增:# to compare against — never guess from a missing file. A VM with no version
261新增:# marker but a known base predates the marker, which makes it stale.
262新增:_agent_vm_stale_state() {
263新增: local vm_name="$1"
264新增: local base_ver="$AGENT_VM_STATE_DIR/.agent-vm-base-version"
265新增: local vm_ver="$AGENT_VM_STATE_DIR/.agent-vm-version-${vm_name}"
266新增: if [[ ! -f "$base_ver" ]]; then
267新增: echo unknown
268新增: elif [[ ! -f "$vm_ver" ]]; then
269新增: echo 1
270新增: elif [[ "$(cat "$base_ver" 2>/dev/null)" != "$(cat "$vm_ver" 2>/dev/null)" ]]; then
271新增: echo 1
272新增: else
273新增: echo 0
274新增: fi
154275}
155276
156277# Stage a single host file at <dst> via hardlink, falling back to copy if the
@@ -279,20 +400,63 @@ _agent_vm_build_mounts_json() {
279400 printf '%s' "$mounts_json"
280401}
281402
403新增:# Current resources of <vm_name> as "cpus|memory_gib|disk_gib".
404新增:# Prints nothing (and returns 1) when the VM is unknown to Lima. No pipe into
405新增:# grep/head: see _agent_vm_has_line for why that is unsafe under pipefail.
406新增:_agent_vm_resources() {
407新增: local vm_name="$1" all line
408新增: all="$(limactl list --format '{{.Name}}|{{.CPUs}}|{{.Memory}}|{{.Disk}}' 2>/dev/null || true)"
409新增: while IFS= read -r line; do
410新增: case "$line" in
411新增: "${vm_name}|"*)
412新增: local cpus mem_bytes disk_bytes
413新增: IFS='|' read -r _ cpus mem_bytes disk_bytes <<< "$line"
414新增: printf '%s|%s|%s\n' "$cpus" "$((mem_bytes / 1073741824))" "$((disk_bytes / 1073741824))"
415新增: return 0 ;;
416新增: esac
417新增: done <<< "$all"
418新增: return 1
419新增:}
420新增:
282421# Print VM resource details (CPUs, memory, disk)
283422_agent_vm_print_resources() {
284删除: local vm_name="$1"
285删除: local info
286删除: info=$(limactl list --format '{{.Name}}|{{.CPUs}}|{{.Memory}}|{{.Disk}}' 2>/dev/null | grep "^${vm_name}|" | head -1)
287删除: if [[ -n "$info" ]]; then
288删除: local cpus mem_bytes disk_bytes
289删除: IFS='|' read -r _ cpus mem_bytes disk_bytes <<< "$info"
290删除: local mem_gib=$((mem_bytes / 1073741824))
291删除: local disk_gib=$((disk_bytes / 1073741824))
423新增: local res cpus mem_gib disk_gib
424新增: if res="$(_agent_vm_resources "$1")"; then
425新增: IFS='|' read -r cpus mem_gib disk_gib <<< "$res"
292426 echo " Resources: CPUs: ${cpus}, Memory: ${mem_gib} GiB, Disk: ${disk_gib} GiB"
293427 fi
294428}
295429
430新增:# Would the requested resources actually change anything on <vm_name>?
431新增:# Empty request fields mean "not specified". Returns 0 when something differs
432新增:# (or when the current values can't be read — never claim "no change" from
433新增:# missing information), 1 when the VM already matches the request.
434新增:#
435新增:# Disk is compared one-way on purpose: Lima can grow a disk but not shrink it,
436新增:# so a request below the current size is not a change that stopping could apply.
437新增:#
438新增:# Both sides are integer GiB, so a VM whose memory is not a whole number of GiB
439新增:# can still compare unequal every time. That is the pre-existing behaviour
440新增:# (prompt on every call), not a new failure mode.
441新增:_agent_vm_resources_differ() {
442新增: local vm_name="$1" want_cpus="$2" want_mem="$3" want_disk="$4"
443新增: local cur cur_cpus cur_mem cur_disk
444新增: if ! cur="$(_agent_vm_resources "$vm_name")"; then
445新增: return 0
446新增: fi
447新增: IFS='|' read -r cur_cpus cur_mem cur_disk <<< "$cur"
448新增: if [[ -n "$want_cpus" && "$want_cpus" != "$cur_cpus" ]]; then
449新增: return 0
450新增: fi
451新增: if [[ -n "$want_mem" && "$want_mem" != "$cur_mem" ]]; then
452新增: return 0
453新增: fi
454新增: if [[ -n "$want_disk" && "$want_disk" -gt "$cur_disk" ]]; then
455新增: return 0
456新增: fi
457新增: return 1
458新增:}
459新增:
296460# Ensure the VM for cwd exists and is running, creating/starting as needed
297461# Usage: _agent_vm_ensure_running <vm_name> <host_dir> [--disk GB] [--memory GB] [--reset]
298462_agent_vm_ensure_running() {
@@ -329,7 +493,7 @@ _agent_vm_ensure_running() {
329493 # cryptic "no such file or directory".
330494 _agent_vm_clean_partial_state "$vm_name"
331495
332删除: if ! limactl list -q 2>/dev/null | grep -q "^${AGENT_VM_TEMPLATE}$"; then
496新增: if ! _agent_vm_base_exists; then
333497 echo "Error: Base VM not found. Run 'agent-vm setup' first." >&2
334498 return 1
335499 fi
@@ -359,7 +523,7 @@ _agent_vm_ensure_running() {
359523 edit_args+=(--set ".mounts = ${mounts_json}")
360524 [[ -n "$memory" ]] && edit_args+=(--memory "$memory")
361525 [[ -n "$cpus" ]] && edit_args+=(--cpus "$cpus")
362删除: (cd /tmp && limactl edit "$vm_name" "${edit_args[@]}") &>/dev/null
526新增: (cd /tmp && limactl edit "$vm_name" ${edit_args[@]+"${edit_args[@]}"}) &>/dev/null
363527 if [[ -n "$disk" ]]; then
364528 if ! (cd /tmp && limactl edit "$vm_name" --disk "$disk") &>/dev/null; then
365529 echo "Warning: Cannot set disk to ${disk} GiB (shrinking is not supported). Re-run 'agent-vm setup --disk ${disk}' for a smaller base." >&2
@@ -371,8 +535,12 @@ _agent_vm_ensure_running() {
371535 if [[ -f "$base_ver" ]]; then
372536 cp "$base_ver" "$AGENT_VM_STATE_DIR/.agent-vm-version-${vm_name}"
373537 fi
374删除: elif [[ -n "$disk" || -n "$memory" || -n "$cpus" ]]; then
375删除: # Auto-resize existing VM if --disk, --memory, or --cpus changed
538新增: elif [[ -n "$disk" || -n "$memory" || -n "$cpus" ]] \
539新增: && _agent_vm_resources_differ "$vm_name" "$cpus" "$memory" "$disk"; then
540新增: # Resize the existing VM, but only when the request actually differs from
541新增: # what the VM already has. Prompting on the mere *presence* of a resource
542新增: # flag means every caller that passes its defaults on each invocation gets
543新增: # "Stop the VM and apply changes?" forever, for a no-op.
376544 if _agent_vm_running "$vm_name"; then
377545 echo "VM '$vm_name' is currently running. It must be stopped to apply new resource settings."
378546 printf "Stop the VM and apply changes? [y/N] " >&2
@@ -391,11 +559,16 @@ _agent_vm_ensure_running() {
391559 local edit_args=()
392560 [[ -n "$memory" ]] && edit_args+=(--memory "$memory")
393561 [[ -n "$cpus" ]] && edit_args+=(--cpus "$cpus")
394删除: local edit_output
395删除: if ! edit_output=$(cd /tmp && limactl edit "$vm_name" "${edit_args[@]}" 2>&1); then
396删除: echo "Error: Failed to update VM resources:" >&2
397删除: echo "$edit_output" >&2
398删除: return 1
562新增: # Only call limactl when there is something to set: `limactl edit <vm>` with
563新增: # no flags drops into $EDITOR, which would hang a non-interactive caller
564新增: # that passed --disk on its own.
565新增: if [[ ${#edit_args[@]} -gt 0 ]]; then
566新增: local edit_output
567新增: if ! edit_output=$(cd /tmp && limactl edit "$vm_name" "${edit_args[@]}" 2>&1); then
568新增: echo "Error: Failed to update VM resources:" >&2
569新增: echo "$edit_output" >&2
570新增: return 1
571新增: fi
399572 fi
400573 if [[ -n "$disk" ]]; then
401574 if ! edit_output=$(cd /tmp && limactl edit "$vm_name" --disk "$disk" 2>&1); then
@@ -405,10 +578,10 @@ _agent_vm_ensure_running() {
405578 _agent_vm_print_resources "$vm_name"
406579 fi
407580
408删除: # Warn if this VM was cloned from an older base
409删除: local base_ver="$AGENT_VM_STATE_DIR/.agent-vm-base-version"
410删除: local vm_ver="$AGENT_VM_STATE_DIR/.agent-vm-version-${vm_name}"
411删除: if [[ -f "$base_ver" ]] && { [[ ! -f "$vm_ver" ]] || [[ "$(cat "$base_ver")" != "$(cat "$vm_ver")" ]]; }; then
581新增: # Warn if this VM was cloned from an older base. `agent-vm info` exposes the
582新增: # same verdict as vm_stale= so integrators can ask before starting instead of
583新增: # reading this warning after the fact.
584新增: if [[ "$(_agent_vm_stale_state "$vm_name")" == "1" ]]; then
412585 echo "Warning: Base VM has been updated since this VM was cloned. Use --reset to re-clone from the new base." >&2
413586 fi
414587
@@ -540,7 +713,7 @@ _agent_vm_ensure_running() {
540713 # host propagate after a VM restart (ln/cp against the cached staging path).
541714 # New VMs just staged fresh copies in _agent_vm_build_mounts_json, so there
542715 # is nothing to refresh.
543删除: if [[ -z "$is_new_vm" ]]; then
716新增: if [[ -z "$is_new_vm" ]] && [[ ${#file_mount_entries[@]} -gt 0 ]]; then
544717 local host_src host_staging _bind_src _bind_dst
545718 for entry in "${file_mount_entries[@]}"; do
546719 IFS='|' read -r host_src host_staging _bind_src _bind_dst <<< "$entry"
@@ -588,20 +761,31 @@ _agent_vm_ensure_running() {
588761
589762agent-vm() {
590763 local vm_opts=()
591删除: # Parse global options before the subcommand
764新增: # Parse global options before the subcommand.
765新增: #
766新增: # Resource values are validated here, as `setup` already does for its own
767新增: # flags. Without it a typo like `--disk 10G` travels all the way into the
768新增: # resource comparison and surfaces as a raw bash diagnostic
769新增: # ("[[: 10G: value too great for base") before anything actionable is said.
592770 while [[ $# -gt 0 ]]; do
593771 case "$1" in
594772 --disk)
773新增: _agent_vm_validate_int --disk "$2" || return 1
595774 vm_opts+=(--disk "$2"); shift 2 ;;
596775 --disk=*)
776新增: _agent_vm_validate_int --disk "${1#*=}" || return 1
597777 vm_opts+=(--disk "${1#*=}"); shift ;;
598778 --memory|--ram)
779新增: _agent_vm_validate_int --memory "$2" || return 1
599780 vm_opts+=(--memory "$2"); shift 2 ;;
600781 --memory=*|--ram=*)
782新增: _agent_vm_validate_int --memory "${1#*=}" || return 1
601783 vm_opts+=(--memory "${1#*=}"); shift ;;
602784 --cpus)
785新增: _agent_vm_validate_int --cpus "$2" || return 1
603786 vm_opts+=(--cpus "$2"); shift 2 ;;
604787 --cpus=*)
788新增: _agent_vm_validate_int --cpus "${1#*=}" || return 1
605789 vm_opts+=(--cpus "${1#*=}"); shift ;;
606790 --reset)
607791 vm_opts+=(--reset); shift ;;
@@ -625,7 +809,7 @@ agent-vm() {
625809 # itself; help needs nothing.) Without this, stop/list/status/etc. would fail
626810 # with confusing empty output instead of a clear, actionable message.
627811 case "$cmd" in
628删除: help|--help|-h|setup) ;;
812新增: help|--help|-h|setup|version|--version|-V|name|info|env) ;;
629813 *)
630814 if ! command -v limactl &>/dev/null; then
631815 echo "Error: limactl (Lima) not found. Run 'agent-vm setup' first, or install" >&2
@@ -636,25 +820,25 @@ agent-vm() {
636820
637821 case "$cmd" in
638822 setup)
639删除: _agent_vm_setup "${vm_opts[@]}" "$@"
823新增: _agent_vm_setup ${vm_opts[@]+"${vm_opts[@]}"} "$@"
640824 ;;
641825 claude)
642删除: _agent_vm_claude "${vm_opts[@]}" "$@"
826新增: _agent_vm_claude ${vm_opts[@]+"${vm_opts[@]}"} "$@"
643827 ;;
644828 opencode)
645删除: _agent_vm_opencode "${vm_opts[@]}" "$@"
829新增: _agent_vm_opencode ${vm_opts[@]+"${vm_opts[@]}"} "$@"
646830 ;;
647831 codex)
648删除: _agent_vm_codex "${vm_opts[@]}" "$@"
832新增: _agent_vm_codex ${vm_opts[@]+"${vm_opts[@]}"} "$@"
649833 ;;
650834 vibe)
651删除: _agent_vm_vibe "${vm_opts[@]}" "$@"
835新增: _agent_vm_vibe ${vm_opts[@]+"${vm_opts[@]}"} "$@"
652836 ;;
653837 shell|sh)
654删除: _agent_vm_shell "${vm_opts[@]}" "$@"
838新增: _agent_vm_shell ${vm_opts[@]+"${vm_opts[@]}"} "$@"
655839 ;;
656840 run)
657删除: _agent_vm_run "${vm_opts[@]}" "$@"
841新增: _agent_vm_run ${vm_opts[@]+"${vm_opts[@]}"} "$@"
658842 ;;
659843 stop)
660844 _agent_vm_stop "$@"
@@ -671,6 +855,22 @@ agent-vm() {
671855 status)
672856 _agent_vm_status "$@"
673857 ;;
858新增: name)
859新增: local name_dir
860新增: name_dir="$(_agent_vm_abs_dir "${1:-}")" || return 1
861新增: _agent_vm_name "$name_dir"
862新增: ;;
863新增: info)
864新增: local info_dir
865新增: info_dir="$(_agent_vm_abs_dir "${1:-}")" || return 1
866新增: _agent_vm_info "$info_dir"
867新增: ;;
868新增: env)
869新增: _agent_vm_env "$@"
870新增: ;;
871新增: version|--version|-V)
872新增: echo "$AGENT_VM_VERSION"
873新增: ;;
674874 help|--help|-h)
675875 _agent_vm_help
676876 ;;
@@ -682,6 +882,180 @@ agent-vm() {
682882 esac
683883}
684884
885新增:# Machine-readable state, one key=value per line. This is the supported way for
886新增:# another tool to ask what agent-vm knows, instead of reverse-engineering VM
887新增:# naming, the template name, or the state-dir version markers — all of which
888新增:# are internal and free to change.
889新增:#
890新增:# Keys: version, template, state_dir, dir, vm_name, base_exists, vm_exists,
891新增:# vm_running, vm_stale. Booleans are 1/0; anything that cannot be determined is
892新增:# "unknown" rather than a guess.
893新增:_agent_vm_info() {
894新增: local dir="${1:-$(pwd)}"
895新增: local vm_name
896新增: vm_name="$(_agent_vm_name "$dir")"
897新增:
898新增: echo "version=$AGENT_VM_VERSION"
899新增: echo "template=$AGENT_VM_TEMPLATE"
900新增: echo "state_dir=$AGENT_VM_STATE_DIR"
901新增: echo "dir=$dir"
902新增: echo "vm_name=$vm_name"
903新增:
904新增: if ! command -v limactl &>/dev/null; then
905新增: # Still useful without Lima: the static keys above answer "what would this
906新增: # VM be called", which is all a caller needs before setup has ever run.
907新增: echo "base_exists=unknown"
908新增: echo "vm_exists=unknown"
909新增: echo "vm_running=unknown"
910新增: echo "vm_stale=unknown"
911新增: return 0
912新增: fi
913新增:
914新增: # Keep the three-way answer from the query helpers: a failed query reports
915新增: # `unknown`, never a confident 0. A caller told `base_exists=0` when the truth
916新增: # was "could not ask" would offer to build a base VM that already exists.
917新增: local base_exists vm_exists vm_running
918新增: _agent_vm_base_exists; base_exists="$(_agent_vm_tristate $?)"
919新增: _agent_vm_exists "$vm_name"; vm_exists="$(_agent_vm_tristate $?)"
920新增: _agent_vm_running "$vm_name"; vm_running="$(_agent_vm_tristate $?)"
921新增: echo "base_exists=$base_exists"
922新增: echo "vm_exists=$vm_exists"
923新增: echo "vm_running=$vm_running"
924新增: # Staleness compares this VM against the base it was cloned from; with no VM
925新增: # (or no way to tell) there is nothing to compare.
926新增: if [[ "$vm_exists" == "1" ]]; then
927新增: echo "vm_stale=$(_agent_vm_stale_state "$vm_name")"
928新增: else
929新增: echo "vm_stale=unknown"
930新增: fi
931新增:}
932新增:
933新增:# Escape a value for a single-quoted shell literal: ' becomes '"'"'.
934新增:#
935新增:# Via sed, NOT `${v//\'/\'\"\'\"\'}`: bash 3.2 — what macOS ships — keeps the
936新增:# backslashes in the replacement half of that substitution and emits
937新增:# `O\'"\'"\'Brien`. The resulting line is a syntax error, and a shell sourcing
938新增:# ~/.agent-vm.env then abandons the WHOLE file, losing every secret in it, not
939新增:# just the one with the quote.
940新增:_agent_vm_sq_escape() {
941新增: printf '%s' "$1" | sed "s/'/'\"'\"'/g"
942新增:}
943新增:
944新增:# Read, write and delete entries in ~/.agent-vm/env — the dotenv file pushed
945新增:# into every VM on each start and auto-sourced there.
946新增:#
947新增:# Exists so integrators don't hand-roll the quoting: the file is *sourced* by a
948新增:# shell, so one bad escape costs every secret in it (see _agent_vm_sq_escape).
949新增:#
950新增:# agent-vm env set KEY VALUE replace or add KEY (value never echoed)
951新增:# agent-vm env get KEY print KEY's value
952新增:# agent-vm env has KEY exit 0 if KEY is set, 1 otherwise (no output)
953新增:# agent-vm env unset KEY remove KEY
954新增:# agent-vm env list print the key NAMES only, never the values
955新增:#
956新增:# Writes are atomic (temp file then mv) and the file is kept mode 600. Lines
957新增:# this command does not manage are preserved untouched.
958新增:_agent_vm_env() {
959新增: local action="${1:-list}"
960新增: local key="${2:-}"
961新增: local file="$AGENT_VM_STATE_DIR/env"
962新增:
963新增: case "$action" in
964新增: set|get|has|unset)
965新增: if [[ -z "$key" ]]; then
966新增: echo "Error: 'agent-vm env $action' needs a KEY." >&2
967新增: return 1
968新增: fi
969新增: # A key must be a shell-assignable name: anything else would produce a
970新增: # line that breaks the file for every reader.
971新增: if [[ ! "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then
972新增: echo "Error: '$key' is not a valid environment variable name." >&2
973新增: return 1
974新增: fi ;;
975新增: esac
976新增:
977新增: case "$action" in
978新增: set)
979新增: if [[ $# -lt 3 ]]; then
980新增: echo "Error: 'agent-vm env set' needs a VALUE." >&2
981新增: return 1
982新增: fi
983新增: local value="$3" tmp line
984新增: mkdir -p "$AGENT_VM_STATE_DIR"
985新增: tmp="$(mktemp "${file}.XXXXXX")"
986新增: chmod 600 "$tmp"
987新增: if [[ -f "$file" ]]; then
988新增: while IFS= read -r line || [[ -n "$line" ]]; do
989新增: case "$line" in
990新增: "${key}="*) : ;;
991新增: *) printf '%s\n' "$line" >> "$tmp" ;;
992新增: esac
993新增: done < "$file"
994新增: fi
995新增: printf "%s='%s'\n" "$key" "$(_agent_vm_sq_escape "$value")" >> "$tmp"
996新增: # A silently-dropped write here means the caller is told the secret was
997新增: # stored when it was not — the worst possible failure for this file.
998新增: if ! mv "$tmp" "$file"; then
999新增: rm -f "$tmp"
1000新增: echo "Error: could not write $file" >&2
1001新增: return 1
1002新增: fi
1003新增: chmod 600 "$file"
1004新增: ;;
1005新增: unset)
1006新增: [[ -f "$file" ]] || return 0
1007新增: local tmp line
1008新增: tmp="$(mktemp "${file}.XXXXXX")"
1009新增: chmod 600 "$tmp"
1010新增: while IFS= read -r line || [[ -n "$line" ]]; do
1011新增: case "$line" in
1012新增: "${key}="*) : ;;
1013新增: *) printf '%s\n' "$line" >> "$tmp" ;;
1014新增: esac
1015新增: done < "$file"
1016新增: if ! mv "$tmp" "$file"; then
1017新增: rm -f "$tmp"
1018新增: echo "Error: could not write $file" >&2
1019新增: return 1
1020新增: fi
1021新增: chmod 600 "$file"
1022新增: ;;
1023新增: get|has)
1024新增: [[ -f "$file" ]] || return 1
1025新增: # Source in a subshell rather than parse: the file is shell, so this is
1026新增: # the only reading that agrees with how the VM will interpret it.
1027新增: #
1028新增: # `unset` first: the subshell inherits this shell's environment, so
1029新增: # without it a variable that merely happens to be exported here would be
1030新增: # reported as stored in the file. An integrator asking "is GH_TOKEN
1031新增: # saved?" would get a false yes — and the caller of agent-vm is very
1032新增: # often a VM that already has these very variables in its environment.
1033新增: #
1034新增: # Presence travels as the exit status and the value as stdout, tested with
1035新增: # ${key+x}. Comparing the value against a sentinel string instead would
1036新增: # report a variable whose stored value happens to equal that sentinel as
1037新增: # absent.
1038新增: local value
1039新增: if ! value="$(unset "$key"
1040新增: set -a; . "$file" >/dev/null 2>&1; set +a
1041新增: eval "[ \"\${${key}+x}\" = x ] || exit 1
1042新增: printf '%s' \"\${${key}}\"")"; then
1043新增: return 1
1044新增: fi
1045新增: [[ "$action" == "has" ]] && return 0
1046新增: printf '%s\n' "$value"
1047新增: ;;
1048新增: list)
1049新增: [[ -f "$file" ]] || return 0
1050新增: # Names only — never values, so this stays safe to paste into an issue.
1051新增: sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' "$file"
1052新增: ;;
1053新增: *)
1054新增: echo "Usage: agent-vm env {set KEY VALUE|get KEY|has KEY|unset KEY|list}" >&2
1055新增: return 1 ;;
1056新增: esac
1057新增:}
1058新增:
6851059_agent_vm_help() {
6861060 cat << 'EOF'
6871061Usage: agent-vm [options] <command> [args]
@@ -702,6 +1076,18 @@ Commands:
7021076 destroy-all Stop and delete all agent-vm VMs
7031077 list List all agent-vm VMs
7041078 status Show status of all VMs (current dir marked with >)
1079新增: name [dir] Print the VM name for a directory (default: cwd)
1080新增: info [dir] Print machine-readable state as key=value lines
1081新增: (version, template, state_dir, dir, vm_name,
1082新增: base_exists, vm_exists, vm_running, vm_stale).
1083新增: Use this from scripts instead of parsing the output
1084新增: of the human-facing commands.
1085新增: env <sub> [args] Read/write ~/.agent-vm/env, the secrets pushed into every
1086新增: VM. Subcommands: set KEY VALUE, get KEY, has KEY (exit
1087新增: status only), unset KEY, list (key names, never values).
1088新增: Use this rather than editing the file: it is sourced by a
1089新增: shell, so one bad quote costs every secret in it.
1090新增: version Print the agent-vm version
7051091 help Show this help
7061092
7071093VM options (for claude, opencode, codex, vibe, shell, run):
@@ -763,6 +1149,15 @@ _agent_vm_setup() {
7631149 local install_ruby=0 install_rust=0 install_golang=0
7641150 local install_docker=1 install_chromium=1 install_gh=1
7651151 local install_claude=1 install_opencode=1 install_codex=1 install_vibe=1
1152新增: # MCP servers wired into the agents' configs. Named mcp-* in --preinstall so
1153新增: # future MCP servers share one obvious namespace. Only servers with a
1154新增: # dependency worth baking into the image belong here: a remote MCP server is
1155新增: # a URL (and often a secret), which belongs in per-project config rather than
1156新增: # in an image every VM is cloned from. Both current ones drive the installed
1157新增: # Chromium. mcp-playwright is opt-in like the Ruby/Rust/Go languages: a second
1158新增: # browser-driving server is redundant for most users, and every wired server
1159新增: # costs tool definitions in the agent's context.
1160新增: local install_mcp_chrome=1 install_mcp_playwright=0
7661161
7671162 while [[ $# -gt 0 ]]; do
7681163 case "$1" in
@@ -790,12 +1185,23 @@ Options:
7901185 'none' for nothing.
7911186 Available names:
7921187 python, node, ruby, rust, golang, docker, chromium,
793删除: gh, claude, opencode, codex, vibe
1188新增: gh, claude, opencode, codex, vibe, mcp-chrome,
1189新增: mcp-playwright
7941190 Selecting codex, or chromium with any AI agent, also
7951191 installs node because those paths require npm/npx.
1192新增: The mcp-* names wire an MCP server into each installed
1193新增: agent's config. Both 'mcp-chrome' (Chrome DevTools) and
1194新增: 'mcp-playwright' drive the preinstalled Chromium, so
1195新增: both need node and chromium and are skipped, with a
1196新增: notice, without them. 'mcp-playwright' is opt-in and not
1197新增: part of 'default' — a second browser-driving server is
1198新增: redundant for most users. Omit them to leave the agents'
1199新增: MCP config untouched — useful when MCP servers are
1200新增: managed per project rather than baked into the image.
7961201 Examples:
7971202 --preinstall=default,rust # default set plus Rust
7981203 --preinstall=python,docker,claude
1204新增: --preinstall=node,chromium,opencode # no chrome MCP
7991205 --help Show this help
8001206EOF
8011207 return 0
@@ -868,6 +1274,7 @@ EOF
8681274 install_python=0 install_node=0 install_ruby=0 install_rust=0 install_golang=0
8691275 install_docker=0 install_chromium=0 install_gh=0
8701276 install_claude=0 install_opencode=0 install_codex=0 install_vibe=0
1277新增: install_mcp_chrome=0 install_mcp_playwright=0
8711278 [[ -z "$preinstall" ]] && preinstall="default"
8721279 # Iterate the comma-list portably across bash and zsh by appending a
8731280 # trailing comma and peeling off one token per iteration.
@@ -884,11 +1291,13 @@ EOF
8841291 install_rust=1 install_golang=1
8851292 install_docker=1 install_chromium=1 install_gh=1
8861293 install_claude=1 install_opencode=1 install_codex=1 install_vibe=1
1294新增: install_mcp_chrome=1 install_mcp_playwright=1
8871295 ;;
8881296 default)
8891297 install_python=1 install_node=1
8901298 install_docker=1 install_chromium=1 install_gh=1
8911299 install_claude=1 install_opencode=1 install_codex=1 install_vibe=1
1300新增: install_mcp_chrome=1
8921301 ;;
8931302 none) ;; # explicit no-op token; with the all-off reset above,
8941303 # `--preinstall=none` ships nothing.
@@ -904,9 +1313,11 @@ EOF
9041313 opencode) install_opencode=1 ;;
9051314 codex) install_codex=1 ;;
9061315 vibe) install_vibe=1 ;;
1316新增: mcp-chrome) install_mcp_chrome=1 ;;
1317新增: mcp-playwright) install_mcp_playwright=1 ;;
9071318 *)
9081319 echo "Unknown preinstall name: $f (names are lowercase)" >&2
909删除: echo "Valid: python, node, ruby, rust, golang, docker, chromium, gh, claude, opencode, codex, vibe, default, all, none" >&2
1320新增: echo "Valid: python, node, ruby, rust, golang, docker, chromium, gh, claude, opencode, codex, vibe, mcp-chrome, mcp-playwright, default, all, none" >&2
9101321 return 1
9111322 ;;
9121323 esac
@@ -946,8 +1357,9 @@ EOF
9461357 printf 'Software\n' >&2
9471358 printf '────────\n' >&2
9481359 printf ' Install: Python, Node.js, Docker, Chromium, gh,\n' >&2
949删除: printf ' Claude Code, OpenCode, Codex CLI, Mistral Vibe\n' >&2
950删除: printf ' Skip: Ruby, Rust, Go\n\n' >&2
1360新增: printf ' Claude Code, OpenCode, Codex CLI, Mistral Vibe,\n' >&2
1361新增: printf ' Chrome DevTools MCP\n' >&2
1362新增: printf ' Skip: Ruby, Rust, Go, Playwright MCP\n\n' >&2
9511363 local use_default_software
9521364 use_default_software=$(_agent_vm_ask_yn "Use this default" Y)
9531365 if [[ "$use_default_software" != "1" ]]; then
@@ -964,10 +1376,24 @@ EOF
9641376 install_chromium=$(_agent_vm_ask_yn "Chromium (headless browser)" Y)
9651377 install_gh=$(_agent_vm_ask_yn "GitHub CLI (gh)" Y)
9661378
1379新增: # MCP servers, wired into each installed agent's config. Chrome DevTools
1380新增: # drives the Chromium above, so it is only worth asking when that is on.
1381新增: # Playwright brings its own browser download, hence the N default.
1382新增: if [[ "$install_chromium" == "1" ]]; then
1383新增: install_mcp_chrome=$(_agent_vm_ask_yn "Chrome DevTools MCP (wired into each agent's config)" Y)
1384新增: else
1385新增: install_mcp_chrome=0
1386新增: fi
1387新增: if [[ "$install_chromium" == "1" ]]; then
1388新增: install_mcp_playwright=$(_agent_vm_ask_yn "Playwright MCP (also drives that Chromium)" N)
1389新增: else
1390新增: install_mcp_playwright=0
1391新增: fi
1392新增:
9671393 local node_forced_reason=""
9681394 if [[ "$install_codex" == "1" ]]; then
9691395 node_forced_reason="Codex CLI requires Node.js"
970删除: elif [[ "$install_chromium" == "1" && ( "$install_claude" == "1" || "$install_opencode" == "1" || "$install_vibe" == "1" ) ]]; then
1396新增: elif [[ "$install_chromium" == "1" && "$install_mcp_chrome" == "1" && ( "$install_claude" == "1" || "$install_opencode" == "1" || "$install_vibe" == "1" ) ]]; then
9711397 node_forced_reason="Chrome DevTools MCP uses npx"
9721398 fi
9731399
@@ -1005,7 +1431,7 @@ EOF
10051431 printf '\n' >&2
10061432 fi
10071433
1008删除: if [[ "$install_chromium" == "1" ]]; then
1434新增: if [[ "$install_chromium" == "1" && "$install_mcp_chrome" == "1" ]]; then
10091435 local wants_chrome_mcp=0
10101436 [[ "$install_claude" == "1" || "$install_opencode" == "1" || "$install_codex" == "1" || "$install_vibe" == "1" ]] && wants_chrome_mcp=1
10111437 if [[ "$wants_chrome_mcp" == "1" && "$install_node" != "1" ]]; then
@@ -1076,6 +1502,8 @@ EOF
10761502 printf 'export AGENT_VM_INSTALL_OPENCODE=%s\n' "$install_opencode"
10771503 printf 'export AGENT_VM_INSTALL_CODEX=%s\n' "$install_codex"
10781504 printf 'export AGENT_VM_INSTALL_VIBE=%s\n' "$install_vibe"
1505新增: printf 'export AGENT_VM_INSTALL_MCP_CHROME=%s\n' "$install_mcp_chrome"
1506新增: printf 'export AGENT_VM_INSTALL_MCP_PLAYWRIGHT=%s\n' "$install_mcp_playwright"
10791507 cat "${AGENT_VM_SCRIPT_DIR}/agent-vm.setup.sh"
10801508 } | limactl shell "$AGENT_VM_TEMPLATE" bash -l || { echo "Error: Setup script failed." >&2; return 1; }
10811509
@@ -1148,11 +1576,11 @@ _agent_vm_claude() {
11481576 local vm_name
11491577 vm_name="$(_agent_vm_name "$host_dir")"
11501578
1151删除: _agent_vm_ensure_running "$vm_name" "$host_dir" "${vm_opts[@]}" || return 1
1579新增: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
11521580 _agent_vm_print_resources "$vm_name"
11531581
11541582 local exit_code=0
1155删除: _agent_vm_lima_run "$vm_name" "$host_dir" "" claude --dangerously-skip-permissions "${args[@]}"
1583新增: _agent_vm_lima_run "$vm_name" "$host_dir" "" claude --dangerously-skip-permissions ${args[@]+"${args[@]}"}
11561584 exit_code=$?
11571585 [[ -n "$rm" ]] && { echo "Removing VM..."; _agent_vm_destroy; }
11581586 return $exit_code
@@ -1180,14 +1608,14 @@ _agent_vm_opencode() {
11801608 local vm_name
11811609 vm_name="$(_agent_vm_name "$host_dir")"
11821610
1183删除: _agent_vm_ensure_running "$vm_name" "$host_dir" "${vm_opts[@]}" || return 1
1611新增: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
11841612 _agent_vm_print_resources "$vm_name"
11851613
11861614 # --auto auto-approves permission prompts that aren't explicitly denied,
11871615 # giving full autonomy (safe inside the sandbox). This is OpenCode's shipped
11881616 # equivalent of a "yolo" mode; the proposed --yolo flag was never merged.
11891617 local exit_code=0
1190删除: _agent_vm_lima_run "$vm_name" "$host_dir" 1 opencode --auto "${args[@]}"
1618新增: _agent_vm_lima_run "$vm_name" "$host_dir" 1 opencode --auto ${args[@]+"${args[@]}"}
11911619 exit_code=$?
11921620 [[ -n "$rm" ]] && { echo "Removing VM..."; _agent_vm_destroy; }
11931621 return $exit_code
@@ -1215,11 +1643,11 @@ _agent_vm_codex() {
12151643 local vm_name
12161644 vm_name="$(_agent_vm_name "$host_dir")"
12171645
1218删除: _agent_vm_ensure_running "$vm_name" "$host_dir" "${vm_opts[@]}" || return 1
1646新增: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
12191647 _agent_vm_print_resources "$vm_name"
12201648
12211649 local exit_code=0
1222删除: _agent_vm_lima_run "$vm_name" "$host_dir" "" codex --dangerously-bypass-approvals-and-sandbox "${args[@]}"
1650新增: _agent_vm_lima_run "$vm_name" "$host_dir" "" codex --dangerously-bypass-approvals-and-sandbox ${args[@]+"${args[@]}"}
12231651 exit_code=$?
12241652 [[ -n "$rm" ]] && { echo "Removing VM..."; _agent_vm_destroy; }
12251653 return $exit_code
@@ -1247,13 +1675,13 @@ _agent_vm_vibe() {
12471675 local vm_name
12481676 vm_name="$(_agent_vm_name "$host_dir")"
12491677
1250删除: _agent_vm_ensure_running "$vm_name" "$host_dir" "${vm_opts[@]}" || return 1
1678新增: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
12511679 _agent_vm_print_resources "$vm_name"
12521680
12531681 # Vibe is a full-screen TUI, so allocate a tty (like opencode).
12541682 # --agent auto-approve gives full autonomy (safe inside the sandbox).
12551683 local exit_code=0
1256删除: _agent_vm_lima_run "$vm_name" "$host_dir" 1 vibe --agent auto-approve "${args[@]}"
1684新增: _agent_vm_lima_run "$vm_name" "$host_dir" 1 vibe --agent auto-approve ${args[@]+"${args[@]}"}
12571685 exit_code=$?
12581686 [[ -n "$rm" ]] && { echo "Removing VM..."; _agent_vm_destroy; }
12591687 return $exit_code
@@ -1287,7 +1715,7 @@ _agent_vm_shell() {
12871715 local vm_name
12881716 vm_name="$(_agent_vm_name "$host_dir")"
12891717
1290删除: _agent_vm_ensure_running "$vm_name" "$host_dir" "${vm_opts[@]}" || return 1
1718新增: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
12911719 _agent_vm_print_resources "$vm_name"
12921720
12931721 local exit_code=0
@@ -1338,7 +1766,7 @@ _agent_vm_run() {
13381766 local vm_name
13391767 vm_name="$(_agent_vm_name "$host_dir")"
13401768
1341删除: _agent_vm_ensure_running "$vm_name" "$host_dir" "${vm_opts[@]}" || return 1
1769新增: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
13421770 _agent_vm_print_resources "$vm_name"
13431771
13441772 # `--tty` forces limactl to allocate a pseudo-terminal in the VM, which
新增install.sh+134 −0看文件
@@ -0,0 +1,134 @@
1新增:#!/usr/bin/env bash
2新增:#
3新增:# agent-vm installer.
4新增:#
5新增:# ./install.sh install (idempotent, safe to re-run)
6新增:# ./install.sh --uninstall remove what this script added
7新增:#
8新增:# Does two things, both optional and both reversible:
9新增:#
10新增:# 1. Puts `agent-vm` on your PATH, as a symlink to agent-vm.sh in this repo.
11新增:# The script already dispatches when executed rather than sourced, so the
12新增:# link is all that is needed. Being a link (not a copy) means `git pull`
13新增:# updates the command with no reinstall.
14新增:#
15新增:# 2. Adds `source <repo>/agent-vm.sh` to your shell rc, which additionally
16新增:# defines `agent-vm` as a shell *function*.
17新增:#
18新增:# Sourcing has always been the documented install and KEEPS WORKING EXACTLY AS
19新增:# BEFORE — an existing install needs nothing but `git pull`. The PATH entry is
20新增:# additive: it makes `agent-vm` reachable from scripts and other tools, which a
21新增:# shell function is not (functions are not inherited by child processes).
22新增:#
23新增:# If you already source agent-vm.sh, the function wins inside your interactive
24新增:# shell and the symlink serves everything else. The two agree: same file.
25新增:
26新增:set -euo pipefail
27新增:
28新增:# CDPATH= : `dirname` can yield a bare relative path, and a CDPATH hit would
29新增:# resolve a different directory than the one this script actually lives in.
30新增:REPO_DIR="$(CDPATH= cd -P -- "$(dirname "${BASH_SOURCE[0]:-$0}")" >/dev/null && pwd)"
31新增:SCRIPT="$REPO_DIR/agent-vm.sh"
32新增:BIN_DIR="${AGENT_VM_BIN_DIR:-$HOME/.local/bin}"
33新增:LINK="$BIN_DIR/agent-vm"
34新增:
35新增:c_g=''; c_y=''; c_r=''; c_0=''
36新增:if [ -t 1 ]; then c_g=$'\033[32m'; c_y=$'\033[33m'; c_r=$'\033[31m'; c_0=$'\033[0m'; fi
37新增:ok() { printf '%s✓%s %s\n' "$c_g" "$c_0" "$*"; }
38新增:warn() { printf '%s!%s %s\n' "$c_y" "$c_0" "$*"; }
39新增:err() { printf '%s✗%s %s\n' "$c_r" "$c_0" "$*" >&2; }
40新增:
41新增:# The rc file where a shell *function* belongs: the interactive one.
42新增:# (A PATH entry would go elsewhere for zsh — ~/.zshenv — but that is not what
43新增:# this line is for.)
44新增:rc_file() {
45新增: case "${SHELL##*/}" in
46新增: zsh) printf '%s' "$HOME/.zshrc" ;;
47新增: bash) case "$(uname -s)" in
48新增: Darwin) printf '%s' "$HOME/.bash_profile" ;;
49新增: *) printf '%s' "$HOME/.bashrc" ;;
50新增: esac ;;
51新增: *) printf '%s' "$HOME/.profile" ;;
52新增: esac
53新增:}
54新增:
55新增:# Is agent-vm.sh already sourced from any of the usual rc files?
56新增:already_sourced() {
57新增: local f
58新增: for f in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile" "$HOME/.zshenv"; do
59新增: [ -f "$f" ] || continue
60新增: grep -q '^[^#]*agent-vm\.sh' "$f" 2>/dev/null && return 0
61新增: done
62新增: return 1
63新增:}
64新增:
65新增:uninstall() {
66新增: if [ -L "$LINK" ] && [ "$(readlink "$LINK")" = "$SCRIPT" ]; then
67新增: rm -f "$LINK"
68新增: ok "removed $LINK"
69新增: else
70新增: [ -e "$LINK" ] && warn "$LINK is not our symlink — left alone." || ok "no symlink to remove"
71新增: fi
72新增: if already_sourced; then
73新增: warn "The 'source ...agent-vm.sh' line in your shell rc is left in place."
74新增: warn "Remove it by hand if you want the shell function gone too."
75新增: fi
76新增: ok "Done. The repository itself was not touched."
77新增:}
78新增:
79新增:if [ "${1:-}" = "--uninstall" ]; then
80新增: uninstall
81新增: exit 0
82新增:fi
83新增:
84新增:[ -r "$SCRIPT" ] || { err "agent-vm.sh not found next to this installer."; exit 1; }
85新增:chmod +x "$SCRIPT" 2>/dev/null || true
86新增:
87新增:# --- 1. agent-vm on PATH -------------------------------------------------------
88新增:mkdir -p "$BIN_DIR"
89新增:if [ -L "$LINK" ] && [ "$(readlink "$LINK")" = "$SCRIPT" ]; then
90新增: ok "agent-vm already linked at $LINK"
91新增:elif [ -e "$LINK" ]; then
92新增: err "$LINK already exists and is not a link to $SCRIPT."
93新增: err "Move it aside, or set AGENT_VM_BIN_DIR to another directory."
94新增: exit 1
95新增:else
96新增: ln -s "$SCRIPT" "$LINK"
97新增: ok "linked $LINK -> $SCRIPT"
98新增:fi
99新增:
100新增:case ":$PATH:" in
101新增: *":$BIN_DIR:"*) ok "$BIN_DIR is on your PATH" ;;
102新增: *)
103新增: warn "$BIN_DIR is not on your PATH. Add this to your shell rc:"
104新增: printf ' export PATH="%s:$PATH"\n' "$BIN_DIR" ;;
105新增:esac
106新增:
107新增:# --- 2. shell function (optional, additive) ------------------------------------
108新增:if already_sourced; then
109新增: ok "agent-vm.sh is already sourced by your shell — nothing to add"
110新增:else
111新增: RC="$(rc_file)"
112新增: printf 'Also define agent-vm as a shell function in %s? [Y/n] ' "$RC"
113新增: reply=''
114新增: # Test the terminal before redirecting from it: `< /dev/tty` on a machine
115新增: # without one (CI, a pipe) fails loudly before any `||` can catch it.
116新增: if [ -r /dev/tty ]; then
117新增: IFS= read -r reply </dev/tty || reply='n'
118新增: else
119新增: reply='n'
120新增: printf '(no terminal — skipping)\n'
121新增: fi
122新增: case "${reply:-Y}" in
123新增: [Nn]*)
124新增: ok "Skipped. The command on your PATH is enough for everyday use." ;;
125新增: *)
126新增: printf '\n# agent-vm\nsource "%s"\n' "$SCRIPT" >> "$RC"
127新增: ok "added the source line to $RC (effective in a new terminal)" ;;
128新增: esac
129新增:fi
130新增:
131新增:echo
132新增:ok "agent-vm $("$SCRIPT" version) installed."
133新增:echo " Next: agent-vm setup # build the base VM (once)"
134新增:echo " agent-vm help"
新增test.sh+443 −0看文件
@@ -0,0 +1,443 @@
1新增:#!/usr/bin/env bash
2新增:#
3新增:# agent-vm test suite.
4新增:#
5新增:# ./test.sh
6新增:#
7新增:# Runs against a stub limactl in a throwaway HOME, so it never creates, starts
8新增:# or deletes a VM and never touches your real ~/.agent-vm. No network needed.
9新增:#
10新增:# Scope: the pure logic and the machine-readable surface — VM naming, list
11新增:# matching, resource comparison, staleness, `info`/`version`/`name`, the
12新增:# --preinstall parser, and the MCP config writer. Anything that genuinely needs
13新增:# Lima is out of scope here.
14新增:#
15新增:# Also worth running under bash 3.2 (what macOS ships), which is stricter about
16新增:# empty array expansion under `set -u`:
17新增:# docker run --rm -v "$PWD:/w" -w /w bash:3.2 ./test.sh
18新增:
19新增:set -uo pipefail
20新增:
21新增:SELF_DIR="$(CDPATH= cd -- "$(dirname "${BASH_SOURCE[0]:-$0}")" >/dev/null && pwd)"
22新增:AGENT_VM_SH="${AGENT_VM_SH:-$SELF_DIR/agent-vm.sh}"
23新增:SETUP_SH="${SETUP_SH:-$SELF_DIR/agent-vm.setup.sh}"
24新增:
25新增:FAIL=0
26新增:PASSED=0
27新增:pass() { PASSED=$((PASSED + 1)); printf ' ok %s\n' "$1"; }
28新增:fail() { FAIL=$((FAIL + 1)); printf ' FAIL %s\n' "$1"; }
29新增:check() {
30新增: if [ "$2" = "$3" ]; then pass "$1"
31新增: else fail "$1"; printf ' expected: %s\n actual: %s\n' "$3" "$2"; fi
32新增:}
33新增:section() { printf '\n%s\n' "$1"; }
34新增:
35新增:SB="$(mktemp -d)"
36新增:trap 'rm -rf "$SB"' EXIT
37新增:export HOME="$SB/home"
38新增:# A real directory: `name` and `info` resolve their argument and reject a
39新增:# path that does not exist, so the tests cannot use a made-up one.
40新增:PROJ="$SB/proj"
41新增:mkdir -p "$HOME" "$SB/bin" "$PROJ"
42新增:
43新增:# --- stubs --------------------------------------------------------------------
44新增:# One base VM plus one project VM, running, 4 CPUs / 8 GiB / 32 GiB.
45新增:# `shell` dumps stdin so we can assert on what setup pipes into the VM.
46新增:cat > "$SB/bin/limactl" <<'STUB'
47新增:#!/usr/bin/env bash
48新增:case "$1" in
49新增: list)
50新增: case "$*" in
51新增: *"{{.Name}}|{{.CPUs}}|{{.Memory}}|{{.Disk}}"*)
52新增: echo "agent-vm-base|4|8589934592|34359738368"
53新增: echo "agent-vm-proj-deadbeef|4|8589934592|34359738368" ;;
54新增: *"{{.Name}} {{.Status}}"*)
55新增: echo "agent-vm-base Stopped"
56新增: echo "agent-vm-proj-deadbeef Running" ;;
57新增: *-q*)
58新增: echo "agent-vm-base"
59新增: echo "agent-vm-proj-deadbeef" ;;
60新增: esac ;;
61新增: shell) cat > "${AGENT_VM_TEST_CAPTURE:-/dev/null}" ;;
62新增: *) : ;;
63新增:esac
64新增:exit 0
65新增:STUB
66新增:chmod +x "$SB/bin/limactl"
67新增:
68新增:# Minimal images (and some Linux hosts) have no shasum; _agent_vm_name needs one.
69新增:if ! command -v shasum >/dev/null 2>&1; then
70新增: cat > "$SB/bin/shasum" <<'STUB'
71新增:#!/usr/bin/env bash
72新增:if command -v sha256sum >/dev/null 2>&1; then sha256sum | cut -d' ' -f1
73新增:else echo "0000000000000000"; fi
74新增:STUB
75新增: chmod +x "$SB/bin/shasum"
76新增:fi
77新增:export PATH="$SB/bin:$PATH"
78新增:
79新增:# shellcheck source=./agent-vm.sh
80新增:source "$AGENT_VM_SH"
81新增:
82新增:# The machine running the tests has no /dev/kvm; that check is not under test.
83新增:_agent_vm_check_linux_prereqs() { return 0; }
84新增:
85新增:printf 'agent-vm test suite (sandbox: %s)\n' "$SB"
86新增:
87新增:# =============================================================================
88新增:section "sourcing under a strict caller"
89新增:# =============================================================================
90新增:# agent-vm is meant to be sourced by other tools. Empty array expansion under
91新增:# `set -u` is an error on bash 3.2, and `cmd | grep -q` under `pipefail` can
92新增:# fail from a SIGPIPE race — both would show up here.
93新增:( set -u; set -o pipefail
94新增: _agent_vm_exists agent-vm-base >/dev/null
95新增: _agent_vm_running agent-vm-proj-deadbeef >/dev/null
96新增: _agent_vm_base_exists >/dev/null
97新增: agent-vm version >/dev/null
98新增: agent-vm info "$PROJ" >/dev/null
99新增:) 2>"$SB/strict.err"
100新增:if [ -s "$SB/strict.err" ]; then
101新增: fail "no diagnostics under set -u / pipefail"; sed 's/^/ /' "$SB/strict.err"
102新增:else
103新增: pass "no diagnostics under set -u / pipefail"
104新增:fi
105新增:
106新增:# =============================================================================
107新增:section "VM naming"
108新增:# =============================================================================
109新增:n1="$(_agent_vm_name /tmp/some-project)"
110新增:n2="$(_agent_vm_name /tmp/some-project)"
111新增:check "deterministic for the same directory" "$n1" "$n2"
112新增:if [ "$(_agent_vm_name /tmp/a)" != "$(_agent_vm_name /tmp/b)" ]; then
113新增: pass "different directories get different names"
114新增:else
115新增: fail "different directories collide"
116新增:fi
117新增:case "$(_agent_vm_name /tmp/some-project)" in
118新增: agent-vm-some-project-*) pass "name carries the directory basename" ;;
119新增: *) fail "unexpected name shape: $(_agent_vm_name /tmp/some-project)" ;;
120新增:esac
121新增:case "$(_agent_vm_name '/tmp/Weird Name!')" in
122新增: *[!a-zA-Z0-9-]*) fail "name not sanitised: $(_agent_vm_name '/tmp/Weird Name!')" ;;
123新增: *) pass "odd characters are sanitised out of the name" ;;
124新增:esac
125新增:
126新增:# =============================================================================
127新增:section "exact line matching (no pipe into grep -q)"
128新增:# =============================================================================
129新增:if _agent_vm_has_line "$(printf 'alpha\nbeta\n')" beta; then pass "finds an exact line"
130新增:else fail "missed an exact line"; fi
131新增:if _agent_vm_has_line "$(printf 'alphabet\n')" alpha; then fail "matched a prefix"
132新增:else pass "does not match a prefix"; fi
133新增:if _agent_vm_has_line "" alpha; then fail "matched in empty input"
134新增:else pass "no match in empty input"; fi
135新增:
136新增:# =============================================================================
137新增:section "resource comparison (only prompt on a real change)"
138新增:# =============================================================================
139新增:VM=agent-vm-proj-deadbeef
140新增:check "reads current resources" "$(_agent_vm_resources "$VM")" "4|8|32"
141新增:if _agent_vm_resources_differ "$VM" 4 8 32; then
142新增: fail "identical request (4/8/32) seen as a change"
143新增:else
144新增: pass "identical request (4/8/32) is not a change"
145新增:fi
146新增:_agent_vm_resources_differ "$VM" 8 8 32 && pass "cpus 4->8 detected" || fail "cpus 4->8 missed"
147新增:_agent_vm_resources_differ "$VM" 4 16 32 && pass "memory 8->16 detected" || fail "memory 8->16 missed"
148新增:_agent_vm_resources_differ "$VM" 4 8 64 && pass "disk grow 32->64 detected" || fail "disk grow missed"
149新增:if _agent_vm_resources_differ "$VM" 4 8 10; then
150新增: fail "disk shrink 32->10 treated as a change (Lima cannot shrink)"
151新增:else
152新增: pass "disk shrink 32->10 ignored (Lima cannot shrink)"
153新增:fi
154新增:if _agent_vm_resources_differ "$VM" "" "" ""; then
155新增: fail "empty request seen as a change"
156新增:else
157新增: pass "empty request is not a change"
158新增:fi
159新增:_agent_vm_resources_differ agent-vm-unknown 4 8 32 \
160新增: && pass "unknown VM does not claim 'no change'" \
161新增: || fail "unknown VM treated as identical"
162新增:
163新增:# =============================================================================
164新增:section "staleness (never guess from a missing file)"
165新增:# =============================================================================
166新增:mkdir -p "$HOME/.agent-vm"
167新增:check "no markers at all -> unknown" "$(_agent_vm_stale_state vmx)" "unknown"
168新增:echo 111 > "$HOME/.agent-vm/.agent-vm-base-version"
169新增:check "base known, VM unmarked -> stale" "$(_agent_vm_stale_state vmx)" "1"
170新增:echo 111 > "$HOME/.agent-vm/.agent-vm-version-vmx"
171新增:check "same version -> up to date" "$(_agent_vm_stale_state vmx)" "0"
172新增:echo 222 > "$HOME/.agent-vm/.agent-vm-base-version"
173新增:check "base newer -> stale" "$(_agent_vm_stale_state vmx)" "1"
174新增:rm -f "$HOME/.agent-vm/.agent-vm-base-version" "$HOME/.agent-vm/.agent-vm-version-vmx"
175新增:
176新增:# =============================================================================
177新增:section "machine-readable surface"
178新增:# =============================================================================
179新增:check "version" "$(agent-vm version)" "$AGENT_VM_VERSION"
180新增:check "--version" "$(agent-vm --version)" "$AGENT_VM_VERSION"
181新增:check "name matches the internal helper" "$(agent-vm name "$PROJ")" "$(_agent_vm_name "$PROJ")"
182新增:
183新增:info_out="$(agent-vm info "$PROJ")"
184新增:get() { printf '%s\n' "$info_out" | grep "^$1=" | cut -d= -f2-; }
185新增:check "info: version" "$(get version)" "$AGENT_VM_VERSION"
186新增:check "info: template" "$(get template)" "agent-vm-base"
187新增:check "info: dir" "$(get dir)" "$PROJ"
188新增:check "info: base_exists" "$(get base_exists)" "1"
189新增:check "info: vm_exists" "$(get vm_exists)" "0"
190新增:check "info: vm_stale unknown with no VM" "$(get vm_stale)" "unknown"
191新增:check "info: key count" "$(printf '%s\n' "$info_out" | grep -c '^[a-z_]*=')" "9"
192新增:
193新增:# Every key must be present even with no Lima on the box. Build a PATH with the
194新增:# limactl-bearing directories dropped rather than a hardcoded one, so this also
195新增:# holds on a machine where Lima is genuinely installed.
196新增:# Peel one entry per iteration instead of `for d in $PATH` with IFS=: — zsh does
197新增:# not word-split unquoted expansions, so that form would hand back the whole
198新增:# PATH as a single word and quietly keep the stub limactl visible.
199新增:nolima_path=""
200新增:_rest="$PATH:"
201新增:while [ -n "$_rest" ]; do
202新增: _d="${_rest%%:*}"
203新增: _rest="${_rest#*:}"
204新增: [ -z "$_d" ] && continue
205新增: [ -x "$_d/limactl" ] && continue
206新增: nolima_path="${nolima_path:+$nolima_path:}$_d"
207新增:done
208新增:nolima="$(PATH="$nolima_path" bash -c 'source "$1"; agent-vm info "$2"' _ "$AGENT_VM_SH" "$PROJ" 2>/dev/null)"
209新增:check "info without limactl still prints 9 keys" \
210新增: "$(printf '%s\n' "$nolima" | grep -c '^[a-z_]*=')" "9"
211新增:case "$nolima" in
212新增: *"base_exists=unknown"*) pass "info without limactl says unknown, not 0" ;;
213新增: *) fail "info without limactl should report unknown" ;;
214新增:esac
215新增:
216新增:# =============================================================================
217新增:section "directory arguments are normalised"
218新增:# =============================================================================
219新增:# The VM name is a hash of the directory STRING, and the VM-running commands
220新增:# always feed it `$(pwd)`. Without normalising, `name /tmp` and `name /tmp/`
221新增:# would be two different VMs for one directory, and neither need match what
222新增:# `cd /tmp && agent-vm opencode` produces.
223新增:canon="$(agent-vm name "$PROJ")"
224新增:check "trailing slash agrees" "$(agent-vm name "$PROJ/")" "$canon"
225新增:check "relative path agrees" "$(cd "$PROJ" && agent-vm name .)" "$canon"
226新增:check "no argument means cwd" "$(cd "$PROJ" && agent-vm name)" "$canon"
227新增:check "info agrees with name" "$(agent-vm info "$PROJ/" | grep '^vm_name=' | cut -d= -f2)" "$canon"
228新增:if agent-vm name "$SB/does-not-exist" >/dev/null 2>&1; then
229新增: fail "a nonexistent directory should be rejected, not hashed"
230新增:else
231新增: pass "a nonexistent directory is rejected"
232新增:fi
233新增:
234新增:# CDPATH must not leak into the resolution. With it set, `cd <relative>` searches
235新增:# it before the current directory AND prints where it landed — so an unprotected
236新增:# `cd "$dir" && pwd` both emits a stray line and resolves a different directory
237新增:# than the `-d` test validated. Two decoys with the same basename make the
238新增:# difference observable.
239新增:mkdir -p "$SB/decoy/twin" "$SB/real/twin"
240新增:check "CDPATH does not redirect the lookup" \
241新增: "$(cd "$SB/real" && CDPATH="$SB/decoy" agent-vm name twin)" \
242新增: "$(agent-vm name "$SB/real/twin")"
243新增:
244新增:# Stray `cd` output has to be observed on `info`, not on `name`: the name is run
245新增:# through `tr -cs 'a-zA-Z0-9' '-'`, which would quietly turn the extra newline
246新增:# into a dash. `info` prints the resolved path raw, so a leaked line shows up as
247新增:# a tenth line among the nine key=value pairs.
248新增:check "no stray cd output leaks into info" \
249新增: "$(cd "$SB/real" && CDPATH="$SB/decoy" agent-vm info twin | wc -l | tr -d ' ')" "9"
250新增:
251新增:# =============================================================================
252新增:section "--preinstall parsing"
253新增:# =============================================================================
254新增:preinstall_exports() {
255新增: export AGENT_VM_TEST_CAPTURE="$SB/piped.sh"
256新增: : > "$AGENT_VM_TEST_CAPTURE"
257新增: _agent_vm_setup --preinstall="$1" >/dev/null 2>&1
258新增: grep -E "^export AGENT_VM_INSTALL_$2=" "$AGENT_VM_TEST_CAPTURE" | cut -d= -f2
259新增:}
260新增:check "default: node on" "$(preinstall_exports default NODE)" "1"
261新增:check "default: ruby off" "$(preinstall_exports default RUBY)" "0"
262新增:check "all: ruby on" "$(preinstall_exports all RUBY)" "1"
263新增:check "none: node off" "$(preinstall_exports none NODE)" "0"
264新增:check "explicit subset: gh on" "$(preinstall_exports node,gh GH)" "1"
265新增:check "explicit subset: docker off" "$(preinstall_exports node,gh DOCKER)" "0"
266新增:
267新增:section "--preinstall: MCP names"
268新增:check "default wires the chrome MCP" "$(preinstall_exports default MCP_CHROME)" "1"
269新增:check "default leaves playwright out" "$(preinstall_exports default MCP_PLAYWRIGHT)" "0"
270新增:check "all wires both" "$(preinstall_exports all MCP_CHROME)" "1"
271新增:check "all wires playwright too" "$(preinstall_exports all MCP_PLAYWRIGHT)" "1"
272新增:# The point of the mcp-* names: a caller that manages MCP servers per project
273新增:# just omits them. Nothing new has to be passed, so older builds stay compatible.
274新增:check "omitting mcp-chrome disables it" "$(preinstall_exports node,gh,chromium,opencode MCP_CHROME)" "0"
275新增:check "naming mcp-chrome enables it" "$(preinstall_exports node,chromium,opencode,mcp-chrome MCP_CHROME)" "1"
276新增:check "naming mcp-playwright enables it" "$(preinstall_exports node,chromium,opencode,mcp-playwright MCP_PLAYWRIGHT)" "1"
277新增:
278新增:if _agent_vm_setup --preinstall=node,not-a-real-name >/dev/null 2>&1; then
279新增: fail "an unknown --preinstall name should be fatal"
280新增:else
281新增: pass "an unknown --preinstall name is fatal"
282新增:fi
283新增:
284新增:# =============================================================================
285新增:section "script dir resolves through symlinks"
286新增:# =============================================================================
287新增:# install.sh puts a symlink on PATH. Without following it, AGENT_VM_SCRIPT_DIR
288新增:# points at the link's directory and `agent-vm setup` cannot find
289新增:# agent-vm.setup.sh, which lives next to the real file.
290新增:REALDIR="$(CDPATH= cd -P -- "$(dirname "$AGENT_VM_SH")" >/dev/null && pwd)"
291新增:mkdir -p "$SB/link1" "$SB/link2"
292新增:ln -sf "$AGENT_VM_SH" "$SB/link1/agent-vm"
293新增:ln -sf "$SB/link1/agent-vm" "$SB/link2/agent-vm"
294新增:# Paths go in as positional parameters: interpolating them into single-quoted
295新增:# shell text would break on a path containing a single quote.
296新增:script_dir_of() {
297新增: bash -c 'source "$1" 2>/dev/null; printf "%s" "$AGENT_VM_SCRIPT_DIR"' _ "$1"
298新增:}
299新增:check "direct symlink" "$(script_dir_of "$SB/link1/agent-vm")" "$REALDIR"
300新增:check "chain of two symlinks" "$(script_dir_of "$SB/link2/agent-vm")" "$REALDIR"
301新增:check "no symlink (the historical sourcing)" "$(script_dir_of "$AGENT_VM_SH")" "$REALDIR"
302新增:
303新增:# =============================================================================
304新增:section "env: the shared secrets file"
305新增:# =============================================================================
306新增:# This file is SOURCED by the VM's shell, so one bad escape costs every secret
307新增:# in it — not just the one that was mis-quoted. That is why the quoting lives
308新增:# here rather than in each integrator.
309新增:ENVHOME="$SB/envhome"; mkdir -p "$ENVHOME"
310新增:avenv() { HOME="$ENVHOME" bash "$AGENT_VM_SH" env "$@"; }
311新增:
312新增:avenv set ALBERT_API_KEY "k1" >/dev/null
313新增:avenv set AC_GIT_USER_NAME "O'Brien" >/dev/null
314新增:check "get returns the value" "$(avenv get ALBERT_API_KEY)" "k1"
315新增:check "a single quote survives" "$(avenv get AC_GIT_USER_NAME)" "O'Brien"
316新增:avenv set ALBERT_API_KEY "k2" >/dev/null
317新增:check "rotation replaces, not appends" "$(grep -c '^ALBERT_API_KEY=' "$ENVHOME/.agent-vm/env")" "1"
318新增:check "rotation keeps the fresh value" "$(avenv get ALBERT_API_KEY)" "k2"
319新增:check "the quoted entry still reads back" "$(avenv get AC_GIT_USER_NAME)" "O'Brien"
320新增:
321新增:printf 'SOMEONE_ELSE=keep-me\n' >> "$ENVHOME/.agent-vm/env"
322新增:avenv set ALBERT_API_KEY "k3" >/dev/null
323新增:check "unmanaged lines are preserved" "$(grep -c '^SOMEONE_ELSE=keep-me$' "$ENVHOME/.agent-vm/env")" "1"
324新增:
325新增:avenv has ALBERT_API_KEY && pass "has: present key" || fail "has: present key"
326新增:avenv has NOPE_NOT_HERE && fail "has: absent key" || pass "has: absent key"
327新增:
328新增:# `has`/`get` must answer about the FILE. The subshell inherits this shell's
329新增:# environment, so without unsetting first, a merely-exported variable reads as
330新增:# stored — and agent-vm's own callers often run inside a VM that exports these.
331新增:if HOME="$ENVHOME" AMBIENT_ONLY=x bash "$AGENT_VM_SH" env has AMBIENT_ONLY; then
332新增: fail "has must ignore the ambient environment"
333新增:else
334新增: pass "has ignores the ambient environment"
335新增:fi
336新增:
337新增:check "list prints names only" "$(avenv list | sort | tr '\n' ' ')" "AC_GIT_USER_NAME ALBERT_API_KEY SOMEONE_ELSE "
338新增:if avenv list | grep -q "O'Brien\|k3"; then fail "list must never print values"; else pass "list never prints values"; fi
339新增:
340新增:avenv unset ALBERT_API_KEY >/dev/null
341新增:avenv has ALBERT_API_KEY && fail "unset removed the key" || pass "unset removes the key"
342新增:check "unset keeps the others" "$(grep -c '^SOMEONE_ELSE=' "$ENVHOME/.agent-vm/env")" "1"
343新增:check "file is mode 600" "$(ls -l "$ENVHOME/.agent-vm/env" | cut -c2-10)" "rw-------"
344新增:
345新增:if avenv set "not-a-name" x >/dev/null 2>&1; then
346新增: fail "an invalid variable name must be rejected"
347新增:else
348新增: pass "an invalid variable name is rejected"
349新增:fi
350新增:
351新增:# The file has to survive being sourced the way the VM sources it.
352新增:val="$(set -a; . "$ENVHOME/.agent-vm/env"; set +a; printf '%s' "${AC_GIT_USER_NAME:-BROKEN}")"
353新增:check "the file sources cleanly in a shell" "$val" "O'Brien"
354新增:
355新增:# =============================================================================
356新增:section "release hygiene"
357新增:# =============================================================================
358新增:# Every dispatched command must appear in `help`: a command nobody can discover
359新增:# is a command nobody uses. (`sh`/`destroy` are aliases documented inline.)
360新增:help_text="$(agent-vm help)"
361新增:missing=""
362新增:for verb in setup claude opencode codex vibe shell run stop rm destroy-all \
363新增: list status name info env version help; do
364新增: case "$help_text" in
365新增: *" $verb"*) ;;
366新增: *) missing="$missing $verb" ;;
367新增: esac
368新增:done
369新增:# One verdict, not a pass that fires whatever the loop found.
370新增:if [ -n "$missing" ]; then
371新增: fail "dispatched but missing from help:$missing"
372新增:else
373新增: pass "every dispatched command appears in help"
374新增:fi
375新增:check "the version in help output matches the constant" \
376新增: "$(agent-vm version)" "$AGENT_VM_VERSION"
377新增:
378新增:# A bad resource value must produce an actionable message, not a raw bash
379新增:# arithmetic diagnostic leaking from the comparison helper.
380新增:bad="$( (agent-vm --disk 10G version) 2>&1 )" || true
381新增:case "$bad" in
382新增: *"must be a positive integer"*) pass "a non-numeric --disk is rejected clearly" ;;
383新增: *"value too great for base"*) fail "raw bash arithmetic error leaked: $bad" ;;
384新增: *) fail "unexpected output for --disk 10G: $bad" ;;
385新增:esac
386新增:check "a valid resource value still passes" "$(agent-vm --disk 32 --cpus 4 version)" "$AGENT_VM_VERSION"
387新增:
388新增:# A failed write of the secrets file must not be reported as success: a caller
389新增:# told the secret was stored when it was not is the worst outcome for this file.
390新增:# Root ignores permission bits, so the condition cannot be staged as root —
391新增:# which is exactly what the bash 3.2 container runs as.
392新增:if [ "$(id -u)" -eq 0 ]; then
393新增: printf ' skip env-set-failure test (running as root: permission bits do not apply)\n'
394新增:else
395新增: RO="$SB/readonly-home"
396新增: mkdir -p "$RO/.agent-vm"
397新增: printf "K='v'\n" > "$RO/.agent-vm/env"
398新增: chmod 500 "$RO/.agent-vm"
399新增: if HOME="$RO" bash "$AGENT_VM_SH" env set OTHER x >/dev/null 2>&1; then
400新增: fail "env set reported success on an unwritable directory"
401新增: else
402新增: pass "env set fails loudly when the write cannot happen"
403新增: fi
404新增: chmod 700 "$RO/.agent-vm"
405新增:fi
406新增:
407新增:# =============================================================================
408新增:section "MCP config writer"
409新增:# =============================================================================
410新增:# configure_mcp lives in the in-VM setup script, whose top level performs the
411新增:# actual installs — so lift just that function out rather than sourcing it.
412新增:if ! command -v jq >/dev/null 2>&1; then
413新增: printf ' skip configure_mcp tests (jq not installed)\n'
414新增:else
415新增: MCPHOME="$SB/mcp"; mkdir -p "$MCPHOME"
416新增: (
417新增: HOME="$MCPHOME"
418新增: eval "$(awk '/^configure_mcp\(\) \{/,/^\}/' "$SETUP_SH")"
419新增: INSTALL_CLAUDE=1 INSTALL_OPENCODE=1 INSTALL_VIBE=1 INSTALL_CODEX=1
420新增: for _ in 1 2; do # twice: the writer must be idempotent
421新增: configure_mcp chrome-devtools npx -y chrome-devtools-mcp@latest --headless=true
422新增: configure_mcp playwright env PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npx -y @playwright/mcp@latest
423新增: done
424新增: ) >/dev/null 2>&1
425新增:
426新增: oc="$MCPHOME/.config/opencode/opencode.json"
427新增: check "opencode: two servers" "$(jq '.mcp | length' "$oc")" "2"
428新增: check "opencode: \$schema kept" "$(jq -r '."$schema"' "$oc")" "https://opencode.ai/config.json"
429新增: check "opencode: command starts with the launcher" \
430新增: "$(jq -r '.mcp.playwright.command[0]' "$oc")" "env"
431新增: check "opencode: env assignment survives as its own argv entry" \
432新增: "$(jq -r '.mcp.playwright.command[1]' "$oc")" "PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1"
433新增: check "claude: two servers" \
434新增: "$(jq '.mcpServers | length' "$MCPHOME/.claude.json")" "2"
435新增: check "codex: no duplicate table after two runs" \
436新增: "$(grep -cF '[mcp_servers.playwright]' "$MCPHOME/.codex/config.toml")" "1"
437新增: check "vibe: no duplicate entry after two runs" \
438新增: "$(grep -c '^\[\[mcp_servers\]\]' "$MCPHOME/.vibe/config.toml")" "2"
439新增:fi
440新增:
441新增:# =============================================================================
442新增:printf '\n%s passed, %s failed\n' "$PASSED" "$FAIL"
443新增:[ "$FAIL" -eq 0 ] || exit 1