跳到主要内容

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

提交记录

0.2.0 release: large rewrite, .git protection, host-enforced --readonly, --scratch, Windows exp support

Security - Every .git and .hg in the shares is read-only for the VM (Lima sshfs.readonlyNames, enforced on the host), plus the in-project core.hooksPath folder. - Before a VM boots with writable shares, agent-vm stops on each risk it cannot remove (no readonlyNames, unconfined reverse-sshfs, hooks, git config) and asks; no terminal means no. --unsafe-disable-security- prompts and `info` security_questions= for integrators. - --readonly is enforced on the host, covers every share, applies before the first boot, and is refused where Lima cannot enforce it. - The project's runtime and env files are read by the VM, not followed on the host; home, /, and agent-vm's or Lima's directories are refused as projects. Added - --scratch: a throwaway VM with nothing of yours mounted. - Windows (Git Bash + QEMU), experimental; WSL hints. - curl installer, `agent-vm install/uninstall`, `doctor`, `version --min`, `project-env`, --ssh-port, Pi, per-project and relative entries in ~/.agent-vm/volumes, BASE column in `list`. - test-e2e.sh against a real VM. Changed - Code split into lib/; options parsed the same before and after the command; --cpus/--memory clamped to half the host. - Sourced by zsh, agent-vm.sh only defines a function that runs it with bash. - Smaller base VM, quieter setup, runtime scripts run under their shebang's shell. Removed - --offline and --git-read-only (both enforced in the guest only). Fixes #25. Fixes #26. Fixes #30. Fixes #21. Fixes #22. Fixes #28. Fixes #20. Closes #11. And many others, see CHANGELOG.md.

作者
Sylvain Zimmer
时间
2026/10/01 21:53
提交
569257b
上一个
09b2536
这个版本的全部文件
新增.gitattributes+10 −0看文件
@@ -0,0 +1,10 @@
1新增:# Shell scripts must keep LF endings everywhere: a CRLF checkout on
2新增:# Windows breaks bash, including the test suite on the windows-latest runner.
3新增:*.sh text eol=lf
4新增:
5新增:# Left out of the release tarball (release.sh builds it with git archive):
6新增:# the site and the tests are not what an install runs.
7新增:/www export-ignore
8新增:/tests export-ignore
9新增:/test.sh export-ignore
10新增:/test-e2e.sh export-ignore
修改.github/workflows/test.yml+42 −8看文件
@@ -4,33 +4,67 @@ on:
44 push:
55 pull_request:
66
7新增:# Both jobs only read the repository.
8新增:permissions:
9新增: contents: read
10新增:
711jobs:
812 test:
913 runs-on: ubuntu-latest
1014 steps:
11删除: - uses: actions/checkout@v4
15新增: - uses: actions/checkout@v7
1216 with:
1317 # The steps below run test.sh from the PR branch. Leaving the checkout
1418 # token in .git/config would put it within reach of that code.
1519 persist-credentials: false
1620
21新增: # For the tests of the zsh shim (tests/03-install.sh).
22新增: - name: Install zsh
23新增: run: sudo apt-get update && sudo apt-get install -y zsh
24新增:
1725 - name: Syntax check
1826 run: |
19删除: for f in agent-vm.sh agent-vm.setup.sh runtime.example.sh test.sh; do
27新增: for f in agent-vm.sh lib/*.sh agent-vm.setup.sh runtime.example.sh test.sh tests/*.sh test-e2e.sh install.sh release.sh; do
2028 echo "bash -n $f"
2129 bash -n "$f"
2230 done
31新增: # Served as `curl | sh`: plain sh, not bash.
32新增: echo "sh -n www/public/install.sh"
33新增: sh -n www/public/install.sh
2334
2435 - name: Test suite
2536 run: ./test.sh
2637
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`.
38新增: # macOS still ships bash 3.2, which errors on empty array expansion
39新增: # under `set -u`.
2940 # Modern bash does not, so a 3.2 run is the only way to catch it in CI.
41新增: # With perl, which macOS ships too: project-env needs it.
3042 - 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
43新增: run: docker run --rm -v "$PWD:/w" -w /w bash:3.2 sh -c 'apk add --no-cache perl >/dev/null && ./test.sh'
44新增:
45新增: # Windows coverage: the stub suite under Git Bash, which is how agent-vm
46新增: # runs there. No docker (bash 3.2) on a Windows runner, and no
47新增: # real VM anywhere in this workflow (test-e2e.sh stays manual, on every OS).
48新增: test-windows:
49新增: runs-on: windows-latest
50新增: defaults:
51新增: run:
52新增: shell: bash
53新增: steps:
54新增: - uses: actions/checkout@v7
55新增: with:
56新增: # Same reason as above: test.sh runs code from the PR branch.
57新增: persist-credentials: false
3258
33删除: - name: Test suite under zsh (the usual way it is sourced)
59新增: - name: Syntax check
3460 run: |
35删除: sudo apt-get update && sudo apt-get install -y zsh
36删除: zsh ./test.sh
61新增: for f in agent-vm.sh lib/*.sh agent-vm.setup.sh runtime.example.sh test.sh tests/*.sh test-e2e.sh install.sh release.sh; do
62新增: echo "bash -n $f"
63新增: bash -n "$f"
64新增: done
65新增: # Served as `curl | sh`: plain sh, not bash.
66新增: echo "sh -n www/public/install.sh"
67新增: sh -n www/public/install.sh
68新增:
69新增: - name: Test suite (Git Bash, stub limactl)
70新增: run: ./test.sh
新增.github/workflows/www.yml+77 −0看文件
@@ -0,0 +1,77 @@
1新增:name: www
2新增:
3新增:on:
4新增: push:
5新增: # 0.2.0 publishes until it is merged: remove it then, and from the
6新增: # github-pages environment's deployment branches.
7新增: branches: [main, 0.2.0]
8新增: paths:
9新增: - 'www/**'
10新增: - '.github/workflows/www.yml'
11新增: pull_request:
12新增: paths:
13新增: - 'www/**'
14新增: - '.github/workflows/www.yml'
15新增: # So a broken deploy can be re-run without an empty commit.
16新增: workflow_dispatch:
17新增:
18新增:permissions:
19新增: contents: read
20新增:
21新增:jobs:
22新增: build:
23新增: runs-on: ubuntu-latest
24新增: defaults:
25新增: run:
26新增: working-directory: www
27新增: steps:
28新增: - uses: actions/checkout@v7
29新增: with:
30新增: persist-credentials: false
31新增:
32新增: - uses: actions/setup-node@v7
33新增: with:
34新增: node-version: 24
35新增: cache: npm
36新增: cache-dependency-path: www/package-lock.json
37新增:
38新增: - name: Install
39新增: run: npm ci
40新增:
41新增: # Catches a key that exists in en.ts but not in fr.ts, which would
42新增: # otherwise only show up as a blank spot on the French page.
43新增: - name: Type check
44新增: run: npm run check
45新增:
46新增: - name: Build
47新增: run: npm run build
48新增:
49新增: - name: Check the custom domain survived
50新增: # public/CNAME is what keeps www.agent-vm.org pointed here. Losing it
51新增: # does not fail the build, it just quietly serves the github.io URL.
52新增: run: test -f dist/CNAME
53新增:
54新增: - uses: actions/upload-pages-artifact@v5
55新增: with:
56新增: path: www/dist
57新增:
58新增: deploy:
59新增: # A pull request builds but does not publish.
60新增: if: github.event_name != 'pull_request'
61新增: needs: build
62新增: runs-on: ubuntu-latest
63新增: # On the deploy job only: at workflow level, a pull request build would
64新增: # share the group and replace a pending deploy. The in-progress deploy is
65新增: # never cancelled; a newer pending one replaces an older pending one.
66新增: concurrency:
67新增: group: pages
68新增: cancel-in-progress: false
69新增: permissions:
70新增: pages: write
71新增: id-token: write
72新增: environment:
73新增: name: github-pages
74新增: url: ${{ steps.deploy.outputs.page_url }}
75新增: steps:
76新增: - id: deploy
77新增: uses: actions/deploy-pages@v5
修改.gitignore+2 −0看文件
@@ -1,2 +1,4 @@
11.DS_Store
22.claude
3新增:node_modules
4新增:dist
新增CHANGELOG.md+374 −0看文件
@@ -0,0 +1,374 @@
1新增:# Changelog
2新增:
3新增:## 0.2.0
4新增:
5新增:### Security
6新增:
7新增:- The host no longer reads the project's `.agent-vm.runtime.sh` by its
8新增: path. The VM can write the project and make it a symlink to any file of
9新增: yours: the host followed it on every start and handed the content to the
10新增: VM (`ln -s ~/.ssh/id_ed25519 .agent-vm.runtime.sh` got the key on the next
11新增: command). The VM now reads it itself, where a link only reaches the VM's
12新增: own files. The project's `.agent-vm.env`, new here, is read the same way,
13新增: and `project-env` refuses a file that is a link, or reached through one,
14新增: without a window the VM could race; it needs `perl` for that. Whether a
15新增: file is in the project is decided by where its path leads, not by how it
16新增: is spelled (the project's real path while it is used through a link). A
17新增: file kept outside the project with `AGENT_VM_PROJECT_ENV` or
18新增: `AGENT_VM_PROJECT_RUNTIME` is read on the host.
19新增:- The home directory, `/`, agent-vm's own directory, its state directory,
20新增: Lima's, any directory containing one of them, and any directory inside one
21新增: of the last three are refused as a project: `cd ~ && agent-vm shell`
22新增: shared `~/.ssh` and every dotfile read-write, and from inside agent-vm's
23新增: folder the VM could change the files the host runs next.
24新增:- `--readonly` on a stopped VM that last ran writable makes it read-only
25新增: before it boots. It used to start it writable, then stop it and apply the
26新增: change.
27新增:- Whether `--readonly` is enforced on the host is decided from what Lima
28新增: reports for the VM, not by asking the guest, which could lie.
29新增:- A `limactl stop` that did not stop the VM is caught before its shares are
30新增: changed.
31新增:- Every `.git` in the shared folders is read-only for the VMs, at any depth,
32新增: when Lima has `sshfs.readonlyNames`. Before, a VM could write a project's
33新增: `.git/config` or hooks, and git on the host (editors and shell prompts
34新增: included) would run what they name: commands on your machine. Lima's SFTP
35新增: server enforces it on the host, so root in the VM cannot lift it. The shares
36新增: then use `reverse-sshfs` with the builtin SFTP driver, and existing VMs
37新增: switch on their next start. A VM made by agent-vm 0.1.0, or cloned from a
38新增: base it built, has no `sshfs`: it boots once without shares to install it,
39新增: with a warning, before it gets them. Without it, Lima installed Debian's at
40新增: boot, which needs apt then and breaks symlinks (see #22 below). `doctor`
41新增: reports a base built by 0.1.0. This migration will be removed in a future
42新增: release: `setup`, then `--reset`. The field is not in upstream Lima yet
43新增: (lima-vm/lima#5529): `setup` checks for it, says what is at stake without
44新增: it, and offers to install `sylvinus/tap/lima-sylvinus` with Homebrew.
45新增: `doctor` reports it too. `--unsafe-writable-git`, or
46新增: `AGENT_VM_UNSAFE_WRITABLE_GIT=1` in the shell, turns it off, for those who
47新增: let the agent commit in the project, with a warning on every run.
48新增:- Every `.hg` is read-only as well: Mercurial runs the hooks of `.hg/hgrc`
49新增: in a repository you own. When git's `core.hooksPath` puts the hooks in the
50新增: project (husky sets `.husky/_`), the first folder of that path, from the
51新增: top of its repository, joins the names too, so the agent cannot change the
52新增: hooks git runs on your commits. The repository holding the project and
53新增: those up to two levels below it are checked, with git before 2.31 too. A
54新增: name that does not start with a dot would lock every folder of that name
55新增: in the project, so the start asks first (yes by default). Hooks at the top
56新增: of a repository cannot be protected by name. `doctor` reports all of it.
57新增:- Before a VM boots with writable shares, agent-vm stops on each risk it
58新增: cannot remove and asks whether to go on; Enter, or no terminal, aborts,
59新增: and nothing has changed. The risks: a Lima that cannot keep `.git`
60新增: read-only (on Windows, where the shares are then `reverse-sshfs`, the
61新增: rest of the disk is at stake, and the box says so); hooks that cannot be
62新增: protected, or a name declined; a git config file included from the
63新增: project, there yet or not, or a setting (`core.fsmonitor`, a
64新增: filter, a `!` alias...) whose command is a file in it; and
65新增: `safe.bareRepository=explicit` missing from the global git config, which
66新增: it offers to set, or ignored by a git older than 2.38. Without that
67新增: setting, a folder holding `HEAD`, `objects/`, `refs/` and a `config` is a
68新增: repository to git under any name, which `readonlyNames` does not cover,
69新增: and git on the host runs the commands its `config` names (`core.pager` as
70新增: soon as `git log` is typed there). A question is only asked when stderr is
71新增: a terminal too, so a caller capturing it gets "no" rather than a question
72新增: nobody sees. For a VM that already runs, the warnings are printed without
73新增: a question; one that lacks a protection it should have is offered a
74新增: restart, and continuing without it is the same kind of risk. A running VM
75新增: that is stopped to boot again (new resources, a protection, a repair) is
76新增: asked once stopped, as any VM about to boot. `--readonly` asks none of
77新增: these questions, and `--unsafe-writable-git` none about `.git`.
78新增: `--unsafe-disable-security-prompts`, or
79新增: `AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1` in the shell, goes on without
80新增: asking, and without offering to change the git config; the warnings are
81新增: still printed.
82新增:- A Lima whose answer to the `readonlyNames` probe cannot be read (a failing
83新增: `limactl validate`, a wording agent-vm does not know) stops the start with
84新增: an error, rather than being taken for a Lima without `readonlyNames`,
85新增: which would drop the protection of a stopped VM on its next start.
86新增:- The home directory and agent-vm's directories are refused as a project
87新增: whatever the case they are typed in, on macOS and Windows: Git Bash keeps
88新增: the spelling typed, so `cd /c/users/me` got past the check.
89新增:- `--readonly` is now set on the Lima shares, so the host refuses the writes
90新增: and root in the VM cannot lift it. It used to be a remount inside the
91新增: guest. Under `reverse-sshfs` without `readonlyNames`, where Lima only passes
92新增: the flag to the guest, agent-vm refuses `--readonly` instead of pretending.
93新增: Switching the mode of a running VM restarts it, asked first (no by
94新增: default): declined, or with no terminal, the command fails, in both
95新增: directions, so another session's `--readonly` VM is not made writable
96新增: under it.
97新增:- `--readonly` is refused on virtiofs under QEMU, where Lima's virtiofsd has no
98新增: read-only mode and the flag only reaches the guest. It was accepted there as
99新增: enforced on the host. 9p, QEMU's default, and virtiofs on `vz` are enforced.
100新增:- `--readonly` covers every share, `rw` entries of `~/.agent-vm/volumes`
101新增: included. Read-only is enforced per share, so a writable volume containing
102新增: the project was a second way to write it.
103新增:- `agent-vm env get/has` read the file instead of sourcing it, as the new
104新增: `project-env get/has` do: the project env file sits in a directory the VM
105新增: can write to. Values that need a shell to be interpreted are refused with
106新增: exit status 2, and so is every key once one line is: after an open quote,
107新增: a trailing backslash or a command, the shell reads the file differently
108新增: than it looks, and could assign any key.
109新增:- A project path containing a quote, a backslash or a control character is
110新增: refused. It was spliced into the Lima mount config and could add mounts of
111新增: its own (the home directory, read-write).
112新增:- Declining to stop a running VM for a `--disk`, `--memory`, `--cpus` or
113新增: `--ssh-port` change, or having no terminal to accept it on, no longer skips
114新增: the rest of the start: `--readonly` was then never applied and the command
115新增: ran on a writable VM. The VM now keeps its settings and everything else
116新增: applies.
117新增:
118新增:### Removed
119新增:
120新增:Both flags claimed a restriction they could not hold: inside the VM the agent
121新增:has passwordless sudo, so anything enforced there is advisory at best.
122新增:
123新增:- `--offline` set `iptables` rules in the guest; one
124新增: `sudo iptables -P OUTPUT ACCEPT` undid them. Blocking outbound traffic has to
125新增: happen on the host, and Lima exposes no setting for it: see
126新增: [the roadmap](https://www.agent-vm.org/#roadmap).
127新增:- `--git-read-only` bind-mounted `.git` read-only in the guest; one
128新增: `sudo umount` undid it. A nested read-only share over a writable parent is not
129新增: a boundary either, since unmounting the child exposes the same files through
130新增: the parent. Keep commits on the host and review the diff yourself.
131新增:- `iptables` is no longer in the base packages (Docker still pulls it in).
132新增:- `runtime.example.sh` no longer suggests copying an SSH private key into every
133新增: VM. Use a revocable `GH_TOKEN` in `~/.agent-vm/env`.
134新增:
135新增:### Changed
136新增:
137新增:- For scripts and tools that run agent-vm without a terminal: a start can
138新增: now stop on a security question (see Security above), with the reason on
139新增: stderr and a failing status. `agent-vm info` says beforehand what it would
140新增: stop on (`security_questions=`). Pass `--unsafe-disable-security-prompts`,
141新增: or set `AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1`, once the user has
142新增: agreed; or use `--readonly`.
143新增:- `agent-vm.sh` loads the rest of agent-vm from `lib/`, next to it, and stops
144新增: with the name of the missing file when it is not there: a copy of
145新增: `agent-vm.sh` on its own no longer works. Clones, the curl installer and
146新增: release tarballs have it.
147新增:- Sourced by zsh (the `~/.zshrc` line of the 0.1.0 installer), `agent-vm.sh`
148新增: only defines an `agent-vm` function that runs it with bash, like the
149新增: command on `PATH`: agent-vm no longer runs inside zsh, with its semantics
150新增: and your options. Its internal `_agent_vm_*` functions are no longer
151新增: defined there. Sourcing it from bash is unchanged.
152新增:- agent-vm's options are read the same way before the command and right after
153新增: its name: `agent-vm claude --disk=50` resizes the VM instead of passing
154新增: `--disk=50` to Claude, and `agent-vm claude --disk 10G` is refused with the
155新增: reason instead of failing later with a bash error.
156新增:- `--readonly` is applied before the runtime scripts run, not after. A
157新增: `~/.agent-vm/runtime.sh` or `.agent-vm.runtime.sh` that writes into the project
158新增: fails under the flag.
159新增:- VM options are only read before the command or right after its name:
160新增: `agent-vm run docker run --rm alpine` passes `--rm` to docker. It used to be
161新增: taken as agent-vm's own `--rm`, which deleted the VM afterwards.
162新增:- `destroy-all` says it deletes the base template too, and forgets it properly.
163新增:- `agent-vm setup` asks before installing Lima with Homebrew, offering the
164新增: build that keeps `.git` read-only first, and without a terminal prints the
165新增: command instead.
166新增:- The setup wizard is skipped when no terminal can be opened. It used to test
167新增: `-r /dev/tty`, which is true in CI too.
168新增:- `--cpus` and `--memory` are clamped to half the host (`AGENT_VM_HOST_SHARE`
169新增: changes the divisor), with a notice.
170新增:- Runtime scripts run under the shell their shebang names (bash, sh; zsh
171新增: otherwise).
172新增:- `agent-vm shell` rejects arguments it does not know instead of skipping them.
173新增:- `setup` rejects `--reset` and `--readonly` instead of ignoring them, and
174新增: the other commands that start no VM (`stop`, `status`, `env`…) reject
175新增: every VM option: `agent-vm --readonly stop` read as if something had been
176新增: made read-only.
177新增:- The wizard's per-component prompts default Ruby, Rust and Go to no, like
178新增: the default set.
179新增:- The base VM is about 300 MB smaller and runs fewer daemons: apt no longer
180新增: installs Recommends. Those brought in, through Chromium, printer
181新增: configuration, Samba libraries, `avahi-daemon`, `upower` and Vulkan
182新增: drivers. The recommended packages that are used (`docker-buildx-plugin`,
183新增: `xauth`, `python3-dev`...) are installed by name, as is `pkgconf`, which
184新增: mise builds use and which was only there with Go.
185新增:- Node.js comes from the NodeSource repository configured directly, instead
186新增: of running NodeSource's setup script as root, which also installed `gnupg`.
187新增:- `fonts-dejavu-core` is installed with Chromium. With Liberation alone, pages
188新增: asking for the generic `sans-serif` or `serif` rendered in Liberation Mono.
189新增:- The base VM is created without Lima's containerd. Its unit shadowed Docker's
190新增: `containerd.service`, and `docker` could not reach its daemon. Existing VMs
191新增: keep it until `agent-vm setup` and `--reset`.
192新增:- Every agent-vm command that uses a VM makes one `limactl shell` round trip
193新增: fewer: the env push and the check that the project share is writable share
194新增: one.
195新增:- `setup` shows the creation and first start of the base VM (which downloads
196新增: the Debian image) and the package install in a 10-line window that scrolls
197新增: in place and is cleared when done. The full output goes to
198新增: `~/.agent-vm/setup.log`, whose end is printed again if a step fails. Without
199新增: a terminal, the output is printed as before.
200新增:- `setup` opens on the wizard, agents first, and runs its security check
201新增: (`.git` protection) last, before creating the VM. Its warnings are
202新增: shorter, in a box fitted to the terminal, with the question right below.
203新增:
204新增:### Added
205新增:
206新增:- `--scratch`: a new VM with nothing of yours mounted, neither the project
207新增: nor `~/.agent-vm/volumes`, deleted when the command ends, Ctrl-C included.
208新增: On a terminal the deletion is asked first, yes by default: no opens a
209新增: shell in the VM, to look at what the command left, and leaving it asks
210新增: again. It has a name of its own (`agent-vm-<folder>-scratch-<random>`), so the
211新增: folder's VM is left alone and several can run at once. The project's env
212新增: file and runtime script stay out; `~/.agent-vm/env` and
213新增: `~/.agent-vm/runtime.sh` go in. Sharing nothing, it asks none of the
214新增: security questions and works on any Lima. A run killed outright leaves its
215新增: VM recorded, and the next `--scratch` run deletes it; `doctor` lists it
216新增: meanwhile.
217新增:- `agent-vm env set KEY` and `project-env set KEY` without a value read it
218新增: from stdin, or have you type it unseen: a value on the command line lands
219新增: in the shell history and in `ps`.
220新增:- `info` prints `git_protected=` (whether a start keeps `.git` read-only)
221新增: and `security_questions=` (what a start would stop on: `lima`,
222新增: `lima-unknown`, `hooks`, `git-config`, `bare-repo`, or `none`).
223新增:- Windows, experimental, from Git Bash, with QEMU. `setup` offers to
224新增: download a Lima build for Windows that keeps `.git` read-only (checked
225新增: against checksums pinned in agent-vm, not the release's `SHA256SUMS`, and
226新增: replaced when agent-vm moves to a newer one),
227新增: finds winget's QEMU where it installs it, and explains a start that fails
228新增: on WHPX: QEMU needs the "Windows Hypervisor Platform" feature, which only
229新增: an administrator can turn on. Paths go to Lima in Windows form, with Git
230新增: Bash's argument rewriting off for `limactl`. `install` writes a small
231新增: launcher where Git Bash makes no symlinks. Runtime scripts and env files
232新增: saved with CRLF reach the VM without the CRs.
233新增:- Inside WSL, `setup` and `doctor` say when KVM is missing because of WSL1 or
234新增: of nested virtualization on the Windows side.
235新增:- An entry of `~/.agent-vm/volumes` can be limited to some projects with a
236新增: fourth field, after an explicit mode: `source:destination:mode:project`,
237新增: where `project` is a path, `~` expanded, and `*` matches anything
238新增: (`~/.cache/pip:/home/you.guest/.cache/pip:rw:~/work/*`). An entry that
239新增: does not read that way (an empty project, a project without a mode before
240新增: it, a mode after it, more fields, a control character) is skipped with a
241新增: warning rather than mounted in every project. Based on #30 by Manuel
242新增: Raynaud.
243新增:- A relative destination in `~/.agent-vm/volumes` is inside the project
244新增: (`~/.claude-vm/webapp:.claude:ro:~/work/webapp`). The mount point is created in
245新增: the project on the host when missing. One that leaves the project with `..`
246新增: or goes through a symlink in it is skipped. It used to reach Lima as is,
247新增: which refuses a relative mount point.
248新增:- `--ssh-port N` gives a VM a fixed host port for SSH, for IDEs and GUI agents
249新增: that save the port rather than an alias (#28). `0` goes back to a new port on
250新增: each start. A port another agent-vm VM has is refused. `info` gains
251新增: `ssh_host` and `ssh_config`: Lima's alias for the VM and the SSH config file
252新增: it keeps current. [The website](https://www.agent-vm.org/#connect-an-ide-over-ssh)
253新增: has the `~/.ssh/config` lines to use them, which keep the host's SSH agent out
254新增: of the VM.
255新增:- `curl -fsSL https://www.agent-vm.org/install.sh | sh` installs the latest
256新增: release, checked against its `SHA256SUMS`, in `~/.local/share/agent-vm`, and
257新增: runs `agent-vm install`. Running it again updates. `--version X.Y.Z` picks a
258新增: release, `--git` installs a clone instead. `version --min` now names the
259新增: update command that fits the install: `git pull`, `brew upgrade` or the
260新增: installer, with `--dir` when it is not in the installer's default place.
261新增:- `agent-vm install` and `agent-vm uninstall` replace `install.sh`, which
262新增: stays for now as a wrapper (`--uninstall` included). `uninstall` works from
263新增: anywhere, not only from the clone, and `install` refuses a dangling link in
264新增: the way instead of failing on it. When the base VM is not built yet,
265新增: `install` offers to run `setup` right away. It no longer adds
266新增: `source agent-vm.sh` to a shell rc: the command on `PATH` works from every
267新增: shell, fish included, and an rc line left by an earlier install is named
268新增: as no longer needed.
269新增:- `agent-vm doctor`: read-only checks of the host, Lima, the base template and
270新增: the current directory, with what to run about each problem. It also says
271新增: whether Lima and the current directory's VM keep `.git` read-only, and
272新增: whether git ignores repositories not named `.git`.
273新增:- `sshfs` in the base packages, for the `reverse-sshfs` shares.
274新增:- `agent-vm version --min X.Y.Z`, `agent-vm project-env`,
275新增: `AGENT_VM_PROJECT_ENV`, `AGENT_VM_PROJECT_RUNTIME` and `AGENT_VM_STATE_DIR`,
276新增: and `project_env=` / `state_dir=` in `agent-vm info`.
277新增:- `test-e2e.sh`, which builds a real VM in a throwaway `LIMA_HOME` and checks
278新增: that root in the guest cannot lift `--readonly`, nor write `.git` when Lima
279新增: has `readonlyNames`.
280新增:- `agent-vm pi` runs [Pi](https://pi.dev), opt-in at setup (`pi` in
281新增: `--preinstall`, not in `default`). It pulls in `node`. Pi has no permission
282新增: prompts, so it takes no flag; setup trusts a project's `.pi/` extensions and
283新增: skills, which `pi -p` would skip otherwise. Pi has no MCP support, so the
284新增: `mcp-*` servers are not wired into it.
285新增:- Starting a VM prints when its base VM was built (`Base VM: built
286新增: 2026-09-28`): its agents and packages are that old.
287新增:- `list` adds a BASE column: the agent-vm version that built the base each
288新增: VM was cloned from, and the day (`0.2.0 2026-09-28`). A base built before
289新增: 0.2.0 shows `0.1.0`. It marks the current directory's VM with `>`, as
290新增: `status` did: `status` is now the same command.
291新增:
292新增:### Fixed
293新增:
294新增:- With zsh, two or more files in `~/.agent-vm/volumes` no longer break the
295新增: VM's shares: a variable of the loop was printed into the mounts config
296新增: (agent-vm now runs under bash, see Changed).
297新增:- `agent-vm run -i foo` (any command starting with `-`) runs it, instead of
298新增: handing the option to `env` in the VM.
299新增:- Sourced into a shell with `noclobber` (`set -C`), agent-vm rewrites its
300新增: files: `env set` failed, and the record of a VM's shares kept its old
301新增: value.
302新增:- `env set KEY a b`, and `get`, `has`, `unset` or `list` with a word too
303新增: many, are refused instead of keeping the first word.
304新增:- `list` fails, saying so, when Lima cannot be queried, instead of printing
305新增: "(no VMs)".
306新增:- `info` and `name` refuse a directory whose name holds a control
307新增: character: a newline added lines of its own to `info`'s output.
308新增:- `setup` only marks the base ready once it has stopped: Lima cannot clone a
309新增: running instance, so every new project VM failed after a stop that did not
310新增: take.
311新增:- `setup --disk`, `--memory` or `--cpus` without a value is one clear error,
312新增: also under a caller's `set -u`.
313新增:- The base setup script no longer loses its own lines to a command reading
314新增: standard input (a dpkg prompt, an npm install script): it reaches bash on
315新增: stdin, so such a command read the rest of the script, which never ran.
316新增:- Creating a VM fails loudly, with Lima's message, when `limactl clone` or
317新增: the edit that gives the VM its shares, memory, CPUs and SSH port fails, and
318新增: the half-made VM is deleted so the next run starts over (#21). Both used to
319新增: be silent: the VM then ran with the template's config, without the
320新增: `~/.agent-vm/volumes` entries or the requested resources.
321新增:- Symlinks to an absolute path or through `..` work again in `reverse-sshfs`
322新增: shares, `node_modules/.bin` included (#22). Debian's sshfs security update
323新增: (CVE-2026-47187) refuses them by default, with `EPERM`, to protect a client
324新增: from a rogue server. Here the server is your host, so the base VM runs sshfs
325新增: with `-o no_contain_symlinks`. Rebuild the base with `setup`, then `--reset`
326新增: the project VMs.
327新增:- VM names fall back to `sha256sum` when `shasum` is missing, and naming fails
328新增: rather than dropping the hash (two projects with the same directory name
329新增: would have shared one VM).
330新增:- When an agent, a shell or `run` in the VM ends, the terminal's mouse
331新增: tracking, focus reports, bracketed paste and keyboard modes are turned off.
332新增: A program that did not restore them (a crash, a dropped connection) left
333新增: the host shell typing escape sequences on every mouse move. The screen is
334新增: not cleared.
335新增:- `status` says "(no VMs)" when there are none.
336新增:- A new VM prints its resources once instead of twice.
337新增:- `destroy-all` no longer risks skipping VMs when `limactl` reads stdin.
338新增:- Prompts no longer print a `/dev/tty` error when there is no terminal.
339新增:- The VM's mise install uses `curl -f`, so an HTTP error fails setup instead of
340新增: piping an error page into `sh`.
341新增:- Version checks compare each component as a decimal number: `1.0.1000` no
342新增: longer outranks `1.1.0`, and `08` is no longer an octal error.
343新增:- `AGENT_VM_HOST_SHARE` that is not a positive integer falls back to 2 with a
344新增: warning, instead of a division error or being evaluated as a variable name.
345新增:- A shared env file without a final newline no longer merges its last line
346新增: into the project env's first one.
347新增:- Removing every env entry on the host now empties `~/.agent-vm.env` in the
348新增: VM, instead of leaving the previous values there.
349新增:- `env set` and `env unset` on a key holding a multi-line value remove all of
350新增: it. They removed the first line only, leaving an unterminated quote that
351新增: broke the file in the VM for every key after it. `unset` also removes an
352新增: `export KEY=` line, and `list` no longer shows a line inside a value as a
353新增: key.
354新增:- `--reset`, `rm` and `destroy-all` fail, naming the VM, when Lima still
355新增: lists it after the delete. `--reset` used to carry on with the old VM and
356新增: the shares it was given, and `rm` to report it destroyed.
357新增:- Behind a proxy, `sudo` in the VM keeps the proxy settings Lima copies from
358新增: the host (`env_keep` in `/etc/sudoers.d/10-agent-vm-proxy`). Debian's sudo
359新增: dropped them, so `setup` failed at its first `apt-get` (#25), and so did
360新增: `sudo apt install` in the VMs. Rebuild the base with `setup`, then
361新增: `--reset` the project VMs.
362新增:- The VM's zsh keeps its history in `~/.zsh_history`, across sessions and
363新增: restarts (#20); a command typed with a leading space is left out. New
364新增: bases only: `setup`, then `--reset`.
365新增:- `LIMA_HOME` is honoured when cleaning up an interrupted VM creation and in
366新增: the log paths printed on a failed start.
367新增:- A runtime script with an option in its shebang (`#!/bin/bash -e`,
368新增: `#!/usr/bin/env -S bash -e`) runs under bash, not zsh.
369新增:
370新增:## 0.1.0
371新增:
372新增:- `install.sh` puts `agent-vm` on the `PATH`, so other tools can call it.
373新增:- New commands for integrators: `version`, `name`, `info`, `env`.
374新增:- `mcp-chrome` and `mcp-playwright` in `--preinstall`.
修改README.md+25 −417看文件
@@ -1,444 +1,52 @@
11# agent-vm
22
3删除:Run AI coding agents inside sandboxed Linux VMs. The agent gets full autonomy while your host system stays safe.
3新增:Run AI coding agents in a disposable Linux VM per project, with permissions bypassed. The VM gets your project directory and nothing else of yours: no SSH keys, no browser sessions, no rest of your disk.
44
5删除:Uses [Lima](https://lima-vm.io/) to create lightweight Debian VMs on macOS and Linux. Ships with dev tools, Docker, and a headless Chrome browser with [Chrome DevTools MCP](https://github.com/ChromeDevTools/chrome-devtools-mcp) pre-configured.
5新增:Built on [Lima](https://lima-vm.io/). Ships dev tools, Docker, headless Chromium with [Chrome DevTools MCP](https://github.com/ChromeDevTools/chrome-devtools-mcp), and [Claude Code](https://claude.ai/code), [OpenCode](https://github.com/anomalyco/opencode), [Codex CLI](https://github.com/openai/codex), [Mistral Vibe](https://docs.mistral.ai/vibe/code/cli/install-setup) and, opt-in, [Pi](https://pi.dev). macOS, Linux, and Windows (Git Bash, experimental).
66
7删除:Supports [Claude Code](https://claude.ai/code), [OpenCode](https://github.com/anomalyco/opencode), [Codex CLI](https://github.com/openai/codex), and [Mistral Vibe](https://docs.mistral.ai/vibe/code/cli/install-setup) out of the box. Other agents can be run via `agent-vm shell`.
8删除:
9删除:Never install attack vectors such as npm, claude or even Docker on your host machine again!
10删除:
11删除:Feedback welcome!
12删除:
13删除:## Prerequisites
14删除:
15删除:- macOS or Linux
16删除:- [Lima](https://lima-vm.io/docs/installation/) (installed automatically via Homebrew if available)
17删除:- A subscription or API key for your agent of choice
7新增:**Documentation: [www.agent-vm.org](https://www.agent-vm.org/)**
188
199## Install
2010
2111```bash
22删除:git clone https://github.com/sylvinus/agent-vm.git
23删除:cd 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:
38删除:
39删除:```bash
40删除:echo "source $(pwd)/agent-vm.sh" >> ~/.zshrc # zsh
41删除:echo "source $(pwd)/agent-vm.sh" >> ~/.bashrc # or bash
12新增:curl -fsSL https://www.agent-vm.org/install.sh | sh
4213```
4314
44删除:Sourcing puts `agent-vm` in your shell as a function. You can also invoke the script directly (`./agent-vm.sh setup`) without sourcing — useful for one-off runs.
45删除:
46删除:## Usage
47删除:
48删除:### One-time setup
49删除:
50删除:```bash
51删除:agent-vm setup
52删除:```
53删除:
54删除:Creates a base VM template with dev tools, Docker, Chromium, and AI coding agents pre-installed. Run interactively to open the wizard; its first prompt offers a one-tap "default install" (everything except the opt-in languages Ruby, Rust, Go), answer `n` for per-component prompts. Pass `--preinstall=...` to skip the wizard. When stdin is not a terminal (CI), the wizard is auto-skipped and the default set is installed.
55删除:
56删除:Options:
57删除:
58删除:| Flag | Description | Default |
59删除:|------|-------------|---------|
60删除:| `--disk GB` | VM disk size in GB | 10 |
61删除:| `--memory GB` | VM memory in GB | 3 |
62删除:| `--cpus N` | Number of CPUs | 1 |
63删除:| `--preinstall=LIST` | Preinstall only this comma-separated subset in the base image (skips the wizard) | — |
64删除:
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`.
15新增:Or `brew install sylvinus/tap/agent-vm`, or from a clone: `./agent-vm.sh install`. See [Install](https://www.agent-vm.org/#install) for prerequisites and Windows.
6616
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.
68删除:
69删除:```bash
70删除:agent-vm setup # Interactive wizard
71删除:agent-vm setup --preinstall=default # Default set, no prompts
72删除:agent-vm setup --preinstall=default,rust # Default set plus Rust
73删除:agent-vm setup --preinstall=default,mcp-playwright # Default set plus Playwright MCP
74删除:agent-vm setup --preinstall=python,docker,claude # Minimal Claude-only setup
75删除:agent-vm setup --preinstall=node,chromium,opencode # OpenCode, no MCP wired in
76删除:agent-vm setup --disk 50 --memory 16 --cpus 8 # Larger VM for heavy workloads
77删除:```
78删除:
79删除:### Run an agent in a VM
17新增:## Use
8018
8119```bash
20新增:agent-vm setup # build the base template, once
8221cd your-project
83删除:agent-vm claude # Claude Code
84删除:agent-vm opencode # OpenCode
85删除:agent-vm codex # Codex CLI
86删除:agent-vm vibe # Mistral Vibe
87删除:```
88删除:
89删除:Creates a persistent VM for the current directory (or reuses it if one already exists), mounts your working directory, and runs the agent with full permissions. The VM persists after the agent exits so you can reconnect later. Ports opened inside the VM (e.g. by Docker containers or dev servers) are automatically forwarded to your host by Lima.
90删除:
91删除:Each agent runs with its respective auto-approve flag:
92删除:- `claude` runs with `--dangerously-skip-permissions`, and the VM also enforces bypass mode via managed settings (`/etc/claude-code/managed-settings.json`) so autonomy survives Claude Code's self-update/fullscreen relaunches — which otherwise drop the CLI flag ([#72479](https://github.com/anthropics/claude-code/issues/72479))
93删除:- `opencode` runs with `--auto` (auto-approves permission prompts that aren't explicitly denied)
94删除:- `codex` runs with `--dangerously-bypass-approvals-and-sandbox`
95删除:- `vibe` runs with `--agent auto-approve`
96删除:
97删除:Any extra arguments are forwarded to the agent command:
98删除:
99删除:```bash
100删除:agent-vm claude -p "fix all lint errors" # Run with a prompt
101删除:agent-vm claude --resume # Resume previous session
102删除:agent-vm opencode -p "refactor auth module" # OpenCode with a prompt
103删除:agent-vm codex -q "explain this codebase" # Codex with a query
104删除:agent-vm vibe -p "fix all lint errors" # Mistral Vibe with a prompt
105删除:```
106删除:
107删除:### Shell access and running commands
108删除:
109删除:```bash
110删除:agent-vm shell # Open a zsh shell in the VM
111删除:agent-vm run npm install # Run a one-off command in the VM
112删除:agent-vm run docker compose up -d # Start services
113删除:```
114删除:
115删除:### VM lifecycle
116删除:
117删除:Each directory gets its own persistent VM. You can manage it with:
118删除:
119删除:```bash
120删除:agent-vm status # Show status of all VMs (current dir marked with >)
121删除:agent-vm stop # Stop the VM (can be restarted later)
122删除:agent-vm rm # Stop and permanently delete the VM
123删除:agent-vm destroy-all # Stop and delete all agent-vm VMs
124删除:```
125删除:
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删除:
162删除:To automatically destroy a VM after the agent exits (like `docker run --rm`):
163删除:
164删除:```bash
165删除:agent-vm --rm claude # Run Claude, then destroy the VM
166删除:agent-vm --rm run npm test # Run tests, then destroy the VM
167删除:```
168删除:
169删除:To resize an existing VM's disk or memory, just pass `--disk` or `--memory` again — the VM will be stopped, reconfigured, and restarted automatically:
170删除:
171删除:```bash
172删除:agent-vm --disk 50 claude # Grow disk to 50GB, then run Claude
173删除:agent-vm --memory 16 --cpus 8 shell # Increase memory and CPUs, then open shell
174删除:```
175删除:
176删除:Note: disk can only be grown, not shrunk.
177删除:
178删除:Running `agent-vm setup` again updates the base template but does **not** update existing VMs. You'll see a warning when using a VM cloned from an older base. Use `--reset` to re-clone:
179删除:
180删除:```bash
181删除:agent-vm --reset claude # Destroy and re-clone VM, then run Claude
182删除:```
183删除:
184删除:### Offline mode and read-only mounts
185删除:
186删除:```bash
187删除:agent-vm --offline claude # Block outbound internet access
188删除:agent-vm --readonly shell # Mount project directory as read-only
189删除:agent-vm --offline --readonly claude # Both
190删除:```
191删除:
192删除:`--offline` blocks outbound internet from the VM using iptables while preserving host/VM communication (mounts, port forwarding). Useful for ensuring agents don't phone home or download unexpected packages.
193删除:
194删除:`--readonly` remounts the project directory as read-only. Useful for code review or audit tasks where the agent shouldn't modify files. Both flags are per-session and reset when the VM restarts.
195删除:
196删除:## Customization
197删除:
198删除:### Sharing tokens across VMs: `~/.agent-vm/env`
199删除:
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.
210删除:
211删除:```bash
212删除:# ~/.agent-vm/env
213删除:GH_TOKEN=github_pat_xxxxxxxxxxxxxxxxxxxxxxxx
214删除:ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxxxx
215删除:OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxx
216删除:MISTRAL_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxx
217删除:```
218删除:
219删除:These are picked up automatically by the tools that look for them: `gh` reads `GH_TOKEN`, Claude Code uses `ANTHROPIC_API_KEY` when not signed in, Codex uses `OPENAI_API_KEY`, Vibe uses `MISTRAL_API_KEY`, etc. The file is pushed into the VM at `~/.agent-vm.env` (mode 0600) on every `agent-vm` invocation, so edits propagate without `--reset`.
220删除:
221删除:For 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.
222删除:
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删除:
233删除:### Extra host mounts: `~/.agent-vm/volumes`
234删除:
235删除:List 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`:
236删除:
237删除:```bash
238删除:# ~/.agent-vm/volumes
239删除:
240删除:# Mount at the same path in the VM (read-only)
241删除:~/.gitconfig
242删除:~/.gitignore
243删除:
244删除:# Mount at a different path in the VM (read-only)
245删除:# Note: the destination is used verbatim (no shell expansion) — replace
246删除:# $USER with your actual username. Only the source (left) side expands a
247删除:# leading ~.
248删除:~/.claude:/home/youruser.linux/.claude
249删除:
250删除:# Writable directory
251删除:~/.cache/shared:/home/youruser.linux/.cache/shared:rw
252删除:```
253删除:
254删除:When no destination is specified, the path is mounted at the same location inside the VM. Non-existent paths are skipped with a warning. Changes to this file take effect on new VMs (use `--reset` to re-apply to existing ones).
255删除:
256删除:`rw` is only supported for **directories**. Files are always read-only: with the hardlink/staging strategy used below, writable file mounts would silently desync on cross-filesystem setups. If you need a writable single file, mount its parent directory as `rw` instead. A destination literally named `ro` or `rw` is treated as a mode keyword — append an explicit `:ro`/`:rw` to disambiguate.
257删除:
258删除:Individual files are supported without exposing their parent directory: agent-vm hardlinks the source into a per-VM staging dir under `~/.agent-vm/file-mounts/<vm>/`, then bind-mounts it at the final destination on each VM start. If the source sits on a different filesystem (hardlink impossible), it falls back to a copy and live host changes won't propagate until the next VM restart. The staged hardlink is refreshed on each `agent-vm` invocation, so atomic-rename edits (common in editors) are picked up at the next VM (re)start.
259删除:
260删除:### Per-user setup: `~/.agent-vm/setup.sh`
261删除:
262删除:Create this file to install extra tools into the base VM template. It runs once during `agent-vm setup`, as the default VM user (with sudo available):
263删除:
264删除:```bash
265删除:# ~/.agent-vm/setup.sh
266删除:sudo apt-get install -y postgresql-client
267删除:pip install pandas numpy
268删除:```
269删除:
270删除:### Per-user runtime: `~/.agent-vm/runtime.sh`
271删除:
272删除:Create this file to run commands inside every VM on each start. It runs **before** the per-project `.agent-vm.runtime.sh` script.
273删除:
274删除:Use it for anything that should be available in all your VMs: SSH keys, git config, GitHub CLI auth, Claude Code skills, MCP servers, etc.
275删除:
276删除:**Getting started:**
277删除:
278删除:```bash
279删除:cp runtime.example.sh ~/.agent-vm/runtime.sh
280删除:# Edit with your own values
281删除:```
282删除:
283删除:See [`runtime.example.sh`](runtime.example.sh) for a fully commented template covering:
284删除:- SSH key injection for GitHub (base64-encoded private key)
285删除:- Git identity and SSH-forced remotes (`url.insteadOf`)
286删除:- GitHub CLI authentication (`gh auth login --with-token`)
287删除:- Claude Code skills installation (global and per-project)
288删除:- MCP server registration (`claude mcp add --scope user`)
289删除:- Status line configuration in `~/.claude/settings.json`
290删除:
291删除:**Encoding your SSH key:**
292删除:
293删除:```bash
294删除:cat ~/.ssh/id_ed25519 | base64
295删除:```
296删除:
297删除:Paste the output into your `runtime.sh` — the script decodes it at boot and sets up `~/.ssh` with proper permissions.
298删除:
299删除:**Global vs per-project runtime:**
300删除:
301删除:| File | Scope | Runs when |
302删除:|------|-------|-----------|
303删除:| `~/.agent-vm/runtime.sh` | All VMs | Every VM start, first |
304删除:| `.agent-vm.runtime.sh` | Current project only | Every VM start, after global |
305删除:
306删除:**Important:** Always launch `agent-vm` from a path without spaces. macOS iCloud paths contain spaces (`~/Library/Mobile Documents/...`), which can break mounts. Create a symlink instead:
307删除:
308删除:```bash
309删除:ln -s ~/Library/Mobile\ Documents/com~apple~CloudDocs/Dev ~/Dev
310删除:cd ~/Dev/your-project
311删除:agent-vm claude
312删除:```
313删除:
314删除:### Per-project: `.agent-vm.runtime.sh`
315删除:
316删除:Create this file at the root of any project. It runs inside the VM each time a new VM is created for the project, just before you get access. Use it for project-specific setup like installing dependencies or starting services:
317删除:
318删除:```bash
319删除:# your-project/.agent-vm.runtime.sh
320删除:npm install
321删除:docker compose up -d
22新增:agent-vm claude # or opencode, codex, vibe, pi
23新增:agent-vm shell # a shell in this project's VM
24新增:agent-vm run npm test # one command in it
25新增:agent-vm --readonly shell # nothing on the host writable from the VM
26新增:agent-vm --scratch claude # nothing of yours mounted, VM deleted on exit
27新增:agent-vm stop # or rm; list for all VMs
28新增:agent-vm doctor # what is wrong, and what to run
32229```
32330
324删除:For projects using a specific language version (Ruby, Python, etc.), install it via mise in the runtime script. mise automatically picks up `.ruby-version`, `.python-version`, `.node-version`, and `.tool-versions` files:
31新增:Every command and option: [Usage](https://www.agent-vm.org/#usage) and [Reference](https://www.agent-vm.org/#reference).
32532
326删除:```bash
327删除:# your-project/.agent-vm.runtime.sh
328删除:mise install
329删除:bundle install
330删除:```
33新增:## Security
33134
332删除:### MCP servers
35新增:The agent is root in its VM and has the network. What it can reach on your machine is what crosses the shares:
33336
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.
37新增:- Every `.git` and `.hg`, and the folder of a `core.hooksPath` inside the project, are read-only for the VM with a Lima that has `sshfs.readonlyNames`, which `agent-vm setup` offers to install. Before a VM boots, agent-vm stops on what it cannot protect and asks whether to go on: [Protecting .git](https://www.agent-vm.org/#git).
38新增:- The agent writes the project folder: on your machine, open it in your editor and use git there, and run everything else in the VM. Open agent-vm projects in VS Code's Restricted Mode. Editors, agents, commit hooks and commands you run on the host can run code the agent wrote: [What else reads the project](https://www.agent-vm.org/#what-else-on-your-machine-reads-the-project).
39新增:- The VM reaches your machine's loopback and prints to your terminal: [Security](https://www.agent-vm.org/#security).
33540
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.
337删除:
338删除:To 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:
339删除:
340删除:```json
341删除:{
342删除: "mcpServers": {
343删除: "chrome-devtools": {
344删除: "command": "npx",
345删除: "args": ["-y", "chrome-devtools-mcp@latest", "--headless=true", "--isolated=true"]
346删除: },
347删除: "postgres": {
348删除: "command": "npx",
349删除: "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost:5432/mydb"]
350删除: }
351删除: }
352删除:}
353删除:```
354删除:
355删除:## How it works
356删除:
357删除:1. **`agent-vm setup`** creates a Debian 13 VM with Lima, runs `agent-vm.setup.sh` inside it to install dev tools + Chrome + agents, and stops it as a reusable base template
358删除:2. **`agent-vm claude|opencode|codex [args]`** clones the base template into a persistent per-directory VM, mounts your working directory, runs optional runtime scripts (`~/.agent-vm/runtime.sh` then `.agent-vm.runtime.sh`), then launches the agent with full permissions
359删除:3. The VM persists after exit. Running any agent command or `agent-vm shell` in the same directory reuses the same VM
360删除:4. Use `agent-vm stop` to stop the VM or `agent-vm rm` to delete it. Use `--rm` to auto-delete after the command exits
361删除:
362删除:Each 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.
363删除:
364删除:## Tests
41新增:## Development
36542
36643```bash
367删除:./test.sh
44新增:./test.sh # stub limactl, no VM, no network
45新增:docker run --rm -v "$PWD:/w" -w /w bash:3.2 ./test.sh # what macOS ships
46新增:./test-e2e.sh # a real VM, needs Lima
36847```
36948
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删除:
383删除:## Project structure
384删除:
385删除:| File | Description |
386删除:|------|-------------|
387删除:| `agent-vm.sh` | Main script — source this in your shell config |
388删除:| `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 |
391删除:
392删除:## What's in the VM
393删除:
394删除:The wizard's "default install" and `--preinstall=default` produce the same set: everything in the table below except the opt-in languages (Ruby, Rust, Go). Pass a different `--preinstall=` to install a different subset.
395删除:
396删除:| Category | Packages | Name | Installed by default? |
397删除:|----------|----------|------|----------------------|
398删除:| Core | git, curl, wget, jq, zsh, ca-certificates, build-essential, unzip, zip, ripgrep, fd-find, htop, iptables | (always) | always |
399删除:| Build libs | libssl-dev, libreadline-dev, zlib1g-dev, libyaml-dev, libffi-dev | (always) | always |
400删除:| Version manager | [mise](https://mise.jdx.dev/) | (always) | always |
401删除:| Python | python3, pip, venv | `python` | yes |
402删除:| Node.js | Node.js 24 LTS (via NodeSource) | `node` | yes |
403删除:| Ruby | ruby-full | `ruby` | no |
404删除:| Rust | rustup (stable toolchain) | `rust` | no |
405删除:| Go | golang-go | `golang` | no |
406删除:| GitHub CLI | gh | `gh` | yes |
407删除:| Browser | Chromium (headless), xvfb | `chromium` | yes |
408删除:| Containers | Docker Engine, Docker Compose | `docker` | yes |
409删除:| AI agents | Claude Code, OpenCode, Codex CLI, Mistral Vibe | `claude`, `opencode`, `codex`, `vibe` | yes |
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 |
412删除:
413删除:## Security model
414删除:
415删除:AI coding agents need full permissions to be useful — they install dependencies, run builds, execute tests, start servers. But running `npm install` or `pip install` means executing arbitrary third-party code on your machine.
416删除:
417删除:This is not a theoretical risk. The [Shai-Hulud](https://unit42.paloaltonetworks.com/npm-supply-chain-attack/) worm compromised thousands of npm packages in 2025 by injecting malicious code that runs during `npm install`. It harvested npm tokens, GitHub PATs, SSH keys, and cloud credentials from developers' machines, then used those credentials to spread to other packages the developer maintained. All of this happened silently, in the background, while the legitimate install appeared normal.
418删除:
419删除:An AI agent running with `--dangerously-skip-permissions` on your host would give such an attack full access to everything: your SSH keys, your cloud credentials, your browser sessions, your entire filesystem.
420删除:
421删除:**agent-vm runs all code inside the VM.** The VM only has access to your project directory (read-write mount, or read-only with `--readonly`). It has **no access** to your SSH keys, npm tokens, cloud credentials, git config, browser sessions, or anything else on your host. If a supply chain attack executes inside the VM, it finds nothing to steal (except your source code) and nowhere to spread. Use `--offline` to block internet access entirely.
422删除:
423删除:Meanwhile, your host machine stays clean. You don't need Node.js, Docker, or any dev tooling installed locally. The only host dependency is Lima. Your SSH keys and signing credentials never enter the VM — we recommend running `git commit` on the host yourself.
424删除:
425删除:### Why not Docker?
426删除:
427删除:| | No sandbox | Docker | VM (agent-vm) |
428删除:|---|---|---|---|
429删除:| Agent can run any command | Yes | Yes | Yes |
430删除:| File system isolation | None | Partial (shared kernel) | Full |
431删除:| Network isolation | None | Partial | Optional (`--offline`) |
432删除:| Can run Docker inside | Yes | Requires DinD or socket mount | Yes (native) |
433删除:| Kernel-level isolation | None | None (shares host kernel) | Full (separate kernel) |
434删除:| Protection from container escapes | None | None | Yes |
435删除:| Browser / GUI tools | Host only | Complex setup | Built-in (headless Chromium) |
436删除:
437删除:Docker containers share the host kernel. A motivated attacker (or a compromised dependency running inside the container) could exploit kernel vulnerabilities to escape. A VM runs its own kernel — even root access inside the VM can't reach the host.
438删除:
439删除:A VM also avoids the practical headaches of Docker sandboxing. Docker runs natively inside the VM without Docker-in-Docker hacks. Headless Chromium works out of the box. Lima automatically forwards ports to your host. The agent gets a normal Linux environment where everything just works.
440删除:
441删除:This workflow also replaces Docker Desktop on the Mac, which has become more and more bloated over the years.
49新增:Layout and guidelines: [Contribute](https://www.agent-vm.org/#contribute). Releases: `./release.sh X.Y.Z --dry-run`, then without it. The website is in [`www/`](www/README.md). Changes: [CHANGELOG.md](CHANGELOG.md).
44250
44351## License
44452
修改agent-vm.setup.sh+134 −57看文件
@@ -1,7 +1,7 @@
11#!/usr/bin/env bash
22#
33# agent-vm.setup.sh: Package installation script that runs inside the base VM
4删除:# Part of https://github.com/sylvinus/agent-vm
4新增:# Part of https://www.agent-vm.org/
55#
66# This script is executed inside the VM during "agent-vm setup".
77#
@@ -10,9 +10,27 @@ set -euo pipefail
1010
1111export DEBIAN_FRONTEND=noninteractive
1212
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.
27新增:apt_get() {
28新增: sudo env DEBIAN_FRONTEND=noninteractive apt-get "$@" </dev/null
29新增:}
30新增:
1331# Component toggles. The host wizard prepends `export` lines for these before
1432# piping the script in. Members of the default install set (everything except
15删除:# Ruby/Rust/Go) default to 1 so running this script standalone (without the
33新增:# Ruby/Rust/Go/Pi/Playwright MCP) default to 1 so running this script standalone (without the
1634# wizard) produces the same install you'd get from `agent-vm setup --preinstall=default`.
1735INSTALL_PYTHON="${AGENT_VM_INSTALL_PYTHON:-1}"
1836INSTALL_NODE="${AGENT_VM_INSTALL_NODE:-1}"
@@ -26,22 +44,27 @@ INSTALL_CLAUDE="${AGENT_VM_INSTALL_CLAUDE:-1}"
2644INSTALL_OPENCODE="${AGENT_VM_INSTALL_OPENCODE:-1}"
2745INSTALL_CODEX="${AGENT_VM_INSTALL_CODEX:-1}"
2846INSTALL_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.
47新增:INSTALL_PI="${AGENT_VM_INSTALL_PI:-0}"
48新增:# MCP servers wired into every installed agent's config (see lib/setup.sh).
3549INSTALL_MCP_CHROME="${AGENT_VM_INSTALL_MCP_CHROME:-1}"
3650INSTALL_MCP_PLAYWRIGHT="${AGENT_VM_INSTALL_MCP_PLAYWRIGHT:-0}"
3751
38删除:# Several installers (Claude Code, Vibe, …) check PATH at install time and
39删除:# print a "~/.local/bin is not in your PATH" warning otherwise. The persistent
40删除:# PATH lives in ~/.zshrc / ~/.zshenv (added below), so once the user opens a
41删除:# VM shell it's fine — but this bash script runs under a fresh session that
42删除:# doesn't see those edits yet. Export it here so installers stay quiet.
52新增:# For this session too: installers (Claude Code, Vibe) warn when ~/.local/bin
53新增:# is not on PATH, which ~/.zshenv only sets for the next ones.
4354export PATH="$HOME/.local/bin:$PATH"
4455
56新增:# Behind a proxy: Lima copies the host's proxy settings into /etc/environment,
57新增:# which ssh sessions (this script, `agent-vm shell`) load. sudo drops them
58新增:# (env_reset), and Debian's sudo does not read that file, so every `sudo
59新增:# apt-get` below went out without the proxy and failed (#25). Keeping them
60新增:# through sudo covers this script and every VM cloned from this base. Checked
61新增:# with visudo before it is installed: a broken sudoers file breaks sudo.
62新增:printf 'Defaults env_keep += "http_proxy https_proxy ftp_proxy no_proxy HTTP_PROXY HTTPS_PROXY FTP_PROXY NO_PROXY"\n' \
63新增: > /tmp/agent-vm-proxy.sudoers
64新增:sudo visudo -cqf /tmp/agent-vm-proxy.sudoers
65新增:sudo install -m 0440 -o root -g root /tmp/agent-vm-proxy.sudoers /etc/sudoers.d/10-agent-vm-proxy
66新增:rm -f /tmp/agent-vm-proxy.sudoers
67新增:
4568# Disable needrestart's interactive prompts
4669sudo mkdir -p /etc/needrestart/conf.d
4770echo '$nrconf{restart} = '"'"'a'"'"';' | sudo tee /etc/needrestart/conf.d/no-prompt.conf > /dev/null
@@ -49,38 +72,60 @@ echo '$nrconf{restart} = '"'"'a'"'"';' | sudo tee /etc/needrestart/conf.d/no-pro
4972# Base packages always installed: core CLI tools plus the dev libraries needed
5073# to compile Ruby/Python/Node versions via mise (kept here so that toggling a
5174# language off doesn't strip the libs the user may still want to build with).
75新增:# sshfs: the project VMs use Lima's reverse-sshfs when it can keep .git
76新增:# read-only. Lima would install it on each clone's first boot otherwise.
77新增:#
78新增:# Every install passes --no-install-recommends. Recommends pulled in hundreds
79新增:# of MB nobody uses here (Chromium alone brought printer config, Samba,
80新增:# avahi-daemon, upower, Vulkan drivers), some of them running daemons. The
81新增:# recommended packages that are used are listed by name instead.
5282echo "Installing base packages..."
53删除:sudo apt-get update
54删除:sudo apt-get install -y \
83新增:apt_get update
84新增:apt_get install -y --no-install-recommends \
5585 git curl jq zsh \
56删除: wget build-essential \
86新增: wget build-essential pkgconf patch \
5787 ripgrep fd-find htop \
5888 unzip zip \
59删除: ca-certificates \
60删除: iptables \
89新增: ca-certificates sshfs \
6190 libssl-dev libreadline-dev zlib1g-dev libyaml-dev libffi-dev
6291
92新增:# sshfs 3.7.6 (and Debian's 3.7.3-1.2~deb13u1) refuses symlinks whose target
93新增:# is absolute or contains "..", with EPERM: contain_symlinks, on by default
94新增:# (CVE-2026-47187). That breaks every node_modules/.bin link in a share. It
95新增:# protects a client from a rogue SFTP server; here the server is the user's
96新增:# own host, and a link followed in the VM only reaches the VM's files. Lima
97新增:# runs `sshfs` from PATH and takes no extra option, so the wrapper adds it.
98新增:sudo tee /usr/local/bin/sshfs > /dev/null <<'EOF'
99新增:#!/bin/sh
100新增:# Installed by agent-vm: see agent-vm.setup.sh.
101新增:if /usr/bin/sshfs -h 2>&1 | grep -q no_contain_symlinks; then
102新增: exec /usr/bin/sshfs "$@" -o no_contain_symlinks
103新增:fi
104新增:exec /usr/bin/sshfs "$@"
105新增:EOF
106新增:sudo chmod 755 /usr/local/bin/sshfs
107新增:
63108if [[ "$INSTALL_PYTHON" == "1" ]]; then
64109 echo "Installing Python 3..."
65删除: sudo apt-get install -y python3 python3-pip python3-venv
110新增: # python3-dev: headers for pip builds of C extensions.
111新增: apt_get install -y --no-install-recommends python3 python3-pip python3-venv python3-dev
66112fi
67113
68114if [[ "$INSTALL_RUBY" == "1" ]]; then
69115 echo "Installing Ruby..."
70删除: sudo apt-get install -y ruby-full
116新增: apt_get install -y --no-install-recommends ruby-full
71117fi
72118
73119if [[ "$INSTALL_GOLANG" == "1" ]]; then
74120 echo "Installing Go..."
75删除: sudo apt-get install -y golang-go
121新增: apt_get install -y --no-install-recommends golang-go
76122fi
77123
78124if [[ "$INSTALL_RUST" == "1" ]]; then
79125 # Rustup is the canonical Rust installer. --no-modify-path keeps it from
80删除: # editing ~/.profile/~/.bashrc — we add ~/.cargo/bin to zsh's PATH below.
126新增: # editing ~/.profile/~/.bashrc: ~/.cargo/bin goes on zsh's PATH below.
81127 echo "Installing Rust..."
82128 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path --default-toolchain stable
83删除: echo 'export PATH=$HOME/.cargo/bin:$PATH' >> ~/.zshrc
84129 echo 'export PATH=$HOME/.cargo/bin:$PATH' >> ~/.zshenv
85130fi
86131
@@ -89,8 +134,20 @@ sudo chsh -s /usr/bin/zsh "$(whoami)"
89134
90135# Always set the VM prompt and put ~/.local/bin on PATH (mise installs there;
91136# Vibe's installer puts `vibe`/`vibe-acp` there too).
137新增:#
138新增:# PATH additions go in ~/.zshenv only: every zsh reads it, and nothing in
139新增:# Debian 13's /etc/zsh/{zprofile,zshrc} resets PATH afterwards.
92140echo 'export PS1="vm:%1~%% "' >> ~/.zshrc
93删除:echo 'export PATH=$HOME/.local/bin:$PATH' >> ~/.zshrc
141新增:
142新增:# Shell history, kept across sessions and restarts: zsh saves none unless told
143新增:# where (#20). It lives on the VM's disk, where the agent can read it, like
144新增:# everything else there. A command started with a space is left out of it.
145新增:cat >> ~/.zshrc <<'ZSHRC'
146新增:HISTFILE=~/.zsh_history
147新增:HISTSIZE=10000
148新增:SAVEHIST=10000
149新增:setopt INC_APPEND_HISTORY HIST_IGNORE_DUPS HIST_IGNORE_SPACE
150新增:ZSHRC
94151echo 'export PATH=$HOME/.local/bin:$PATH' >> ~/.zshenv
95152
96153# Auto-source ~/.agent-vm.env if present. The host pushes ~/.agent-vm/env into
@@ -103,8 +160,7 @@ echo '[ -f "$HOME/.agent-vm.env" ] && { set -a; . "$HOME/.agent-vm.env"; set +a;
103160# Always installed so users can `mise install ruby@latest`, etc., even when
104161# they've opted out of preinstalled Node.
105162echo "Installing mise..."
106删除:curl https://mise.run | sh
107删除:echo 'eval "$(~/.local/bin/mise activate zsh)"' >> ~/.zshrc
163新增:curl -fsSL https://mise.run | sh
108164echo 'eval "$(~/.local/bin/mise activate zsh)"' >> ~/.zshenv
109165
110166if [[ "$INSTALL_DOCKER" == "1" ]]; then
@@ -114,22 +170,38 @@ if [[ "$INSTALL_DOCKER" == "1" ]]; then
114170 sudo curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
115171 sudo chmod a+r /etc/apt/keyrings/docker.asc
116172 echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
117删除: sudo apt-get update
118删除: sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
173新增: apt_get update
174新增: # buildx and pigz are Recommends: `docker build` needs buildx, pigz speeds
175新增: # up layer decompression. docker-ce-rootless-extras is left out: the user is
176新增: # in the docker group of the rootful daemon.
177新增: apt_get install -y --no-install-recommends docker-ce docker-ce-cli containerd.io \
178新增: docker-compose-plugin docker-buildx-plugin pigz
119179 sudo usermod -aG docker "$(whoami)"
120180fi
121181
122182if [[ "$INSTALL_NODE" == "1" ]]; then
123183 # Install Node.js 24 LTS (needed for MCP servers and Codex CLI)
184新增: # The NodeSource repo is set up by hand, as their setup_24.x script does,
185新增: # rather than piping that script to a root shell: it also installs gnupg
186新增: # just to dearmor the key, while apt reads an armored .asc key as is. The pin
187新增: # keeps apt on NodeSource's nodejs over Debian's older one.
124188 echo "Installing Node.js 24..."
125删除: curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash -
126删除: sudo apt-get install -y nodejs
189新增: sudo install -m 0755 -d /etc/apt/keyrings
190新增: sudo curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key -o /etc/apt/keyrings/nodesource.asc
191新增: sudo chmod a+r /etc/apt/keyrings/nodesource.asc
192新增: 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
193新增: printf 'Package: nodejs\nPin: origin deb.nodesource.com\nPin-Priority: 600\n' | sudo tee /etc/apt/preferences.d/nodejs > /dev/null
194新增: apt_get update
195新增: apt_get install -y --no-install-recommends nodejs
127196fi
128197
129198if [[ "$INSTALL_CHROMIUM" == "1" ]]; then
130199 # Install Chromium and dependencies for headless browsing
131200 echo "Installing Chromium..."
132删除: sudo apt-get install -y chromium fonts-liberation xvfb
201新增: # xauth: xvfb-run needs it, and it is only a Recommends of xvfb.
202新增: # fonts-dejavu-core: with Liberation alone, fontconfig resolves the generic
203新增: # sans-serif and serif to Liberation Mono.
204新增: apt_get install -y --no-install-recommends chromium fonts-liberation fonts-dejavu-core xvfb xauth
133205 sudo ln -sf /usr/bin/chromium /usr/bin/google-chrome
134206 sudo ln -sf /usr/bin/chromium /usr/bin/google-chrome-stable
135207 sudo mkdir -p /opt/google/chrome
@@ -143,14 +215,13 @@ if [[ "$INSTALL_GH" == "1" ]]; then
143215 wget -qO- https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo tee /etc/apt/keyrings/githubcli-archive-keyring.gpg > /dev/null
144216 sudo chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg
145217 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
146删除: sudo apt-get update
147删除: sudo apt-get install -y gh
218新增: apt_get update
219新增: apt_get install -y --no-install-recommends gh
148220fi
149221
150222if [[ "$INSTALL_CLAUDE" == "1" ]]; then
151223 echo "Installing Claude Code..."
152224 curl -fsSL https://claude.ai/install.sh | bash
153删除: echo 'export PATH=$HOME/.claude/local/bin:$PATH' >> ~/.zshrc
154225 echo 'export PATH=$HOME/.claude/local/bin:$PATH' >> ~/.zshenv
155226
156227 # Enforce full autonomy via *managed* settings (highest precedence), not the
@@ -177,7 +248,6 @@ fi
177248if [[ "$INSTALL_OPENCODE" == "1" ]]; then
178249 echo "Installing OpenCode..."
179250 curl -fsSL https://opencode.ai/install | bash
180删除: echo 'export PATH=$HOME/.opencode/bin:$PATH' >> ~/.zshrc
181251 echo 'export PATH=$HOME/.opencode/bin:$PATH' >> ~/.zshenv
182252fi
183253
@@ -186,7 +256,7 @@ if [[ "$INSTALL_CODEX" == "1" ]]; then
186256 echo "Skipping Codex CLI: requires Node.js (re-run setup with Node.js enabled)." >&2
187257 else
188258 echo "Installing Codex CLI..."
189删除: sudo npm i -g @openai/codex
259新增: sudo npm i -g @openai/codex </dev/null
190260 fi
191261fi
192262
@@ -198,6 +268,28 @@ if [[ "$INSTALL_VIBE" == "1" ]]; then
198268 curl -LsSf https://mistral.ai/vibe/install.sh | bash
199269fi
200270
271新增:if [[ "$INSTALL_PI" == "1" ]]; then
272新增: if [[ "$INSTALL_NODE" != "1" ]]; then
273新增: echo "Skipping Pi: requires Node.js (re-run setup with Node.js enabled)." >&2
274新增: else
275新增: # @earendil-works is the maintained scope; @mariozechner/pi-coding-agent is
276新增: # deprecated and misses security fixes. --ignore-scripts as Pi's docs say.
277新增: echo "Installing Pi..."
278新增: sudo npm i -g --ignore-scripts @earendil-works/pi-coding-agent </dev/null
279新增: # Pi never asks before running tools. Its one gate is trust for a project's
280新增: # .pi/ extensions and skills, which the VM makes moot and which `pi -p`
281新增: # silently skips. Telemetry covers the install ping and the attribution
282新增: # headers Pi adds to some providers' requests.
283新增: mkdir -p "$HOME/.pi/agent"
284新增: cat > "$HOME/.pi/agent/settings.json" << 'JSON'
285新增:{
286新增: "defaultProjectTrust": "always",
287新增: "enableInstallTelemetry": false
288新增:}
289新增:JSON
290新增: fi
291新增:fi
292新增:
201293# Wire one stdio MCP server into every installed agent's config. Each agent
202294# stores MCP servers in its own format, so that mapping is written once here
203295# instead of being copy-pasted per server.
@@ -285,7 +377,7 @@ configure_mcp() {
285377 fi
286378}
287379
288删除:# True when at least one agent is installed — nothing to configure otherwise,
380新增:# True when at least one agent is installed: nothing to configure otherwise,
289381# and no reason to print a "skipping" notice either.
290382any_agent_installed() {
291383 [[ "$INSTALL_CLAUDE" == "1" || "$INSTALL_OPENCODE" == "1" \
@@ -302,26 +394,11 @@ if [[ "$INSTALL_MCP_CHROME" == "1" ]] && any_agent_installed; then
302394 fi
303395fi
304396
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
397新增:# Playwright MCP drives the Chromium installed above (--executable-path), not
398新增:# a browser of its own: PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD, on this command only,
399新增:# skips the several hundred MB of browsers the `playwright` package downloads
400新增:# on install, while a project's own `npx playwright test` still gets them. A
401新增:# distro Chromium can drift from what playwright-core expects:
325402# `npx playwright install chromium` here if that ever bites.
326403if [[ "$INSTALL_MCP_PLAYWRIGHT" == "1" ]] && any_agent_installed; then
327404 if [[ "$INSTALL_NODE" == "1" && "$INSTALL_CHROMIUM" == "1" ]]; then
修改agent-vm.sh+826 −1585看文件
@@ -1,53 +1,38 @@
11#!/usr/bin/env bash
22#
33# agent-vm: Run AI coding agents inside sandboxed Lima VMs
4删除:# Part of https://github.com/sylvinus/agent-vm
5删除:#
6删除:# Source this file in your shell config:
7删除:# source /path/to/agent-vm/agent-vm.sh
8删除:#
9删除:# Usage:
10删除:# agent-vm setup - Create the base VM template (run once)
11删除:# agent-vm claude - Run Claude Code in a persistent VM for cwd
12删除:# agent-vm opencode - Run OpenCode in a persistent VM for cwd
13删除:# agent-vm codex - Run Codex CLI in a persistent VM for cwd
14删除:# agent-vm vibe - Run Mistral Vibe in a persistent VM for cwd
15删除:# agent-vm shell - Open a shell in the persistent VM for cwd
16删除:# (alias: 'sh'; add -c "..." for a one-shot command)
17删除:# agent-vm stop - Stop the VM for cwd
18删除:# agent-vm rm - Stop and delete the VM for cwd
19删除:# agent-vm list - List all agent-vm VMs
20删除:# 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
24删除:# agent-vm help - Show help
4新增:# Part of https://www.agent-vm.org/
255#
6新增:# Put it on your PATH with `./agent-vm.sh install`. It can also be sourced
7新增:# from bash, which defines agent-vm as a shell function. Commands:
8新增:# `agent-vm help` (lib/help.sh).
9新增:
10新增:# zsh, which 0.1.0's installer had source this file from ~/.zshrc: only a
11新增:# function that runs this file with bash. %x is the file being sourced, :A
12新增:# makes it absolute with links resolved. The eval keeps bash from parsing zsh
13新增:# syntax.
14新增:if [[ -n "${ZSH_VERSION:-}" ]]; then
15新增: eval '
16新增: [[ "${ZSH_EVAL_CONTEXT:-}" == *:file* ]] || exec bash "$0" "$@"
17新增: eval "agent-vm() { command bash ${(qq)${(%):-%x}:A} \"\$@\"; }"
18新增: '
19新增: return 0
20新增:fi
2621
2722# Semantic version of this file. Bumped by hand on release. Integrators gate on
2823# it via `agent-vm version`; a build with no `version` command predates it.
29删除:AGENT_VM_VERSION="0.1.0"
24新增:AGENT_VM_VERSION="0.2.0"
3025
3126AGENT_VM_TEMPLATE="agent-vm-base"
32删除:AGENT_VM_STATE_DIR="${HOME}/.agent-vm"
27新增:# Overridable, for a test or a second install, without moving HOME (and
28新增:# Lima's state with it). `agent-vm info` publishes it as state_dir=.
29新增:AGENT_VM_STATE_DIR="${AGENT_VM_STATE_DIR:-${HOME}/.agent-vm}"
3330
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.
31新增:# Directory of the real agent-vm.sh, symlinks followed: the PATH entry
32新增:# `install` makes is one. By hand, as macOS's readlink has no -f. `CDPATH=`
33新增:# everywhere a relative path is cd'ed to: with it set, cd searches it first.
4934_agent_vm_script_dir() {
50删除: local src="${BASH_SOURCE[0]:-$0}" dir
35新增: local src="$1" dir
5136 while [ -L "$src" ]; do
5237 dir="$(CDPATH= cd -P -- "$(dirname "$src")" >/dev/null && pwd)"
5338 src="$(readlink "$src")"
@@ -58,691 +43,626 @@ _agent_vm_script_dir() {
5843 done
5944 (CDPATH= cd -P -- "$(dirname "$src")" >/dev/null && pwd)
6045}
61删除:AGENT_VM_SCRIPT_DIR="$(_agent_vm_script_dir)"
62删除:
63删除:# Prompt for a value with a default. Reads from /dev/tty so this still works
64删除:# when called inside command substitution. Writes the prompt to stderr and the
65删除:# answer (or the default if the user just pressed Enter) to stdout.
66删除:_agent_vm_ask() {
67删除: local prompt="$1" default="$2" reply=""
68删除: printf ' %s [%s]: ' "$prompt" "$default" >&2
69删除: IFS= read -r reply </dev/tty 2>/dev/null || reply=""
70删除: printf '%s\n' "${reply:-$default}"
71删除:}
72删除:
73删除:# Yes/no prompt. Second arg is the default: Y or N (case-insensitive). Prints
74删除:# 1 (yes) or 0 (no) to stdout. Empty input picks the default.
75删除:_agent_vm_ask_yn() {
76删除: local prompt="$1" default="${2:-Y}" reply="" indicator
77删除: case "$default" in
78删除: [Yy]*) indicator="[Y/n]"; default=Y ;;
79删除: *) indicator="[y/N]"; default=N ;;
80删除: esac
81删除: printf ' %s %s: ' "$prompt" "$indicator" >&2
82删除: IFS= read -r reply </dev/tty 2>/dev/null || reply=""
83删除: reply="${reply:-$default}"
84删除: case "$reply" in
85删除: [Yy]*) printf '1\n' ;;
86删除: *) printf '0\n' ;;
87删除: esac
88删除:}
89删除:
90删除:# Prompt for a positive integer with default. Re-prompts on invalid input.
91删除:# Used for disk/memory/cpus where a typo (e.g. "10G") would otherwise produce
92删除:# a cryptic limactl error several seconds later.
93删除:_agent_vm_ask_int() {
94删除: local prompt="$1" default="$2" reply
95删除: while true; do
96删除: reply=$(_agent_vm_ask "$prompt" "$default")
97删除: if [[ "$reply" =~ ^[1-9][0-9]*$ ]]; then
98删除: printf '%s\n' "$reply"
99删除: return 0
100删除: fi
101删除: printf ' (must be a positive integer, e.g. 10 — got: %s)\n' "$reply" >&2
102删除: done
103删除:}
104删除:
105删除:# Validate a positive-integer arg from the CLI (no retry — fail fast).
106删除:_agent_vm_validate_int() {
107删除: local name="$1" val="$2"
108删除: if [[ ! "$val" =~ ^[1-9][0-9]*$ ]]; then
109删除: echo "Error: $name must be a positive integer (got: '$val')" >&2
110删除: return 1
111删除: fi
112删除:}
113删除:
114删除:# Check Linux prerequisites Lima needs to spin up a QEMU+KVM VM. macOS uses
115删除:# different backends (vz/qemu-via-brew) so this is a no-op there. Returns
116删除:# non-zero with actionable install/permission hints when something's missing —
117删除:# without this, the user gets a generic `Error: Failed to create base VM` and
118删除:# has to dig into `~/.lima/<vm>/ha.stderr.log` to figure out why.
119删除:_agent_vm_check_linux_prereqs() {
120删除: [[ "$(uname -s)" == "Linux" ]] || return 0
121删除:
122删除: local arch_bin arch_pkg
123删除: case "$(uname -m)" in
124删除: x86_64) arch_bin="qemu-system-x86_64"; arch_pkg="qemu-system-x86" ;;
125删除: aarch64|arm64) arch_bin="qemu-system-aarch64"; arch_pkg="qemu-system-arm" ;;
126删除: *) arch_bin="qemu-system-$(uname -m)"; arch_pkg="qemu-system" ;;
127删除: esac
128删除:
129删除: local errs=0
46新增:AGENT_VM_SCRIPT_DIR="$(_agent_vm_script_dir "${BASH_SOURCE[0]:-$0}")"
47新增:if [[ -z "$AGENT_VM_SCRIPT_DIR" ]]; then
48新增: echo "agent-vm: cannot find the directory of agent-vm.sh" >&2
49新增: return 1 2>/dev/null || exit 1
50新增:fi
13051
131删除: if ! command -v "$arch_bin" &>/dev/null; then
132删除: echo "Error: Lima needs '$arch_bin' on PATH (not found)." >&2
133删除: echo " Install with: sudo apt-get install $arch_pkg" >&2
134删除: errs=1
52新增:# The rest of agent-vm, one file per concern, sourced like this one. Only
53新增:# functions and settings: nothing runs until a command does. A file that is
54新增:# missing stops here, not half-way through a command.
55新增:for _agent_vm_lib in ui options host vm mounts git runtime env info install doctor help setup; do
56新增: _agent_vm_lib="$AGENT_VM_SCRIPT_DIR/lib/$_agent_vm_lib.sh"
57新增: if [[ ! -r "$_agent_vm_lib" ]] || ! . "$_agent_vm_lib"; then
58新增: echo "agent-vm: cannot load $_agent_vm_lib" >&2
59新增: unset _agent_vm_lib
60新增: return 1 2>/dev/null || exit 1
13561 fi
136删除:
137删除: if [[ ! -e /dev/kvm ]]; then
138删除: echo "Error: /dev/kvm does not exist (KVM unavailable)." >&2
139删除: echo " Hardware virtualization may be disabled in BIOS, or the kernel" >&2
140删除: echo " lacks KVM support (nested virt in a guest VM, etc.)." >&2
141删除: errs=1
142删除: elif [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then
143删除: echo "Error: /dev/kvm exists but you don't have read/write access." >&2
144删除: local groups
145删除: groups="$(id -nG 2>/dev/null || true)"
146删除: if [[ " $groups " != *" kvm "* ]]; then
147删除: echo " Fix: sudo usermod -aG kvm \"\$USER\"" >&2
148删除: echo " Then log out and back in (or run 'newgrp kvm') so the new" >&2
149删除: echo " group membership takes effect." >&2
62新增:done
63新增:unset _agent_vm_lib
64新增:
65新增:# --- starting a project's VM --------------------------------------------------
66新增:
67新增:# The security checks of a start, for the project <dir> and its VM <vm>. Reads the caller's
68新增:# vm_up, scratch and rdonly, and sets its protect_git, ro_names and
69新增:# hooks_notes. With vm_up set (a running VM that keeps running), the risks are
70新增:# printed and nothing is asked. Fails when the start must stop.
71新增:_agent_vm_start_checks() {
72新增: local host_dir="$1" vm_name="$2" lima_st=0
73新增: protect_git="" ro_names="" hooks_notes=""
74新增:
75新增: # Every .git read-only for the guest, when this Lima can enforce it and it
76新增: # was not turned off. The mounts built afterwards, on every path, follow the
77新增: # answer. A Lima that cannot, with shares left writable and nobody having
78新增: # asked for a writable .git, is a risk to accept. One whose answer could not
79新增: # be read stops the start: taking it for a no would drop the protection of
80新增: # the VM.
81新增: if [[ -n "$scratch" ]]; then
82新增: :
83新增: elif _agent_vm_writable_git_optout; then
84新增: _agent_vm_writable_git_warning >&2
85新增: else
86新增: _agent_vm_lima_protects_git || lima_st=$?
87新增: if [[ "$lima_st" == 0 ]]; then
88新增: protect_git=1
89新增: elif [[ -n "$rdonly" ]]; then
90新增: :
91新增: elif [[ "$lima_st" == 2 ]]; then
92新增: echo "Error: cannot tell whether this Lima keeps .git read-only: 'limactl validate' gave no answer agent-vm knows ('agent-vm doctor' shows more)." >&2
93新增: echo " --readonly, or --unsafe-writable-git to accept a writable .git, still starts the VM." >&2
94新增: return 1
95新增: elif _agent_vm_unprotected_mount_is_sshfs "$vm_name"; then
96新增: # Asked below, with the rest of the disk.
97新增: :
98新增: elif [[ -n "$vm_up" ]]; then
99新增: echo "Warning: this Lima cannot keep .git read-only, so the VM can write .git ('agent-vm doctor' says more)." >&2
150100 else
151删除: echo " You're already in the kvm group but /dev/kvm denies access." >&2
152删除: echo " Check ownership/mode: ls -l /dev/kvm" >&2
101新增: _agent_vm_git_protection_hint | _agent_vm_box "Lima cannot keep .git read-only"
102新增: if ! _agent_vm_confirm_unsafe; then
103新增: echo "Aborted. Install that Lima build, or use --readonly; --unsafe-writable-git accepts a writable .git." >&2
104新增: return 1
105新增: fi
153106 fi
154删除: errs=1
155删除: fi
156删除:
157删除: [[ $errs -eq 0 ]]
158删除:}
159删除:
160删除:# Lima leaves a partial state dir behind if `limactl create` is interrupted
161删除:# (Ctrl-C before lima.yaml is written). After that every subsequent limactl
162删除:# call on that name dies with `open ~/.lima/<vm>/lima.yaml: no such file or
163删除:# directory` — pre-emptively clean the dir so the next setup/start works.
164删除:_agent_vm_clean_partial_state() {
165删除: local vm_name="$1"
166删除: local lima_dir="$HOME/.lima/$vm_name"
167删除: if [[ -d "$lima_dir" ]] && [[ ! -f "$lima_dir/lima.yaml" ]]; then
168删除: echo "Detected partial VM state at $lima_dir (no lima.yaml) — cleaning up." >&2
169删除: rm -rf "$lima_dir"
170删除: fi
171删除:}
172删除:
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删除:
200删除:# Generate a deterministic VM name for a directory
201删除:_agent_vm_name() {
202删除: local dir="${1:-$(pwd)}"
203删除: local hash
204删除: hash=$(echo -n "$dir" | shasum -a 256 | cut -c1-8)
205删除: local base
206删除: base=$(basename "$dir" | tr -cs 'a-zA-Z0-9' '-' | sed 's/^-//;s/-$//')
207删除: echo "agent-vm-${base}-${hash}"
208删除:}
209删除:
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.
229删除:_agent_vm_exists() {
230删除: local list
231删除: list="$(limactl list -q 2>/dev/null)" || return 2
232删除: _agent_vm_has_line "$list" "$1"
233删除:}
234删除:
235删除:# Check if a VM is running. Same three statuses as _agent_vm_exists.
236删除:_agent_vm_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
274107 fi
275删除:}
276108
277删除:# Stage a single host file at <dst> via hardlink, falling back to copy if the
278删除:# source and destination live on different filesystems. Hardlinking keeps the
279删除:# content live-synced with the host (same inode) without exposing the source's
280删除:# parent directory to the VM. The copy fallback preserves the no-exposure
281删除:# property but loses live sync until the next VM (re)start.
282删除:_agent_vm_stage_file() {
283删除: local src="$1" dst="$2"
284删除: mkdir -p "$(dirname "$dst")" 2>/dev/null || return 1
285删除: rm -f "$dst"
286删除: if ln "$src" "$dst" 2>/dev/null; then
287删除: return 0
288删除: fi
289删除: if cp -p "$src" "$dst" 2>/dev/null; then
290删除: echo "Warning: Staged '${src}' via copy (cross-filesystem hardlink failed); live host changes will not propagate until VM (re)start." >&2
291删除: return 0
109新增: # Not only .git: shares Lima does not confine leave the rest of the disk
110新增: # in reach (see _agent_vm_unprotected_mount_is_sshfs), --unsafe-writable-git
111新增: # or not. --readonly cannot be enforced on them either: refused before
112新增: # anything boots.
113新增: if [[ -z "$scratch" && -z "$protect_git" ]] && _agent_vm_unprotected_mount_is_sshfs "$vm_name"; then
114新增: if [[ -n "$rdonly" ]]; then
115新增: echo "Error: --readonly cannot be enforced here: the shares would be reverse-sshfs, which this Lima does not confine. Install the Lima build 'agent-vm setup' offers, or use --scratch." >&2
116新增: return 1
117新增: elif [[ -n "$vm_up" ]]; then
118新增: echo "Warning: this Lima cannot keep the VM to its shares: root in the VM may reach files outside them, your SSH keys included ('agent-vm doctor' says more)." >&2
119新增: else
120新增: { _agent_vm_sshfs_exposure_note; _agent_vm_git_protection_hint; } | _agent_vm_box "Lima cannot keep the VM to its shares"
121新增: if ! _agent_vm_confirm_unsafe; then
122新增: echo "Aborted. Install that Lima build, or use --scratch, which shares nothing." >&2
123新增: return 1
124新增: fi
125新增: fi
292126 fi
293删除: return 1
294删除:}
295127
296删除:# Remove all per-VM state files (version marker, terminfo cache, file mount
297删除:# cache, staging dirs). Called after a VM is deleted or before it is re-cloned
298删除:# via --reset.
299删除:_agent_vm_cleanup_state() {
300删除: local vm_name="$1"
301删除: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-version-${vm_name}"
302删除: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-term-${vm_name}"
303删除: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-file-mounts-${vm_name}"
304删除: rm -rf "$AGENT_VM_STATE_DIR/file-mounts/${vm_name}"
305删除:}
306删除:
307删除:# Build the .mounts JSON array for a VM. The first entry is always the project
308删除:# dir (writable). Additional entries come from ~/.agent-vm/volumes, parsed as
309删除:# Docker-Compose-ish `source[:destination][:mode]` (mode ∈ {ro,rw}, default ro).
310删除:#
311删除:# Side effects: stages any file mounts as hardlinks under
312删除:# ~/.agent-vm/file-mounts/<vm>/ and persists the file mount metadata to
313删除:# ~/.agent-vm/.agent-vm-file-mounts-<vm> so subsequent starts can re-apply the
314删除:# inside-VM bind mounts without re-parsing the volumes file. Stdout: the
315删除:# mounts JSON array (consumed by `limactl edit --set ".mounts = ..."`).
316删除:_agent_vm_build_mounts_json() {
317删除: local vm_name="$1" host_dir="$2"
318删除: local mounts_json="[{\"location\": \"${host_dir}\", \"writable\": true}"
319删除: local mounts_file="$AGENT_VM_STATE_DIR/volumes"
320删除: local file_mount_entries=()
321删除: local file_mounts_cache="$AGENT_VM_STATE_DIR/.agent-vm-file-mounts-${vm_name}"
322删除:
323删除: if [[ -f "$mounts_file" ]]; then
324删除: local staging_idx=0
325删除: while IFS= read -r line || [[ -n "$line" ]]; do
326删除: line="${line%%#*}" # strip comments
327删除: line="${line#"${line%%[![:space:]]*}"}" # trim leading whitespace
328删除: line="${line%"${line##*[![:space:]]}"}" # trim trailing whitespace
329删除: [[ -z "$line" ]] && continue
330删除: # Parse source[:destination][:mode] syntax (like docker compose volumes).
331删除: # The trailing mode segment is only recognized when it equals "ro" or
332删除: # "rw" — anything else is treated as a destination path.
333删除: local src="$line" dst="" mode="ro"
334删除: if [[ "$line" == *:ro || "$line" == *:rw ]]; then
335删除: mode="${line##*:}"
336删除: line="${line%:*}"
337删除: fi
338删除: if [[ "$line" == *:* ]]; then
339删除: src="${line%%:*}"
340删除: dst="${line#*:}"
341删除: else
342删除: src="$line"
343删除: fi
344删除: src="${src/#\~/$HOME}" # expand ~
345删除: # Reject characters that would break JSON interpolation below or the
346删除: # pipe-separated cache format used for file mounts.
347删除: if [[ "$src" == *[$'"\\\n|']* || "$dst" == *[$'"\\\n|']* ]]; then
348删除: echo "Warning: Mount entry '${line}' (from ~/.agent-vm/volumes) contains invalid characters (quote/backslash/newline/pipe), skipping." >&2
128新增: # With it, the names the shares need: those always listed, and one per
129新增: # hooks folder git runs from in the project (see _agent_vm_project_hooks),
130新增: # its first component. A dot-name (.husky, .githooks) is taken as is; any
131新增: # other is read-only in every folder of the project, so it is asked first
132新增: # (yes by default, and when no one can answer). A folder that cannot be
133新增: # protected, or one declined, is a risk to accept. So are git config files
134新增: # in the project, and settings running commands from it. Under --readonly
135新增: # the VM writes none of them: the names are taken as they come, with no
136新增: # warning and no question.
137新增: local hooks_rel hooks_in hooks_name hooks_names=()
138新增: if [[ -n "$protect_git" ]]; then
139新增: while IFS=$'\t' read -r hooks_rel hooks_in; do
140新增: [[ -n "$hooks_rel" ]] || continue
141新增: if [[ -n "$rdonly" ]]; then
142新增: hooks_name="$(_agent_vm_hooks_name "$hooks_in")" && hooks_names+=("$hooks_name")
349143 continue
350144 fi
351删除: if [[ ! -e "$src" ]]; then
352删除: echo "Warning: Mount path '${src}' (from ~/.agent-vm/volumes) does not exist, skipping." >&2
353删除: continue
354删除: fi
355删除: if [[ -f "$src" ]]; then
356删除: if [[ "$mode" == "rw" ]]; then
357删除: echo "Warning: Mount entry '${line}' (from ~/.agent-vm/volumes) requests rw on a file; only directories support rw. Mount the parent directory instead. Skipping." >&2
358删除: continue
145新增: if ! hooks_name="$(_agent_vm_hooks_name "$hooks_in")"; then
146新增: if [[ "$hooks_rel" == . ]]; then
147新增: echo "Warning: git's core.hooksPath is the project directory itself, which the VM can write: git on this machine runs the hooks the agent puts there." >&2
148新增: else
149新增: echo "Warning: git's core.hooksPath is '$hooks_rel', in the project, and its name cannot be made read-only: git on this machine runs the hooks the agent puts there." >&2
359150 fi
360删除: # File mount: hardlink the source into a per-VM host staging dir so
361删除: # the VM sees only this file (never the source's parent). Lima mounts
362删除: # the staging dir via virtiofs; a bind mount inside the VM (applied
363删除: # after boot) exposes the file at its final destination.
364删除: local filename
365删除: filename="$(basename "$src")"
366删除: local file_staging_dir="$AGENT_VM_STATE_DIR/file-mounts/${vm_name}/${staging_idx}"
367删除: local host_staging="${file_staging_dir}/${filename}"
368删除: if ! _agent_vm_stage_file "$src" "$host_staging"; then
369删除: echo "Warning: Failed to stage '${src}', skipping." >&2
370删除: rm -rf "$file_staging_dir"
371删除: continue
151新增: if [[ -z "$vm_up" ]] && ! _agent_vm_confirm_unsafe; then
152新增: echo "Aborted. Point core.hooksPath to a folder of the project (agent-vm keeps it read-only), or outside it." >&2
153新增: return 1
372154 fi
373删除: local staging_mount="/tmp/.agent-vm-file-mounts/${staging_idx}"
374删除: local bind_dst="${dst:-${src}}"
375删除: file_mount_entries+=("${src}|${host_staging}|${staging_mount}/${filename}|${bind_dst}")
376删除: mounts_json+=", {\"location\": \"${file_staging_dir}\", \"mountPoint\": \"${staging_mount}\", \"writable\": false}"
377删除: staging_idx=$((staging_idx + 1))
378155 continue
379156 fi
380删除: if [[ ! -d "$src" ]]; then
381删除: echo "Warning: Mount path '${src}' (from ~/.agent-vm/volumes) is not a regular file or directory, skipping." >&2
157新增: if [[ "$hooks_name" != .* && -z "$vm_up" ]] && ! _agent_vm_prompts_disabled_by >/dev/null \
158新增: && _agent_vm_can_ask \
159新增: && [[ "$(_agent_vm_ask_yn "Git runs hooks from $hooks_rel. Make every '$hooks_name' folder in the project read-only for the VM?" Y)" != "1" ]]; then
160新增: echo "Warning: '$hooks_name' stays writable, and git on this machine runs the hooks the agent puts in $hooks_rel." >&2
161新增: if ! _agent_vm_confirm_unsafe; then
162新增: echo "Aborted. Answer yes to protect it, or point core.hooksPath outside the project." >&2
163新增: return 1
164新增: fi
382165 continue
383166 fi
384删除: local writable="false"
385删除: [[ "$mode" == "rw" ]] && writable="true"
386删除: if [[ -n "$dst" ]]; then
387删除: mounts_json+=", {\"location\": \"${src}\", \"mountPoint\": \"${dst}\", \"writable\": ${writable}}"
388删除: else
389删除: mounts_json+=", {\"location\": \"${src}\", \"writable\": ${writable}}"
167新增: hooks_names+=("$hooks_name")
168新增: hooks_notes="$hooks_notes$(_agent_vm_hooks_note "$hooks_rel" "$hooks_name")"$'\n'
169新增: done <<< "$(_agent_vm_project_hooks "$host_dir")"
170新增: ro_names="$(_agent_vm_names_json ${hooks_names[@]+"${hooks_names[@]}"})"
171新增:
172新增: local git_risks=""
173新增: [[ -n "$rdonly" ]] || git_risks="$(_agent_vm_project_config_risks "$host_dir")"
174新增: if [[ -n "$git_risks" ]]; then
175新增: echo "Warning: git on this machine uses these, and the VM can write them:" >&2
176新增: printf '%s\n' "$git_risks" | sed 's/^/ /' >&2
177新增: if [[ -z "$vm_up" ]] && ! _agent_vm_confirm_unsafe; then
178新增: echo "Aborted. Move them out of the project, or have them name commands outside it." >&2
179新增: return 1
390180 fi
391删除: done < "$mounts_file"
181新增: fi
392182 fi
393删除: mounts_json+="]"
394删除:
395删除: rm -f "$file_mounts_cache"
396删除: if [[ ${#file_mount_entries[@]} -gt 0 ]]; then
397删除: printf '%s\n' "${file_mount_entries[@]}" > "$file_mounts_cache"
183新增: # A repository not named .git, which no name protects (see
184新增: # _agent_vm_bare_repo_state): only a VM that can write needs the setting.
185新增: if [[ -z "$rdonly" && -z "$scratch" ]]; then
186新增: _agent_vm_check_bare_repo_setting "$vm_up" || return 1
398187 fi
399删除:
400删除: printf '%s' "$mounts_json"
401188}
402189
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
190新增:# A VM that ran when the start began, so whose start asked nothing (see
191新增:# _agent_vm_start_checks), has just been stopped to boot again: ask now, as
192新增:# for any VM about to boot. Reads and clears the caller's vm_up. Fails, with
193新增:# the VM left stopped, when the start must stop.
194新增:_agent_vm_recheck_after_stop() {
195新增: [[ -n "$vm_up" ]] || return 0
196新增: vm_up=""
197新增: if ! _agent_vm_start_checks "$1" "$2"; then
198新增: echo "VM '$2' is stopped." >&2
199新增: return 1
200新增: fi
419201}
420202
421删除:# Print VM resource details (CPUs, memory, disk)
422删除:_agent_vm_print_resources() {
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"
426删除: echo " Resources: CPUs: ${cpus}, Memory: ${mem_gib} GiB, Disk: ${disk_gib} GiB"
203新增:# Stops <vm>, for the project <dir>, to boot it again changed, then asks what
204新增:# its start did not (see above). Fails, saying so, when it did not stop.
205新增:_agent_vm_stop_to_change() {
206新增: if ! _agent_vm_stop_vm "$1"; then
207新增: echo "Error: could not stop VM '$1': nothing was changed." >&2
208新增: return 1
427209 fi
210新增: _agent_vm_recheck_after_stop "$2" "$1"
428211}
429212
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
213新增:# Gives the stopped <vm> its shares for the project <dir>, writable or not
214新增:# (<writable> true/false), with the caller's protect_git and ro_names, or none
215新增:# for its scratch, and records them (see _agent_vm_record_mounts).
216新增:_agent_vm_apply_shares() {
217新增: local vm="$1" dir="$2" writable="$3" json="[]" out
218新增: [[ -n "$scratch" ]] || json="$(_agent_vm_build_mounts_json "$vm" "$dir" "$writable" "${protect_git:+$ro_names}")"
219新增: if ! out=$(cd /tmp && limactl edit "$vm" --set "$(_agent_vm_mounts_expr "$json" "$protect_git")" 2>&1); then
220新增: echo "Error: could not set the shares of VM '$vm':" >&2
221新增: echo "$out" >&2
222新增: return 1
450223 fi
451删除: if [[ -n "$want_mem" && "$want_mem" != "$cur_mem" ]]; then
452删除: return 0
224新增: _agent_vm_record_mounts "$vm" "$json"
225新增:}
226新增:
227新增:# The caller's memory, cpus, ssh_port and disk, on the stopped <vm>. The disk
228新增:# apart, with a warning only: Lima rejects a whole edit that would shrink it.
229新增:_agent_vm_apply_resources() {
230新增: local vm="$1" out args=()
231新增: [[ -z "$memory" ]] || args+=(--memory "$memory")
232新增: [[ -z "$cpus" ]] || args+=(--cpus "$cpus")
233新增: [[ -z "$ssh_port" ]] || args+=(--set ".ssh.localPort = $ssh_port")
234新增: # Never without arguments: `limactl edit <vm>` alone opens $EDITOR.
235新增: if [[ ${#args[@]} -gt 0 ]] && ! out=$(cd /tmp && limactl edit "$vm" "${args[@]}" 2>&1); then
236新增: echo "Error: could not set the memory, CPUs or SSH port of VM '$vm':" >&2
237新增: echo "$out" >&2
238新增: return 1
453239 fi
454删除: if [[ -n "$want_disk" && "$want_disk" -gt "$cur_disk" ]]; then
455删除: return 0
240新增: if [[ -n "$disk" ]] && ! out=$(cd /tmp && limactl edit "$vm" --disk "$disk" 2>&1); then
241新增: echo "Warning: cannot set the disk of VM '$vm' to $disk GiB: it can grow, not shrink ('agent-vm setup --disk $disk' for a smaller base)." >&2
242新增: echo "$out" >&2
456243 fi
457删除: return 1
244新增: return 0
245新增:}
246新增:
247新增:# The env push and the write probe (see _agent_vm_push_env_and_probe), with
248新增:# the caller's vm_name, host_dir, env_payload, guest_env and guest_runtime,
249新增:# into its probe_out and is_writable.
250新增:_agent_vm_push_and_probe() {
251新增: is_writable="false"
252新增: probe_out="$(_agent_vm_push_env_and_probe "$vm_name" "$host_dir" "$env_payload" \
253新增: "$guest_env" "$guest_runtime")" && is_writable="true"
254新增: [[ "$probe_out" == *env-ok* ]] || echo "Warning: failed to push the env files into VM '$vm_name'." >&2
458255}
459256
460257# Ensure the VM for cwd exists and is running, creating/starting as needed
461删除:# Usage: _agent_vm_ensure_running <vm_name> <host_dir> [--disk GB] [--memory GB] [--reset]
258新增:# Usage: _agent_vm_ensure_running <vm_name> <host_dir> [vm_opts...], the options
259新增:# as _agent_vm_take_opt collects them (checked already).
462260_agent_vm_ensure_running() {
463261 local vm_name="$1"
464262 local host_dir="$2"
465263 shift 2
466删除: local disk="" memory="" cpus="" reset="" offline="" rdonly="" git_ro=""
264新增: local disk="" memory="" cpus="" ssh_port="" reset="" rdonly="" scratch="" _agent_vm_unsafe_git_flag="" _agent_vm_unsafe_no_prompts=""
467265 while [[ $# -gt 0 ]]; do
468266 case "$1" in
469267 --disk) disk="$2"; shift 2 ;;
470删除: --memory|--ram) memory="$2"; shift 2 ;;
268新增: --memory) memory="$2"; shift 2 ;;
471269 --cpus) cpus="$2"; shift 2 ;;
270新增: --ssh-port) ssh_port="$2"; shift 2 ;;
472271 --reset) reset=1; shift ;;
473删除: --offline) offline=1; shift ;;
474272 --readonly) rdonly=1; shift ;;
475删除: --git-read-only|--git-ro) git_ro=1; shift ;;
273新增: --scratch) scratch=1; shift ;;
274新增: --unsafe-writable-git) _agent_vm_unsafe_git_flag=1; shift ;;
275新增: --unsafe-disable-security-prompts) _agent_vm_unsafe_no_prompts=1; shift ;;
476276 *) shift ;;
477277 esac
478278 done
479279
480删除: # Lima's host mount cannot share a path containing whitespace: the mount
481删除: # fails silently and the VM starts with a bare, root-owned mountpoint, so
482删除: # every write into the project (e.g. creating .claude) fails with
483删除: # "Permission denied". Fail fast with an actionable message instead.
484删除: if [[ "$host_dir" == *[[:space:]]* ]]; then
485删除: echo "Error: project path contains whitespace, which Lima cannot mount:" >&2
280新增: # --scratch (see _agent_vm_run_scratch) shares nothing: no share check
281新增: # below applies to it.
282新增: if [[ -n "$scratch" && ( -n "$reset" || -n "$rdonly" ) ]]; then
283新增: echo "Error: --scratch makes a new VM that shares nothing: --reset and --readonly do not go with it." >&2
284新增: return 1
285新增: fi
286新增:
287新增: local want_writable="true"
288新增: [[ -n "$rdonly" ]] && want_writable="false"
289新增:
290新增: # Clamped once, so every path below compares and applies the same values.
291新增: cpus="$(_agent_vm_cap_resource cpus "$cpus")"
292新增: memory="$(_agent_vm_cap_resource memory "$memory")"
293新增: _agent_vm_warn_disk_space "$disk"
294新增:
295新增: # Two VMs set to one port: the second would fail to start.
296新增: if [[ -n "$ssh_port" && "$ssh_port" != 0 ]]; then
297新增: local other
298新增: other="$(limactl list --format '{{.Name}} {{.Config.SSH.LocalPort}}' 2>/dev/null \
299新增: | awk -v vm="$vm_name" -v p="$ssh_port" '$1 != vm && $2 == p { print $1; exit }')"
300新增: if [[ -n "$other" ]]; then
301新增: echo "Error: SSH port $ssh_port is already set for VM '$other'." >&2
302新增: return 1
303新增: fi
304新增: fi
305新增:
306新增: # `cd ~ && agent-vm shell` would hand the VM your dotfiles and SSH keys,
307新增: # read-write, and a share holding agent-vm's own files lets the VM change
308新增: # what the host runs next.
309新增: local unsafe
310新增: if [[ -z "$scratch" ]] && unsafe="$(_agent_vm_unsafe_project "$host_dir")"; then
311新增: echo "Error: refusing to share $host_dir with a VM: it $unsafe." >&2
312新增: echo "Run agent-vm from a project directory." >&2
313新增: return 1
314新增: fi
315新增:
316新增: local bad
317新增: if [[ -z "$scratch" ]] && bad="$(_agent_vm_unmountable_path "$host_dir")"; then
318新增: echo "Error: project path $bad:" >&2
486319 echo " $host_dir" >&2
487删除: echo "Rename the directory to remove spaces (e.g. with '-'), then retry." >&2
320新增: echo "Rename the directory, then retry." >&2
488321 return 1
489322 fi
490323
491删除: # Recover from an interrupted previous run that left ~/.lima/<vm>/ without
492删除: # a lima.yaml — otherwise every limactl call on this name aborts with a
493删除: # cryptic "no such file or directory".
324新增: # A run interrupted while Lima created it leaves a folder without lima.yaml.
494325 _agent_vm_clean_partial_state "$vm_name"
495326
496327 if ! _agent_vm_base_exists; then
497删除: echo "Error: Base VM not found. Run 'agent-vm setup' first." >&2
328新增: # Distinguish "never set up" from "setup died halfway": the second one
329新增: # leaves a template that looks fine in `limactl list` but is empty.
330新增: if _agent_vm_exists "$AGENT_VM_TEMPLATE"; then
331新增: echo "Error: Base VM setup did not complete. Run 'agent-vm setup' again." >&2
332新增: else
333新增: echo "Error: Base VM not found. Run 'agent-vm setup' first." >&2
334新增: fi
498335 return 1
499336 fi
500337
338新增: # The security checks, before anything changes. A running VM is asked
339新增: # nothing until stopped (see _agent_vm_recheck_after_stop).
340新增: local vm_up="" protect_git="" ro_names="" hooks_notes=""
341新增: [[ -z "$reset" ]] && _agent_vm_running "$vm_name" && vm_up=1
342新增: _agent_vm_start_checks "$host_dir" "$vm_name" || return 1
343新增:
501344 # Destroy existing VM if --reset was requested
502345 if [[ -n "$reset" ]] && _agent_vm_exists "$vm_name"; then
503346 echo "Resetting VM '$vm_name'..."
504删除: limactl stop "$vm_name" &>/dev/null
505删除: limactl delete "$vm_name" --force &>/dev/null
506删除: _agent_vm_cleanup_state "$vm_name"
347新增: _agent_vm_delete_vm "$vm_name" || return 1
507348 fi
508349
509删除: local is_new_vm=""
350新增: local is_new_vm="" apply_resize=""
510351 local file_mount_entries=()
511352 local file_mounts_cache="$AGENT_VM_STATE_DIR/.agent-vm-file-mounts-${vm_name}"
512353
513354 if ! _agent_vm_exists "$vm_name"; then
514355 is_new_vm=1
515356 echo "Creating VM '$vm_name'..."
516删除: limactl clone "$AGENT_VM_TEMPLATE" "$vm_name" --tty=false &>/dev/null
517删除: # Apply mount and resource settings via edit after clone
518删除: # Mount and memory/cpus are applied separately from disk, because
519删除: # Lima rejects the entire edit if disk shrinking is attempted.
520删除: local mounts_json
521删除: mounts_json=$(_agent_vm_build_mounts_json "$vm_name" "$host_dir")
522删除: local edit_args=()
523删除: edit_args+=(--set ".mounts = ${mounts_json}")
524删除: [[ -n "$memory" ]] && edit_args+=(--memory "$memory")
525删除: [[ -n "$cpus" ]] && edit_args+=(--cpus "$cpus")
526删除: (cd /tmp && limactl edit "$vm_name" ${edit_args[@]+"${edit_args[@]}"}) &>/dev/null
527删除: if [[ -n "$disk" ]]; then
528删除: if ! (cd /tmp && limactl edit "$vm_name" --disk "$disk") &>/dev/null; then
529删除: echo "Warning: Cannot set disk to ${disk} GiB (shrinking is not supported). Re-run 'agent-vm setup --disk ${disk}' for a smaller base." >&2
530删除: fi
357新增: local create_out
358新增: if ! create_out=$(limactl clone "$AGENT_VM_TEMPLATE" "$vm_name" --tty=false 2>&1); then
359新增: echo "Error: could not clone the base template into '$vm_name':" >&2
360新增: echo "$create_out" >&2
361新增: return 1
531362 fi
532删除: _agent_vm_print_resources "$vm_name"
533删除: # Record which base version this VM was cloned from
363新增: # Which agent-vm built its base: none recorded for a base of 0.1.0, which
364新增: # has no sshfs for the protected shares. Then migrated before the edit,
365新增: # on the bare clone (see _agent_vm_migrate_0_1).
366新增: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-built-by-${vm_name}" "$AGENT_VM_STATE_DIR/.agent-vm-sshfs-${vm_name}"
367新增: if [[ -f "$AGENT_VM_STATE_DIR/.agent-vm-base-built-by" ]]; then
368新增: cp "$AGENT_VM_STATE_DIR/.agent-vm-base-built-by" "$AGENT_VM_STATE_DIR/.agent-vm-built-by-${vm_name}"
369新增: fi
370新增: if [[ -n "$protect_git" ]] && ! _agent_vm_migrate_0_1_if_needed "$vm_name"; then
371新增: _agent_vm_delete_vm "$vm_name"
372新增: return 1
373新增: fi
374新增: # Configured before its first start. A clone that could not be holds
375新增: # nothing yet: it goes, and the next run starts over (#21).
376新增: if ! _agent_vm_apply_shares "$vm_name" "$host_dir" "$want_writable" \
377新增: || ! _agent_vm_apply_resources "$vm_name"; then
378新增: _agent_vm_delete_vm "$vm_name"
379新增: return 1
380新增: fi
381新增: printf '%s' "$hooks_notes"
382新增: # Which base it was cloned from, for the stale warning below.
534383 local base_ver="$AGENT_VM_STATE_DIR/.agent-vm-base-version"
535384 if [[ -f "$base_ver" ]]; then
536385 cp "$base_ver" "$AGENT_VM_STATE_DIR/.agent-vm-version-${vm_name}"
537386 fi
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.
387新增: elif { [[ -n "$disk" || -n "$memory" || -n "$cpus" ]] \
388新增: && _agent_vm_resources_differ "$vm_name" "$cpus" "$memory" "$disk"; } \
389新增: || _agent_vm_ssh_port_differs "$vm_name" "$ssh_port"; then
390新增: # Only when the request differs from what the VM has: a caller passing
391新增: # its defaults every time would otherwise be asked every time. Declined,
392新增: # the VM keeps its settings and everything below still applies.
393新增: apply_resize=1
544394 if _agent_vm_running "$vm_name"; then
545删除: echo "VM '$vm_name' is currently running. It must be stopped to apply new resource settings."
546删除: printf "Stop the VM and apply changes? [y/N] " >&2
547删除: local reply=""
548删除: IFS= read -r reply </dev/tty 2>/dev/null || reply=""
549删除: if [[ ! "$reply" =~ ^[Yy]$ ]]; then
550删除: echo "Aborted. Starting with current settings."
551删除: return 0
552删除: fi
553删除: echo "Stopping VM..."
554删除: limactl stop "$vm_name" &>/dev/null
555删除: fi
556删除: echo "Updating VM resources..."
557删除: # Don't touch .mounts here — those are baked in at creation (including any
558删除: # entries from ~/.agent-vm/volumes). Re-setting them would clobber extras.
559删除: local edit_args=()
560删除: [[ -n "$memory" ]] && edit_args+=(--memory "$memory")
561删除: [[ -n "$cpus" ]] && edit_args+=(--cpus "$cpus")
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
572删除: fi
573删除: if [[ -n "$disk" ]]; then
574删除: if ! edit_output=$(cd /tmp && limactl edit "$vm_name" --disk "$disk" 2>&1); then
575删除: echo "Warning: Cannot set disk to ${disk} GiB (shrinking is not supported). Re-run 'agent-vm setup --disk ${disk}' for a smaller base." >&2
395新增: echo "VM '$vm_name' is currently running. It must be stopped to apply new settings."
396新增: if _agent_vm_can_ask && [[ "$(_agent_vm_ask_yn "Stop the VM and apply changes?" N)" == "1" ]]; then
397新增: echo "Stopping VM..."
398新增: _agent_vm_stop_to_change "$vm_name" "$host_dir" || return 1
399新增: else
400新增: echo "Not applied: the VM keeps its current settings."
401新增: apply_resize=""
576402 fi
577403 fi
578删除: _agent_vm_print_resources "$vm_name"
404新增: fi
405新增: if [[ -n "$apply_resize" ]]; then
406新增: echo "Updating VM settings..."
407新增: _agent_vm_apply_resources "$vm_name" || return 1
579408 fi
580409
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.
410新增: # The same verdict as `info`'s vm_stale=.
584411 if [[ "$(_agent_vm_stale_state "$vm_name")" == "1" ]]; then
585412 echo "Warning: Base VM has been updated since this VM was cloned. Use --reset to re-clone from the new base." >&2
586413 fi
587414
588删除: if ! _agent_vm_running "$vm_name"; then
415新增: # Whether another session may be using it: read before the start below.
416新增: local was_running=""
417新增: _agent_vm_running "$vm_name" && was_running=1
418新增:
419新增: # Shares recorded otherwise than asked: the .git protection (git_stale), its
420新增: # names (names_stale), the mode (mode_stale). A stopped VM is changed before
421新增: # it boots, so nothing starting with it gets a writable window; a running
422新增: # one keeps its shares until stopped, or is offered a restart.
423新增: local was_protected="" git_stale="" names_stale="" mode_stale=""
424新增: _agent_vm_mounts_protect_git "$vm_name" && was_protected=1
425新增: [[ "$was_protected" != "$protect_git" ]] && git_stale=1
426新增: if [[ -n "$protect_git" && -n "$was_protected" ]] \
427新增: && ! _agent_vm_mounts_have_readonly_names "$vm_name" "$ro_names"; then
428新增: names_stale=1
429新增: fi
430新增: if [[ -n "$scratch" ]]; then
431新增: # Shares nothing, as made: nothing to bring in line.
432新增: git_stale=""
433新增: elif [[ "$want_writable" == "false" ]]; then
434新增: _agent_vm_mounts_all_readonly "$vm_name" || mode_stale=1
435新增: elif _agent_vm_mounts_all_readonly "$vm_name"; then
436新增: mode_stale=1
437新增: fi
438新增: # A running VM lacking a protection it should have: restarting it cuts its
439新增: # other sessions, so it is asked; declined, it is a risk to accept. Not
440新增: # under --readonly, which restarts it below anyway.
441新增: if [[ -z "$rdonly" && -n "$was_running" && -n "$protect_git" && ( -n "$git_stale" || -n "$names_stale" ) ]]; then
442新增: if [[ -n "$git_stale" ]]; then
443新增: echo "Warning: VM '$vm_name' is running with .git writable, so the agent can still write .git." >&2
444新增: else
445新增: echo "Warning: VM '$vm_name' runs with an older list of read-only names (it needs $(_agent_vm_names_text "$ro_names")), so the agent can still write the new ones." >&2
446新增: fi
447新增: if ! _agent_vm_prompts_disabled_by >/dev/null && _agent_vm_can_ask \
448新增: && [[ "$(_agent_vm_ask_yn "Restart it now to apply them? Sessions using it are cut." Y)" == "1" ]]; then
449新增: _agent_vm_stop_to_change "$vm_name" "$host_dir" || return 1
450新增: was_running=""
451新增: elif ! _agent_vm_confirm_unsafe; then
452新增: echo "Aborted. 'agent-vm stop', then run again." >&2
453新增: return 1
454新增: fi
455新增: fi
456新增: if [[ -n "$git_stale" && -n "$was_running" ]]; then
457新增: if [[ -n "$protect_git" ]]; then
458新增: :
459新增: elif _agent_vm_writable_git_optout; then
460新增: echo "Note: VM '$vm_name' keeps .git read-only until it stops." >&2
461新增: else
462新增: echo "Warning: this Lima cannot keep .git read-only; VM '$vm_name' keeps its current shares until it stops." >&2
463新增: fi
464新增: elif [[ -n "$names_stale" && -n "$was_running" ]]; then
465新增: :
466新增: elif [[ -z "$was_running" && ( -n "$git_stale" || -n "$names_stale" || -n "$mode_stale" ) ]]; then
467新增: if [[ -n "$git_stale" ]]; then
468新增: if [[ -n "$protect_git" ]]; then
469新增: echo "Making every .git read-only for VM '$vm_name'..."
470新增: elif _agent_vm_writable_git_optout; then
471新增: echo "Making .git writable for VM '$vm_name' ($(_agent_vm_writable_git_why))..." >&2
472新增: else
473新增: echo "Warning: this Lima cannot keep .git read-only; VM '$vm_name' goes back to Lima's default mount type." >&2
474新增: fi
475新增: elif [[ -n "$names_stale" ]]; then
476新增: echo "Making $(_agent_vm_names_text "$ro_names") read-only for VM '$vm_name'..."
477新增: fi
478新增: [[ -n "$git_stale" || -n "$names_stale" ]] && printf '%s' "$hooks_notes"
479新增: if [[ -n "$protect_git" ]]; then
480新增: _agent_vm_migrate_0_1_if_needed "$vm_name" || return 1
481新增: fi
482新增: if [[ -n "$mode_stale" && "$want_writable" == "false" ]]; then
483新增: echo "Making every share of VM '$vm_name' read-only..."
484新增: elif [[ -n "$mode_stale" ]]; then
485新增: echo "VM '$vm_name' was left read-only by --readonly; making it writable again..."
486新增: fi
487新增: _agent_vm_apply_shares "$vm_name" "$host_dir" "$want_writable" || return 1
488新增: fi
489新增:
490新增: if [[ -z "$was_running" ]]; then
589491 echo "Starting VM '$vm_name'..."
590492 local start_log
591493 if ! start_log=$(limactl start "$vm_name" 2>&1); then
494新增: local ha_log
495新增: ha_log="$(_agent_vm_lima_home)/$vm_name/ha.stderr.log"
592496 echo "Error: Failed to start VM '$vm_name'." >&2
593497 echo "--- limactl start output ---" >&2
594498 echo "$start_log" >&2
595删除: echo "Full log: ~/.lima/$vm_name/ha.stderr.log" >&2
499新增: echo "Full log: $ha_log" >&2
500新增: _agent_vm_windows_start_hint "$ha_log"
501新增: return 1
502新增: fi
503新增: fi
504新增:
505新增: # Bring the shares of the running VM in line with the mode asked: a write
506新增: # probe on the project (see _agent_vm_push_env_and_probe, which pushes the
507新增: # env too), and the record for the other shares, a missing one counting as
508新增: # writable. A mismatch is a stop, edit and start: a broken mount repaired,
509新增: # --readonly applied, or a --readonly VM made writable again.
510新增: # --scratch takes nothing of the project but ~/.agent-vm/env, and works at
511新增: # the project's path on the VM's own disk.
512新增: local is_writable="false" probe_out guest_env="" guest_runtime="" project_env="" project_runtime="" env_payload
513新增: if [[ -n "$scratch" ]]; then
514新增: if ! limactl shell "$vm_name" sh -c 'sudo install -d -o "$(id -u)" -g "$(id -g)" "$1"' sh "$host_dir" </dev/null >/dev/null 2>&1; then
515新增: echo "Error: could not make $host_dir in VM '$vm_name'." >&2
596516 return 1
597517 fi
518新增: env_payload="$( [ ! -f "$AGENT_VM_STATE_DIR/env" ] || _agent_vm_strip_cr < "$AGENT_VM_STATE_DIR/env" )"
519新增: else
520新增: project_env="$(_agent_vm_project_env_file "$host_dir")"
521新增: project_runtime="$(_agent_vm_project_runtime_path "$host_dir")"
522新增: # By their path in the project, the one the VM has.
523新增: local in_rel
524新增: in_rel="$(_agent_vm_project_rel "$host_dir" "$project_env")" && guest_env="$host_dir/$in_rel"
525新增: in_rel="$(_agent_vm_project_rel "$host_dir" "$project_runtime")" && guest_runtime="$host_dir/$in_rel"
526新增: env_payload="$(_agent_vm_env_payload "$host_dir")"
598527 fi
528新增: _agent_vm_push_and_probe
529新增: # A scratch VM has no share to repair: the repair below would mount the
530新增: # project into it.
531新增: if [[ -n "$scratch" && "$is_writable" != "true" ]]; then
532新增: echo "Error: $host_dir is not writable in VM '$vm_name'." >&2
533新增: return 1
534新增: fi
535新增: local needs_remount=""
536新增: [[ "$is_writable" != "$want_writable" ]] && needs_remount=1
537新增: if [[ "$want_writable" == "false" ]] && ! _agent_vm_mounts_all_readonly "$vm_name"; then
538新增: needs_remount=1
539新增: fi
540新增:
541新增: if [[ -n "$needs_remount" ]]; then
542新增: # Stopping kills whatever else is using this VM, so ask first rather than
543新增: # yanking a running session out from under another terminal, in both
544新增: # directions. The repair direction does not ask: a broken mount is
545新增: # already unusable.
546新增: if [[ "$want_writable" == "true" && -n "$was_running" ]] && _agent_vm_mounts_all_readonly "$vm_name"; then
547新增: echo "VM '$vm_name' runs read-only (--readonly). It must be restarted to make its shares writable."
548新增: if ! _agent_vm_can_ask || [[ "$(_agent_vm_ask_yn "Stop the VM and make it writable? Sessions using it are cut." N)" != "1" ]]; then
549新增: echo "Error: not restarted. Pass --readonly to use it as it is, or 'agent-vm stop' it first." >&2
550新增: return 1
551新增: fi
552新增: elif [[ "$want_writable" == "false" ]] && [[ -n "$was_running" ]]; then
553新增: echo "VM '$vm_name' was already running. It must be restarted to make its shares read-only."
554新增: if ! _agent_vm_can_ask || [[ "$(_agent_vm_ask_yn "Stop the VM and apply --readonly?" N)" != "1" ]]; then
555新增: # Not "continue with current settings" like the resize path does:
556新增: # carrying on writable after --readonly was asked for is the one
557新增: # outcome that must not be silent.
558新增: echo "Error: --readonly was requested but not applied. Aborting." >&2
559新增: return 1
560新增: fi
561新增: elif [[ "$want_writable" == "true" ]]; then
562新增: echo "Project mount is not writable; repairing..." >&2
563新增: fi
599564
600删除: # Sanity-check that the project directory is actually shared and writable.
601删除: # A silently-failed or stale mount leaves a bare, root-owned mountpoint;
602删除: # without this check every later write (runtime scripts, the agent itself)
603删除: # fails with a confusing cascade of "Permission denied" instead of one clear
604删除: # error. Runs before the optional --readonly remount below, so it reflects
605删除: # the mount itself, not the requested read-only restriction.
606删除: #
607删除: # If the mount is broken, try to self-heal once: re-apply the mount config
608删除: # (Lima only allows editing a stopped VM) and restart. This repairs a stale
609删除: # or silently-missing mount without forcing a full --reset, and adds no
610删除: # overhead on the common path where the mount is already healthy.
611删除: if ! limactl shell "$vm_name" test -w "$host_dir" &>/dev/null; then
612删除: echo "Project mount is not writable; repairing..." >&2
613删除: limactl stop "$vm_name" &>/dev/null
614删除: # Rebuild the full mounts JSON so any ~/.agent-vm/volumes entries are
615删除: # preserved across the repair (a plain project-dir-only set would silently
616删除: # drop them).
617删除: local repair_mounts_json
618删除: repair_mounts_json=$(_agent_vm_build_mounts_json "$vm_name" "$host_dir")
619删除: (cd /tmp && limactl edit "$vm_name" \
620删除: --set ".mounts = ${repair_mounts_json}") &>/dev/null
621删除: limactl start "$vm_name" &>/dev/null
622删除: if ! limactl shell "$vm_name" test -w "$host_dir" &>/dev/null; then
623删除: echo "Error: project directory is still not writable inside the VM:" >&2
624删除: echo " $host_dir" >&2
625删除: echo "The host mount failed to attach. Try 'agent-vm --reset <command>'" >&2
626删除: echo "to re-clone the VM from the base template." >&2
565新增: # Stopped for sure first: recording read-only shares while it still runs
566新增: # writable would claim what is not true.
567新增: _agent_vm_stop_to_change "$vm_name" "$host_dir" || return 1
568新增: if [[ -n "$protect_git" ]]; then
569新增: _agent_vm_migrate_0_1_if_needed "$vm_name" || return 1
570新增: fi
571新增: _agent_vm_apply_shares "$vm_name" "$host_dir" "$want_writable" || return 1
572新增: # Checked: the probe below cannot tell a dead VM from a read-only one.
573新增: if ! limactl start "$vm_name" &>/dev/null; then
574新增: echo "Error: VM '$vm_name' did not come back up after changing the project mount." >&2
575新增: return 1
576新增: fi
577新增: # Again: in the repair case the first probe could not see the project's
578新增: # env file and runtime script.
579新增: _agent_vm_push_and_probe
580新增: if [[ "$is_writable" != "$want_writable" ]]; then
581新增: if [[ "$want_writable" == "true" ]]; then
582新增: echo "Error: project directory is still not writable inside the VM:" >&2
583新增: echo " $host_dir" >&2
584新增: echo "The host mount failed to attach. Try 'agent-vm --reset <command>'" >&2
585新增: echo "to re-clone the VM from the base template." >&2
586新增: else
587新增: echo "Error: failed to mount the project directory read-only:" >&2
588新增: echo " $host_dir" >&2
589新增: fi
627590 return 1
628591 fi
629592 fi
630593
631删除: # Install the host's terminfo entry inside the VM so non-standard terminals
632删除: # (xterm-ghostty, xterm-kitty, …) work correctly. Without this, zsh/ZLE
633删除: # can't decode keys → broken backspace, arrows, etc. Cached per-VM so we only
634删除: # pay the limactl shell roundtrip when $TERM actually changes.
594新增: # --readonly is only claimed where the host enforces it (see
595新增: # _agent_vm_mount_is_host_enforced); "could not tell" is refused too.
596新增: if [[ -n "$rdonly" ]]; then
597新增: _agent_vm_mount_is_host_enforced "$vm_name"
598新增: case $? in
599新增: 0) echo "Read-only: the project and every other share (enforced on the host)." ;;
600新增: 1) echo "Error: --readonly cannot be enforced with this mount type." >&2
601新增: echo " Lima only applies it inside the guest for reverse-sshfs (without" >&2
602新增: echo " readonlyNames) and for virtiofs under QEMU, where root in the VM" >&2
603新增: echo " can remount it read-write. Use virtiofs on vz, or 9p on QEMU (both" >&2
604新增: echo " enforce it on the host), in your Lima config, then --reset." >&2
605新增: return 1 ;;
606新增: *) echo "Error: could not determine the project mount type, so --readonly" >&2
607新增: echo " cannot be confirmed as enforced outside the VM. Aborting." >&2
608新增: return 1 ;;
609新增: esac
610新增: fi
611新增:
612新增: # The host's terminfo entry in the VM, for terminals Debian does not know
613新增: # (xterm-ghostty, xterm-kitty): zsh cannot read their keys otherwise. Once
614新增: # per VM and $TERM.
635615 local term_cache="$AGENT_VM_STATE_DIR/.agent-vm-term-${vm_name}"
636616 if [[ -n "${TERM:-}" ]] && [[ "$(cat "$term_cache" 2>/dev/null)" != "$TERM" ]] \
637617 && infocmp -x "$TERM" &>/dev/null; then
638618 if infocmp -x "$TERM" | limactl shell "$vm_name" sudo tic -x - &>/dev/null; then
639删除: echo "$TERM" > "$term_cache"
619新增: echo "$TERM" >| "$term_cache"
640620 else
641621 echo "Warning: failed to install '$TERM' terminfo inside VM." >&2
642622 fi
643623 fi
644624
645删除: # Push ~/.agent-vm/env (a dotenv-style file of tokens / API keys) into the VM
646删除: # at $HOME/.agent-vm.env on every start, so updates on the host propagate
647删除: # without --reset. The base VM's ~/.zshenv auto-sources it via `set -a`, so
648删除: # the contents stay a plain KEY=value file (no `export` needed). `umask 077`
649删除: # creates the file mode-600 since it usually holds secrets.
650删除: if [ -f "$AGENT_VM_STATE_DIR/env" ]; then
651删除: if ! limactl shell "$vm_name" sh -c 'umask 077 && rm -f "$HOME/.agent-vm.env" && cat > "$HOME/.agent-vm.env"' \
652删除: < "$AGENT_VM_STATE_DIR/env" 2>/dev/null; then
653删除: echo "Warning: failed to push ~/.agent-vm/env into VM '$vm_name'." >&2
654删除: fi
655删除: fi
656删除:
657625 # Run per-user runtime script if it exists
658626 if [ -f "$AGENT_VM_STATE_DIR/runtime.sh" ]; then
659627 echo "Running user runtime setup..."
660删除: limactl shell --workdir "$host_dir" "$vm_name" zsh -l < "$AGENT_VM_STATE_DIR/runtime.sh"
628新增: _agent_vm_run_runtime "$vm_name" "$host_dir" "$AGENT_VM_STATE_DIR/runtime.sh"
661629 fi
662630
663删除: # Run project-specific runtime script if it exists
664删除: if [ -f "${host_dir}/.agent-vm.runtime.sh" ]; then
665删除: echo "Running project runtime setup..."
666删除: limactl shell --workdir "$host_dir" "$vm_name" zsh -l < "${host_dir}/.agent-vm.runtime.sh"
667删除: fi
668删除:
669删除: # Apply per-session restrictions
670删除: if [[ -n "$offline" ]]; then
671删除: echo "Enabling offline mode..."
672删除: limactl shell "$vm_name" sudo iptables -F OUTPUT 2>/dev/null
673删除: limactl shell "$vm_name" sudo iptables -A OUTPUT -o lo -j ACCEPT
674删除: limactl shell "$vm_name" sudo iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT
675删除: limactl shell "$vm_name" sudo iptables -A OUTPUT -d 172.16.0.0/12 -j ACCEPT
676删除: limactl shell "$vm_name" sudo iptables -A OUTPUT -d 192.168.0.0/16 -j ACCEPT
677删除: limactl shell "$vm_name" sudo iptables -P OUTPUT DROP
678删除: fi
679删除:
680删除: if [[ -n "$rdonly" ]]; then
681删除: # `mount -o remount,ro` on the host share fails silently when Lima uses
682删除: # a FUSE-backed mount (sshfs/virtiofs in some configurations) — FUSE
683删除: # rejects the `remount` option and the FS stays writable. Self-bind the
684删除: # directory first so we have a plain Linux bind-mount layer to remount,
685删除: # which works regardless of what's underneath.
686删除: echo "Mounting project directory as read-only..."
687删除: if ! limactl shell "$vm_name" sudo mount --bind "$host_dir" "$host_dir" \
688删除: || ! limactl shell "$vm_name" sudo mount -o remount,ro,bind "$host_dir"; then
689删除: echo "Error: Failed to mount project directory as read-only." >&2
690删除: return 1
691删除: fi
692删除: fi
693删除:
694删除: if [[ -n "$git_ro" ]] && [[ -d "$host_dir/.git" ]]; then
695删除: echo "Mounting .git directory as read-only..."
696删除: if ! limactl shell "$vm_name" sudo mount --bind "$host_dir/.git" "$host_dir/.git" \
697删除: || ! limactl shell "$vm_name" sudo mount -o remount,ro,bind "$host_dir/.git"; then
698删除: echo "Error: Failed to mount .git directory as read-only." >&2
699删除: return 1
631新增: # Run project-specific runtime script if it exists: by its path in the VM
632新增: # when it is in the project (the probe above said whether it is there),
633新增: # piped from the host when AGENT_VM_PROJECT_RUNTIME puts it elsewhere.
634新增: if [[ -n "$guest_runtime" ]]; then
635新增: if [[ "$probe_out" == *runtime-found* ]]; then
636新增: echo "Running project runtime setup..."
637新增: _agent_vm_run_project_runtime "$vm_name" "$host_dir" "$guest_runtime"
700638 fi
639新增: elif [ -f "$project_runtime" ]; then
640新增: echo "Running project runtime setup..."
641新增: _agent_vm_run_runtime "$vm_name" "$host_dir" "$project_runtime"
701642 fi
702643
703删除: # Load file mount entries from the cache. _agent_vm_build_mounts_json writes
704删除: # them there (from its own local scope) for both new and existing VMs, so we
705删除: # always read them back here to drive the inside-VM bind mounts below.
644新增: # Single files of ~/.agent-vm/volumes (see _agent_vm_build_mounts_json, which
645新增: # lists them in the cache): an existing VM's staged copy refreshed, so an
646新增: # edit saved by rename on the host shows, then each bound at its place in
647新增: # the VM, in one round trip. The bind does not survive a restart, and is
648新增: # skipped when there.
706649 if [[ -f "$file_mounts_cache" ]]; then
707删除: local entry
708删除: while IFS= read -r entry; do
709删除: [[ -n "$entry" ]] && file_mount_entries+=("$entry")
710删除: done < "$file_mounts_cache"
711删除:
712删除: # For existing VMs, refresh host-side hardlinks so atomic-rename edits on the
713删除: # host propagate after a VM restart (ln/cp against the cached staging path).
714删除: # New VMs just staged fresh copies in _agent_vm_build_mounts_json, so there
715删除: # is nothing to refresh.
716删除: if [[ -z "$is_new_vm" ]] && [[ ${#file_mount_entries[@]} -gt 0 ]]; then
717删除: local host_src host_staging _bind_src _bind_dst
718删除: for entry in "${file_mount_entries[@]}"; do
719删除: IFS='|' read -r host_src host_staging _bind_src _bind_dst <<< "$entry"
720删除: [[ -z "$host_staging" ]] && continue
721删除: if [[ ! -e "$host_src" ]]; then
722删除: echo "Warning: Mount source '${host_src}' no longer exists; VM will see the last-staged copy." >&2
723删除: continue
724删除: fi
650新增: local host_src host_staging bind_src bind_dst
651新增: while IFS='|' read -r host_src host_staging bind_src bind_dst; do
652新增: [[ -n "$host_staging" ]] || continue
653新增: if [[ -n "$is_new_vm" ]]; then
654新增: :
655新增: elif [[ ! -e "$host_src" ]]; then
656新增: echo "Warning: Mount source '${host_src}' no longer exists; VM will see the last-staged copy." >&2
657新增: else
725658 _agent_vm_stage_file "$host_src" "$host_staging" \
726659 || echo "Warning: Failed to refresh staged '${host_src}'; VM may see stale content." >&2
727删除: done
728删除: fi
729删除: fi
730删除:
731删除: # Apply inside-VM bind mounts so each staged file appears at its final path.
732删除: # Lima re-mounts staging dirs on each start, but the bind onto the final dest
733删除: # is ephemeral. Batched into one limactl shell call (roundtrips cost ~1-2s)
734删除: # and made idempotent so re-runs on a running VM are cheap no-ops.
735删除: if [[ ${#file_mount_entries[@]} -gt 0 ]]; then
736删除: local file_bind_payload=()
737删除: local _host_src _host_staging bind_src bind_dst
738删除: for entry in "${file_mount_entries[@]}"; do
739删除: IFS='|' read -r _host_src _host_staging bind_src bind_dst <<< "$entry"
740删除: [[ -n "$bind_src" && -n "$bind_dst" ]] && file_bind_payload+=("${bind_src}|${bind_dst}")
741删除: done
742删除: if [[ ${#file_bind_payload[@]} -gt 0 ]]; then
660新增: fi
661新增: [[ -n "$bind_src" && -n "$bind_dst" ]] && file_mount_entries+=("${bind_src}|${bind_dst}")
662新增: done < "$file_mounts_cache"
663新增: if [[ ${#file_mount_entries[@]} -gt 0 ]]; then
743664 echo "Mounting individual files..."
744删除: # Paths are passed as positional args (single-quoted script) so entries
745删除: # containing quotes or metacharacters cannot be interpreted as shell code.
665新增: # The paths as arguments, never in the script.
746666 limactl shell "$vm_name" sudo bash -c '
747667 set -e
748668 for entry in "$@"; do
@@ -754,64 +674,44 @@ _agent_vm_ensure_running() {
754674 mount -o remount,ro,bind "$bind_dst"
755675 fi
756676 done
757删除: ' -- "${file_bind_payload[@]}"
677新增: ' -- "${file_mount_entries[@]}"
758678 fi
759679 fi
760680}
761681
682新增:# --- agent-vm: the command, dispatching to the rest ---------------------------
683新增:
762684agent-vm() {
763删除: local vm_opts=()
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.
685新增: # Options before the command are checked here and handed to it as written:
686新增: # the commands that start a VM read them again, with their own.
687新增: local lead=() vm_opts=() rm="" taken
770688 while [[ $# -gt 0 ]]; do
771删除: case "$1" in
772删除: --disk)
773删除: _agent_vm_validate_int --disk "$2" || return 1
774删除: vm_opts+=(--disk "$2"); shift 2 ;;
775删除: --disk=*)
776删除: _agent_vm_validate_int --disk "${1#*=}" || return 1
777删除: vm_opts+=(--disk "${1#*=}"); shift ;;
778删除: --memory|--ram)
779删除: _agent_vm_validate_int --memory "$2" || return 1
780删除: vm_opts+=(--memory "$2"); shift 2 ;;
781删除: --memory=*|--ram=*)
782删除: _agent_vm_validate_int --memory "${1#*=}" || return 1
783删除: vm_opts+=(--memory "${1#*=}"); shift ;;
784删除: --cpus)
785删除: _agent_vm_validate_int --cpus "$2" || return 1
786删除: vm_opts+=(--cpus "$2"); shift 2 ;;
787删除: --cpus=*)
788删除: _agent_vm_validate_int --cpus "${1#*=}" || return 1
789删除: vm_opts+=(--cpus "${1#*=}"); shift ;;
790删除: --reset)
791删除: vm_opts+=(--reset); shift ;;
792删除: --offline)
793删除: vm_opts+=(--offline); shift ;;
794删除: --readonly)
795删除: vm_opts+=(--readonly); shift ;;
796删除: --git-read-only|--git-ro)
797删除: vm_opts+=(--git-read-only); shift ;;
798删除: --rm)
799删除: vm_opts+=(--rm); shift ;;
800删除: *)
801删除: break ;;
802删除: esac
689新增: _agent_vm_take_opt "$@" || return 1
690新增: [[ $taken -gt 0 ]] || break
691新增: lead+=("${@:1:$taken}")
692新增: shift "$taken"
803693 done
804694
805695 local cmd="${1:-help}"
806696 shift 2>/dev/null || true
807697
698新增: # VM options mean nothing to the other commands: `agent-vm --readonly stop`
699新增: # must not read as if something had been made read-only.
700新增: if [[ ${#lead[@]} -gt 0 ]]; then
701新增: case "$cmd" in
702新增: stop|rm|destroy|destroy-all|list|status|name|info|env|project-env|version|--version|-V|doctor|install|uninstall|help|--help|-h)
703新增: echo "Error: ${lead[*]:0:1} is an option for the commands that start a VM (claude, opencode, codex, vibe, pi, shell, run), not for '$cmd'." >&2
704新增: return 1 ;;
705新增: esac
706新增: fi
707新增:
808708 # Every command except help/setup needs limactl present. (setup installs it
809709 # itself; help needs nothing.) Without this, stop/list/status/etc. would fail
810710 # with confusing empty output instead of a clear, actionable message.
811711 case "$cmd" in
812删除: help|--help|-h|setup|version|--version|-V|name|info|env) ;;
712新增: help|--help|-h|setup|version|--version|-V|name|info|env|project-env|doctor|install|uninstall) ;;
813713 *)
814删除: if ! command -v limactl &>/dev/null; then
714新增: if [[ -z "$(_agent_vm_limactl_path)" ]]; then
815715 echo "Error: limactl (Lima) not found. Run 'agent-vm setup' first, or install" >&2
816716 echo "it from https://lima-vm.io/docs/installation/" >&2
817717 return 1
@@ -820,25 +720,16 @@ agent-vm() {
820720
821721 case "$cmd" in
822722 setup)
823删除: _agent_vm_setup ${vm_opts[@]+"${vm_opts[@]}"} "$@"
824删除: ;;
825删除: claude)
826删除: _agent_vm_claude ${vm_opts[@]+"${vm_opts[@]}"} "$@"
827删除: ;;
828删除: opencode)
829删除: _agent_vm_opencode ${vm_opts[@]+"${vm_opts[@]}"} "$@"
830删除: ;;
831删除: codex)
832删除: _agent_vm_codex ${vm_opts[@]+"${vm_opts[@]}"} "$@"
723新增: _agent_vm_setup ${lead[@]+"${lead[@]}"} "$@"
833724 ;;
834删除: vibe)
835删除: _agent_vm_vibe ${vm_opts[@]+"${vm_opts[@]}"} "$@"
725新增: claude|opencode|codex|vibe|pi)
726新增: _agent_vm_agent "$cmd" ${lead[@]+"${lead[@]}"} "$@"
836727 ;;
837728 shell|sh)
838删除: _agent_vm_shell ${vm_opts[@]+"${vm_opts[@]}"} "$@"
729新增: _agent_vm_shell ${lead[@]+"${lead[@]}"} "$@"
839730 ;;
840731 run)
841删除: _agent_vm_run ${vm_opts[@]+"${vm_opts[@]}"} "$@"
732新增: _agent_vm_run ${lead[@]+"${lead[@]}"} "$@"
842733 ;;
843734 stop)
844735 _agent_vm_stop "$@"
@@ -849,11 +740,8 @@ agent-vm() {
849740 destroy-all)
850741 _agent_vm_destroy_all "$@"
851742 ;;
852删除: list)
853删除: _agent_vm_list "$@"
854删除: ;;
855删除: status)
856删除: _agent_vm_status "$@"
743新增: list|status)
744新增: _agent_vm_list
857745 ;;
858746 name)
859747 local name_dir
@@ -866,10 +754,37 @@ agent-vm() {
866754 _agent_vm_info "$info_dir"
867755 ;;
868756 env)
869删除: _agent_vm_env "$@"
757新增: _agent_vm_env env "$AGENT_VM_STATE_DIR/env" "" "$@"
758新增: ;;
759新增: project-env)
760新增: local project_env_file project_top="" project_rel
761新增: project_env_file="$(_agent_vm_project_env_file)"
762新增: if project_rel="$(_agent_vm_project_rel "$(pwd)" "$project_env_file")"; then
763新增: project_top="$(pwd)"
764新增: project_env_file="$project_top/$project_rel"
765新增: fi
766新增: _agent_vm_env project-env "$project_env_file" "$project_top" "$@" || return $?
767新增: # Only after a write, and only if it worked: that is when the file is
768新增: # new to the repository and when the user is looking.
769新增: if [ "${1:-}" = "set" ]; then
770新增: _agent_vm_warn_unignored "$project_env_file"
771新增: fi
870772 ;;
871773 version|--version|-V)
872删除: echo "$AGENT_VM_VERSION"
774新增: _agent_vm_version "$@"
775新增: ;;
776新增: doctor)
777新增: if [[ $# -gt 0 ]]; then
778新增: echo "Usage: agent-vm doctor" >&2
779新增: return 2
780新增: fi
781新增: _agent_vm_doctor
782新增: ;;
783新增: install)
784新增: _agent_vm_install "$@"
785新增: ;;
786新增: uninstall)
787新增: _agent_vm_uninstall "$@"
873788 ;;
874789 help|--help|-h)
875790 _agent_vm_help
@@ -882,654 +797,7 @@ agent-vm() {
882797 esac
883798}
884799
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删除:
1059删除:_agent_vm_help() {
1060删除: cat << 'EOF'
1061删除:Usage: agent-vm [options] <command> [args]
1062删除:
1063删除:Commands:
1064删除: setup Create the base VM template (run once)
1065删除: claude [args] Run Claude Code in the VM for the current directory
1066删除: opencode [args] Run OpenCode in the VM for the current directory
1067删除: codex [args] Run Codex CLI in the VM for the current directory
1068删除: vibe [args] Run Mistral Vibe in the VM for the current directory
1069删除: shell, sh Open a shell in the VM. Add -c "..." to run a one-shot
1070删除: command via login zsh and exit.
1071删除: run <cmd> [args] Run a command in the VM (no shell — for pipes/redirects
1072删除: use 'shell -c "..."' instead; pass --tty for TUIs like
1073删除: opencode, vibe, htop, etc.)
1074删除: stop Stop the VM for the current directory
1075删除: rm Stop and delete the VM for the current directory
1076删除: destroy-all Stop and delete all agent-vm VMs
1077删除: list List all agent-vm VMs
1078删除: 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
1091删除: help Show this help
1092删除:
1093删除:VM options (for claude, opencode, codex, vibe, shell, run):
1094删除: --disk GB VM disk size (default: 10)
1095删除: --memory GB VM memory (default: 3)
1096删除: --cpus N Number of CPUs (default: 1)
1097删除: --reset Destroy and re-clone the VM from the base template
1098删除: --offline Block outbound internet (keeps host/VM communication)
1099删除: --readonly Mount the project directory as read-only
1100删除: --git-read-only Mount .git directory as read-only (allows git diff/log but not commit/stash)
1101删除: --rm Automatically destroy the VM after the command exits
1102删除:
1103删除:Examples:
1104删除: agent-vm setup # Create base VM
1105删除: agent-vm claude # Run Claude in a VM
1106删除: agent-vm opencode # Run OpenCode in a VM
1107删除: agent-vm codex # Run Codex in a VM
1108删除: agent-vm vibe # Run Mistral Vibe in a VM
1109删除: agent-vm --disk 50 --memory 16 --cpus 8 claude # Custom resources
1110删除: agent-vm --reset claude # Fresh VM from base template
1111删除: agent-vm --rm claude # Destroy VM after Claude exits
1112删除: agent-vm --offline claude # No internet access
1113删除: agent-vm --readonly shell # Read-only project mount
1114删除: agent-vm --git-ro claude # Protect .git from writes
1115删除: agent-vm shell # Shell into the VM
1116删除: agent-vm sh -c "ls -la | grep config" # One-shot command via login zsh
1117删除: agent-vm run npm install # Run a command in the VM
1118删除: agent-vm run --tty opencode -p "..." # Run a TUI with PTY allocated
1119删除: agent-vm claude -p "fix lint errors" # Pass args to claude
1120删除:
1121删除:VMs are persistent and unique per directory. Running "agent-vm shell" or
1122删除:"agent-vm claude" in the same directory will reuse the same VM.
1123删除:
1124删除:Customization:
1125删除: ~/.agent-vm/env Shared env vars / tokens (dotenv-style;
1126删除: auto-loaded into every VM shell)
1127删除: ~/.agent-vm/volumes Extra host paths to mount in VMs (one per
1128删除: line, supports both directories and files)
1129删除: ~/.agent-vm/setup.sh Per-user setup (runs during "agent-vm setup")
1130删除: ~/.agent-vm/runtime.sh Per-user runtime (runs on each VM start)
1131删除: <project>/.agent-vm.runtime.sh Per-project runtime (runs on each VM start)
1132删除:
1133删除:More info: https://github.com/sylvinus/agent-vm
1134删除:EOF
1135删除:}
1136删除:
1137删除:_agent_vm_setup() {
1138删除: local disk=10
1139删除: local memory=3
1140删除: local cpus=1
1141删除: local preinstall=""
1142删除: local preinstall_seen=""
1143删除: # Defaults match the "default install" set: every component on EXCEPT the
1144删除: # opt-in languages (Ruby, Rust, Go). These apply when --preinstall isn't
1145删除: # passed and either the wizard's first prompt is accepted or stdin is not a
1146删除: # terminal (e.g. CI). `--preinstall=all` turns everything on;
1147删除: # `--preinstall=default,rust` composes the default set with an opt-in.
1148删除: local install_python=1 install_node=1
1149删除: local install_ruby=0 install_rust=0 install_golang=0
1150删除: local install_docker=1 install_chromium=1 install_gh=1
1151删除: 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
1161删除:
1162删除: while [[ $# -gt 0 ]]; do
1163删除: case "$1" in
1164删除: --help|-h)
1165删除: cat << 'EOF'
1166删除:Usage: agent-vm setup [options]
1167删除:
1168删除:Create a base VM template with dev tools and agents pre-installed. Runs an
1169删除:interactive wizard by default; the first prompt offers a "default install"
1170删除:(everything except the opt-in languages Ruby, Rust, Go). Answer 'n' for
1171删除:per-component prompts. Pass --preinstall=... to skip the wizard and pick a
1172删除:specific subset non-interactively. When stdin is not a terminal (e.g. CI),
1173删除:the wizard is skipped automatically and the default set is installed.
1174删除:
1175删除:Options:
1176删除: --disk GB VM disk size (default: 10)
1177删除: --memory GB VM memory (default: 3)
1178删除: --cpus N Number of CPUs (default: 1)
1179删除: --preinstall=LIST Comma-separated list of tools to preinstall in the base
1180删除: VM image (skips the wizard). Anything not listed is
1181删除: skipped. Use:
1182删除: 'default' for the default set
1183删除: (everything except Ruby, Rust, Go),
1184删除: 'all' for everything,
1185删除: 'none' for nothing.
1186删除: Available names:
1187删除: python, node, ruby, rust, golang, docker, chromium,
1188删除: gh, claude, opencode, codex, vibe, mcp-chrome,
1189删除: mcp-playwright
1190删除: Selecting codex, or chromium with any AI agent, also
1191删除: 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.
1201删除: Examples:
1202删除: --preinstall=default,rust # default set plus Rust
1203删除: --preinstall=python,docker,claude
1204删除: --preinstall=node,chromium,opencode # no chrome MCP
1205删除: --help Show this help
1206删除:EOF
1207删除: return 0
1208删除: ;;
1209删除: --disk)
1210删除: disk="$2"
1211删除: shift 2
1212删除: _agent_vm_validate_int --disk "$disk" || return 1
1213删除: ;;
1214删除: --disk=*)
1215删除: disk="${1#*=}"
1216删除: shift
1217删除: _agent_vm_validate_int --disk "$disk" || return 1
1218删除: ;;
1219删除: --memory|--ram)
1220删除: memory="$2"
1221删除: shift 2
1222删除: _agent_vm_validate_int --memory "$memory" || return 1
1223删除: ;;
1224删除: --memory=*|--ram=*)
1225删除: memory="${1#*=}"
1226删除: shift
1227删除: _agent_vm_validate_int --memory "$memory" || return 1
1228删除: ;;
1229删除: --cpus)
1230删除: cpus="$2"
1231删除: shift 2
1232删除: _agent_vm_validate_int --cpus "$cpus" || return 1
1233删除: ;;
1234删除: --cpus=*)
1235删除: cpus="${1#*=}"
1236删除: shift
1237删除: _agent_vm_validate_int --cpus "$cpus" || return 1
1238删除: ;;
1239删除: --preinstall)
1240删除: preinstall_seen=1
1241删除: # Only consume the next argument as the value when it is an actual
1242删除: # value, not another option. Bare `--preinstall` falls back to the
1243删除: # default set (handled below) without swallowing e.g. a following
1244删除: # `--disk`.
1245删除: if [[ -n "$2" && "$2" != -* ]]; then
1246删除: preinstall="$2"
1247删除: shift 2
1248删除: else
1249删除: shift
1250删除: fi
1251删除: ;;
1252删除: --preinstall=*)
1253删除: preinstall="${1#*=}"
1254删除: preinstall_seen=1
1255删除: shift
1256删除: ;;
1257删除: --reset|--offline|--readonly|--git-read-only|--git-ro)
1258删除: shift ;;
1259删除: *)
1260删除: echo "Unknown option: $1" >&2
1261删除: echo "Usage: agent-vm setup [--disk GB] [--memory GB] [--cpus N] [--preinstall=LIST]" >&2
1262删除: return 1
1263删除: ;;
1264删除: esac
1265删除: done
1266删除:
1267删除: # Apply --preinstall=LIST: start with everything OFF and turn on what's
1268删除: # listed. 'default' / 'all' / 'none' are shortcuts. Setting this also
1269删除: # bypasses the interactive wizard below. `--preinstall=` with no value
1270删除: # (or `--preinstall` swallowed by a following flag) falls back to the
1271删除: # default set — explicitly opting into the wizard's recommended install.
1272删除: # Pass `--preinstall=none` if you really want nothing.
1273删除: if [[ -n "$preinstall_seen" ]]; then
1274删除: install_python=0 install_node=0 install_ruby=0 install_rust=0 install_golang=0
1275删除: install_docker=0 install_chromium=0 install_gh=0
1276删除: install_claude=0 install_opencode=0 install_codex=0 install_vibe=0
1277删除: install_mcp_chrome=0 install_mcp_playwright=0
1278删除: [[ -z "$preinstall" ]] && preinstall="default"
1279删除: # Iterate the comma-list portably across bash and zsh by appending a
1280删除: # trailing comma and peeling off one token per iteration.
1281删除: local rest="${preinstall}," f
1282删除: while [[ -n "$rest" ]]; do
1283删除: f="${rest%%,*}"
1284删除: rest="${rest#*,}"
1285删除: # Trim whitespace. Use bash/zsh-portable substitutions only.
1286删除: f="${f# }"; f="${f% }"
1287删除: [[ -z "$f" ]] && continue
1288删除: case "$f" in
1289删除: all)
1290删除: install_python=1 install_node=1 install_ruby=1
1291删除: install_rust=1 install_golang=1
1292删除: install_docker=1 install_chromium=1 install_gh=1
1293删除: install_claude=1 install_opencode=1 install_codex=1 install_vibe=1
1294删除: install_mcp_chrome=1 install_mcp_playwright=1
1295删除: ;;
1296删除: default)
1297删除: install_python=1 install_node=1
1298删除: install_docker=1 install_chromium=1 install_gh=1
1299删除: install_claude=1 install_opencode=1 install_codex=1 install_vibe=1
1300删除: install_mcp_chrome=1
1301删除: ;;
1302删除: none) ;; # explicit no-op token; with the all-off reset above,
1303删除: # `--preinstall=none` ships nothing.
1304删除: python) install_python=1 ;;
1305删除: node) install_node=1 ;;
1306删除: ruby) install_ruby=1 ;;
1307删除: rust) install_rust=1 ;;
1308删除: golang) install_golang=1 ;;
1309删除: docker) install_docker=1 ;;
1310删除: chromium) install_chromium=1 ;;
1311删除: gh) install_gh=1 ;;
1312删除: claude) install_claude=1 ;;
1313删除: opencode) install_opencode=1 ;;
1314删除: codex) install_codex=1 ;;
1315删除: vibe) install_vibe=1 ;;
1316删除: mcp-chrome) install_mcp_chrome=1 ;;
1317删除: mcp-playwright) install_mcp_playwright=1 ;;
1318删除: *)
1319删除: echo "Unknown preinstall name: $f (names are lowercase)" >&2
1320删除: echo "Valid: python, node, ruby, rust, golang, docker, chromium, gh, claude, opencode, codex, vibe, mcp-chrome, mcp-playwright, default, all, none" >&2
1321删除: return 1
1322删除: ;;
1323删除: esac
1324删除: done
1325删除: fi
1326删除:
1327删除: # Fail-fast checks before the (potentially long) wizard so the user doesn't
1328删除: # answer 15 prompts only to be told their host is missing Lima or KVM.
1329删除: if ! command -v limactl &>/dev/null; then
1330删除: if command -v brew &>/dev/null; then
1331删除: echo "Installing Lima..."
1332删除: brew install lima
1333删除: else
1334删除: echo "Error: Lima is required. Install from https://lima-vm.io/docs/installation/" >&2
1335删除: return 1
1336删除: fi
1337删除: fi
1338删除:
1339删除: _agent_vm_check_linux_prereqs || return 1
1340删除:
1341删除: # Interactive wizard, unless --preinstall was passed or no terminal is
1342删除: # attached (e.g. running under CI). Defaults shown in [] are prefilled from
1343删除: # any --disk/--memory/--cpus flags the user already passed, so they can
1344删除: # confirm or override. Components default to the "default install" set
1345删除: # (everything except Ruby/Rust/Go). The first prompt offers that whole set
1346删除: # as a one-tap shortcut — answer 'n' for per-component prompts.
1347删除: if [[ -z "$preinstall_seen" ]] && [[ -r /dev/tty ]]; then
1348删除: printf '\nagent-vm setup wizard\n' >&2
1349删除: printf '─────────────────────\n\n' >&2
1350删除: printf 'These settings apply to the base VM image. Every per-project VM is\n' >&2
1351删除: printf 'cloned from it, so anything preinstalled here is available in all\n' >&2
1352删除: printf 'future agent VMs. You can still install extra tools inside any\n' >&2
1353删除: printf 'individual VM later (e.g. via `agent-vm shell`).\n\n' >&2
1354删除: printf 'For more: https://github.com/sylvinus/agent-vm\n\n' >&2
1355删除:
1356删除: # Software first — the more interesting choice for most users.
1357删除: printf 'Software\n' >&2
1358删除: printf '────────\n' >&2
1359删除: printf ' Install: Python, Node.js, Docker, Chromium, gh,\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
1363删除: local use_default_software
1364删除: use_default_software=$(_agent_vm_ask_yn "Use this default" Y)
1365删除: if [[ "$use_default_software" != "1" ]]; then
1366删除: printf '\nAI coding agents\n' >&2
1367删除: printf '────────────────\n' >&2
1368删除: install_claude=$(_agent_vm_ask_yn "Claude Code" Y)
1369删除: install_opencode=$(_agent_vm_ask_yn "OpenCode" Y)
1370删除: install_codex=$(_agent_vm_ask_yn "Codex CLI" Y)
1371删除: install_vibe=$(_agent_vm_ask_yn "Mistral Vibe" Y)
1372删除:
1373删除: printf '\nSystem tools\n' >&2
1374删除: printf '────────────\n' >&2
1375删除: install_docker=$(_agent_vm_ask_yn "Docker" Y)
1376删除: install_chromium=$(_agent_vm_ask_yn "Chromium (headless browser)" Y)
1377删除: install_gh=$(_agent_vm_ask_yn "GitHub CLI (gh)" Y)
1378删除:
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删除:
1393删除: local node_forced_reason=""
1394删除: if [[ "$install_codex" == "1" ]]; then
1395删除: node_forced_reason="Codex CLI requires Node.js"
1396删除: elif [[ "$install_chromium" == "1" && "$install_mcp_chrome" == "1" && ( "$install_claude" == "1" || "$install_opencode" == "1" || "$install_vibe" == "1" ) ]]; then
1397删除: node_forced_reason="Chrome DevTools MCP uses npx"
1398删除: fi
1399删除:
1400删除: printf '\nLanguages\n' >&2
1401删除: printf '─────────\n' >&2
1402删除: install_python=$(_agent_vm_ask_yn "Python 3" Y)
1403删除: if [[ -n "$node_forced_reason" ]]; then
1404删除: install_node=1
1405删除: printf 'Node.js 24: yes (%s)\n' "$node_forced_reason" >&2
1406删除: else
1407删除: install_node=$(_agent_vm_ask_yn "Node.js 24" Y)
1408删除: fi
1409删除: install_ruby=$(_agent_vm_ask_yn "Ruby" Y)
1410删除: install_rust=$(_agent_vm_ask_yn "Rust" Y)
1411删除: install_golang=$(_agent_vm_ask_yn "Go" Y)
1412删除: fi
1413删除:
1414删除: # Resources second — same pattern, accept-in-one-go shortcut. Current
1415删除: # values reflect any --disk/--memory/--cpus already passed on the CLI.
1416删除: # These are starting values: any later `agent-vm` command can resize the
1417删除: # per-project VM with --disk/--memory/--cpus.
1418删除: printf '\nDefault resources\n' >&2
1419删除: printf '─────────────────\n' >&2
1420删除: printf '(per-VM override with --disk / --memory / --cpus on any agent-vm command)\n\n' >&2
1421删除: printf ' Disk %s GB\n' "$disk" >&2
1422删除: printf ' Memory %s GB\n' "$memory" >&2
1423删除: printf ' CPUs %s\n\n' "$cpus" >&2
1424删除: local use_default_resources
1425删除: use_default_resources=$(_agent_vm_ask_yn "Use these defaults" Y)
1426删除: if [[ "$use_default_resources" != "1" ]]; then
1427删除: disk=$(_agent_vm_ask_int "Disk size in GB" "$disk")
1428删除: memory=$(_agent_vm_ask_int "Memory in GB" "$memory")
1429删除: cpus=$(_agent_vm_ask_int "Number of CPUs" "$cpus")
1430删除: fi
1431删除: printf '\n' >&2
1432删除: fi
1433删除:
1434删除: if [[ "$install_chromium" == "1" && "$install_mcp_chrome" == "1" ]]; then
1435删除: local wants_chrome_mcp=0
1436删除: [[ "$install_claude" == "1" || "$install_opencode" == "1" || "$install_codex" == "1" || "$install_vibe" == "1" ]] && wants_chrome_mcp=1
1437删除: if [[ "$wants_chrome_mcp" == "1" && "$install_node" != "1" ]]; then
1438删除: echo "Enabling Node.js because Chrome DevTools MCP uses npx." >&2
1439删除: install_node=1
1440删除: fi
1441删除: fi
1442删除:
1443删除: if [[ "$install_codex" == "1" && "$install_node" != "1" ]]; then
1444删除: echo "Enabling Node.js because Codex CLI requires npm." >&2
1445删除: install_node=1
1446删除: fi
1447删除:
1448删除: _agent_vm_clean_partial_state "$AGENT_VM_TEMPLATE"
1449删除:
1450删除: limactl stop "$AGENT_VM_TEMPLATE" &>/dev/null
1451删除: limactl delete "$AGENT_VM_TEMPLATE" --force &>/dev/null
1452删除:
1453删除: echo "Creating base VM..."
1454删除: local create_args=(
1455删除: --set '.mounts=[]'
1456删除: --disk="$disk"
1457删除: --memory="$memory"
1458删除: --cpus="$cpus"
1459删除: --tty=false
1460删除: )
1461删除: local create_log
1462删除: if ! create_log=$(limactl create --name="$AGENT_VM_TEMPLATE" template:debian-13 "${create_args[@]}" 2>&1); then
1463删除: echo "Error: Failed to create base VM." >&2
1464删除: echo "--- limactl create output ---" >&2
1465删除: echo "$create_log" >&2
1466删除: return 1
1467删除: fi
1468删除:
1469删除: _agent_vm_print_resources "$AGENT_VM_TEMPLATE"
1470删除:
1471删除: local start_log
1472删除: if ! start_log=$(limactl start "$AGENT_VM_TEMPLATE" 2>&1); then
1473删除: echo "Error: Failed to start base VM." >&2
1474删除: echo "--- limactl start output ---" >&2
1475删除: echo "$start_log" >&2
1476删除: echo "Full log: ~/.lima/$AGENT_VM_TEMPLATE/ha.stderr.log" >&2
1477删除: return 1
1478删除: fi
1479删除:
1480删除: # Run the setup script inside the VM. Component selections are passed by
1481删除: # prepending `export` lines to the script on stdin — keeps the integration
1482删除: # to one knob (env vars) and avoids quoting headaches with `limactl shell
1483删除: # env KEY=VAL`. The setup script's defaults for each flag match the host
1484删除: # wizard's "default install" set (Ruby/Rust/Go off, everything else on),
1485删除: # so invoking the in-VM script standalone — without these exports — still
1486删除: # produces the same default install.
1487删除: echo "Installing packages inside VM..."
1488删除: if [[ ! -r "${AGENT_VM_SCRIPT_DIR}/agent-vm.setup.sh" ]]; then
1489删除: echo "Error: Setup script not found at ${AGENT_VM_SCRIPT_DIR}/agent-vm.setup.sh" >&2
1490删除: return 1
1491删除: fi
1492删除: {
1493删除: printf 'export AGENT_VM_INSTALL_PYTHON=%s\n' "$install_python"
1494删除: printf 'export AGENT_VM_INSTALL_NODE=%s\n' "$install_node"
1495删除: printf 'export AGENT_VM_INSTALL_RUBY=%s\n' "$install_ruby"
1496删除: printf 'export AGENT_VM_INSTALL_RUST=%s\n' "$install_rust"
1497删除: printf 'export AGENT_VM_INSTALL_GOLANG=%s\n' "$install_golang"
1498删除: printf 'export AGENT_VM_INSTALL_DOCKER=%s\n' "$install_docker"
1499删除: printf 'export AGENT_VM_INSTALL_CHROMIUM=%s\n' "$install_chromium"
1500删除: printf 'export AGENT_VM_INSTALL_GH=%s\n' "$install_gh"
1501删除: printf 'export AGENT_VM_INSTALL_CLAUDE=%s\n' "$install_claude"
1502删除: printf 'export AGENT_VM_INSTALL_OPENCODE=%s\n' "$install_opencode"
1503删除: printf 'export AGENT_VM_INSTALL_CODEX=%s\n' "$install_codex"
1504删除: 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"
1507删除: cat "${AGENT_VM_SCRIPT_DIR}/agent-vm.setup.sh"
1508删除: } | limactl shell "$AGENT_VM_TEMPLATE" bash -l || { echo "Error: Setup script failed." >&2; return 1; }
1509删除:
1510删除: # Run user's custom setup script if it exists
1511删除: local user_setup="$AGENT_VM_STATE_DIR/setup.sh"
1512删除: if [ -f "$user_setup" ]; then
1513删除: echo "Running custom setup from $user_setup..."
1514删除: limactl shell "$AGENT_VM_TEMPLATE" zsh -l < "$user_setup" || { echo "Error: Custom setup script failed." >&2; return 1; }
1515删除: fi
1516删除:
1517删除: limactl stop "$AGENT_VM_TEMPLATE" &>/dev/null
1518删除:
1519删除: # Record base VM version so we can warn about stale clones
1520删除: mkdir -p "$AGENT_VM_STATE_DIR"
1521删除: date +%s > "$AGENT_VM_STATE_DIR/.agent-vm-base-version"
1522删除:
1523删除: echo ""
1524删除: echo "Base VM ready. Try one of these in any project directory:"
1525删除: echo " agent-vm shell"
1526删除: [[ "$install_claude" == "1" ]] && echo " agent-vm claude"
1527删除: [[ "$install_opencode" == "1" ]] && echo " agent-vm opencode"
1528删除: [[ "$install_codex" == "1" ]] && echo " agent-vm codex"
1529删除: [[ "$install_vibe" == "1" ]] && echo " agent-vm vibe"
1530删除: echo ""
1531删除: echo "Note: Existing VMs were not updated. Use --reset to re-clone them from the new base."
1532删除:}
800新增:# --- commands -----------------------------------------------------------------
1533801
1534802# Run a command in the VM through a login zsh.
1535803#
@@ -1543,7 +811,9 @@ EOF
1543811#
1544812# The command and its arguments are passed as positional parameters, so the
1545813# guest shell never re-parses them; `env` runs the command and keeps leading
1546删除:# VAR=value assignments working.
814新增:# VAR=value assignments working. `env --`: GNU env still reads assignments
815新增:# after it, and a command starting with `-` (`run -i foo`) is not taken for
816新增:# one of its options.
1547817#
1548818# Usage: _agent_vm_lima_run <vm_name> <host_dir> <tty:1|""> <command> [args...]
1549819_agent_vm_lima_run() {
@@ -1551,345 +821,316 @@ _agent_vm_lima_run() {
1551821 shift 3
1552822 local shell_opts=(--workdir "$host_dir")
1553823 [[ -n "$want_tty" ]] && shell_opts+=(--tty)
1554删除: limactl shell "${shell_opts[@]}" "$vm_name" -- zsh -l -c 'exec env "$@"' agent-vm "$@"
824新增: limactl shell "${shell_opts[@]}" "$vm_name" -- zsh -l -c 'exec env -- "$@"' agent-vm "$@"
1555825}
1556826
1557删除:_agent_vm_claude() {
1558删除: local vm_opts=()
1559删除: local args=()
1560删除: local rm=""
1561删除: while [[ $# -gt 0 ]]; do
1562删除: case "$1" in
1563删除: --disk) vm_opts+=(--disk "$2"); shift 2 ;;
1564删除: --memory|--ram) vm_opts+=(--memory "$2"); shift 2 ;;
1565删除: --cpus) vm_opts+=(--cpus "$2"); shift 2 ;;
1566删除: --reset) vm_opts+=(--reset); shift ;;
1567删除: --offline) vm_opts+=(--offline); shift ;;
1568删除: --readonly) vm_opts+=(--readonly); shift ;;
1569删除: --git-read-only|--git-ro) vm_opts+=(--git-read-only); shift ;;
1570删除: --rm) rm=1; shift ;;
1571删除: *) args+=("$1"); shift ;;
1572删除: esac
1573删除: done
1574删除: local host_dir
827新增:# Starts this directory's VM with the caller's vm_opts, runs <function> with
828新增:# the VM name and the directory before its own arguments, then deletes the VM
829新增:# when the caller's rm is set. Returns the function's status. With --scratch,
830新增:# see _agent_vm_run_scratch.
831新增:_agent_vm_in_vm() {
832新增: local fn="$1" host_dir vm_name st=0 o
833新增: shift
1575834 host_dir="$(pwd)"
1576删除: local vm_name
1577删除: vm_name="$(_agent_vm_name "$host_dir")"
1578删除:
1579删除: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
1580删除: _agent_vm_print_resources "$vm_name"
1581删除:
1582删除: local exit_code=0
1583删除: _agent_vm_lima_run "$vm_name" "$host_dir" "" claude --dangerously-skip-permissions ${args[@]+"${args[@]}"}
1584删除: exit_code=$?
1585删除: [[ -n "$rm" ]] && { echo "Removing VM..."; _agent_vm_destroy; }
1586删除: return $exit_code
1587删除:}
1588删除:
1589删除:_agent_vm_opencode() {
1590删除: local vm_opts=()
1591删除: local args=()
1592删除: local rm=""
1593删除: while [[ $# -gt 0 ]]; do
1594删除: case "$1" in
1595删除: --disk) vm_opts+=(--disk "$2"); shift 2 ;;
1596删除: --memory|--ram) vm_opts+=(--memory "$2"); shift 2 ;;
1597删除: --cpus) vm_opts+=(--cpus "$2"); shift 2 ;;
1598删除: --reset) vm_opts+=(--reset); shift ;;
1599删除: --offline) vm_opts+=(--offline); shift ;;
1600删除: --readonly) vm_opts+=(--readonly); shift ;;
1601删除: --git-read-only|--git-ro) vm_opts+=(--git-read-only); shift ;;
1602删除: --rm) rm=1; shift ;;
1603删除: *) args+=("$1"); shift ;;
1604删除: esac
835新增: for o in ${vm_opts[@]+"${vm_opts[@]}"}; do
836新增: if [[ "$o" == --scratch ]]; then
837新增: _agent_vm_run_scratch "$fn" "$host_dir" "$@"
838新增: return
839新增: fi
1605840 done
1606删除: local host_dir
1607删除: host_dir="$(pwd)"
1608删除: local vm_name
1609删除: vm_name="$(_agent_vm_name "$host_dir")"
1610删除:
841新增: vm_name="$(_agent_vm_name "$host_dir")" || return 1
1611842 _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
1612843 _agent_vm_print_resources "$vm_name"
1613删除:
1614删除: # --auto auto-approves permission prompts that aren't explicitly denied,
1615删除: # giving full autonomy (safe inside the sandbox). This is OpenCode's shipped
1616删除: # equivalent of a "yolo" mode; the proposed --yolo flag was never merged.
1617删除: local exit_code=0
1618删除: _agent_vm_lima_run "$vm_name" "$host_dir" 1 opencode --auto ${args[@]+"${args[@]}"}
1619删除: exit_code=$?
1620删除: [[ -n "$rm" ]] && { echo "Removing VM..."; _agent_vm_destroy; }
1621删除: return $exit_code
844新增: "$fn" "$vm_name" "$host_dir" "$@" || st=$?
845新增: _agent_vm_reset_term_modes
846新增: if [[ -n "$rm" ]]; then
847新增: echo "Removing VM..."
848新增: _agent_vm_destroy
849新增: fi
850新增: return "$st"
1622851}
1623852
1624删除:_agent_vm_codex() {
1625删除: local vm_opts=()
1626删除: local args=()
1627删除: local rm=""
1628删除: while [[ $# -gt 0 ]]; do
1629删除: case "$1" in
1630删除: --disk) vm_opts+=(--disk "$2"); shift 2 ;;
1631删除: --memory|--ram) vm_opts+=(--memory "$2"); shift 2 ;;
1632删除: --cpus) vm_opts+=(--cpus "$2"); shift 2 ;;
1633删除: --reset) vm_opts+=(--reset); shift ;;
1634删除: --offline) vm_opts+=(--offline); shift ;;
1635删除: --readonly) vm_opts+=(--readonly); shift ;;
1636删除: --git-read-only|--git-ro) vm_opts+=(--git-read-only); shift ;;
1637删除: --rm) rm=1; shift ;;
1638删除: *) args+=("$1"); shift ;;
1639删除: esac
1640删除: done
1641删除: local host_dir
1642删除: host_dir="$(pwd)"
1643删除: local vm_name
1644删除: vm_name="$(_agent_vm_name "$host_dir")"
1645删除:
1646删除: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
1647删除: _agent_vm_print_resources "$vm_name"
1648删除:
1649删除: local exit_code=0
1650删除: _agent_vm_lima_run "$vm_name" "$host_dir" "" codex --dangerously-bypass-approvals-and-sandbox ${args[@]+"${args[@]}"}
1651删除: exit_code=$?
1652删除: [[ -n "$rm" ]] && { echo "Removing VM..."; _agent_vm_destroy; }
1653删除: return $exit_code
853新增:# --scratch: a new VM of its own (see _agent_vm_scratch_name), sharing
854新增:# nothing, deleted once <function> returns, whatever it returns, unless the
855新增:# user keeps it a while to look inside (asked below). Ctrl-C
856新增:# included: the trap lets the run go on to the deletion instead of ending
857新增:# the shell with the interrupted command (bash ends a script whose child dies
858新增:# of SIGINT, unless it traps it). A run that is killed outright leaves its VM
859新增:# recorded with its pid, and the next --scratch run deletes it.
860新增:_agent_vm_run_scratch() {
861新增: local fn="$1" host_dir="$2" vm_name st=0 old_int="" leftover
862新增: shift 2
863新增: while IFS= read -r leftover; do
864新增: [[ -n "$leftover" ]] || continue
865新增: echo "Deleting scratch VM '$leftover', left by a run that did not finish..."
866新增: _agent_vm_delete_vm "$leftover"
867新增: done <<< "$(_agent_vm_scratch_leftovers)"
868新增: vm_name="$(_agent_vm_scratch_name "$host_dir")" || return 1
869新增: mkdir -p "$AGENT_VM_STATE_DIR" && printf '%s\n' "$$" > "$(_agent_vm_scratch_marker "$vm_name")" || return 1
870新增: # The caller's: the shell session says the VM goes on exit.
871新增: rm=1
872新增: old_int="$(trap -p INT)"
873新增: trap ':' INT
874新增: if _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"}; then
875新增: _agent_vm_print_resources "$vm_name"
876新增: "$fn" "$vm_name" "$host_dir" "$@" || st=$?
877新增: _agent_vm_reset_term_modes
878新增: # Asked before the deletion, when it can be (yes by default): a no opens
879新增: # a shell in the VM, to look at what the command left, and asks again on
880新增: # its exit. Only an explicit no keeps it: no terminal, or a question cut
881新增: # short, deletes.
882新增: while _agent_vm_can_ask \
883新增: && [[ "$(_agent_vm_ask_yn "Delete scratch VM '$vm_name'?" Y)" == "0" ]]; do
884新增: echo "A shell in scratch VM '$vm_name'. Type 'exit' to be asked again."
885新增: limactl shell --workdir "$host_dir" "$vm_name" zsh -l
886新增: _agent_vm_reset_term_modes
887新增: done
888新增: else
889新增: st=1
890新增: fi
891新增: echo "Deleting scratch VM '$vm_name'..."
892新增: _agent_vm_delete_vm "$vm_name" || st=1
893新增: trap - INT
894新增: [[ -z "$old_int" ]] || eval "$old_int"
895新增: return "$st"
1654896}
1655897
1656删除:_agent_vm_vibe() {
1657删除: local vm_opts=()
1658删除: local args=()
1659删除: local rm=""
1660删除: while [[ $# -gt 0 ]]; do
1661删除: case "$1" in
1662删除: --disk) vm_opts+=(--disk "$2"); shift 2 ;;
1663删除: --memory|--ram) vm_opts+=(--memory "$2"); shift 2 ;;
1664删除: --cpus) vm_opts+=(--cpus "$2"); shift 2 ;;
1665删除: --reset) vm_opts+=(--reset); shift ;;
1666删除: --offline) vm_opts+=(--offline); shift ;;
1667删除: --readonly) vm_opts+=(--readonly); shift ;;
1668删除: --git-read-only|--git-ro) vm_opts+=(--git-read-only); shift ;;
1669删除: --rm) rm=1; shift ;;
1670删除: *) args+=("$1"); shift ;;
1671删除: esac
1672删除: done
1673删除: local host_dir
1674删除: host_dir="$(pwd)"
1675删除: local vm_name
1676删除: vm_name="$(_agent_vm_name "$host_dir")"
1677删除:
1678删除: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
1679删除: _agent_vm_print_resources "$vm_name"
1680删除:
1681删除: # Vibe is a full-screen TUI, so allocate a tty (like opencode).
1682删除: # --agent auto-approve gives full autonomy (safe inside the sandbox).
1683删除: local exit_code=0
1684删除: _agent_vm_lima_run "$vm_name" "$host_dir" 1 vibe --agent auto-approve ${args[@]+"${args[@]}"}
1685删除: exit_code=$?
1686删除: [[ -n "$rm" ]] && { echo "Removing VM..."; _agent_vm_destroy; }
1687删除: return $exit_code
898新增:# `agent-vm <agent> [options] [args]`: the agent, with the flag that lets it
899新增:# work unattended (safe in the VM), and a TTY for the full-screen ones.
900新增:_agent_vm_agent() {
901新增: local agent="$1" cmd=() tty="" vm_opts=() rm="" args=()
902新增: shift
903新增: case "$agent" in
904新增: # The VM also enforces bypass mode with managed settings (see
905新增: # agent-vm.setup.sh): Claude Code drops the flag when it relaunches itself.
906新增: claude) cmd=(claude --dangerously-skip-permissions) ;;
907新增: # Approves every prompt that is not explicitly denied: OpenCode's shipped
908新增: # "yolo" (a --yolo flag was proposed, never merged).
909新增: opencode) cmd=(opencode --auto); tty=1 ;;
910新增: codex) cmd=(codex --dangerously-bypass-approvals-and-sandbox) ;;
911新增: vibe) cmd=(vibe --agent auto-approve); tty=1 ;;
912新增: # No permission prompts: it runs every tool as asked.
913新增: pi) cmd=(pi); tty=1 ;;
914新增: *) echo "Error: unknown agent: $agent" >&2; return 1 ;;
915新增: esac
916新增: _agent_vm_split_args "$@" || return 1
917新增: _agent_vm_in_vm _agent_vm_lima_run "$tty" "${cmd[@]}" ${args[@]+"${args[@]}"}
1688918}
1689919
920新增:# `agent-vm shell [-c "command"]`: a login zsh in the VM, so ~/.zshenv (mise,
921新增:# PATH, ~/.agent-vm.env) is loaded. Takes no command of its own, so a word it
922新增:# does not know is an error, not something skipped as if it had applied.
1690923_agent_vm_shell() {
1691删除: local vm_opts=()
1692删除: local rm=""
1693删除: local cmd_string=""
924新增: local vm_opts=() rm="" cmd_string="" taken
1694925 while [[ $# -gt 0 ]]; do
926新增: _agent_vm_take_opt "$@" || return 1
927新增: if [[ $taken -gt 0 ]]; then
928新增: shift "$taken"
929新增: continue
930新增: fi
1695931 case "$1" in
1696删除: --disk) vm_opts+=(--disk "$2"); shift 2 ;;
1697删除: --memory|--ram) vm_opts+=(--memory "$2"); shift 2 ;;
1698删除: --cpus) vm_opts+=(--cpus "$2"); shift 2 ;;
1699删除: --reset) vm_opts+=(--reset); shift ;;
1700删除: --offline) vm_opts+=(--offline); shift ;;
1701删除: --readonly) vm_opts+=(--readonly); shift ;;
1702删除: --git-read-only|--git-ro) vm_opts+=(--git-read-only); shift ;;
1703删除: --rm) rm=1; shift ;;
1704932 -c|--command)
1705933 if [[ $# -lt 2 || -z "$2" ]]; then
1706934 echo "Error: -c/--command requires a command string." >&2
1707935 return 1
1708936 fi
1709937 cmd_string="$2"; shift 2 ;;
1710删除: *) shift ;;
938新增: *)
939新增: echo "Error: unknown argument for shell: $1" >&2
940新增: echo "Usage: agent-vm [vm options] shell [-c \"command\"]" >&2
941新增: return 1 ;;
1711942 esac
1712943 done
1713删除: local host_dir
1714删除: host_dir="$(pwd)"
1715删除: local vm_name
1716删除: vm_name="$(_agent_vm_name "$host_dir")"
1717删除:
1718删除: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
1719删除: _agent_vm_print_resources "$vm_name"
944新增: _agent_vm_in_vm _agent_vm_shell_session "$cmd_string"
945新增:}
1720946
1721删除: local exit_code=0
947新增:_agent_vm_shell_session() {
948新增: local vm_name="$1" host_dir="$2" cmd_string="$3"
1722949 if [[ -n "$cmd_string" ]]; then
1723删除: # One-shot: run the command via a login zsh so ~/.zshenv (mise, PATH,
1724删除: # ~/.agent-vm.env, …) is loaded. No "Type 'exit'..." chatter.
1725950 limactl shell --workdir "$host_dir" "$vm_name" zsh -l -c "$cmd_string"
1726删除: exit_code=$?
951新增: return
952新增: fi
953新增: echo "VM: $vm_name | Dir: $host_dir"
954新增: if [[ -n "$rm" ]]; then
955新增: echo "Type 'exit' to leave. VM will be destroyed after exit."
1727956 else
1728删除: echo "VM: $vm_name | Dir: $host_dir"
1729删除: if [[ -n "$rm" ]]; then
1730删除: echo "Type 'exit' to leave. VM will be destroyed after exit."
1731删除: else
1732删除: echo "Type 'exit' to leave (VM keeps running). Use 'agent-vm stop' to stop it."
1733删除: fi
1734删除: limactl shell --workdir "$host_dir" "$vm_name" zsh -l
1735删除: exit_code=$?
957新增: echo "Type 'exit' to leave (VM keeps running). Use 'agent-vm stop' to stop it."
1736958 fi
1737删除: [[ -n "$rm" ]] && { echo "Removing VM..."; _agent_vm_destroy; }
1738删除: return $exit_code
959新增: limactl shell --workdir "$host_dir" "$vm_name" zsh -l
1739960}
1740961
962新增:# `agent-vm run [--tty] <command> [args]`. --tty gives the command a
963新增:# pseudo-terminal, which full-screen TUIs (htop, …) need to draw.
1741964_agent_vm_run() {
1742删除: local vm_opts=()
1743删除: local args=()
1744删除: local rm=""
1745删除: local tty_flag=""
1746删除: while [[ $# -gt 0 ]]; do
1747删除: case "$1" in
1748删除: --disk) vm_opts+=(--disk "$2"); shift 2 ;;
1749删除: --memory|--ram) vm_opts+=(--memory "$2"); shift 2 ;;
1750删除: --cpus) vm_opts+=(--cpus "$2"); shift 2 ;;
1751删除: --reset) vm_opts+=(--reset); shift ;;
1752删除: --offline) vm_opts+=(--offline); shift ;;
1753删除: --readonly) vm_opts+=(--readonly); shift ;;
1754删除: --git-read-only|--git-ro) vm_opts+=(--git-read-only); shift ;;
1755删除: --rm) rm=1; shift ;;
1756删除: --tty) tty_flag=1; shift ;;
1757删除: *) args+=("$1"); shift ;;
1758删除: esac
1759删除: done
965新增: local vm_opts=() rm="" tty="" args=()
966新增: _agent_vm_split_args "$@" || return 1
1760967 if [[ ${#args[@]} -eq 0 ]]; then
1761968 echo "Usage: agent-vm run [--tty] <command> [args]" >&2
1762969 return 1
1763970 fi
1764删除: local host_dir
1765删除: host_dir="$(pwd)"
971新增: _agent_vm_in_vm _agent_vm_lima_run "$tty" "${args[@]}"
972新增:}
973新增:
974新增:# Resolve the VM that `stop` / `rm` acts on, and prove it exists.
975新增:# Prints the name on stdout; diagnostics go to stderr.
976新增:#
977新增:# With no argument: the current directory's VM, as before.
978新增:#
979新增:# With one argument: a VM name as printed by `agent-vm list`. It has to be a
980新增:# NAME and not a directory, because the case it exists for is a VM no directory
981新增:# can reach any more: the name embeds a hash of the path, so renaming or
982新增:# deleting the project folder orphans the VM, and `_agent_vm_abs_dir` would
983新增:# refuse the old path anyway. `list` remains the only handle on it.
984新增:#
985新增:# The `agent-vm-` prefix is required: without it a typo could stop or delete an
986新增:# unrelated Lima instance on the same machine.
987新增:_agent_vm_resolve_target() {
988新增: local verb="$1"
989新增: shift
990新增:
1766991 local vm_name
1767删除: vm_name="$(_agent_vm_name "$host_dir")"
992新增: case $# in
993新增: 0) vm_name="$(_agent_vm_name "$(pwd)")" || return 1 ;;
994新增: 1)
995新增: vm_name="$1"
996新增: case "$vm_name" in
997新增: agent-vm-*) ;;
998新增: *)
999新增: echo "Error: '$vm_name' is not an agent-vm VM name (they start with 'agent-vm-')." >&2
1000新增: echo "Run 'agent-vm list' to see them." >&2
1001新增: return 1 ;;
1002新增: esac ;;
1003新增: *)
1004新增: echo "Usage: agent-vm $verb [vm-name]" >&2
1005新增: return 1 ;;
1006新增: esac
17681007
1769删除: _agent_vm_ensure_running "$vm_name" "$host_dir" ${vm_opts[@]+"${vm_opts[@]}"} || return 1
1770删除: _agent_vm_print_resources "$vm_name"
1008新增: local st=0
1009新增: _agent_vm_exists "$vm_name" || st=$?
1010新增: case "$st" in
1011新增: 0) ;;
1012新增: 1)
1013新增: if [[ $# -eq 0 ]]; then
1014新增: echo "No VM found for this directory." >&2
1015新增: echo "Run 'agent-vm list' to see existing VMs, then 'agent-vm $verb <vm-name>'." >&2
1016新增: else
1017新增: echo "Error: no such VM: $vm_name" >&2
1018新增: echo "Run 'agent-vm list' to see existing VMs." >&2
1019新增: fi
1020新增: return 1 ;;
1021新增: *)
1022新增: echo "Error: could not query Lima. Is it installed and working?" >&2
1023新增: return 1 ;;
1024新增: esac
17711025
1772删除: # `--tty` forces limactl to allocate a pseudo-terminal in the VM, which
1773删除: # full-screen TUIs (opencode, vibe, htop, …) need to render correctly when
1774删除: # invoked through `agent-vm run`. Without it, line-mode tools work fine but
1775删除: # ncurses-style UIs break.
1776删除: local exit_code=0
1777删除: _agent_vm_lima_run "$vm_name" "$host_dir" "$tty_flag" "${args[@]}"
1778删除: exit_code=$?
1779删除: [[ -n "$rm" ]] && { echo "Removing VM..."; _agent_vm_destroy; }
1780删除: return $exit_code
1026新增: echo "$vm_name"
17811027}
17821028
17831029_agent_vm_stop() {
1784删除: local host_dir
1785删除: host_dir="$(pwd)"
17861030 local vm_name
1787删除: vm_name="$(_agent_vm_name "$host_dir")"
1031新增: vm_name="$(_agent_vm_resolve_target stop "$@")" || return 1
17881032
1789删除: if ! _agent_vm_exists "$vm_name"; then
1790删除: echo "No VM found for this directory." >&2
1033新增: echo "Stopping VM '$vm_name'..."
1034新增: if ! _agent_vm_stop_vm "$vm_name"; then
1035新增: echo "Error: VM '$vm_name' is still running, or Lima cannot say. See 'limactl list'." >&2
17911036 return 1
17921037 fi
1793删除:
1794删除: echo "Stopping VM '$vm_name'..."
1795删除: limactl stop "$vm_name" &>/dev/null
17961038 echo "VM stopped."
17971039}
17981040
17991041_agent_vm_destroy() {
1800删除: local host_dir
1801删除: host_dir="$(pwd)"
18021042 local vm_name
1803删除: vm_name="$(_agent_vm_name "$host_dir")"
1804删除:
1805删除: if ! _agent_vm_exists "$vm_name"; then
1806删除: echo "No VM found for this directory." >&2
1807删除: return 1
1808删除: fi
1043新增: vm_name="$(_agent_vm_resolve_target rm "$@")" || return 1
18091044
18101045 echo "Stopping and deleting VM '$vm_name'..."
1811删除: limactl stop "$vm_name" &>/dev/null
1812删除: limactl delete "$vm_name" --force &>/dev/null
1813删除: _agent_vm_cleanup_state "$vm_name"
1046新增: _agent_vm_delete_vm "$vm_name" || return 1
18141047 echo "VM destroyed."
18151048}
18161049
1050新增:# Every agent-vm VM, the base template included: this is the command that
1051新增:# gives the disk space back. `agent-vm setup` rebuilds the template.
18171052_agent_vm_destroy_all() {
1818删除: local vms
1819删除: vms=$(limactl list -q 2>/dev/null | grep "^agent-vm-" || true)
1053新增: local list vms
1054新增: if ! list="$(limactl list -q 2>/dev/null)"; then
1055新增: echo "Error: could not query Lima. Is it installed and working?" >&2
1056新增: return 1
1057新增: fi
1058新增: vms="$(printf '%s\n' "$list" | grep "^agent-vm-" || true)"
18201059 if [[ -z "$vms" ]]; then
18211060 echo "No agent-vm VMs found."
18221061 return 0
18231062 fi
18241063 echo "This will destroy the following VMs:"
18251064 echo "$vms"
1826删除: printf "Continue? [y/N] " >&2
1827删除: local reply=""
1828删除: IFS= read -r reply </dev/tty 2>/dev/null || reply=""
1829删除: if [[ ! "$reply" =~ ^[Yy]$ ]]; then
1065新增: if _agent_vm_has_line "$vms" "$AGENT_VM_TEMPLATE"; then
1066新增: echo "($AGENT_VM_TEMPLATE is the base template: 'agent-vm setup' rebuilds it.)"
1067新增: fi
1068新增: if ! _agent_vm_can_ask || [[ "$(_agent_vm_ask_yn "Continue?" N)" != "1" ]]; then
18301069 echo "Aborted."
18311070 return 0
18321071 fi
1833删除: echo "$vms" | while read -r vm; do
1834删除: echo "Destroying $vm..."
1835删除: limactl stop "$vm" &>/dev/null
1836删除: limactl delete "$vm" --force &>/dev/null
1837删除: _agent_vm_cleanup_state "$vm"
1838删除: done
1072新增: _agent_vm_destroy_vms "$vms" || return 1
18391073 echo "All VMs destroyed."
18401074}
18411075
1842删除:_agent_vm_list() {
1843删除: limactl list | head -1
1844删除: limactl list | grep "^agent-vm-" || echo "(no VMs)"
1076新增:# Stop, delete and forget each VM named on its own line in $1. Goes through
1077新增:# all of them, and fails if one could not be deleted.
1078新增:# limactl gets /dev/null as stdin (see _agent_vm_delete_vm): the names are
1079新增:# read from stdin, and a limactl that reads it would swallow the ones still to
1080新增:# come.
1081新增:_agent_vm_destroy_vms() {
1082新增: local vm st=0
1083新增: while IFS= read -r vm; do
1084新增: [[ -n "$vm" ]] || continue
1085新增: echo "Destroying $vm..."
1086新增: _agent_vm_delete_vm "$vm" || st=1
1087新增: done <<< "$1"
1088新增: return "$st"
18451089}
18461090
1847删除:_agent_vm_status() {
1848删除: local host_dir
1849删除: host_dir="$(pwd)"
1850删除: local current_vm_name
1851删除: current_vm_name="$(_agent_vm_name "$host_dir")"
1852删除:
1853删除: local header
1854删除: header=$(limactl list | head -1)
1855删除:
1856删除: echo "VMs (current directory: $host_dir):"
1857删除: echo ""
1858删除: echo "$header" | sed 's/^/ /'
1859删除: limactl list | grep "^agent-vm-" | while read -r line; do
1860删除: local vm_name
1861删除: vm_name=$(echo "$line" | awk '{print $1}')
1862删除: if [[ "$vm_name" == "$current_vm_name" ]]; then
1863删除: echo "$line" | sed 's/^/> /'
1864删除: else
1865删除: echo "$line" | sed 's/^/ /'
1091新增:# Lima's table of the agent-vm VMs, with the base each was cloned from (see
1092新增:# _agent_vm_base_label) in a last column. Lima pads every column but its last,
1093新增:# so the lines are padded here to line it up.
1094新增:# `list` and `status`: Lima's table of the agent-vm VMs, the current
1095新增:# directory's marked with >, and the base each was cloned from (see
1096新增:# _agent_vm_base_label) in a last column. Lima pads every column but its last,
1097新增:# so the lines are padded here to line it up.
1098新增:_agent_vm_list() {
1099新增: local list line lines=() w=0 header=1 current mark
1100新增: current="$(_agent_vm_name "$(pwd)" 2>/dev/null)" || current=""
1101新增: if ! list="$(limactl list 2>/dev/null)"; then
1102新增: echo "Error: could not query Lima. Is it installed and working?" >&2
1103新增: return 1
1104新增: fi
1105新增: while IFS= read -r line; do
1106新增: [[ -n "$line" ]] || continue
1107新增: if [[ ${#lines[@]} -eq 0 || "$line" == agent-vm-* ]]; then
1108新增: lines+=("$line")
1109新增: [[ ${#line} -gt $w ]] && w=${#line}
18661110 fi
1867删除: done || echo " (no VMs)"
1868删除:}
1869删除:
1870删除:# When the file is executed directly (`./agent-vm.sh setup`) rather than
1871删除:# sourced, dispatch to the agent-vm function so it doesn't silently no-op.
1872删除:# Sourcing remains the canonical install path because it makes `agent-vm`
1873删除:# available as a shell function across all future commands. Detection is
1874删除:# shell-specific:
1875删除:# bash: BASH_SOURCE[0] differs from $0 when sourced
1876删除:# zsh: ZSH_EVAL_CONTEXT contains ':file' when sourced
1877删除:_agent_vm_is_sourced() {
1878删除: if [[ -n "${BASH_VERSION:-}" ]]; then
1879删除: [[ "${BASH_SOURCE[0]}" != "$0" ]]
1880删除: elif [[ -n "${ZSH_VERSION:-}" ]]; then
1881删除: [[ "${ZSH_EVAL_CONTEXT:-}" == *:file* ]]
1882删除: else
1883删除: return 0 # unknown shell — assume sourced and don't auto-run
1111新增: done <<< "$list"
1112新增: if [[ ${#lines[@]} -lt 2 ]]; then
1113新增: [[ ${#lines[@]} -eq 0 ]] || printf ' %s\n' "${lines[@]}"
1114新增: echo " (no VMs)"
1115新增: return 0
18841116 fi
1117新增: for line in "${lines[@]}"; do
1118新增: if [[ -n "$header" ]]; then
1119新增: header=""
1120新增: printf ' %-*s %s\n' "$w" "$line" "BASE"
1121新增: else
1122新增: mark=" "
1123新增: [[ "${line%% *}" == "$current" ]] && mark=">"
1124新增: printf '%s %-*s %s\n' "$mark" "$w" "$line" "$(_agent_vm_base_label "${line%% *}")"
1125新增: fi
1126新增: done
18851127}
18861128
1887删除:if ! _agent_vm_is_sourced; then
1888删除: unset -f _agent_vm_is_sourced
1129新增:# When the file is executed (the command `install` puts on PATH, or
1130新增:# `./agent-vm.sh setup`) rather than sourced, dispatch to the agent-vm
1131新增:# function so it doesn't silently no-op. BASH_SOURCE[0] differs from $0 when
1132新增:# sourced.
1133新增:if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
18891134 agent-vm "$@"
1890删除: # Preserve agent-vm's exit code — without the explicit exit, the script
1891删除: # would end on the implicit `unset -f` below, which always returns 0 and
1892删除: # would mask command failures (`./agent-vm.sh bad-cmd; echo $?` → 0).
18931135 exit $?
18941136fi
1895删除:unset -f _agent_vm_is_sourced
修改install.sh+1 −133看文件
@@ -1,134 +1,2 @@
11#!/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"
2新增:exec bash "$(dirname "$0")/agent-vm.sh" "$([ "${1:-}" = --uninstall ] && echo uninstall || echo install)"
新增lib/doctor.sh+379 −0看文件
@@ -0,0 +1,379 @@
1新增:# --- doctor -------------------------------------------------------------------
2新增:# Checks the host, Lima, the base template and the current directory, and says
3新增:# what to do about each problem. Read-only: it never creates, starts or stops
4新增:# a VM, so it is safe to run first and to paste into an issue (no secret
5新增:# values, only names). Exit 1 when a check failed, 0 otherwise.
6新增:
7新增:# Octal mode of <file> (e.g. 600), without file-type bits. Prints nothing
8新增:# and returns 1 when it cannot be read. GNU stat first, BSD/macOS second;
9新增:# both are probed rather than assumed from uname, so a PATH with only one
10新增:# of them still works.
11新增:_agent_vm_file_mode() {
12新增: local mode
13新增: mode="$(stat -c %a "$1" 2>/dev/null || stat -f %Lp "$1" 2>/dev/null)" || return 1
14新增: [[ "$mode" =~ ^[0-7]+$ ]] || return 1
15新增: printf '%s\n' "$mode"
16新增:}
17新增:
18新增:# 0 when no group/other permission bit is set on <file> (600, 400 and 700
19新增:# all count as private). 1 when group/other can read, write or execute it.
20新增:# 2 when the mode could not be read: never claim "private" from missing
21新增:# information, and never claim "exposed" from a failed stat either.
22新增:_agent_vm_file_is_private() {
23新增: local mode
24新增: if ! mode="$(_agent_vm_file_mode "$1")"; then
25新增: return 2
26新增: fi
27新增: # 8# for base-8: $mode may carry a leading zero.
28新增: (( 8#$mode & 8#77 )) && return 1
29新增: return 0
30新增:}
31新增:
32新增:_agent_vm_doctor_line() {
33新增: # <ok|warn|fail|info> <message> [hint...]
34新增: local level="$1" msg="$2"
35新增: shift 2
36新增: case "$level" in
37新增: ok) printf ' ok %s\n' "$msg" ;;
38新增: warn) printf ' warn %s\n' "$msg"; AGENT_VM_DOCTOR_WARN=$((AGENT_VM_DOCTOR_WARN + 1)) ;;
39新增: fail) printf ' FAIL %s\n' "$msg"; AGENT_VM_DOCTOR_FAIL=$((AGENT_VM_DOCTOR_FAIL + 1)) ;;
40新增: *) printf ' - %s\n' "$msg" ;;
41新增: esac
42新增: while [[ $# -gt 0 ]]; do
43新增: printf ' %s\n' "$1"
44新增: shift
45新增: done
46新增:}
47新增:
48新增:_agent_vm_doctor() {
49新增: # Local, and still visible to _agent_vm_doctor_line: bash scopes locals
50新增: # dynamically, so the helper updates these and nothing leaks.
51新增: local AGENT_VM_DOCTOR_WARN=0 AGENT_VM_DOCTOR_FAIL=0
52新增: local d=_agent_vm_doctor_line
53新增:
54新增: echo "agent-vm doctor"
55新增: echo ""
56新增: echo "agent-vm"
57新增: $d info "version $AGENT_VM_VERSION, from $AGENT_VM_SCRIPT_DIR"
58新增: if [[ ! -r "$AGENT_VM_SCRIPT_DIR/agent-vm.setup.sh" ]]; then
59新增: $d fail "agent-vm.setup.sh is missing next to agent-vm.sh" \
60新增: "'agent-vm setup' needs it. Reinstall, or run agent-vm from its clone."
61新增: fi
62新增: if _agent_vm_sha256 </dev/null >/dev/null 2>&1; then
63新增: $d ok "SHA-256 tool available (VM names)"
64新增: else
65新增: $d fail "neither shasum nor sha256sum is installed" \
66新增: "VM names hash the project path. Install perl (shasum) or coreutils (sha256sum)."
67新增: fi
68新增: if ! command -v perl >/dev/null 2>&1; then
69新增: $d warn "perl is not installed: 'agent-vm project-env' and relative destinations in ~/.agent-vm/volumes need it" \
70新增: "They use files in the project without following symlinks, which the shell cannot do."
71新增: fi
72新增:
73新增: echo ""
74新增: echo "Host"
75新增: $d info "$(uname -sm)"
76新增: local cpus mem free_gib
77新增: cpus="$(_agent_vm_host_cpus)"
78新增: mem="$(_agent_vm_host_mem_gib)"
79新增: if [[ -n "$cpus" && -n "$mem" ]]; then
80新增: $d info "${cpus} CPUs, ${mem} GiB RAM; a VM gets at most $(_agent_vm_host_share "$cpus" 1) CPUs and $(_agent_vm_host_share "$mem" 2) GiB (AGENT_VM_HOST_SHARE=$AGENT_VM_HOST_SHARE)"
81新增: else
82新增: $d warn "could not read the host's CPU or RAM: --cpus and --memory are not clamped"
83新增: fi
84新增: if ! free_gib="$(_agent_vm_free_gib)"; then
85新增: $d warn "could not read the free disk space"
86新增: elif [[ "$free_gib" -lt 10 ]]; then
87新增: $d warn "$free_gib GiB free for Lima's VMs" "A default VM disk is 10 GiB (sparse)."
88新增: else
89新增: $d ok "$free_gib GiB free for Lima's VMs"
90新增: fi
91新增:
92新增: echo ""
93新增: echo "Lima"
94新增: local have_lima="" protects_git=""
95新增: if [[ -n "$(_agent_vm_limactl_path)" ]]; then
96新增: have_lima=1
97新增: local lima_ver
98新增: lima_ver="$(limactl --version 2>/dev/null)"
99新增: lima_ver="${lima_ver##* }"
100新增: if [[ -z "$lima_ver" ]]; then
101新增: $d warn "limactl is installed but did not report a version"
102新增: elif ! _agent_vm_ver_ge "$lima_ver" 1.0.0; then
103新增: $d warn "Lima $lima_ver is older than 1.0" \
104新增: "Before 1.0 the default mount type can be reverse-sshfs, where --readonly is refused."
105新增: else
106新增: $d ok "Lima $lima_ver"
107新增: fi
108新增: local lima_st=0
109新增: _agent_vm_lima_protects_git || lima_st=$?
110新增: case "$lima_st" in
111新增: 0)
112新增: _agent_vm_writable_git_optout || protects_git=1
113新增: $d ok "Lima keeps every .git read-only for the VMs (sshfs.readonlyNames)" ;;
114新增: 1)
115新增: $d warn "this Lima cannot keep .git read-only for the VMs, so a start with writable shares asks first"
116新增: # Where a start would ask about it: Windows, Lima's config, or this
117新增: # directory's VM if Lima made it before 1.0 (else the base's).
118新增: if _agent_vm_unprotected_mount_is_sshfs "$(_agent_vm_name "$(pwd)" 2>/dev/null)"; then
119新增: $d warn "it cannot keep the VMs to their shares either"
120新增: _agent_vm_sshfs_exposure_note | _agent_vm_wrap 70 | sed 's/^/ /'
121新增: fi
122新增: _agent_vm_git_protection_hint | _agent_vm_wrap 70 | sed 's/^/ /' ;;
123新增: *)
124新增: $d fail "cannot tell whether this Lima keeps .git read-only: 'limactl validate' gave no answer agent-vm knows" \
125新增: "A start with writable shares stops until it can tell. Check that 'limactl validate' works." ;;
126新增: esac
127新增: if _agent_vm_writable_git_optout; then
128新增: $d warn "AGENT_VM_UNSAFE_WRITABLE_GIT=1: the VMs can write .git, and git on this machine runs what .git/config and hooks name" \
129新增: "Unset it to keep .git read-only."
130新增: fi
131新增: else
132新增: $d fail "Lima is not installed" "Install it from https://lima-vm.io/docs/installation/ (or 'brew install $AGENT_VM_LIMA_FORMULA')."
133新增: fi
134新增: if [[ "$(uname -s)" == "Linux" ]]; then
135新增: local prereq_out
136新增: if prereq_out="$(_agent_vm_check_linux_prereqs 2>&1)"; then
137新增: $d ok "QEMU and /dev/kvm are usable"
138新增: else
139新增: $d fail "QEMU or KVM is not usable"
140新增: printf '%s\n' "$prereq_out" | sed 's/^/ /'
141新增: fi
142新增: fi
143新增: if _agent_vm_on_windows; then
144新增: local win_prereq_out
145新增: if win_prereq_out="$(_agent_vm_check_windows_prereqs 2>&1)"; then
146新增: $d ok "QEMU is installed"
147新增: else
148新增: $d fail "QEMU is not usable"
149新增: printf '%s\n' "$win_prereq_out" | sed 's/^/ /'
150新增: fi
151新增: $d info "QEMU also needs the 'Windows Hypervisor Platform' feature, which only an administrator can check or turn on" \
152新增: "Without it, VMs fail to start with a WHPX error. An administrator runs, once, then reboots:" \
153新增: "$AGENT_VM_WHPX_ON"
154新增: fi
155新增:
156新增: # A bare repository is not named .git, so readonlyNames does not cover one
157新增: # the VM plants in a project (see _agent_vm_bare_repo_state).
158新增: local bare_state
159新增: bare_state="$(_agent_vm_bare_repo_state)"
160新增: if [[ "$bare_state" != "nogit" ]]; then
161新增: echo ""
162新增: echo "Git on this machine"
163新增: case "$bare_state" in
164新增: ok) $d ok "safe.bareRepository = explicit" ;;
165新增: old) $d warn "$(git --version) is older than 2.38: it would use a repository a VM creates under another name than .git, and run what its config names" \
166新增: "Upgrade git, then: git config --global safe.bareRepository explicit" ;;
167新增: *) $d warn "safe.bareRepository is not 'explicit': git would use a repository a VM creates under another name than .git, and run what its config names" \
168新增: "git config --global safe.bareRepository explicit" ;;
169新增: esac
170新增: fi
171新增:
172新增: echo ""
173新增: echo "Base template"
174新增: local st=0
175新增: if [[ -z "$have_lima" ]]; then
176新增: $d info "not checked (see above)"
177新增: else
178新增: _agent_vm_base_exists || st=$?
179新增: case "$st" in
180新增: 0)
181新增: local built
182新增: built="$(cat "$AGENT_VM_STATE_DIR/.agent-vm-base-version" 2>/dev/null)"
183新增: if [[ "$built" =~ ^[0-9]+$ ]]; then
184新增: $d ok "$AGENT_VM_TEMPLATE is ready, built $(_agent_vm_epoch_date "$built" +%F)"
185新增: if [[ $(( ($(date +%s) - built) / 86400 )) -gt 90 ]]; then
186新增: $d warn "the base template is over 90 days old" \
187新增: "Its agents and packages are as old. 'agent-vm setup' rebuilds it."
188新增: fi
189新增: else
190新增: $d ok "$AGENT_VM_TEMPLATE is ready"
191新增: fi
192新增: # 0.1.0 support, to be removed with _agent_vm_migrate_0_1.
193新增: if [[ ! -f "$AGENT_VM_STATE_DIR/.agent-vm-base-built-by" ]]; then
194新增: $d warn "the base template was built by agent-vm 0.1.0, without the sshfs of the shares that keep .git read-only: each VM made from it boots once more to install it" \
195新增: "'agent-vm setup' rebuilds it, then '--reset' the VMs made from it."
196新增: fi ;;
197新增: 1)
198新增: if _agent_vm_exists "$AGENT_VM_TEMPLATE"; then
199新增: $d fail "$AGENT_VM_TEMPLATE exists but its setup did not complete" "Run 'agent-vm setup' again."
200新增: else
201新增: $d fail "no base template yet" "Run 'agent-vm setup'."
202新增: fi ;;
203新增: *) $d warn "could not query Lima" ;;
204新增: esac
205新增: fi
206新增:
207新增: echo ""
208新增: echo "Settings ($AGENT_VM_STATE_DIR)"
209新增: local f
210新增: if [[ -f "$AGENT_VM_STATE_DIR/env" ]]; then
211新增: local env_mode
212新增: # Git Bash emulates permission bits (chmod 600 reads back as 644): the
213新增: # file's ACL is what protects it there, and it cannot be read from here.
214新增: if _agent_vm_on_windows; then
215新增: $d info "env: $(_agent_vm_env env "$AGENT_VM_STATE_DIR/env" "" list | wc -l | tr -d ' ') key(s)"
216新增: elif env_mode="$(_agent_vm_file_mode "$AGENT_VM_STATE_DIR/env")" \
217新增: && _agent_vm_file_is_private "$AGENT_VM_STATE_DIR/env"; then
218新增: $d ok "env: $(_agent_vm_env env "$AGENT_VM_STATE_DIR/env" "" list | wc -l | tr -d ' ') key(s), private to you (mode $env_mode)"
219新增: elif [[ -n "$env_mode" ]]; then
220新增: $d warn "env is readable by other users on this machine (mode $env_mode)" "chmod 600 '$AGENT_VM_STATE_DIR/env'"
221新增: else
222新增: $d warn "env permissions could not be checked" "chmod 600 '$AGENT_VM_STATE_DIR/env'"
223新增: fi
224新增: else
225新增: $d info "env: none (agent-vm env set KEY VALUE)"
226新增: fi
227新增: for f in volumes setup.sh runtime.sh; do
228新增: [[ -f "$AGENT_VM_STATE_DIR/$f" ]] && $d info "$f: present"
229新增: done
230新增:
231新增: echo ""
232新增: local host_dir vm_name vm_exists="" ro_names=""
233新增: host_dir="$(pwd)"
234新增: [[ -n "$protects_git" ]] && ro_names="$(_agent_vm_readonly_names "$host_dir")"
235新增: echo "This directory ($host_dir)"
236新增: local bad
237新增: if bad="$(_agent_vm_unmountable_path "$host_dir")"; then
238新增: $d fail "the path $bad" "agent-vm refuses to mount it. Rename the directory."
239新增: fi
240新增: local unsafe
241新增: if unsafe="$(_agent_vm_unsafe_project "$host_dir")"; then
242新增: $d fail "this directory $unsafe" \
243新增: "agent-vm refuses to share it with a VM. Run it from a project directory."
244新增: fi
245新增: if vm_name="$(_agent_vm_name "$host_dir" 2>/dev/null)"; then
246新增: if [[ -z "$have_lima" ]]; then
247新增: $d info "VM name: $vm_name"
248新增: else
249新增: st=0
250新增: _agent_vm_exists "$vm_name" || st=$?
251新增: case "$st" in
252新增: 0)
253新增: vm_exists=1
254新增: if [[ "$(_agent_vm_stale_state "$vm_name")" == "1" ]]; then
255新增: $d warn "$vm_name was cloned from an older base template" "'agent-vm --reset <command>' re-clones it."
256新增: else
257新增: $d ok "$vm_name exists"
258新增: fi
259新增: if _agent_vm_running "$vm_name"; then
260新增: local mst=0
261新增: _agent_vm_mount_is_host_enforced "$vm_name" || mst=$?
262新增: case "$mst" in
263新增: 0) $d ok "running; the project share is enforced on the host (--readonly works)" ;;
264新增: 1) $d warn "running; the host does not enforce read-only on the project share, so --readonly is refused" \
265新增: "Use virtiofs on vz or 9p on QEMU, then --reset." ;;
266新增: *) $d warn "running, but the project mount type could not be read" ;;
267新增: esac
268新增: else
269新增: $d info "stopped"
270新增: fi
271新增: # What the VM was given, which may predate the Lima installed now:
272新增: # the next start brings it in line (see _agent_vm_ensure_running).
273新增: if [[ -n "$protects_git" ]] && _agent_vm_mounts_protect_git "$vm_name" \
274新增: && ! _agent_vm_mounts_have_readonly_names "$vm_name" "$ro_names"; then
275新增: $d warn "its shares keep .git read-only, but not all of $(_agent_vm_names_text "$ro_names")" \
276新增: "The next start (after 'agent-vm stop' if it runs) fixes that."
277新增: elif _agent_vm_mounts_protect_git "$vm_name"; then
278新增: $d ok "its shares keep every .git read-only"
279新增: elif _agent_vm_writable_git_optout; then
280新增: $d warn "its shares leave .git writable (AGENT_VM_UNSAFE_WRITABLE_GIT=1)"
281新增: else
282新增: $d warn "its shares leave .git writable" \
283新增: "With a Lima that can protect it, the next start (after 'agent-vm stop' if it runs) fixes that."
284新增: fi ;;
285新增: 1) $d info "$vm_name will be created on the first agent-vm command here" ;;
286新增: *) $d warn "could not query Lima" ;;
287新增: esac
288新增: fi
289新增: fi
290新增: # Hooks folders the VM can write, and git on this machine runs (see
291新增: # _agent_vm_project_hooks), in this project and the repositories below it.
292新增: local hooks_rel hooks_in hooks_name hooks_what
293新增: while IFS=$'\t' read -r hooks_rel hooks_in; do
294新增: [[ -n "$hooks_rel" ]] || continue
295新增: hooks_what="git runs hooks from $hooks_rel (core.hooksPath)"
296新增: [[ "$hooks_rel" == . ]] && hooks_what="git runs hooks from the project directory itself (core.hooksPath)"
297新增: if ! hooks_name="$(_agent_vm_hooks_name "$hooks_in")"; then
298新增: $d warn "$hooks_what, which the VM can write" \
299新增: "agent-vm can only keep a folder of the project read-only, by a name without quotes or backslashes: point core.hooksPath to one."
300新增: elif [[ -z "$protects_git" ]]; then
301新增: $d warn "$hooks_what, which the VM can write" \
302新增: "agent-vm keeps it read-only when it keeps .git read-only (see above)."
303新增: elif [[ -z "$vm_exists" ]]; then
304新增: $d info "$hooks_what: every '$hooks_name' in the project will be read-only for the VM"
305新增: elif _agent_vm_mounts_have_readonly_names "$vm_name" "$ro_names"; then
306新增: $d ok "$hooks_what: every '$hooks_name' in the project is read-only for the VM"
307新增: else
308新增: $d warn "$hooks_what, which the VM can still write" \
309新增: "The next start (after 'agent-vm stop' if it runs) makes every '$hooks_name' in the project read-only."
310新增: fi
311新增: done <<< "$(_agent_vm_project_hooks "$host_dir")"
312新增: # Git config the VM can write, or commands it names in the project (see
313新增: # _agent_vm_repo_config_risks).
314新增: local git_risks
315新增: git_risks="$(_agent_vm_project_config_risks "$host_dir")"
316新增: if [[ -n "$git_risks" ]]; then
317新增: $d warn "git on this machine uses these, and the VM can write them:"
318新增: printf '%s\n' "$git_risks" | sed 's/^/ /'
319新增: printf ' %s\n' "Move them out of the project, or have them name commands outside it."
320新增: fi
321新增: local runtime runtime_text runtime_rel project_env
322新增: runtime="$(_agent_vm_project_runtime_path "$host_dir")"
323新增: if runtime_rel="$(_agent_vm_project_rel "$host_dir" "$runtime")"; then
324新增: # Not by its path: the VM can make it a symlink (see _agent_vm_project_rel).
325新增: if runtime_text="$(_agent_vm_nofollow read "$host_dir" "$runtime_rel" 2>/dev/null && printf x)"; then
326新增: $d info "project runtime: $runtime ($(printf '%s' "${runtime_text%x}" | awk "$_AGENT_VM_SHEBANG_AWK"))"
327新增: fi
328新增: elif [[ -f "$runtime" ]]; then
329新增: $d info "project runtime: $runtime ($(_agent_vm_runtime_interpreter "$runtime"))"
330新增: fi
331新增: project_env="$(_agent_vm_project_env_file "$host_dir")"
332新增: if [[ -f "$project_env" ]]; then
333新增: local unignored
334新增: unignored="$(_agent_vm_warn_unignored "$project_env" 2>&1)"
335新增: if [[ -n "$unignored" ]]; then
336新增: $d warn "project env: $project_env"
337新增: printf '%s\n' "$unignored" | sed 's/^ */ /'
338新增: else
339新增: $d ok "project env: $project_env"
340新增: fi
341新增: fi
342新增:
343新增: if [[ -n "$have_lima" ]]; then
344新增: # VMs persist and each is clamped on its own, so several running at once
345新增: # can promise more than the host has.
346新增: local all name vstatus vcpus vmem run_n=0 run_cpus=0 run_mem=0
347新增: all="$(limactl list --format '{{.Name}}|{{.Status}}|{{.CPUs}}|{{.Memory}}' 2>/dev/null || true)"
348新增: while IFS='|' read -r name vstatus vcpus vmem; do
349新增: case "$name" in agent-vm-*) ;; *) continue ;; esac
350新增: [[ "$vstatus" == "Running" ]] || continue
351新增: run_n=$((run_n + 1))
352新增: run_cpus=$((run_cpus + ${vcpus:-0}))
353新增: run_mem=$((run_mem + ${vmem:-0} / 1073741824))
354新增: done <<< "$all"
355新增: echo ""
356新增: echo "All VMs"
357新增: if [[ "$run_n" -eq 0 ]]; then
358新增: $d info "none running"
359新增: elif [[ -n "$mem" && "$run_mem" -gt "$mem" ]]; then
360新增: $d warn "$run_n running, ${run_cpus} CPUs and ${run_mem} GiB in total: more memory than the host has" \
361新增: "'agent-vm list' lists them; 'agent-vm stop <name>' frees one."
362新增: else
363新增: $d info "$run_n running, ${run_cpus} CPUs and ${run_mem} GiB in total"
364新增: fi
365新增: local leftover
366新增: while IFS= read -r leftover; do
367新增: [[ -n "$leftover" ]] || continue
368新增: $d warn "scratch VM $leftover was left by a run that did not finish" \
369新增: "The next --scratch run deletes it, or: agent-vm rm $leftover"
370新增: done <<< "$(_agent_vm_scratch_leftovers)"
371新增: fi
372新增:
373新增: echo ""
374新增: if [[ "$AGENT_VM_DOCTOR_FAIL" -gt 0 ]]; then
375新增: echo "$AGENT_VM_DOCTOR_FAIL problem(s), $AGENT_VM_DOCTOR_WARN warning(s)."
376新增: return 1
377新增: fi
378新增: echo "No problems found, $AGENT_VM_DOCTOR_WARN warning(s)."
379新增:}
新增lib/env.sh+521 −0看文件
@@ -0,0 +1,521 @@
1新增:# --- env: ~/.agent-vm/env and .agent-vm.env -----------------------------------
2新增:
3新增:# Escape a value for a single-quoted shell literal: ' becomes '"'"'.
4新增:#
5新增:# Via sed, NOT `${v//\'/\'\"\'\"\'}`: bash 3.2, what macOS ships, keeps the
6新增:# backslashes in the replacement half of that substitution and emits
7新增:# `O\'"\'"\'Brien`. The resulting line is a syntax error, and a shell sourcing
8新增:# ~/.agent-vm.env then abandons the WHOLE file, losing every secret in it, not
9新增:# just the one with the quote.
10新增:_agent_vm_sq_escape() {
11新增: printf '%s' "$1" | sed "s/'/'\"'\"'/g"
12新增:}
13新增:
14新增:# _agent_vm_env_read <file> <key>: print the value the file assigns to <key>,
15新增:# as a shell would, without running the shell.
16新增:# 0 = found (value on stdout) · 1 = not assigned · 3 = assigned with syntax
17新增:# this reader refuses to interpret.
18新增:#
19新增:# Accepted: optional leading `export `, then a value made of single-quoted
20新增:# parts (possibly spanning lines, as `set` writes a value with a newline),
21新增:# double-quoted parts with nothing to expand, and bare characters other than
22新增:# $ ` \ ; & | < > ( ) ~. A trailing `# comment` is allowed. The last
23新增:# assignment wins, like in the shell.
24新增:#
25新增:# One line refused, and no key can be answered: a quote left open or a
26新增:# trailing backslash makes the shell read the next lines as part of that
27新增:# value, and other syntax can run anything, an assignment to any key before
28新增:# or after it included (eval, typeset, a sourced file). A line that is not an
29新增:# assignment, a comment or blank counts as refused.
30新增:_agent_vm_env_read() {
31新增: awk -v k="$2" -v q="'" '
32新增: function parse(s, v, c, e, more) {
33新增: v = ""
34新增: while (s != "") {
35新增: c = substr(s, 1, 1)
36新增: if (c == q) {
37新增: s = substr(s, 2)
38新增: while (!(e = index(s, q))) {
39新增: if ((getline more) <= 0) { VAL = v; return 3 }
40新增: v = v s "\n"; s = more
41新增: }
42新增: v = v substr(s, 1, e - 1); s = substr(s, e + 1)
43新增: } else if (c == "\"") {
44新增: s = substr(s, 2); e = index(s, "\"")
45新增: if (!e || substr(s, 1, e - 1) ~ /[$`\\]/) { VAL = v; return 3 }
46新增: v = v substr(s, 1, e - 1); s = substr(s, e + 1)
47新增: } else if (c == " " || c == "\t") {
48新增: VAL = v
49新增: return (s ~ /^[ \t]+(#.*)?$/) ? 0 : 3
50新增: } else if (index("$`\\;&|<>()~\r", c)) {
51新增: VAL = v
52新增: return (c == "\r" && s == "\r") ? 0 : 3
53新增: } else {
54新增: v = v c; s = substr(s, 2)
55新增: }
56新增: }
57新增: VAL = v
58新增: return 0
59新增: }
60新增: {
61新增: if (broken) next
62新增: line = $0
63新增: sub(/^[ \t]+/, "", line)
64新增: if (line ~ /^(#.*)?\r?$/) next
65新增: sub(/^export[ \t]+/, "", line)
66新增: if (line !~ /^[A-Za-z_][A-Za-z0-9_]*=/) { broken = 1; next }
67新增: eq = index(line, "=")
68新增: if (parse(substr(line, eq + 1))) { broken = 1; next }
69新增: if (substr(line, 1, eq - 1) == k) { found = 1; val = VAL }
70新增: }
71新增: END {
72新增: if (broken) exit 3
73新增: if (!found) exit 1
74新增: printf "%s", val
75新增: }
76新增: ' "$1"
77新增:}
78新增:
79新增:# _agent_vm_env_lines <list|drop> <file> [key]: walk the file's assignments,
80新增:# following a quoted value onto the lines it spans.
81新增:# list prints each assigned name, once per assignment
82新增:# drop prints the file without <key>'s assignments, whole
83新增:# A line inside a quoted value is never read as an assignment: `set` writes a
84新增:# value with a newline across lines, and a line of it that looks like
85新增:# `NAME=...` is data. Dropping only the first line of such a value would leave
86新增:# its tail behind, an unterminated quote that breaks the file for the shell
87新增:# that sources it.
88新增:_agent_vm_env_lines() {
89新增: awk -v mode="$1" -v k="${3:-}" '
90新增: function scan(s, i, c, n) {
91新增: n = length(s)
92新增: for (i = 1; i <= n; i++) {
93新增: c = substr(s, i, 1)
94新增: if (q == "\047") { if (c == "\047") q = ""; continue }
95新增: # $'"'"'...'"'"': backslash escapes, a quote among them included.
96新增: if (q == "$") {
97新增: if (c == "\\") i++
98新增: else if (c == "\047") q = ""
99新增: continue
100新增: }
101新增: if (q == "\"") {
102新增: if (c == "\\") i++
103新增: else if (c == "\"") q = ""
104新增: continue
105新增: }
106新增: if (c == "\\") i++
107新增: else if (c == "$" && substr(s, i + 1, 1) == "\047") { q = "$"; i++ }
108新增: else if (c == "\047" || c == "\"") q = c
109新增: else if (c == "#" && i > 1 && substr(s, i - 1, 1) ~ /[ \t]/) return
110新增: }
111新增: }
112新增: {
113新增: if (q != "") {
114新增: scan($0)
115新增: if (mode == "drop" && !skip) print
116新增: next
117新增: }
118新增: skip = 0
119新增: line = $0
120新增: sub(/^[ \t]+/, "", line)
121新增: sub(/^export[ \t]+/, "", line)
122新增: if (match(line, /^[A-Za-z_][A-Za-z0-9_]*=/)) {
123新增: name = substr(line, 1, RLENGTH - 1)
124新增: if (mode == "list") print name
125新增: if (name == k) skip = 1
126新增: scan(substr(line, RLENGTH + 1))
127新增: }
128新增: if (mode == "drop" && !skip) print
129新增: }
130新增: ' "$2"
131新增:}
132新增:
133新增:# _agent_vm_project_path <dir> <path>: a project file's path, <path> taken
134新增:# relative to the project <dir> unless absolute. An integrator moves the env
135新增:# file and the runtime script into its own directory (".mytool/env") with
136新增:# AGENT_VM_PROJECT_ENV and AGENT_VM_PROJECT_RUNTIME.
137新增:_agent_vm_project_path() {
138新增: case "$2" in
139新增: /*) _agent_vm_path_join / "$2" ;;
140新增: *) _agent_vm_path_join "$1" "$2" ;;
141新增: esac
142新增:}
143新增:
144新增:# This project's env file: in the project, so it follows a clone, a move and
145新增:# a delete, and one `git add` away from being published (secrets shared by
146新增:# every VM belong in `agent-vm env`).
147新增:_agent_vm_project_env_file() {
148新增: _agent_vm_project_path "${1:-$(pwd)}" "${AGENT_VM_PROJECT_ENV:-.agent-vm.env}"
149新增:}
150新增:
151新增:# _agent_vm_path_join <dir> <path>: <dir>/<path>, with `.` and `..` resolved in
152新增:# the text, as `cd` does. Whether a project file is read by the host or by the
153新增:# VM depends on whether it is inside the project (_agent_vm_in_project): a
154新增:# path that only goes through the project on its way out of it (`../x`) names
155新增:# a file outside, which the VM cannot see.
156新增:_agent_vm_path_join() {
157新增: local out="${1%/}" rest="$2/" comp
158新增: while [[ -n "$rest" ]]; do
159新增: comp="${rest%%/*}"
160新增: rest="${rest#*/}"
161新增: case "$comp" in
162新增: ""|.) ;;
163新增: ..) out="${out%/*}" ;;
164新增: *) out="$out/$comp" ;;
165新增: esac
166新增: done
167新增: printf '%s\n' "${out:-/}"
168新增:}
169新增:
170新增:# After `project-env set`: warns, with the line that fixes it, when the file
171新增:# is tracked by git (rm --cached, then ignore) or not ignored (ignore), as
172新增:# `git check-ignore` sees it. Silent without a repository or git. git runs in
173新增:# a directory the VM can write: see _agent_vm_git_untrusted.
174新增:_agent_vm_warn_unignored() {
175新增: local file="$1" top rel rc=0 drive rest alt
176新增: command -v git >/dev/null 2>&1 || return 0
177新增: top="$(_agent_vm_git_untrusted -C "$(dirname "$file")" rev-parse --show-toplevel 2>/dev/null)" || return 0
178新增: [ -n "$top" ] || return 0
179新增: rel="${file#"$top"/}"
180新增: if [[ "$rel" == "$file" ]]; then
181新增: # Git Bash spells the drive C:/... while the shell spells it /c/.... git
182新增: # itself takes either form, but the string comparison above needs one.
183新增: drive="${top%%:*}"; rest="${top#*:}"
184新增: if [[ "$drive" =~ ^[A-Za-z]$ && "$rest" == /* ]]; then
185新增: alt="/$(printf '%s' "$drive" | tr '[:upper:]' '[:lower:]')$rest"
186新增: rel="${file#"$alt"/}"
187新增: fi
188新增: fi
189新增: # Still no common root (a worktree elsewhere, an odd spelling): not
190新增: # something to lecture about.
191新增: [[ "$rel" == "$file" ]] && return 0
192新增:
193新增: # The printed lines work from any directory, the project one being possibly
194新增: # below the top of the repository: paths are relative to the top, and quoted.
195新增: local q_top q_rel
196新增: q_top="$(_agent_vm_sq_escape "$top")"
197新增: q_rel="$(_agent_vm_sq_escape "$rel")"
198新增: if _agent_vm_git_untrusted -C "$top" ls-files --error-unmatch "$file" >/dev/null 2>&1; then
199新增: echo "Warning: $rel is tracked by git: its contents are in the repository." >&2
200新增: echo " git -C '$q_top' rm --cached '$q_rel' && echo '/$q_rel' >> '$q_top/.gitignore'" >&2
201新增: return 0
202新增: fi
203新增:
204新增: _agent_vm_git_untrusted -C "$top" check-ignore -q "$file" 2>/dev/null || rc=$?
205新增: [ "$rc" -eq 1 ] || return 0
206新增: echo "Warning: $rel is not ignored by git: it can be committed by accident." >&2
207新增: echo " echo '/$q_rel' >> '$q_top/.gitignore'" >&2
208新增:}
209新增:
210新增:# _agent_vm_project_rel <dir> <path>: when <path> is inside the project
211新增:# directory <dir>, where the VM can write, print it relative to <dir> and
212新增:# return 0. The host must not read such a file by its path: the VM can make it
213新增:# a symlink, and the host would follow it to any file of the user's and hand
214新增:# the content over. It is read in the VM instead, by <dir>/<rel>, where a link
215新增:# resolves among the VM's own files (see _agent_vm_push_env_and_probe), or
216新增:# with _agent_vm_nofollow.
217新增:#
218新增:# Inside by its spelling, or by where it leads: the project reached through a
219新增:# link of the user's, the other spelling of a linked directory (/tmp and
220新增:# /private/tmp on macOS), another case where the file system ignores it. So
221新增:# <path> is resolved one component at a time, links followed one hop at a
222新增:# time, and the first step that reaches the project decides, before anything
223新增:# in it is followed: the rest is in the project, and goes through
224新增:# _agent_vm_nofollow or the VM, which follow none of the VM's links on the
225新增:# host. Before that point, every link is outside the project, where the VM
226新增:# cannot change it.
227新增:_agent_vm_project_rel() {
228新增: local dir="${1%/}" target="$2" pdir cur="" next cmp rest comp t hops=0 r
229新增: if [[ "$target" == "$dir/"* ]]; then
230新增: printf '%s\n' "${target#"$dir"/}"
231新增: return 0
232新增: fi
233新增: pdir="$(CDPATH= cd -P -- "$dir" 2>/dev/null && pwd)" || return 1
234新增: [[ -n "$pdir" ]] || return 1
235新增: pdir="$(_agent_vm_fold "$pdir")"
236新增: rest="${target#/}/"
237新增: while [[ -n "$rest" ]]; do
238新增: comp="${rest%%/*}"
239新增: rest="${rest#*/}"
240新增: case "$comp" in
241新增: ""|.) continue ;;
242新增: ..) cur="${cur%/*}"; continue ;;
243新增: esac
244新增: next="$cur/$comp"
245新增: cmp="$(_agent_vm_fold "$next")"
246新增: if [[ "$cmp" == "$pdir" || "$cmp" == "$pdir/"* ]]; then
247新增: r="${next:$((${#pdir} + 1))}/${rest%/}"
248新增: r="${r#/}"
249新增: printf '%s\n' "${r%/}"
250新增: return 0
251新增: fi
252新增: if [[ -L "$next" ]]; then
253新增: hops=$((hops + 1))
254新增: [[ $hops -gt 40 ]] && return 1
255新增: t="$(readlink "$next")" || return 1
256新增: [[ "$t" == /* ]] && cur=""
257新增: rest="${t#/}/$rest"
258新增: continue
259新增: fi
260新增: cur="$next"
261新增: done
262新增: return 1
263新增:}
264新增:
265新增:# 0 when <path> is inside the project directory <dir> (see
266新增:# _agent_vm_project_rel).
267新增:_agent_vm_in_project() {
268新增: _agent_vm_project_rel "$1" "$2" >/dev/null
269新增:}
270新增:
271新增:# What gets pushed into a VM: the shared file first, this project's next.
272新增:# The guest sources it, so the last assignment wins and the project's value
273新增:# overrides the shared one. A function of its own so that order is testable
274新增:# without starting a VM: it is the whole meaning of "per project".
275新增:#
276新增:# The project's file is only in here when AGENT_VM_PROJECT_ENV puts it outside
277新增:# the project. Inside, the VM reads it and appends it (see
278新增:# _agent_vm_in_project).
279新增:_agent_vm_env_payload() {
280新增: local host_dir="${1:-$(pwd)}" project_env
281新增: project_env="$(_agent_vm_project_env_file "$host_dir")"
282新增: # The echo keeps a shared file with no trailing newline from gluing its last
283新增: # line to the project's first one. CRs go: a CRLF file (Windows) would put
284新增: # one at the end of every value in the guest.
285新增: [ -f "$AGENT_VM_STATE_DIR/env" ] && { _agent_vm_strip_cr < "$AGENT_VM_STATE_DIR/env"; echo; }
286新增: if ! _agent_vm_in_project "$host_dir" "$project_env" && [ -f "$project_env" ]; then
287新增: _agent_vm_strip_cr < "$project_env"
288新增: fi
289新增: return 0
290新增:}
291新增:
292新增:# _agent_vm_nofollow <read|write|mkdir|touch> <dir> <rel>: print the file
293新增:# <dir>/<rel>, replace it with stdin, make it a directory (mkdir -p), or make
294新增:# it an empty file unless it is one already, following no symlink below <dir>:
295新增:# the one way the host touches the project, which the VM can write. Through a link
296新增:# planted there, a plain read would copy any file of the user's into the
297新增:# project, and a write could land anywhere. Checking for links first is not
298新增:# enough: the VM can swap one in between the check and the use.
299新增:#
300新增:# So each directory is entered and checked to be the one lstat saw, the file
301新增:# is opened with O_NOFOLLOW (and O_NONBLOCK, so a FIFO cannot hang it), and a
302新增:# write goes to a new file renamed over the old one, which replaces a link
303新增:# rather than following it. Perl, because the shell can do none of this.
304新增:# Missing directories are created except on a read. A file written is mode
305新增:# 600; one made by touch has the umask's mode, like `: > file`.
306新增:#
307新增:# Status: 0 done, 1 no such file (read), 3 a symlink or something other than a
308新增:# directory or a regular file on the way, 2 any other failure.
309新增:_agent_vm_nofollow() {
310新增: if ! command -v perl >/dev/null 2>&1; then
311新增: echo "Error: perl is needed to use a file in the project without following symlinks." >&2
312新增: return 2
313新增: fi
314新增: perl -e '
315新增: use strict;
316新增: use Fcntl qw(O_RDONLY O_WRONLY O_CREAT O_EXCL O_NOFOLLOW O_NONBLOCK);
317新增: my ($op, $top, $rel) = @ARGV;
318新增: chdir $top or exit 2;
319新增: my @dirs = grep { $_ ne "" && $_ ne "." } split m{/}, $rel;
320新增: my $name = pop @dirs;
321新增: exit 3 if !defined $name || grep { $_ eq ".." } @dirs, $name;
322新增: push @dirs, $name if $op eq "mkdir";
323新增: for my $d (@dirs) {
324新增: my @l = lstat $d;
325新增: if (!@l) {
326新增: exit 1 if $op eq "read";
327新增: mkdir $d or exit 2;
328新增: @l = lstat $d or exit 2;
329新增: }
330新增: exit 3 unless -d _;
331新增: chdir $d or exit 2;
332新增: my @s = stat ".";
333新增: exit 3 unless @s && $s[0] == $l[0] && $s[1] == $l[1];
334新增: }
335新增: exit 0 if $op eq "mkdir";
336新增: if ($op eq "touch") {
337新增: if (lstat $name) {
338新增: exit(-f _ ? 0 : 3);
339新增: }
340新增: sysopen(my $new, $name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0666) or exit 2;
341新增: close $new;
342新增: exit 0;
343新增: }
344新增: local $/;
345新增: if ($op eq "read") {
346新增: sysopen(my $in, $name, O_RDONLY | O_NOFOLLOW | O_NONBLOCK) or exit($!{ENOENT} ? 1 : 3);
347新增: exit 3 unless -f $in;
348新增: binmode $in; binmode STDOUT;
349新增: my $data = <$in>;
350新增: print $data if defined $data;
351新增: exit 0;
352新增: }
353新增: binmode STDIN;
354新增: my $data = <STDIN>;
355新增: $data = "" unless defined $data;
356新增: my ($tmp, $out);
357新增: for (1 .. 20) {
358新增: $tmp = sprintf ".%s.agent-vm.%d.%d", $name, $$, int rand 1e9;
359新增: last if sysopen $out, $tmp, O_WRONLY | O_CREAT | O_EXCL, 0600;
360新增: undef $out;
361新增: }
362新增: exit 2 unless $out;
363新增: binmode $out;
364新增: unless ((print {$out} $data) && close $out && rename $tmp, $name) {
365新增: unlink $tmp;
366新增: exit 2;
367新增: }
368新增: exit 0;
369新增: ' "$@"
370新增:}
371新增:
372新增:# _agent_vm_env_file <read|write> <file> <top>: an env file, read to stdout or
373新增:# replaced with stdin. With <top> set, <file> is inside that project directory
374新增:# and goes through _agent_vm_nofollow. Without, it is one of the user's own
375新增:# (~/.agent-vm/env, or a project file kept outside the project), used as is.
376新增:# Status as _agent_vm_nofollow's.
377新增:_agent_vm_env_file() {
378新增: local op="$1" file="$2" top="$3" tmp
379新增: if [[ -n "$top" ]]; then
380新增: _agent_vm_nofollow "$op" "$top" "${file#"${top%/}"/}"
381新增: return
382新增: fi
383新增: if [[ "$op" == read ]]; then
384新增: [[ -f "$file" ]] || return 1
385新增: cat "$file" || return 2
386新增: return 0
387新增: fi
388新增: mkdir -p "$(dirname "$file")" || return 2
389新增: tmp="$(mktemp "${file}.XXXXXX")" || return 2
390新增: chmod 600 "$tmp"
391新增: if cat >| "$tmp" && mv "$tmp" "$file"; then
392新增: chmod 600 "$file"
393新增: return 0
394新增: fi
395新增: rm -f "$tmp"
396新增: return 2
397新增:}
398新增:
399新增:# `env` (~/.agent-vm/env) and `project-env`: set, get, has, unset, list, on a
400新增:# file the VM's shell sources, so the quoting is done here, once (see
401新增:# _agent_vm_sq_escape). Writes are atomic and mode 600, other lines kept as
402新增:# they are; list prints names, never values.
403新增:# Usage: _agent_vm_env <verb> <file> <top> [action [KEY [VALUE]]], <top> being
404新增:# the project directory when <file> is inside it (see _agent_vm_env_file).
405新增:# The file is read into a variable, never a temporary file: it holds secrets.
406新增:_agent_vm_env() {
407新增: local verb="$1" file="$2" top="$3"; shift 3
408新增: local action="${1:-list}"
409新增: local key="${2:-}"
410新增:
411新增: case "$action" in
412新增: set|get|has|unset)
413新增: if [[ -z "$key" ]]; then
414新增: echo "Error: 'agent-vm $verb $action' needs a KEY." >&2
415新增: return 1
416新增: fi
417新增: # A key must be a shell-assignable name: anything else would produce a
418新增: # line that breaks the file for every reader.
419新增: if [[ ! "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then
420新增: echo "Error: '$key' is not a valid environment variable name." >&2
421新增: return 1
422新增: fi ;;
423新增: list) ;;
424新增: *)
425新增: echo "Usage: agent-vm $verb {set KEY [VALUE]|get KEY|has KEY|unset KEY|list}" >&2
426新增: return 1 ;;
427新增: esac
428新增: # A word too many is refused: `set TOKEN my secret` would store "my".
429新增: local max=2
430新增: case "$action" in
431新增: set) max=3 ;;
432新增: list) max=1 ;;
433新增: esac
434新增: if [[ $# -gt $max ]]; then
435新增: echo "Error: too many arguments for 'agent-vm $verb $action'. Quote a value with spaces." >&2
436新增: echo "Usage: agent-vm $verb {set KEY [VALUE]|get KEY|has KEY|unset KEY|list}" >&2
437新增: return 1
438新增: fi
439新增: # Without VALUE, `set` reads it from stdin, typed without echo on a
440新增: # terminal: a value on the command line lands in the shell history and in
441新增: # `ps`. From a pipe, one trailing newline goes, as `echo` adds it.
442新增: local set_value=""
443新增: if [[ "$action" == set ]]; then
444新增: if [[ $# -ge 3 ]]; then
445新增: set_value="$3"
446新增: elif [[ -t 0 ]]; then
447新增: printf 'Value for %s (not shown): ' "$key" >&2
448新增: IFS= read -rs set_value || set_value=""
449新增: printf '\n' >&2
450新增: else
451新增: set_value="$(cat; printf x)"
452新增: set_value="${set_value%x}"
453新增: set_value="${set_value%$'\n'}"
454新增: fi
455新增: if [[ $# -lt 3 && -z "$set_value" ]]; then
456新增: echo "Error: 'agent-vm $verb set $key' needs a VALUE, as an argument or on stdin." >&2
457新增: return 1
458新增: fi
459新增: fi
460新增:
461新增: # The x keeps the file's trailing newlines, which $(...) would strip.
462新增: local content have=1 st=0
463新增: content="$(_agent_vm_env_file read "$file" "$top" && printf x)" || st=$?
464新增: content="${content%x}"
465新增: case "$st" in
466新增: 0) ;;
467新增: 1) have="" ;;
468新增: 3)
469新增: echo "Error: $file is a symlink, is reached through one, or is not a regular file." >&2
470新增: echo " agent-vm follows no link in the project, which the VM can write. Replace it with a plain file." >&2
471新增: return 2 ;;
472新增: *)
473新增: echo "Error: could not read $file" >&2
474新增: return 2 ;;
475新增: esac
476新增:
477新增: case "$action" in
478新增: set|unset)
479新增: [[ "$action" == unset && -z "$have" ]] && return 0
480新增: local new
481新增: new="$(printf '%s' "$content" | _agent_vm_env_lines drop - "$key" && printf x)" || {
482新增: echo "Error: could not read $file" >&2
483新增: return 1
484新增: }
485新增: new="${new%x}"
486新增: if [[ "$action" == set ]]; then
487新增: new="$new$(printf "%s='%s'" "$key" "$(_agent_vm_sq_escape "$set_value")")"$'\n'
488新增: fi
489新增: # A silently-dropped write here means the caller is told the secret was
490新增: # stored when it was not, the worst possible failure for this file.
491新增: if ! printf '%s' "$new" | _agent_vm_env_file write "$file" "$top"; then
492新增: echo "Error: could not write $file" >&2
493新增: return 1
494新增: fi
495新增: ;;
496新增: get|has)
497新增: [[ -n "$have" ]] || return 1
498新增: # Read, never source. The project file sits in a directory the VM can
499新增: # write to, and sourcing it here would run whatever the agent put in it
500新增: # on the host. Only the forms `set` writes and plain dotenv lines are
501新增: # accepted; anything the shell would expand is refused, not evaluated.
502新增: local value rc=0
503新增: value="$(printf '%s' "$content" | _agent_vm_env_read - "$key")" || rc=$?
504新增: case "$rc" in
505新增: 0) ;;
506新增: 1) return 1 ;;
507新增: *)
508新增: echo "Error: $key in $file uses, or comes after, shell syntax agent-vm does not evaluate" >&2
509新增: echo " (\$, backquotes, backslashes, ~, ;, | ...). Rewrite it with 'agent-vm $verb set'." >&2
510新增: return 2 ;;
511新增: esac
512新增: [[ "$action" == "has" ]] && return 0
513新增: printf '%s\n' "$value"
514新增: ;;
515新增: list)
516新增: [[ -n "$have" ]] || return 0
517新增: # Names only, never values: safe to paste into an issue.
518新增: printf '%s' "$content" | _agent_vm_env_lines list - | awk '!seen[$0]++'
519新增: ;;
520新增: esac
521新增:}
新增lib/git.sh+662 −0看文件
@@ -0,0 +1,662 @@
1新增:# --- .git protection ------------------------------------------------------------
2新增:# Git on the host runs what a repository's .git/config and hooks name
3新增:# (core.fsmonitor on every `git status`, hooks on commit), and editors and
4新增:# shell prompts run git on their own. A VM able to write a .git in a shared
5新增:# folder could therefore run commands on the host.
6新增:#
7新增:# Lima's `sshfs.readonlyNames` makes every path with a `.git` component
8新增:# read-only for the guest, at any depth, while the rest of the share stays
9新增:# writable. Lima's builtin SFTP server enforces it on the host, so root in the
10新增:# guest cannot lift it. It needs mountType reverse-sshfs and the builtin driver
11新增:# on every mount.
12新增:#
13新增:# Upstream Lima does not have it yet (lima-vm/lima#5529). Until it does, a
14新增:# Lima build that has it: the Homebrew formula, or the tag it is built from.
15新增:AGENT_VM_LIMA_FORMULA="sylvinus/tap/lima-sylvinus"
16新增:AGENT_VM_LIMA_FORK_TAG="v2.3.0-sylvinus.2"
17新增:# The Windows zips of that tag, in SHA256SUMS format. The download is checked
18新增:# against these, not against the SHA256SUMS of the release, which whoever can
19新增:# replace the zips can replace too. Updated with the tag.
20新增:AGENT_VM_LIMA_FORK_SHA256="053f3479b397628b79fe46b0268a50a7f1fc51073691d7d8bce78c9be2ae2787 lima-2.3.0-sylvinus.2-Windows-AMD64.zip
21新增:a0828aa4518e21c9519d341be9f32adf07cbeb74a3f8beadaa2f350c45b5933b lima-additional-guestagents-2.3.0-sylvinus.2-Windows-AMD64.zip
22新增:1cb2d94a9a5f38b2f38f9c14715d850a861a9623b9a7f7ae7b0f6431b75aaa81 lima-2.3.0-sylvinus.2-Windows-ARM64.zip
23新增:1ae0b7b054191f4197898bd59697ee99350d3b7e95b895c1b0ec061c7ea87e7f lima-additional-guestagents-2.3.0-sylvinus.2-Windows-ARM64.zip"
24新增:AGENT_VM_LIMA_ISSUE="https://github.com/lima-vm/lima/issues/5529"
25新增:
26新增:# Does this Lima enforce sshfs.readonlyNames? 0 yes, 1 no, 2 cannot tell.
27新增:# Stock Lima accepts the field and ignores it, with a mere warning, so support
28新增:# is probed, never assumed: `limactl validate` on a config pairing it with
29新增:# virtiofs, which a Lima that knows the field rejects, naming it. One that
30新增:# does not know it warns about an "unknown field". Any other answer (no
31新增:# limactl, a failure that names neither, a Lima that accepts the file without
32新增:# a word) is "cannot tell", never "no": callers must not drop the protection
33新增:# of a VM on an answer they could not read.
34新增:#
35新增:# Not cached: agent-vm is also a shell function, where a cached answer would
36新增:# outlive a Lima upgrade.
37新增:_agent_vm_lima_protects_git() {
38新增: local dir out accepted=""
39新增: dir="$(mktemp -d 2>/dev/null)" || return 2
40新增: printf 'images: [{location: "/"}]\nmountType: virtiofs\nmounts: [{location: "%s", sshfs: {sftpDriver: builtin, readonlyNames: [.git]}}]\n' \
41新增: "$(_agent_vm_host_path "$dir")" > "$dir/probe.yaml"
42新增: out="$(limactl validate "$(_agent_vm_host_path "$dir/probe.yaml")" 2>&1)" && accepted=1
43新增: rm -rf "$dir"
44新增: if [[ "$out" == *"unknown field"* && "$out" == *readonlyNames* ]]; then
45新增: return 1
46新增: elif [[ -z "$accepted" && "$out" == *readonlyNames* ]]; then
47新增: return 0
48新增: fi
49新增: return 2
50新增:}
51新增:
52新增:# The `limactl edit --set` expression applying a mounts JSON, and the mount
53新增:# type that goes with it. With every .git read-only ($2 = 1): reverse-sshfs,
54新增:# which readonlyNames needs. Without: Lima's default, and not a reverse-sshfs
55新增:# left over from a Lima that had readonlyNames: on a Lima without it, a
56新增:# compromised guest can reach host paths outside the shares through the SFTP
57新增:# server (Lima's mount documentation says so for both drivers).
58新增:_agent_vm_mounts_expr() {
59新增: if [[ "${2:-}" == 1 ]]; then
60新增: printf '.mountType = "reverse-sshfs" | .mounts = %s' "$1"
61新增: else
62新增: printf 'del(.mountType) | .mounts = %s' "$1"
63新增: fi
64新增:}
65新增:
66新增:# The names readonlyNames always lists, one per line. .hg: Mercurial runs the
67新增:# hooks of .hg/hgrc in a repository the user owns, which files written through
68新增:# a share are.
69新增:_agent_vm_base_readonly_names() {
70新增: printf '%s\n' .git .hg
71新增:}
72新增:
73新增:# 0 when the relative path <rel> goes through one of the names above, matched
74新增:# as the SFTP server does: per component, whatever the case.
75新增:_agent_vm_under_readonly_name() {
76新增: local rest="$1/" c names
77新增: names=$'\n'"$(_agent_vm_base_readonly_names)"$'\n'
78新增: while [[ -n "$rest" ]]; do
79新增: c="$(printf '%s' "${rest%%/*}" | tr '[:upper:]' '[:lower:]')"
80新增: rest="${rest#*/}"
81新增: [[ "$names" == *$'\n'"$c"$'\n'* ]] && return 0
82新增: done
83新增: return 1
84新增:}
85新增:
86新增:# 0 on the hosts whose file systems ignore case by default: macOS, Windows.
87新增:_agent_vm_fs_nocase() {
88新增: [[ "$(uname -s 2>/dev/null)" == Darwin ]] || _agent_vm_on_windows
89新增:}
90新增:
91新增:# <s> lowercased on those hosts, as is elsewhere: paths compared as the file
92新增:# system does.
93新增:_agent_vm_fold() {
94新增: if _agent_vm_fs_nocase; then
95新增: printf '%s\n' "$1" | tr '[:upper:]' '[:lower:]'
96新增: else
97新增: printf '%s\n' "$1"
98新增: fi
99新增:}
100新增:
101新增:# <path> relative to <dir>, "." for <dir> itself; fails when it is not inside.
102新增:# Compared whatever the case where the file system ignores it, so a path
103新增:# spelled with other capitals is still found inside.
104新增:_agent_vm_rel_in() {
105新增: local target="${1%/}" dir="${2%/}" p d
106新增: p="$(_agent_vm_fold "$target")"
107新增: d="$(_agent_vm_fold "$dir")"
108新增: if [[ "$p" == "$d" ]]; then
109新增: printf '.\n'
110新增: return 0
111新增: fi
112新增: [[ -n "$d" && "$p" == "$d/"* ]] || return 1
113新增: printf '%s\n' "${target:$(( ${#dir} + 1 ))}"
114新增:}
115新增:
116新增:# <dir> as git spells it: the physical path, C:/... on Windows.
117新增:_agent_vm_git_spelling() {
118新增: local p
119新增: p="$(CDPATH= cd -P -- "$1" 2>/dev/null && pwd)" || return 1
120新增: _agent_vm_host_path "$p"
121新增:}
122新增:
123新增:# <path> made absolute against <base> (both in git's spelling), `.` and `..`
124新增:# resolved in the text.
125新增:_agent_vm_git_abs() {
126新增: case "$1" in
127新增: /*) _agent_vm_path_join / "$1" ;;
128新增: [A-Za-z]:/*) _agent_vm_path_join "${1%%/*}" "${1#*/}" ;;
129新增: *) _agent_vm_path_join "$2" "$1" ;;
130新增: esac
131新增:}
132新增:
133新增:# The git repositories git on this machine uses in the project <dir>: the one
134新增:# holding <dir>, then those up to two levels below it (node_modules skipped),
135新增:# fifty at most. One directory per line, to run git in.
136新增:_agent_vm_project_repos() {
137新增: local dir="$1"
138新增: command -v git >/dev/null 2>&1 || return 0
139新增: _agent_vm_git_untrusted -C "$dir" rev-parse --git-dir >/dev/null 2>&1 && printf '%s\n' "$dir"
140新增: find "$dir" -mindepth 2 -maxdepth 3 \( -name node_modules -prune \) -o \( -name .git -print -prune \) 2>/dev/null \
141新增: | awk 'NR <= 50' | while IFS= read -r g; do
142新增: printf '%s\n' "${g%/.git}"
143新增: done
144新增:}
145新增:
146新增:# The folder git on the host runs the hooks of the repository at <repo> from,
147新增:# when core.hooksPath puts it in the project <proj> (in git's spelling) and
148新增:# outside the names above (husky sets .husky/_). Two fields, tab-separated:
149新增:# the folder relative to the project, "." for the project itself, then
150新增:# relative to the top of the repository when that is in the project (what
151新增:# names it: lib/x/.githooks is .githooks), or the same again. Fails otherwise,
152新增:# or when git cannot tell. `--git-path` without --path-format (git 2.31)
153新增:# answers relative to <repo>.
154新增:_agent_vm_repo_hooks() {
155新增: local repo="$1" proj="$2" base top top_rel hooks rel in_repo
156新增: base="$(_agent_vm_git_spelling "$repo")" || return 1
157新增: hooks="$(_agent_vm_git_untrusted -C "$repo" rev-parse --git-path hooks 2>/dev/null)" || return 1
158新增: [[ -n "$hooks" && "$hooks" != *$'\n'* && "$hooks" != *$'\t'* ]] || return 1
159新增: hooks="$(_agent_vm_git_abs "$hooks" "$base")"
160新增: rel="$(_agent_vm_rel_in "$hooks" "$proj")" || return 1
161新增: [[ "$rel" == . ]] || ! _agent_vm_under_readonly_name "$rel" || return 1
162新增: in_repo="$rel"
163新增: if top="$(_agent_vm_git_untrusted -C "$repo" rev-parse --show-toplevel 2>/dev/null)" \
164新增: && top_rel="$(_agent_vm_rel_in "$top" "$proj")" && [[ "$top_rel" != . ]]; then
165新增: in_repo="$(_agent_vm_rel_in "$hooks" "$top")" || in_repo="$rel"
166新增: fi
167新增: printf '%s\t%s\n' "$rel" "$in_repo"
168新增:}
169新增:
170新增:# Every hooks folder of the project <dir>'s repositories that is in the
171新增:# project and outside the names above (see _agent_vm_repo_hooks), one per
172新增:# line, with its two fields.
173新增:_agent_vm_project_hooks() {
174新增: local dir="$1" proj repo
175新增: proj="$(_agent_vm_git_spelling "$dir")" || return 0
176新增: _agent_vm_project_repos "$dir" | while IFS= read -r repo; do
177新增: _agent_vm_repo_hooks "$repo" "$proj"
178新增: done | awk '!seen[$0]++'
179新增:}
180新增:
181新增:# The name that keeps the hooks folder <rel> read-only: its first component,
182新增:# which covers the folder and whatever it calls next to it (husky's hooks call
183新增:# .husky/<hook>). Fails for the project itself, and for a name the mounts JSON
184新增:# cannot carry.
185新增:_agent_vm_hooks_name() {
186新增: local name="${1%%/*}"
187新增: [[ "$1" != . && -n "$name" && "$name" != *[\"\\]* && "$name" != *[[:cntrl:]]* ]] || return 1
188新增: printf '%s\n' "$name"
189新增:}
190新增:
191新增:# The readonlyNames JSON array: the names always listed, then "$@", each once.
192新增:_agent_vm_names_json() {
193新增: local n out="" seen=$'\n'
194新增: for n in $(_agent_vm_base_readonly_names) "$@"; do
195新增: [[ "$seen" == *$'\n'"$n"$'\n'* ]] && continue
196新增: seen="$seen$n"$'\n'
197新增: out="${out:+$out, }\"$n\""
198新增: done
199新增: printf '[%s]\n' "$out"
200新增:}
201新增:
202新增:# The readonlyNames JSON array a start gives the project <dir> unless the user
203新增:# declines a name: the names always listed, and those keeping its hooks
204新增:# folders read-only.
205新增:_agent_vm_readonly_names() {
206新增: local rel in_repo name names=()
207新增: while IFS=$'\t' read -r rel in_repo; do
208新增: [[ -n "$rel" ]] || continue
209新增: name="$(_agent_vm_hooks_name "$in_repo")" && names+=("$name")
210新增: done <<< "$(_agent_vm_project_hooks "$1")"
211新增: _agent_vm_names_json ${names[@]+"${names[@]}"}
212新增:}
213新增:
214新增:# A readonlyNames JSON array as text: [".git", ".hg"] is ".git, .hg".
215新增:_agent_vm_names_text() {
216新增: local s="${1#\[}"
217新增: s="${s%\]}"
218新增: printf '%s\n' "${s//\"/}"
219新增:}
220新增:
221新增:_agent_vm_hooks_note() {
222新增: echo "Note: git runs hooks from $1 (core.hooksPath): every '$2' in the project is read-only for the VM too."
223新增:}
224新增:
225新增:# What git on this machine takes from files the VM can write, for the
226新增:# repository at <repo> in the project <proj> (git's spelling), one line each:
227新增:# a config file included from the project (whether it exists yet or not),
228新增:# and a setting whose command names
229新增:# a file in the project. The protected names are excepted, and core.hooksPath,
230新增:# which _agent_vm_repo_hooks covers. A relative path in a command is taken
231新增:# from the top of the repository, where git runs most of them.
232新增:#
233新增:# awk sorts the config first, so the shell only sees each file once and the
234新增:# settings that hold a command (section and key names lowercased, as
235新增:# `git config --list` prints them) with a path in their value: a start runs
236新增:# this, and a fork per line would show.
237新增:_agent_vm_repo_config_risks() {
238新增: local repo="$1" proj="$2" base top kind a b w rel
239新增: base="$(_agent_vm_git_spelling "$repo")" || return 0
240新增: top="$(_agent_vm_git_untrusted -C "$repo" rev-parse --show-toplevel 2>/dev/null)" || return 0
241新增: _agent_vm_git_untrusted -C "$repo" config --list --show-origin --includes 2>/dev/null \
242新增: | awk -F '\t' '
243新增: {
244新增: origin = $1; kv = substr($0, length($1) + 2)
245新增: if (origin ~ /^file:/ && !(origin in seen)) {
246新增: seen[origin] = 1; f = substr(origin, 6); gsub(/^"|"$/, "", f); print "O\t" f
247新增: }
248新增: key = kv; sub(/=.*/, "", key); val = substr(kv, length(key) + 2); lk = tolower(key)
249新增: if (lk == "include.path" || lk ~ /^includeif\..*\.path$/) {
250新增: if (origin ~ /^file:/) { f = substr(origin, 6); gsub(/^"|"$/, "", f); print "I\t" f "\t" val }
251新增: next
252新增: }
253新增: if (lk !~ /^(core\.(fsmonitor|sshcommand|editor|pager|askpass|gitproxy|alternaterefscommand)|sequence\.editor|gpg\.program|gpg\..*\.program|diff\.external|diff\..*\.(command|textconv)|(difftool|mergetool|browser|man)\..*\.cmd|merge\..*\.driver|filter\..*\.(clean|smudge|process)|credential\.helper|credential\..*\.helper|pager\..*|alias\..*|interactive\.difffilter|uploadpack\.packobjectshook|web\.browser)$/) next
254新增: if (lk ~ /^alias\./ && val !~ /^!/) next
255新增: if (val ~ /\//) print "K\t" key "\t" val
256新增: }' \
257新增: | while IFS=$'\t' read -r kind a b; do
258新增: if [[ "$kind" == O ]]; then
259新增: rel="$(_agent_vm_rel_in "$(_agent_vm_git_abs "$a" "$base")" "$proj")" \
260新增: && ! _agent_vm_under_readonly_name "$rel" \
261新增: && printf 'config file %s\n' "$rel"
262新增: continue
263新增: fi
264新增: # An include, by its value: git skips a file that does not exist, so
265新增: # --includes does not list it, and the VM can create it once the VM
266新增: # runs. Relative to the file holding it, as git takes it.
267新增: if [[ "$kind" == I ]]; then
268新增: [[ "$b" == "~/"* ]] && b="$HOME/${b#\~/}"
269新增: a="$(_agent_vm_git_abs "$a" "$base")"
270新增: rel="$(_agent_vm_rel_in "$(_agent_vm_git_abs "$b" "${a%/*}")" "$proj")" \
271新增: && ! _agent_vm_under_readonly_name "$rel" \
272新增: && printf 'config file %s\n' "$rel"
273新增: continue
274新增: fi
275新增: # Word by word, through awk: an unquoted expansion would glob them.
276新增: printf '%s\n' "${b#!}" | awk '{ for (i = 1; i <= NF; i++) print $i }' \
277新增: | while IFS= read -r w; do
278新增: w="${w#[\"\']}"; w="${w%[\"\']}"
279新增: # Not an option, an assignment or a URL: a path.
280新增: [[ "$w" == */* && "$w" != -* && "$w" != *=* && "$w" != *://* ]] || continue
281新增: [[ "$w" == "~/"* ]] && w="$HOME/${w#\~/}"
282新增: rel="$(_agent_vm_rel_in "$(_agent_vm_git_abs "$w" "$top")" "$proj")" || continue
283新增: _agent_vm_under_readonly_name "$rel" && continue
284新增: printf '%s = %s\n' "$a" "$b"
285新增: break
286新增: done
287新增: done
288新增:}
289新增:
290新增:# The same for every repository of the project <dir>, each line once.
291新增:_agent_vm_project_config_risks() {
292新增: local dir="$1" proj repo
293新增: proj="$(_agent_vm_git_spelling "$dir")" || return 0
294新增: _agent_vm_project_repos "$dir" | while IFS= read -r repo; do
295新增: _agent_vm_repo_config_risks "$repo" "$proj"
296新增: done | awk '!seen[$0]++'
297新增:}
298新增:
299新增:# What a Lima without readonlyNames exposes when the shares are reverse-sshfs
300新增:# (see _agent_vm_unprotected_mount_is_sshfs), one paragraph, before
301新增:# _agent_vm_git_protection_hint.
302新增:_agent_vm_sshfs_exposure_note() {
303新增: echo "Here the shares then use Lima's reverse-sshfs, which this Lima does not confine: root in the VM may reach files outside the shares (Lima's mount documentation says so), your SSH keys and the rest of your disk included, and write the read-only volumes."
304新增: echo ""
305新增:}
306新增:
307新增:# Why .git is not protected, and how to install a Lima that does it, on stdout.
308新增:# With Homebrew (macOS, or Linux): the formula, which conflicts with brew's own
309新增:# lima, hence the unlink. On Windows: the fork's release zips, which `setup`
310新增:# offers to download. Without either: a build from source, as the formula
311新增:# does it. One paragraph per line: _agent_vm_wrap and _agent_vm_box fit it to
312新增:# the screen.
313新增:_agent_vm_git_protection_hint() {
314新增: cat <<EOF
315新增:An agent could write .git/config or .git/hooks in your projects, and git on this machine would run them, even when your editor or shell prompt calls git.
316新增:
317新增:A Lima build with sshfs.readonlyNames prevents it, until upstream merges it ($AGENT_VM_LIMA_ISSUE):
318新增:EOF
319新增: if _agent_vm_on_windows; then
320新增: echo " agent-vm setup offers the download, or get it by hand:"
321新增: echo " $(_agent_vm_lima_fork_release) (both Windows zips, verified, on PATH)"
322新增: elif command -v brew >/dev/null 2>&1; then
323新增: echo " brew unlink lima 2>/dev/null; brew install $AGENT_VM_LIMA_FORMULA"
324新增: else
325新增: echo " git clone --depth 1 -b $AGENT_VM_LIMA_FORK_TAG https://github.com/sylvinus/lima"
326新增: echo " cd lima && make native && sudo make install # needs Go and make"
327新增: fi
328新增:}
329新增:
330新增:# The URL of the fork release holding the Windows builds.
331新增:_agent_vm_lima_fork_release() {
332新增: printf 'https://github.com/sylvinus/lima/releases/download/%s\n' "$AGENT_VM_LIMA_FORK_TAG"
333新增:}
334新增:
335新增:# Windows architecture as the asset names spell it (AMD64/ARM64), from uname.
336新增:_agent_vm_lima_fork_arch() {
337新增: case "$(uname -m 2>/dev/null)" in
338新增: x86_64) printf 'AMD64\n' ;;
339新增: aarch64|arm64) printf 'ARM64\n' ;;
340新增: *)
341新增: echo "Error: no Lima fork build for this architecture: $(uname -m 2>/dev/null)" >&2
342新增: return 1 ;;
343新增: esac
344新增:}
345新增:
346新增:# The fork release's files for this machine, one per line: both zips, named
347新增:# as upstream's `make artifacts-windows` does,
348新增:# lima-<tag without v>-Windows-<ARCH>.zip.
349新增:_agent_vm_lima_fork_files() {
350新增: local arch tag
351新增: arch="$(_agent_vm_lima_fork_arch)" || return 1
352新增: tag="${AGENT_VM_LIMA_FORK_TAG#v}"
353新增: printf 'lima-%s-Windows-%s.zip\n' "$tag" "$arch"
354新增: printf 'lima-additional-guestagents-%s-Windows-%s.zip\n' "$tag" "$arch"
355新增:}
356新增:
357新增:# Every file named in "$@" inside <dir> must match its entry in <sums>, text
358新增:# in SHA256SUMS format. Fails closed (an unlisted file, a checksum that cannot
359新增:# be computed, a mismatch) naming the culprit, so a half-downloaded Lima never
360新增:# lands on PATH.
361新增:_agent_vm_sha256_sums_check() {
362新增: local sums="$1" dir="$2" f expected actual
363新增: shift 2
364新增: for f in "$@"; do
365新增: # A leading * marks binary mode (`sha256sum -b`, and Git Bash's default).
366新增: expected="$(printf '%s\n' "$sums" | awk -v f="$f" '{ n = $2; sub(/^\*/, "", n) } n == f { print $1; exit }')"
367新增: if [[ -z "$expected" ]]; then
368新增: echo "Error: no checksum listed for $f." >&2
369新增: return 1
370新增: fi
371新增: actual="$(_agent_vm_sha256 < "$dir/$f" 2>/dev/null | cut -d' ' -f1)"
372新增: if [[ -z "$actual" || "$actual" != "$expected" ]]; then
373新增: echo "Error: checksum mismatch for $f (expected $expected, got ${actual:-unreadable})." >&2
374新增: return 1
375新增: fi
376新增: done
377新增:}
378新增:
379新增:# Download and install the fork's Windows build: both zips, verified against
380新增:# AGENT_VM_LIMA_FORK_SHA256, then unpacked into a staging dir next to AGENT_VM_LIMA_DIR
381新增:# (default ~/.local/share/lima-sylvinus), which takes its place only once
382新增:# complete. A failed run leaves the previous install, or none, as it was.
383新增:#
384新增:# An install of AGENT_VM_LIMA_FORK_TAG is reused. One of another tag (or
385新增:# unmarked) is replaced, in the same directory, so the PATH line the user
386新增:# already has keeps working. Windows cannot move a directory whose limactl.exe
387新增:# is running, which is the case while a VM runs: that is said, and the old
388新增:# install stays.
389新增:#
390新增:# The bin dir goes on PATH for the rest of this shell when it is not there
391新增:# already, with the line making it permanent printed alongside: setup needs
392新增:# limactl immediately, and the user needs it in the next terminal.
393新增:_agent_vm_install_fork_windows() {
394新增: local base dir tmp f bin="" stage old=""
395新增: base="$(_agent_vm_lima_fork_release)"
396新增: dir="${AGENT_VM_LIMA_DIR:-$HOME/.local/share/lima-sylvinus}"
397新增: if [[ -x "$dir/bin/limactl.exe" \
398新增: && "$(cat "$dir/.agent-vm-lima-tag" 2>/dev/null)" == "$AGENT_VM_LIMA_FORK_TAG" ]]; then
399新增: bin="$dir/bin"
400新增: echo "Lima $AGENT_VM_LIMA_FORK_TAG is already installed at $bin."
401新增: else
402新增: if [[ -e "$dir" && ! -x "$dir/bin/limactl.exe" ]]; then
403新增: echo "Error: $dir exists and is not a Lima install: move it, or set AGENT_VM_LIMA_DIR." >&2
404新增: return 1
405新增: fi
406新增: command -v curl >/dev/null 2>&1 \
407新增: || { echo "Error: curl is required to download Lima." >&2; return 1; }
408新增: local files
409新增: files="$(_agent_vm_lima_fork_files)" || return 1
410新增: mkdir -p "$(dirname "$dir")" || return 1
411新增: tmp="$(mktemp -d 2>/dev/null)" || return 1
412新增: # The || keeps the last line: command substitution strips its newline.
413新增: while IFS= read -r f || [[ -n "$f" ]]; do
414新增: [[ -n "$f" ]] || continue
415新增: echo "Downloading $f..."
416新增: if ! curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fsSL --retry 3 \
417新增: -o "$tmp/$f" "$base/$f"; then
418新增: echo "Error: could not download $base/$f." >&2
419新增: rm -rf "$tmp"
420新增: return 1
421新增: fi
422新增: if ! _agent_vm_sha256_sums_check "$AGENT_VM_LIMA_FORK_SHA256" "$tmp" "$f"; then
423新增: rm -rf "$tmp"
424新增: return 1
425新增: fi
426新增: done <<< "$files"
427新增: stage="$dir.new.$$"
428新增: rm -rf "$stage"
429新增: mkdir -p "$stage" || { rm -rf "$tmp"; return 1; }
430新增: while IFS= read -r f || [[ -n "$f" ]]; do
431新增: [[ -n "$f" ]] || continue
432新增: if command -v unzip >/dev/null 2>&1; then
433新增: unzip -q -o "$tmp/$f" -d "$stage" || { echo "Error: could not unpack $f." >&2; rm -rf "$tmp" "$stage"; return 1; }
434新增: elif tar -tf "$tmp/$f" >/dev/null 2>&1; then
435新增: tar -xf "$tmp/$f" -C "$stage" || { echo "Error: could not unpack $f." >&2; rm -rf "$tmp" "$stage"; return 1; }
436新增: else
437新增: echo "Error: neither unzip nor tar can unpack $f." >&2
438新增: rm -rf "$tmp" "$stage"
439新增: return 1
440新增: fi
441新增: done <<< "$files"
442新增: rm -rf "$tmp"
443新增: if [[ ! -x "$stage/bin/limactl.exe" ]]; then
444新增: echo "Error: the download unpacked without bin/limactl.exe; nothing was installed." >&2
445新增: rm -rf "$stage"
446新增: return 1
447新增: fi
448新增: printf '%s\n' "$AGENT_VM_LIMA_FORK_TAG" > "$stage/.agent-vm-lima-tag"
449新增: if [[ -e "$dir" ]]; then
450新增: old="$dir.old.$$"
451新增: if ! mv "$dir" "$old" 2>/dev/null; then
452新增: echo "Error: could not replace the Lima install in $dir: stop the running VMs ('agent-vm list'), then retry." >&2
453新增: rm -rf "$stage"
454新增: return 1
455新增: fi
456新增: fi
457新增: if ! mv "$stage" "$dir"; then
458新增: [[ -n "$old" ]] && mv "$old" "$dir"
459新增: rm -rf "$stage"
460新增: return 1
461新增: fi
462新增: [[ -n "$old" ]] && rm -rf "$old"
463新增: bin="$dir/bin"
464新增: echo "Lima $AGENT_VM_LIMA_FORK_TAG is installed at $bin."
465新增: fi
466新增: case ":$PATH:" in
467新增: *":$bin:"*) ;;
468新增: *)
469新增: export PATH="$bin:$PATH"
470新增: echo "Added $bin to PATH for this shell. To keep it, add this line to ~/.bash_profile:"
471新增: printf ' export PATH="%s:$PATH"\n' "$bin" ;;
472新增: esac
473新增:}
474新增:
475新增:# On Windows, when the Lima that _agent_vm_install_fork_windows put in place
476新增:# is of another tag than AGENT_VM_LIMA_FORK_TAG, offer to replace it. Never
477新增:# fails setup: the installed one keeps working.
478新增:_agent_vm_offer_fork_windows_update() {
479新增: _agent_vm_on_windows || return 0
480新增: local dir="${AGENT_VM_LIMA_DIR:-$HOME/.local/share/lima-sylvinus}" have
481新增: [[ -x "$dir/bin/limactl.exe" ]] || return 0
482新增: have="$(cat "$dir/.agent-vm-lima-tag" 2>/dev/null)"
483新增: [[ "$have" != "$AGENT_VM_LIMA_FORK_TAG" ]] || return 0
484新增: _agent_vm_have_tty || { echo "Note: Lima ${have:-(unknown version)} in $dir; 'agent-vm setup' in a terminal offers $AGENT_VM_LIMA_FORK_TAG." >&2; return 0; }
485新增: [[ "$(_agent_vm_ask_yn "Update the Lima in $dir from ${have:-an unknown version} to $AGENT_VM_LIMA_FORK_TAG?" Y)" == "1" ]] || return 0
486新增: _agent_vm_install_fork_windows || echo "Warning: the update failed; the installed Lima stays." >&2
487新增: hash -r 2>/dev/null
488新增: return 0
489新增:}
490新增:
491新增:# AGENT_VM_UNSAFE_WRITABLE_GIT=1, or --unsafe-writable-git for one command,
492新增:# turns the protection off, for those who let the agent commit in the shared
493新增:# project. Only the host can ask for it: a setting in a file of the project
494新增:# would be one the VM can write. _agent_vm_ensure_running sets
495新增:# _agent_vm_unsafe_git_flag, as a local, for the flag.
496新增:_agent_vm_writable_git_optout() {
497新增: [[ "${AGENT_VM_UNSAFE_WRITABLE_GIT:-}" == 1 || -n "${_agent_vm_unsafe_git_flag:-}" ]]
498新增:}
499新增:
500新增:# What turned it off, to name it back to the user.
501新增:_agent_vm_writable_git_why() {
502新增: if [[ -n "${_agent_vm_unsafe_git_flag:-}" ]]; then
503新增: printf '%s\n' "--unsafe-writable-git"
504新增: else
505新增: printf '%s\n' "AGENT_VM_UNSAFE_WRITABLE_GIT=1"
506新增: fi
507新增:}
508新增:
509新增:_agent_vm_writable_git_warning() {
510新增: cat <<EOF
511新增:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
512新增:!! WARNING: $(_agent_vm_writable_git_why). The VM can write every .git.
513新增:!!
514新增:!! The agent can change .git/config and .git/hooks in the shared folders, and
515新增:!! git on this machine runs what they name: on your next commit, and whenever
516新增:!! your editor or shell prompt calls git. That is running commands on your
517新增:!! host, outside the VM. Without it, .git stays read-only.
518新增:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
519新增:EOF
520新增:}
521新增:
522新增:# --- setup: a Lima that keeps .git read-only ------------------------------------
523新增:# Run by `setup` once Lima is there, and by nothing else: nothing to do when it
524新增:# already protects .git. Otherwise it says why that matters and, with a
525新增:# terminal to ask on, offers to install the build that has it: the formula
526新增:# with Homebrew, the release zips on Windows.
527新增:#
528新增:# brew refuses the formula next to its own lima (both install limactl) and asks
529新增:# for that one to be unlinked. Unlinking keeps it installed, so
530新增:# `brew uninstall lima-sylvinus && brew link lima` goes back. VMs are not
531新增:# touched either way. This never fails setup: the VMs work without it.
532新增:_agent_vm_offer_git_protection() {
533新增: _agent_vm_offer_fork_windows_update
534新增: local st=0
535新增: _agent_vm_lima_protects_git || st=$?
536新增: [[ "$st" == 0 ]] && return 0
537新增: if [[ "$st" == 2 ]]; then
538新增: echo "Warning: cannot tell whether this Lima keeps .git read-only: 'limactl validate' gave no answer agent-vm knows. A start with writable shares stops until it can tell ('agent-vm doctor')." >&2
539新增: return 0
540新增: fi
541新增: _agent_vm_git_protection_hint | _agent_vm_box "Lima cannot keep .git read-only"
542新增: local without="Continuing without .git protection: every start with writable shares will ask first." unlinked=""
543新增: if _agent_vm_on_windows; then
544新增: if ! _agent_vm_have_tty \
545新增: || [[ "$(_agent_vm_ask_yn "Download the Lima build that has it now (both Windows zips, about 60 MB)?" Y)" != "1" ]]; then
546新增: echo "$without" >&2
547新增: return 0
548新增: fi
549新增: if ! _agent_vm_install_fork_windows; then
550新增: echo "Warning: the download failed. $without" >&2
551新增: return 0
552新增: fi
553新增: else
554新增: if ! command -v brew >/dev/null 2>&1 || ! _agent_vm_have_tty \
555新增: || [[ "$(_agent_vm_ask_yn "Install $AGENT_VM_LIMA_FORMULA now (built from source, takes a few minutes)?" Y)" != "1" ]]; then
556新增: echo "$without" >&2
557新增: return 0
558新增: fi
559新增: if brew list --formula lima >/dev/null 2>&1; then
560新增: brew unlink lima && unlinked=1
561新增: fi
562新增: if ! brew install "$AGENT_VM_LIMA_FORMULA"; then
563新增: # Unlinked and nothing in its place would leave no limactl at all.
564新增: [[ -n "$unlinked" ]] && brew link lima
565新增: echo "Warning: the install failed. $without" >&2
566新增: return 0
567新增: fi
568新增: fi
569新增: hash -r 2>/dev/null
570新增: if _agent_vm_lima_protects_git; then
571新增: echo "Lima now keeps every .git read-only for the VMs."
572新增: else
573新增: echo "Warning: the limactl on PATH ($(_agent_vm_limactl_path)) still cannot keep .git read-only." >&2
574新增: echo " Another Lima install comes first on PATH. $without" >&2
575新增: fi
576新增: return 0
577新增:}
578新增:
579新增:# --- git on this machine: repositories not named .git ---------------------------
580新增:# readonlyNames protects a name, and a bare repository has none: a folder with
581新增:# HEAD, objects/ and refs/ is a repository to git, found by the same upward
582新增:# search from the current directory as a .git. Its config then applies, and
583新增:# some of it names commands git runs: core.pager on `git log`, for one. The VM
584新增:# can create such a folder anywhere in a share. safe.bareRepository=explicit (git 2.38+)
585新增:# makes git use a bare repository only when --git-dir or GIT_DIR names it.
586新增:
587新增:# git, for agent-vm's own calls in a directory the VM can write. The VM may have
588新增:# planted a repository there: a bare one, whatever the user's
589新增:# safe.bareRepository, or a .git where Lima cannot protect it. -c is honoured
590新增:# for safe.bareRepository (command-line config is trusted, a repository's own
591新增:# is not), which refuses the bare one. core.fsmonitor=false stops the command
592新增:# a repository's config names from running on commands that read the index,
593新增:# and --no-pager the one pager.<cmd> and core.pager would start on a terminal.
594新增:_agent_vm_git_untrusted() {
595新增: git --no-pager -c safe.bareRepository=explicit -c core.fsmonitor=false "$@"
596新增:}
597新增:
598新增:# ok, unset, old (git before 2.38, which ignores the setting) or nogit. Read
599新增:# from /, outside any repository: git only honours the setting from the system
600新增:# and global config, so a repository's own config must not answer.
601新增:_agent_vm_bare_repo_state() {
602新增: command -v git >/dev/null 2>&1 || { echo nogit; return 0; }
603新增: local v
604新增: v="$(git --version 2>/dev/null)"
605新增: v="${v#git version }"
606新增: v="${v%% *}"
607新增: if ! _agent_vm_ver_ge "$v" 2.38.0; then
608新增: echo old
609新增: elif [[ "$(cd / && git config --get safe.bareRepository 2>/dev/null)" == "explicit" ]]; then
610新增: echo ok
611新增: else
612新增: echo unset
613新增: fi
614新增:}
615新增:
616新增:# One paragraph per line, as for _agent_vm_git_protection_hint.
617新增:_agent_vm_bare_repo_hint() {
618新增: cat <<'EOF'
619新增:Git treats any folder with HEAD, objects/ and refs/ as a repository, even without .git, and runs commands its config names (on `git log`, for one). A VM could create one in your projects, and the .git protection does not cover it.
620新增:
621新增:This makes git ignore such folders unless named with --git-dir:
622新增: git config --global safe.bareRepository explicit
623新增:EOF
624新增:}
625新增:
626新增:# Run when a VM starts with writable shares. Offers to run the command above,
627新增:# when it can ask. Not set (no answer, a no, a git that ignores it): the
628新增:# security question of _agent_vm_confirm_unsafe, whose default stops the
629新增:# start. Fails when the start must stop. With the questions disabled, nothing
630新增:# is offered either: the global git config is not changed unasked. With $1
631新增:# set, the VM already runs, so a question would protect nothing: a warning
632新增:# only.
633新增:_agent_vm_check_bare_repo_setting() {
634新增: local state
635新增: state="$(_agent_vm_bare_repo_state)"
636新增: case "$state" in
637新增: ok|nogit) return 0 ;;
638新增: esac
639新增: if [[ -n "${1:-}" ]]; then
640新增: echo "Warning: git on this machine uses repositories a VM creates under another name than .git ('agent-vm doctor' says more)." >&2
641新增: return 0
642新增: fi
643新增: _agent_vm_bare_repo_hint | _agent_vm_box "Git: repositories not named .git"
644新增: if [[ "$state" == old ]]; then
645新增: echo "Warning: $(git --version) is older than 2.38 and ignores that setting." >&2
646新增: _agent_vm_confirm_unsafe && return 0
647新增: echo "Aborted. Upgrade git, then run the command above." >&2
648新增: return 1
649新增: fi
650新增: if ! _agent_vm_prompts_disabled_by >/dev/null && _agent_vm_can_ask \
651新增: && [[ "$(_agent_vm_ask_yn "Run it now? It changes your global git config." Y)" == "1" ]]; then
652新增: if git config --global safe.bareRepository explicit && [[ "$(_agent_vm_bare_repo_state)" == "ok" ]]; then
653新增: echo "Git on this machine now ignores repositories not named .git unless you name them."
654新增: return 0
655新增: fi
656新增: echo "Warning: the setting did not take." >&2
657新增: fi
658新增: echo "Warning: not set. Until it is, git on this machine can run what a VM writes." >&2
659新增: _agent_vm_confirm_unsafe && return 0
660新增: echo "Aborted. Run the command above, then run agent-vm again." >&2
661新增: return 1
662新增:}
新增lib/help.sh+174 −0看文件
@@ -0,0 +1,174 @@
1新增:# --- help ---------------------------------------------------------------------
2新增:
3新增:_agent_vm_help() {
4新增: cat << 'EOF'
5新增:Usage: agent-vm [options] <command> [args]
6新增:
7新增:Commands:
8新增: install Put agent-vm on your PATH (a link in ~/.local/bin, or
9新增: AGENT_VM_BIN_DIR). Run it from the clone:
10新增: ./agent-vm.sh install
11新增: uninstall Remove that link. VMs and ~/.agent-vm are left alone.
12新增: setup Create the base VM template (run once)
13新增: claude [args] Run Claude Code in the VM for the current directory
14新增: opencode [args] Run OpenCode in the VM for the current directory
15新增: codex [args] Run Codex CLI in the VM for the current directory
16新增: vibe [args] Run Mistral Vibe in the VM for the current directory
17新增: pi [args] Run Pi in the VM for the current directory (opt-in at
18新增: setup: --preinstall=default,pi)
19新增: shell, sh Open a shell in the VM. Add -c "..." to run a one-shot
20新增: command via login zsh and exit.
21新增: run <cmd> [args] Run a command in the VM (no shell: for pipes/redirects
22新增: use 'shell -c "..."' instead; pass --tty for TUIs like
23新增: opencode, vibe, htop, etc.)
24新增: stop [vm-name] Stop the VM for the current directory, or the named one
25新增: rm [vm-name] Stop and delete the VM for the current directory, or the
26新增: named one. Pass a name from 'agent-vm list' to reach a VM
27新增: whose directory was renamed or deleted: its name is a
28新增: hash of the old path, so no 'cd' can name it any more.
29新增: destroy-all Stop and delete every agent-vm VM, the base template
30新增: included ('agent-vm setup' rebuilds it)
31新增: list, status List all agent-vm VMs, the current directory's marked
32新增: with >, with the agent-vm version and date of the base
33新增: each was cloned from
34新增: doctor Check the host, Lima, the base template and this
35新增: directory, and say how to fix what is wrong. Read-only.
36新增: name [dir] Print the VM name for a directory (default: cwd)
37新增: info [dir] Print machine-readable state as key=value lines
38新增: (version, template, state_dir, project_env, dir,
39新增: vm_name, base_exists, vm_exists, vm_running, vm_stale,
40新增: ssh_host, ssh_config, git_protected,
41新增: security_questions).
42新增: Use this from scripts instead of parsing the output
43新增: of the human-facing commands.
44新增: env <sub> [args] Read/write ~/.agent-vm/env, the secrets pushed into every
45新增: VM. Subcommands: set KEY [VALUE] (without VALUE, read
46新增: from stdin, or typed unseen: out of your shell history),
47新增: get KEY, has KEY (exit status only), unset KEY, list
48新增: (key names, never values).
49新增: Use this rather than editing the file: it is sourced by a
50新增: shell, so one bad quote costs every secret in it.
51新增: project-env <sub> Same subcommands, for THIS directory's project only. Its
52新增: values are pushed after the shared ones, so a key set in
53新增: both takes the project's value. Stored IN the project
54新增: (.agent-vm.env by default, AGENT_VM_PROJECT_ENV to put it
55新增: elsewhere): so it follows the project and dies with it.
56新增: Being in a repository, it is the wrong place for a secret:
57新增: `agent-vm env` is outside any. `set` warns, with the line
58新增: to run, when the file is not ignored by git. `info` prints
59新增: the path as project_env=.
60新增: version Print the agent-vm version
61新增: version --min X.Y.Z
62新增: Check it: silent and 0 when this engine is at least
63新增: X.Y.Z, an actionable error and 1 when it is older
64新增: (2 when the call itself is wrong). For integrators.
65新增: help Show this help
66新增:
67新增:VM options (for claude, opencode, codex, vibe, pi, shell, run), read before the
68新增:command or right after its name, never later: in 'agent-vm run docker run
69新增:--rm x', --rm belongs to docker.
70新增: --disk GB VM disk size
71新增: --memory GB VM memory
72新增: --cpus N Number of CPUs
73新增: Without them, a new VM has the base template's: 10, 3
74新增: and 1 unless 'setup' was given others.
75新增: Memory and CPUs are clamped to a share of the host (half
76新增: of it, with a notice) so the VM cannot starve the
77新增: machine it runs on.
78新增: AGENT_VM_HOST_SHARE overrides the divisor.
79新增: --ssh-port N Fixed host port for the VM's SSH, for tools that save the
80新增: port (default: a new one on each start; 0 goes back)
81新增: --reset Destroy and re-clone the VM from the base template
82新增: --readonly Make every host share read-only: the project and the
83新增: ~/.agent-vm/volumes entries, rw ones included. Enforced
84新增: on the host side, so root in the VM cannot lift it.
85新增: A running VM in the other mode is restarted, asked first
86新增: (no by default; declined or with no terminal, the
87新增: command fails). The resource options ask the same, and
88新增: declined, the VM keeps its settings.
89新增: --unsafe-writable-git
90新增: Leave every .git writable, so the agent can commit (see
91新增: below). Also accepted as --unsafe-writable-git=1.
92新增: --unsafe-disable-security-prompts
93新增: Go on where a start would stop to ask about a security
94新增: risk (below), without offering to change your git
95新增: config; the warnings are still printed. For scripts
96新增: with no terminal. Also
97新增: AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1 in your shell.
98新增: --rm Automatically destroy the VM after the command exits
99新增: --scratch A new VM with nothing of yours mounted (no project, no
100新增: volumes), deleted when the command ends, Ctrl-C included.
101新增: On a terminal, the deletion is asked first: no opens a
102新增: shell in the VM, and its exit asks again.
103新增: The project's env file and runtime script stay out;
104新增: ~/.agent-vm/env and runtime.sh go in. The folder's own
105新增: VM is left alone, and several can run at once.
106新增:
107新增:Examples:
108新增: agent-vm setup # Create base VM
109新增: agent-vm claude # Run Claude in a VM
110新增: agent-vm opencode # Run OpenCode in a VM
111新增: agent-vm codex # Run Codex in a VM
112新增: agent-vm vibe # Run Mistral Vibe in a VM
113新增: agent-vm pi # Run Pi in a VM
114新增: agent-vm --disk 50 --memory 16 --cpus 8 claude # Custom resources
115新增: agent-vm --reset claude # Fresh VM from base template
116新增: agent-vm --rm claude # Destroy VM after Claude exits
117新增: agent-vm --readonly shell # Nothing on the host is writable
118新增: agent-vm --scratch claude # Nothing of yours mounted, then deleted
119新增: agent-vm shell # Shell into the VM
120新增: agent-vm sh -c "ls -la | grep config" # One-shot command via login zsh
121新增: agent-vm run npm install # Run a command in the VM
122新增: agent-vm run --tty opencode -p "..." # Run a TUI with PTY allocated
123新增: agent-vm claude -p "fix lint errors" # Pass args to claude
124新增: agent-vm rm agent-vm-old-name-1a2b3c4d # Delete a VM by name (see 'list')
125新增:
126新增:VMs are persistent and unique per directory. Running "agent-vm shell" or
127新增:"agent-vm claude" in the same directory will reuse the same VM.
128新增:
129新增:Every .git in the shared folders is read-only for the VMs when Lima supports
130新增:it (sshfs.readonlyNames, not merged upstream yet: 'agent-vm setup' offers a
131新增:Lima build that has it). Every .hg is too, and so is the folder of each
132新增:core.hooksPath in the project (.husky for husky). 'agent-vm doctor' says
133新增:where you stand.
134新增:
135新增:Before a VM boots with writable shares, agent-vm stops on what it cannot
136新增:protect, and asks whether to go on (no by default, and when it cannot ask):
137新增:a Lima without readonlyNames, hooks at the top of the project, git config or
138新增:commands it names in files of the project, and git ignoring
139新增:safe.bareRepository=explicit (which it offers to set: git would otherwise use
140新增:a folder with HEAD, objects/ and refs/ as a repository, under any name). A
141新增:VM that already runs gets the warnings only, and a restart when it lacks a
142新增:protection; once stopped to boot again, it is asked like any other.
143新增:'agent-vm info' lists what a start would ask
144新增:(security_questions=).
145新增:--unsafe-writable-git, or AGENT_VM_UNSAFE_WRITABLE_GIT=1 in your shell, leaves
146新增:.git writable anyway, so the agent can commit in the project; a warning is
147新增:printed on every run. Changing it applies when the VM is next started.
148新增:
149新增:Customization:
150新增: ~/.agent-vm/env Shared env vars / tokens (dotenv-style;
151新增: pushed into every VM, loaded in its shells)
152新增: ~/.agent-vm/volumes Extra host paths to mount in VMs, one per
153新增: line, directories or files:
154新增: source[:destination][:ro|rw[:project]]
155新增: (ro by default; a relative destination is
156新增: in the project; project, after an explicit
157新增: mode, limits the entry to the projects it
158新增: matches, * as wildcard)
159新增: ~/.agent-vm/setup.sh Per-user setup (runs under zsh during
160新增: "agent-vm setup")
161新增: <project>/.agent-vm.env Per-project env (agent-vm project-env)
162新增: Override the path with AGENT_VM_PROJECT_ENV
163新增: ~/.agent-vm/runtime.sh Per-user runtime (runs on every command
164新增: that enters a VM)
165新增: <project>/.agent-vm.runtime.sh Per-project runtime (same, after the
166新增: per-user one)
167新增: Override the path with AGENT_VM_PROJECT_RUNTIME
168新增: (relative to the project, or absolute).
169新增: Runtimes run under the shell their shebang
170新增: names (bash, sh; zsh otherwise).
171新增:
172新增:More info: https://www.agent-vm.org/
173新增:EOF
174新增:}
新增lib/host.sh+263 −0看文件
@@ -0,0 +1,263 @@
1新增:# --- host capacity ------------------------------------------------------------
2新增:# A VM handed more CPU or RAM than the host can spare makes the host unusable
3新增:# for as long as the agent runs, and agents are meant to run unattended, for
4新增:# a while. So a --cpus/--memory above this host's share is clamped to it, out
5新增:# loud rather than silently. Nothing new to type: the flags stay plain
6新增:# integers, and a request that fits is applied as asked.
7新增:#
8新增:# The share is half the host by default. Not a measurement, a policy: it leaves
9新增:# the machine usable while the VM works. AGENT_VM_HOST_SHARE overrides it for
10新增:# anyone who knows better (1 = the whole host, no clamping in practice).
11新增:AGENT_VM_HOST_SHARE="${AGENT_VM_HOST_SHARE:-2}"
12新增:
13新增:# Host CPU count, empty when it cannot be determined. Never guess: an unknown
14新增:# host must leave the requested value alone, not silently shrink it.
15新增:_agent_vm_host_cpus() {
16新增: local n
17新增: if n=$(sysctl -n hw.ncpu 2>/dev/null) && [[ -n "$n" ]]; then printf '%s\n' "$n"
18新增: elif n=$(nproc 2>/dev/null) && [[ -n "$n" ]]; then printf '%s\n' "$n"
19新增: fi
20新增:}
21新增:
22新增:# Host RAM in GiB, empty when it cannot be determined.
23新增:_agent_vm_host_mem_gib() {
24新增: local bytes kib
25新增: if bytes=$(sysctl -n hw.memsize 2>/dev/null) && [[ -n "$bytes" ]]; then
26新增: printf '%s\n' "$((bytes / 1073741824))"
27新增: elif [[ -r /proc/meminfo ]] && kib=$(awk '/^MemTotal:/ {print $2; exit}' /proc/meminfo 2>/dev/null) \
28新增: && [[ -n "$kib" ]]; then
29新增: printf '%s\n' "$((kib / 1048576))"
30新增: fi
31新增:}
32新增:
33新增:# _agent_vm_host_share <total> <floor>: the share of <total> this host will
34新增:# give a VM, never below <floor>. An AGENT_VM_HOST_SHARE that is not a positive
35新增:# integer falls back to 2: it goes into arithmetic, where 0 divides by zero,
36新增:# "08" is bad octal and a name is evaluated as a variable.
37新增:_agent_vm_host_share() {
38新增: local total="$1" floor="$2" div="$AGENT_VM_HOST_SHARE" share
39新增: if [[ ! "$div" =~ ^[1-9][0-9]*$ ]]; then
40新增: echo "Warning: AGENT_VM_HOST_SHARE='$div' is not a positive integer; using 2." >&2
41新增: div=2
42新增: fi
43新增: share=$((10#$total / 10#$div))
44新增: [[ "$share" -lt "$floor" ]] && share="$floor"
45新增: printf '%s\n' "$share"
46新增:}
47新增:
48新增:# _agent_vm_cap_resource <cpus|memory> <value>: the value to actually apply.
49新增:# Above this host's share it comes back clamped, with a notice; at or below it
50新增:# comes back untouched. An empty value (nothing requested) and an unreadable
51新增:# host both mean "don't touch": guessing low on an unknown machine would hand
52新增:# out a 1-CPU VM on a 64-core host, which is worse than not guessing.
53新增:_agent_vm_cap_resource() {
54新增: local kind="$1" val="$2" total floor share
55新增: [[ -z "$val" ]] && { printf '\n'; return 0; }
56新增:
57新增: case "$kind" in
58新增: cpus) total="$(_agent_vm_host_cpus)"; floor=1 ;;
59新增: memory) total="$(_agent_vm_host_mem_gib)"; floor=2 ;;
60新增: *) printf '%s\n' "$val"; return 0 ;;
61新增: esac
62新增: if [[ -z "$total" || "$total" -le 0 ]]; then
63新增: printf '%s\n' "$val"
64新增: return 0
65新增: fi
66新增:
67新增: share="$(_agent_vm_host_share "$total" "$floor")"
68新增: if [[ "$val" -gt "$share" ]]; then
69新增: echo "Note: --$kind $val exceeds this host's share ($total detected); using $share." >&2
70新增: printf '%s\n' "$share"
71新增: return 0
72新增: fi
73新增: printf '%s\n' "$val"
74新增:}
75新增:
76新增:# Free space in GiB where Lima keeps the VMs' disks, in $HOME until Lima has
77新增:# made its directory. "/.": the directory a link there leads to. Fails when
78新增:# df cannot say.
79新增:_agent_vm_free_gib() {
80新增: local kib dir
81新增: dir="$(_agent_vm_lima_home)"
82新增: [[ -d "$dir" ]] || dir="$HOME"
83新增: kib=$(df -Pk "$dir/." 2>/dev/null | awk 'NR==2 {print $4}')
84新增: case "$kib" in ''|*[!0-9]*) return 1 ;; esac
85新增: echo $((kib / 1048576))
86新增:}
87新增:
88新增:# Warn when the host has less free space than the disk being asked for. Lima
89新增:# images are sparse, so this is a warning and not an error: the disk is
90新增:# allocated as it fills, and a smaller host can still work for a while.
91新增:_agent_vm_warn_disk_space() {
92新增: local want="$1" avail_gib
93新增: [[ -n "$want" ]] || return 0
94新增: avail_gib="$(_agent_vm_free_gib)" || return 0
95新增: if [[ "$avail_gib" -lt "$want" ]]; then
96新增: echo "Warning: ~${avail_gib} GiB free for a ${want} GiB VM disk (sparse: allocated as used)." >&2
97新增: fi
98新增:}
99新增:
100新增:# Check Linux prerequisites Lima needs to spin up a QEMU+KVM VM. macOS uses
101新增:# different backends (vz/qemu-via-brew) so this is a no-op there. Returns
102新增:# non-zero with actionable install/permission hints when something's missing:
103新增:# without this, the user gets a generic `Error: Failed to create base VM` and
104新增:# has to dig into `~/.lima/<vm>/ha.stderr.log` to figure out why.
105新增:_agent_vm_check_linux_prereqs() {
106新增: [[ "$(uname -s)" == "Linux" ]] || return 0
107新增:
108新增: local arch_bin arch_pkg
109新增: case "$(uname -m)" in
110新增: x86_64) arch_bin="qemu-system-x86_64"; arch_pkg="qemu-system-x86" ;;
111新增: aarch64|arm64) arch_bin="qemu-system-aarch64"; arch_pkg="qemu-system-arm" ;;
112新增: *) arch_bin="qemu-system-$(uname -m)"; arch_pkg="qemu-system" ;;
113新增: esac
114新增:
115新增: local errs=0
116新增:
117新增: if ! command -v "$arch_bin" &>/dev/null; then
118新增: echo "Error: Lima needs '$arch_bin' on PATH (not found)." >&2
119新增: echo " Install with: sudo apt-get install $arch_pkg" >&2
120新增: errs=1
121新增: fi
122新增:
123新增: if [[ ! -e /dev/kvm ]]; then
124新增: echo "Error: /dev/kvm does not exist (KVM unavailable)." >&2
125新增: # Inside WSL the fix is on the Windows side, by the user: WSL1 has no
126新增: # Linux kernel and can never run VMs, while WSL2 needs the host to let
127新增: # KVM through (nested virtualization). Neither is anything setup can do.
128新增: case "$(_agent_vm_wsl_version)" in
129新增: 1)
130新增: echo " This looks like WSL1, which cannot run VMs." >&2
131新增: echo " Upgrade the distribution to WSL2: wsl --set-version <distro> 2" >&2
132新增: ;;
133新增: 2)
134新增: echo " This looks like WSL2 without nested virtualization: KVM is not" >&2
135新增: echo " passed through from the Windows host. Update WSL (wsl --update)," >&2
136新增: echo " enable virtualization on the host, then retry." >&2
137新增: ;;
138新增: *)
139新增: echo " Hardware virtualization may be disabled in BIOS, or the kernel" >&2
140新增: echo " lacks KVM support (nested virt in a guest VM, etc.)." >&2
141新增: ;;
142新增: esac
143新增: errs=1
144新增: elif [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then
145新增: echo "Error: /dev/kvm exists but you don't have read/write access." >&2
146新增: local groups
147新增: groups="$(id -nG 2>/dev/null || true)"
148新增: if [[ " $groups " != *" kvm "* ]]; then
149新增: echo " Fix: sudo usermod -aG kvm \"\$USER\"" >&2
150新增: echo " Then log out and back in (or run 'newgrp kvm') so the new" >&2
151新增: echo " group membership takes effect." >&2
152新增: else
153新增: echo " You're already in the kvm group but /dev/kvm denies access." >&2
154新增: echo " Check ownership/mode: ls -l /dev/kvm" >&2
155新增: fi
156新增: errs=1
157新增: fi
158新增:
159新增: [[ $errs -eq 0 ]]
160新增:}
161新增:
162新增:# 0 when running on Windows (Git Bash, MSYS2 or Cygwin), as reported by
163新增:# uname: MINGW64_NT-..., MSYS_NT-... or CYGWIN_NT-....
164新增:_agent_vm_on_windows() {
165新增: case "$(uname -s 2>/dev/null)" in
166新增: MINGW*|MSYS*|CYGWIN*) return 0 ;;
167新增: *) return 1 ;;
168新增: esac
169新增:}
170新增:
171新增:# Git Bash and MSYS2 rewrite every argument that looks like a POSIX path when
172新增:# they start a native Windows program: `--workdir /c/proj` reaches limactl.exe
173新增:# as `C:/proj`, and so does a path meant for the guest. On Windows, limactl is
174新增:# therefore called with that rewriting off, and the host paths Lima itself
175新增:# reads are converted by _agent_vm_host_path.
176新增:if _agent_vm_on_windows; then
177新增: limactl() { MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' command limactl "$@"; }
178新增:fi
179新增:
180新增:# Path of the limactl binary, empty when there is none. `command -v` cannot
181新增:# answer where the function above shadows it.
182新增:_agent_vm_limactl_path() {
183新增: type -P limactl 2>/dev/null
184新增:}
185新增:
186新增:# A host path as Lima reads it: C:/Users/... on Windows, unchanged elsewhere.
187新增:_agent_vm_host_path() {
188新增: if _agent_vm_on_windows && command -v cygpath >/dev/null 2>&1; then
189新增: cygpath -m -- "$1"
190新增: else
191新增: printf '%s\n' "$1"
192新增: fi
193新增:}
194新增:
195新增:# Lima's state directory: LIMA_HOME, or ~/.lima.
196新增:_agent_vm_lima_home() {
197新增: printf '%s\n' "${LIMA_HOME:-$HOME/.lima}"
198新增:}
199新增:
200新增:# WSL generation from the kernel release: prints 2 or 1, or nothing when not
201新增:# on WSL. Only meaningful on Linux (WSL1 reports Microsoft without WSL2).
202新增:_agent_vm_wsl_version() {
203新增: local rel
204新增: rel="$(uname -r 2>/dev/null)" || return 0
205新增: case "$rel" in
206新增: *WSL2*) printf '2\n' ;;
207新增: *[Mm]icrosoft*) printf '1\n' ;;
208新增: esac
209新增: return 0
210新增:}
211新增:
212新增:# Check Windows prerequisites Lima needs for its QEMU driver. A no-op
213新增:# everywhere else, like the Linux check above.
214新增:#
215新增:# Only the QEMU binary is checked: whether the "Windows Hypervisor Platform"
216新增:# feature is enabled cannot be read without administrator rights, so a host
217新增:# without it fails at the first start instead, where
218新增:# _agent_vm_windows_start_hint explains it. winget ships with Windows 11, so
219新增:# it is the install path named here. Its QEMU installer does not add itself
220新增:# to PATH: when QEMU is in its default directory, that goes on PATH for this
221新增:# shell, with the line making it permanent.
222新增:_agent_vm_check_windows_prereqs() {
223新增: _agent_vm_on_windows || return 0
224新增:
225新增: local arch_bin qemu_dir
226新增: # uname -m under Git Bash reports the Windows architecture.
227新增: case "$(uname -m)" in
228新增: x86_64) arch_bin="qemu-system-x86_64" ;;
229新增: aarch64|arm64) arch_bin="qemu-system-aarch64" ;;
230新增: *) arch_bin="qemu-system-$(uname -m)" ;;
231新增: esac
232新增:
233新增: command -v "$arch_bin" &>/dev/null && return 0
234新增: qemu_dir="${AGENT_VM_QEMU_DIR:-/c/Program Files/qemu}"
235新增: if [[ -x "$qemu_dir/$arch_bin.exe" ]]; then
236新增: export PATH="$qemu_dir:$PATH"
237新增: echo "Added $qemu_dir to PATH for this shell. To keep it, add this line to ~/.bash_profile:"
238新增: printf ' export PATH="%s:$PATH"\n' "$qemu_dir"
239新增: return 0
240新增: fi
241新增: echo "Error: Lima needs '$arch_bin' on PATH (not found)." >&2
242新增: echo " Install QEMU with: winget install SoftwareFreedom.QEMU" >&2
243新增: echo " QEMU also needs the 'Windows Hypervisor Platform' Windows feature (see 'agent-vm doctor')." >&2
244新增: return 1
245新增:}
246新增:
247新增:# What an administrator runs, once, then reboots, for QEMU to use WHPX.
248新增:AGENT_VM_WHPX_ON="DISM /Online /Enable-Feature /FeatureName:HypervisorPlatform /All"
249新增:
250新增:# Printed after a failed VM start on Windows when one of the <log>s shows QEMU
251新增:# could not use WHPX, Windows' hypervisor API. Lima uses it unconditionally on
252新增:# Windows, with no slower fallback, and turning it on takes an administrator.
253新增:_agent_vm_windows_start_hint() {
254新增: _agent_vm_on_windows || return 0
255新增: grep -qi 'whpx' "$@" 2>/dev/null || return 0
256新增: cat >&2 <<EOF
257新增:QEMU could not use the Windows hypervisor. It needs the "Windows Hypervisor
258新增:Platform" Windows feature, which an administrator turns on once, followed by
259新增:a reboot: in Windows Features, or from an administrator terminal:
260新增: $AGENT_VM_WHPX_ON
261新增:On a managed laptop, that is a request to your IT department.
262新增:EOF
263新增:}
新增lib/info.sh+192 −0看文件
@@ -0,0 +1,192 @@
1新增:# --- version and info: what integrators read ----------------------------------
2新增:# _agent_vm_ver_ge <a> <b>: status 0 when version a >= b. Components compare
3新增:# one by one as base-10 numbers: a string comparison gets "1.10.0" < "1.9.0"
4新增:# wrong, and "08" must not be read as octal. Missing components count as 0, a
5新增:# "-rc1" suffix is ignored. Compared as digit strings, leading zeros dropped,
6新增:# the longer the larger: shell arithmetic overflows past 19 digits.
7新增:_agent_vm_ver_ge() {
8新增: local a="${1%%-*}" b="${2%%-*}" x y
9新增: while [[ -n "$a" || -n "$b" ]]; do
10新增: x="${a%%.*}"; y="${b%%.*}"
11新增: if [[ "$a" == *.* ]]; then a="${a#*.}"; else a=""; fi
12新增: if [[ "$b" == *.* ]]; then b="${b#*.}"; else b=""; fi
13新增: x="${x//[!0-9]/}"; y="${y//[!0-9]/}"
14新增: x="${x#"${x%%[!0]*}"}"; y="${y#"${y%%[!0]*}"}"
15新增: [[ "${#x}" -gt "${#y}" ]] && return 0
16新增: [[ "${#x}" -lt "${#y}" ]] && return 1
17新增: [[ "$x" > "$y" ]] && return 0
18新增: [[ "$x" < "$y" ]] && return 1
19新增: done
20新增: return 0
21新增:}
22新增:
23新增:# How this copy of agent-vm is updated: a git clone, a Homebrew keg, or a
24新增:# release put there by www.agent-vm.org/install.sh. The installer's --dir
25新增:# goes with it when this copy is not in the installer's default directory:
26新增:# without it, the update lands next to this one and this one stays old.
27新增:_agent_vm_update_command() {
28新增: local default="${XDG_DATA_HOME:-$HOME/.local/share}/agent-vm"
29新增: # Physical, as AGENT_VM_SCRIPT_DIR is.
30新增: default="$(CDPATH= cd -P -- "$default" 2>/dev/null && pwd)" || default=""
31新增: if [[ -e "$AGENT_VM_SCRIPT_DIR/.git" ]]; then
32新增: printf "git -C '%s' pull\n" "$(_agent_vm_sq_escape "$AGENT_VM_SCRIPT_DIR")"
33新增: elif [[ "$AGENT_VM_SCRIPT_DIR" == */Cellar/agent-vm/* ]]; then
34新增: echo "brew upgrade agent-vm"
35新增: elif [[ "$AGENT_VM_SCRIPT_DIR" == "$default" ]]; then
36新增: echo "curl -fsSL https://www.agent-vm.org/install.sh | sh"
37新增: else
38新增: printf "curl -fsSL https://www.agent-vm.org/install.sh | sh -s -- --dir '%s'\n" \
39新增: "$(_agent_vm_sq_escape "$AGENT_VM_SCRIPT_DIR")"
40新增: fi
41新增:}
42新增:
43新增:# `version` prints the version. `version --min X.Y.Z` turns it into a check an
44新增:# integrator can put in front of everything else: silent with status 0 when
45新增:# this engine is recent enough, one actionable line on stderr and status 1
46新增:# when it is not.
47新增:#
48新增:# Status 2 is reserved for a malformed call. A typo in the required version
49新增:# must not read as "engine too old" and send a user chasing an upgrade they
50新增:# don't need.
51新增:#
52新增:# Known limit, and the reason this can't be the only check an integrator has:
53新增:# an engine older than the one that introduced --min ignores the flag, prints
54新增:# its version and exits 0. A tool whose floor is below that version still
55新增:# needs its own comparison for the bootstrap check.
56新增:_agent_vm_version() {
57新增: if [[ $# -eq 0 ]]; then
58新增: echo "$AGENT_VM_VERSION"
59新增: return 0
60新增: fi
61新增:
62新增: local want=""
63新增: while [[ $# -gt 0 ]]; do
64新增: case "$1" in
65新增: --min)
66新增: if [[ $# -lt 2 ]]; then
67新增: echo "Error: --min needs a version (e.g. --min 0.2.0)" >&2
68新增: return 2
69新增: fi
70新增: want="$2"; shift 2 ;;
71新增: --min=*)
72新增: want="${1#*=}"; shift ;;
73新增: *)
74新增: echo "Error: unknown option for version: $1" >&2
75新增: return 2 ;;
76新增: esac
77新增: done
78新增:
79新增: if [[ ! "$want" =~ ^[0-9]+(\.[0-9]+)*(-[A-Za-z0-9.]+)?$ ]]; then
80新增: echo "Error: --min expects a version like 1.2.3 (got: '$want')" >&2
81新增: return 2
82新增: fi
83新增:
84新增: _agent_vm_ver_ge "$AGENT_VM_VERSION" "$want" && return 0
85新增:
86新增: echo "Error: agent-vm $AGENT_VM_VERSION is older than the required $want." >&2
87新增: echo " Update it: $(_agent_vm_update_command)" >&2
88新增: return 1
89新增:}
90新增:
91新增:# Machine-readable state, one key=value per line. This is the supported way for
92新增:# another tool to ask what agent-vm knows, instead of reverse-engineering VM
93新增:# naming, the template name, or the state-dir version markers, all of which
94新增:# are internal and free to change.
95新增:#
96新增:# Keys: version, template, state_dir, project_env, dir, vm_name, base_exists,
97新增:# vm_exists, vm_running, vm_stale, ssh_host, ssh_config, git_protected,
98新增:# security_questions. Booleans are 1/0; anything that cannot be determined is
99新增:# "unknown" rather than a guess.
100新增:#
101新增:# git_protected: whether a start keeps .git read-only for the VM (see
102新增:# _agent_vm_lima_protects_git and the --unsafe-writable-git opt-out).
103新增:# security_questions: what a start with writable shares of a stopped VM would
104新增:# stop on unless answered yes (see _agent_vm_confirm_unsafe), comma-separated,
105新增:# or "none": lima (this Lima cannot keep .git read-only), lima-unknown (it
106新增:# cannot tell, which stops the start with an error), hooks (a hooks folder that
107新增:# cannot be protected), git-config (git config or commands in the project),
108新增:# bare-repo (safe.bareRepository). A script with no terminal passes
109新增:# --unsafe-disable-security-prompts to accept them, or --readonly.
110新增:#
111新增:# ssh_host is the Host alias in ssh_config, the file Lima rewrites with the
112新增:# current port on each start (https://www.agent-vm.org/#connect-an-ide-over-ssh).
113新增:_agent_vm_info() {
114新增: local dir="${1:-$(pwd)}"
115新增: local vm_name
116新增: vm_name="$(_agent_vm_name "$dir")" || return 1
117新增:
118新增: echo "version=$AGENT_VM_VERSION"
119新增: echo "template=$AGENT_VM_TEMPLATE"
120新增: echo "state_dir=$AGENT_VM_STATE_DIR"
121新增: echo "project_env=$(_agent_vm_project_env_file "$dir")"
122新增: echo "dir=$dir"
123新增: echo "vm_name=$vm_name"
124新增:
125新增: if [[ -z "$(_agent_vm_limactl_path)" ]]; then
126新增: # Still useful without Lima: the static keys above answer "what would this
127新增: # VM be called", which is all a caller needs before setup has ever run.
128新增: echo "base_exists=unknown"
129新增: echo "vm_exists=unknown"
130新增: echo "vm_running=unknown"
131新增: echo "vm_stale=unknown"
132新增: echo "ssh_host=lima-$vm_name"
133新增: echo "ssh_config=unknown"
134新增: echo "git_protected=unknown"
135新增: echo "security_questions=unknown"
136新增: return 0
137新增: fi
138新增:
139新增: # Keep the three-way answer from the query helpers: a failed query reports
140新增: # `unknown`, never a confident 0. A caller told `base_exists=0` when the truth
141新增: # was "could not ask" would offer to build a base VM that already exists.
142新增: local base_exists vm_exists vm_running
143新增: _agent_vm_base_exists; base_exists="$(_agent_vm_tristate $?)"
144新增: _agent_vm_exists "$vm_name"; vm_exists="$(_agent_vm_tristate $?)"
145新增: _agent_vm_running "$vm_name"; vm_running="$(_agent_vm_tristate $?)"
146新增: echo "base_exists=$base_exists"
147新增: echo "vm_exists=$vm_exists"
148新增: echo "vm_running=$vm_running"
149新增: # Staleness compares this VM against the base it was cloned from; with no VM
150新增: # (or no way to tell) there is nothing to compare.
151新增: if [[ "$vm_exists" == "1" ]]; then
152新增: echo "vm_stale=$(_agent_vm_stale_state "$vm_name")"
153新增: else
154新增: echo "vm_stale=unknown"
155新增: fi
156新增: # Lima names the alias after the instance ("lima-" and the name, whose dots
157新增: # and underscores become dashes: agent-vm names have neither).
158新增: echo "ssh_host=lima-$vm_name"
159新增: local ssh_config=""
160新增: [[ "$vm_exists" == "1" ]] \
161新增: && ssh_config="$(limactl list "$vm_name" --format '{{.SSHConfigFile}}' 2>/dev/null)"
162新增: echo "ssh_config=${ssh_config:-unknown}"
163新增:
164新增: local lima_st=0 protected questions="" rel in_repo
165新增: _agent_vm_lima_protects_git || lima_st=$?
166新增: if _agent_vm_writable_git_optout; then
167新增: protected=0
168新增: # The opt-out leaves .git, not the rest of the disk: still asked there.
169新增: _agent_vm_unprotected_mount_is_sshfs "$vm_name" && questions="lima"
170新增: else
171新增: case "$lima_st" in
172新增: 0) protected=1 ;;
173新增: 1) protected=0; questions="lima" ;;
174新增: *) protected=unknown; questions="lima-unknown" ;;
175新增: esac
176新增: fi
177新增: if [[ "$protected" == 1 ]]; then
178新增: while IFS=$'\t' read -r rel in_repo; do
179新增: [[ -n "$rel" ]] || continue
180新增: if ! _agent_vm_hooks_name "$in_repo" >/dev/null; then
181新增: questions="${questions:+$questions,}hooks"
182新增: break
183新增: fi
184新增: done <<< "$(_agent_vm_project_hooks "$dir")"
185新增: [[ -z "$(_agent_vm_project_config_risks "$dir")" ]] || questions="${questions:+$questions,}git-config"
186新增: fi
187新增: case "$(_agent_vm_bare_repo_state)" in
188新增: unset|old) questions="${questions:+$questions,}bare-repo" ;;
189新增: esac
190新增: echo "git_protected=$protected"
191新增: echo "security_questions=${questions:-none}"
192新增:}
新增lib/install.sh+120 −0看文件
@@ -0,0 +1,120 @@
1新增:# --- install / uninstall: agent-vm on the PATH ----------------------------------
2新增:# `install` puts agent-vm on the PATH as a symlink to agent-vm.sh in the clone:
3新增:# the script dispatches when executed, so a link is all a command needs, and
4新增:# `git pull` updates it (a launcher script where there are no symlinks, see
5新增:# _agent_vm_launcher). It works from every shell, and it is all that is
6新增:# installed: sourcing agent-vm.sh from a shell rc is no longer offered. Safe
7新增:# to re-run. AGENT_VM_BIN_DIR picks the directory (default ~/.local/bin).
8新增:
9新增:_agent_vm_bin_link() {
10新增: printf '%s/agent-vm\n' "${AGENT_VM_BIN_DIR:-$HOME/.local/bin}"
11新增:}
12新增:
13新增:# Where `ln -s` makes no link (Git Bash copies the file unless Windows grants
14新增:# symlinks), a copy of agent-vm.sh would look for lib/ next to itself and not
15新增:# find it. `install` writes this launcher instead: it runs the real file.
16新增:_agent_vm_launcher() {
17新增: printf '#!/usr/bin/env bash\n# Written by agent-vm install: this system makes no symlinks.\nexec bash '"'"'%s'"'"' "$@"\n' \
18新增: "$(_agent_vm_sq_escape "$1")"
19新增:}
20新增:
21新增:# 0 when <path> is what `install` puts there for <script>: a link to it, or
22新增:# the launcher running it.
23新增:_agent_vm_installed_ours() {
24新增: local target="$1" script="$2"
25新增: if [[ -L "$target" ]]; then
26新增: [[ "$(readlink "$target")" == "$script" ]]
27新增: else
28新增: [[ -f "$target" && "$(cat "$target" 2>/dev/null)" == "$(_agent_vm_launcher "$script")" ]]
29新增: fi
30新增:}
31新增:
32新增:# 0 when an uncommented line of a usual rc file names agent-vm.sh: an install
33新增:# from before 0.2.0, which added one.
34新增:_agent_vm_rc_sources_us() {
35新增: local f
36新增: for f in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile" "$HOME/.zshenv"; do
37新增: [[ -f "$f" ]] || continue
38新增: grep -q '^[^#]*agent-vm\.sh' "$f" 2>/dev/null && return 0
39新增: done
40新增: return 1
41新增:}
42新增:
43新增:_agent_vm_install() {
44新增: if [[ $# -gt 0 ]]; then
45新增: echo "Usage: agent-vm install" >&2
46新增: return 2
47新增: fi
48新增: local script="$AGENT_VM_SCRIPT_DIR/agent-vm.sh" link bin_dir
49新增: link="$(_agent_vm_bin_link)"
50新增: bin_dir="$(dirname "$link")"
51新增: if [[ ! -r "$script" ]]; then
52新增: echo "Error: agent-vm.sh not found in $AGENT_VM_SCRIPT_DIR." >&2
53新增: return 1
54新增: fi
55新增: chmod +x "$script" 2>/dev/null || true
56新增: mkdir -p "$bin_dir" || return 1
57新增: if _agent_vm_installed_ours "$link" "$script"; then
58新增: echo "agent-vm is already linked at $link"
59新增: elif [[ -e "$link" || -L "$link" ]]; then
60新增: # -L too: a dangling link is not -e, and ln would fail on it.
61新增: echo "Error: $link already exists and is not a link to $script." >&2
62新增: echo " Move it aside, or set AGENT_VM_BIN_DIR to another directory." >&2
63新增: return 1
64新增: else
65新增: ln -s "$script" "$link" 2>/dev/null
66新增: if [[ -L "$link" ]]; then
67新增: echo "Linked $link -> $script"
68新增: else
69新增: rm -f "$link"
70新增: _agent_vm_launcher "$script" > "$link" && chmod +x "$link" || return 1
71新增: echo "Installed $link, a launcher for $script (no symlinks on this system)"
72新增: fi
73新增: fi
74新增: case ":$PATH:" in
75新增: *":$bin_dir:"*) ;;
76新增: *)
77新增: echo "$bin_dir is not on your PATH. Add this line to your shell rc:"
78新增: printf ' export PATH="%s:$PATH"\n' "$bin_dir" ;;
79新增: esac
80新增: if _agent_vm_rc_sources_us; then
81新增: echo "Your shell rc still sources agent-vm.sh: the command above replaces that line, which you can remove."
82新增: fi
83新增: echo ""
84新增: echo "agent-vm $AGENT_VM_VERSION installed."
85新增: if _agent_vm_base_exists; then
86新增: echo "Next: cd your-project && agent-vm claude # or opencode, codex, vibe"
87新增: return 0
88新增: fi
89新增: if _agent_vm_have_tty \
90新增: && [[ "$(_agent_vm_ask_yn "Build the base VM now with 'agent-vm setup'? It takes a few minutes." Y)" == "1" ]]; then
91新增: echo ""
92新增: _agent_vm_setup
93新增: return
94新增: fi
95新增: echo "Next:"
96新增: echo " agent-vm setup # build the base VM, once"
97新增:}
98新增:
99新增:# Removes the link `install` made, and nothing else: the rc line is named, not
100新增:# edited, and the VMs, ~/.agent-vm and agent-vm's own folder stay.
101新增:_agent_vm_uninstall() {
102新增: if [[ $# -gt 0 ]]; then
103新增: echo "Usage: agent-vm uninstall" >&2
104新增: return 2
105新增: fi
106新增: local script="$AGENT_VM_SCRIPT_DIR/agent-vm.sh" link
107新增: link="$(_agent_vm_bin_link)"
108新增: if _agent_vm_installed_ours "$link" "$script"; then
109新增: rm -f "$link" || return 1
110新增: echo "Removed $link"
111新增: elif [[ -e "$link" || -L "$link" ]]; then
112新增: echo "$link is not a link to this agent-vm: left alone."
113新增: else
114新增: echo "No link to remove at $link"
115新增: fi
116新增: if _agent_vm_rc_sources_us; then
117新增: echo "Your shell rc still sources agent-vm.sh: remove that line to drop the shell function."
118新增: fi
119新增: echo "Left as they are: the VMs ('agent-vm destroy-all' deletes them, run it first), ~/.agent-vm, and agent-vm itself in $AGENT_VM_SCRIPT_DIR (delete that folder to remove it)."
120新增:}
新增lib/mounts.sh+359 −0看文件
@@ -0,0 +1,359 @@
1新增:# --- mounts: the shares a VM gets, and ~/.agent-vm/volumes --------------------
2新增:
3新增:# Stage a single host file at <dst> via hardlink, falling back to copy if the
4新增:# source and destination live on different filesystems. Hardlinking keeps the
5新增:# content live-synced with the host (same inode) without exposing the source's
6新增:# parent directory to the VM. The copy fallback preserves the no-exposure
7新增:# property but loses live sync until the next VM (re)start.
8新增:_agent_vm_stage_file() {
9新增: local src="$1" dst="$2"
10新增: mkdir -p "$(dirname "$dst")" 2>/dev/null || return 1
11新增: rm -f "$dst"
12新增: if ln "$src" "$dst" 2>/dev/null; then
13新增: return 0
14新增: fi
15新增: if cp -p "$src" "$dst" 2>/dev/null; then
16新增: echo "Warning: Staged '${src}' via copy (cross-filesystem hardlink failed); live host changes will not propagate until VM (re)start." >&2
17新增: return 0
18新增: fi
19新增: return 1
20新增:}
21新增:
22新增:# 0 when the project directory <dir> matches <filter>, the 4th field of a
23新增:# ~/.agent-vm/volumes entry: a path, `~` expanded, where `*` matches anything,
24新增:# `/` included. A filter that is not absolute matches nothing, with a warning.
25新增:# `~user/...` is not expanded: it counts as not absolute.
26新增:_agent_vm_volume_matches() {
27新增: local filter="$1" dir="$2"
28新增: case "$filter" in
29新增: "~"|"~/"*) filter="$HOME${filter#\~}" ;;
30新增: esac
31新增: [[ "$filter" == / ]] || filter="${filter%/}"
32新增: if [[ "$filter" != /* ]]; then
33新增: echo "Warning: Project filter '$1' (from ~/.agent-vm/volumes) is not an absolute path, skipping the entry." >&2
34新增: return 1
35新增: fi
36新增: [[ "$dir" == $filter ]]
37新增:}
38新增:
39新增:# A relative destination in ~/.agent-vm/volumes is inside the project. Prints
40新增:# its absolute path, after creating it on the host (a directory, or an empty
41新增:# file for a file source): virtiofs and 9p create mount points before the
42新增:# project is mounted, and --readonly refuses the write from the guest.
43新增:# No component may be ".." or a symlink: the agent can write the project, and
44新增:# mkdir would follow a link it planted there to anywhere on the host. Checked
45新增:# here for the message, and made with _agent_vm_nofollow, since the VM could
46新增:# swap a link in after the check.
47新增:_agent_vm_project_mountpoint() {
48新增: local dir="$1" rel="$2" src="$3" p="$1" comp rest="$2/" norm=""
49新增: while [[ -n "$rest" ]]; do
50新增: comp="${rest%%/*}"
51新增: rest="${rest#*/}"
52新增: [[ -z "$comp" || "$comp" == . ]] && continue
53新增: if [[ "$comp" == .. ]]; then
54新增: echo "Warning: Mount destination '${rel}' (from ~/.agent-vm/volumes) goes out of the project with '..', skipping." >&2
55新增: return 1
56新增: fi
57新增: p="$p/$comp"
58新增: norm="${norm:+$norm/}$comp"
59新增: if [[ -L "$p" ]]; then
60新增: echo "Warning: Mount destination '${rel}' (from ~/.agent-vm/volumes) goes through a symlink in the project ($p), skipping." >&2
61新增: return 1
62新增: fi
63新增: done
64新增: if [[ "$p" == "$dir" ]]; then
65新增: echo "Warning: Mount destination '${rel}' (from ~/.agent-vm/volumes) is the project itself, skipping." >&2
66新增: return 1
67新增: fi
68新增: local op=touch st=0
69新增: [[ -d "$src" ]] && op=mkdir
70新增: _agent_vm_nofollow "$op" "$dir" "$norm" 2>/dev/null || st=$?
71新增: case "$st" in
72新增: 0) ;;
73新增: 3)
74新增: echo "Warning: Mount destination '${rel}' (from ~/.agent-vm/volumes) goes through a symlink in the project, or is not a $([[ "$op" == mkdir ]] && echo directory || echo file) there, skipping." >&2
75新增: return 1 ;;
76新增: *)
77新增: command -v perl >/dev/null 2>&1 \
78新增: || echo "Warning: perl is needed to create the mount point '$p' in the project without following symlinks." >&2
79新增: echo "Warning: Cannot create the mount point '$p' (from ~/.agent-vm/volumes), skipping." >&2
80新增: return 1 ;;
81新增: esac
82新增: printf '%s\n' "$p"
83新增:}
84新增:
85新增:# _agent_vm_build_mounts_json <vm> <dir> [<writable>] [<names>]: the .mounts
86新增:# JSON array for `limactl edit --set`. The project <dir> first, writable
87新增:# unless <writable> is false, then the entries of ~/.agent-vm/volumes
88新增:# (`source[:destination][:ro|rw[:project]]`, ro by default).
89新增:# - <writable> false is --readonly, for every share, rw volumes included: a
90新增:# writable volume holding the project would be a second way to write it.
91新增:# Lima enforces `writable: false` on the host side, where root in the VM
92新增:# cannot undo it, except on reverse-sshfs without readonlyNames (see
93新增:# _agent_vm_mount_is_host_enforced).
94新增:# - <names> keeps names read-only on every share: a readonlyNames JSON array,
95新增:# or 1 for the project's (see _agent_vm_readonly_names). The caller sets the
96新增:# mount type that goes with it (see _agent_vm_mounts_expr).
97新增:# Single files are hardlinked into ~/.agent-vm/file-mounts/<vm>/, shared from
98新增:# there and listed in ~/.agent-vm/.agent-vm-file-mounts-<vm> for the bind in
99新增:# the VM.
100新增:_agent_vm_build_mounts_json() {
101新增: local vm_name="$1" host_dir="$2" project_writable="${3:-true}" sshfs=""
102新增: case "${4:-}" in
103新增: 1) sshfs=", \"sshfs\": {\"sftpDriver\": \"builtin\", \"readonlyNames\": $(_agent_vm_readonly_names "$host_dir")}" ;;
104新增: \[*) sshfs=", \"sshfs\": {\"sftpDriver\": \"builtin\", \"readonlyNames\": $4}" ;;
105新增: esac
106新增: # Every entry names its mount point: agent-vm addresses the guest side by the
107新增: # shell's spelling of the path (--workdir, the write probe), which on Windows
108新增: # is not the C:/... form Lima reads the location in.
109新增: local mounts_json="[{\"location\": \"$(_agent_vm_host_path "$host_dir")\", \"mountPoint\": \"${host_dir}\", \"writable\": ${project_writable}${sshfs}}"
110新增: local mounts_file="$AGENT_VM_STATE_DIR/volumes"
111新增: local file_mount_entries=()
112新增: local file_mounts_cache="$AGENT_VM_STATE_DIR/.agent-vm-file-mounts-${vm_name}"
113新增:
114新增: if [[ -f "$mounts_file" ]]; then
115新增: local staging_idx=0 raw line
116新增: while IFS= read -r raw || [[ -n "$raw" ]]; do
117新增: line="${raw%%#*}" # strip comments
118新增: line="${line#"${line%%[![:space:]]*}"}" # trim leading whitespace
119新增: line="${line%"${line##*[![:space:]]}"}" # trim trailing whitespace
120新增: [[ -z "$line" ]] && continue
121新增: # A control character (a tab, an ESC...) is invalid unescaped in the JSON
122新增: # handed to limactl. The CR of a CRLF file went with the trim above.
123新增: if [[ "$line" == *[[:cntrl:]]* ]]; then
124新增: echo "Warning: Mount entry '${raw}' (from ~/.agent-vm/volumes) contains a control character, skipping." >&2
125新增: continue
126新增: fi
127新增: # An optional 4th field, after an explicit mode, limits the entry to the
128新增: # projects it matches: source:destination:mode:filter. An empty one
129新增: # (`src:dst:rw:`) is refused, not read as "no filter": that would mount
130新增: # an entry meant for one project in every project.
131新增: local filter="" has_filter="" before="${line%:*}"
132新增: if [[ "$line" == *:* && ( "$before" == *:ro || "$before" == *:rw ) ]]; then
133新增: filter="${line##*:}"
134新增: has_filter=1
135新增: line="$before"
136新增: fi
137新增: if [[ -n "$has_filter" ]]; then
138新增: if [[ -z "$filter" ]]; then
139新增: echo "Warning: Mount entry '${raw}' (from ~/.agent-vm/volumes) has an empty project filter; refusing to mount it in every project. Skipping." >&2
140新增: continue
141新增: fi
142新增: _agent_vm_volume_matches "$filter" "$host_dir" || continue
143新增: fi
144新增: # Parse source[:destination][:mode] syntax (like docker compose volumes).
145新增: # The trailing mode segment is only recognized when it equals "ro" or
146新增: # "rw": anything else is treated as a destination path.
147新增: local src="$line" dst="" mode="ro"
148新增: if [[ "$line" == *:ro || "$line" == *:rw ]]; then
149新增: mode="${line##*:}"
150新增: line="${line%:*}"
151新增: fi
152新增: if [[ "$line" == *:* ]]; then
153新增: src="${line%%:*}"
154新增: dst="${line#*:}"
155新增: else
156新增: src="$line"
157新增: fi
158新增: # A ':' left in the destination is a field out of place: a project
159新增: # without a mode before it (`src:dst:/p`), a mode after it
160新增: # (`src:dst:/p:rw`), a second mode, a fifth field. Read as a destination,
161新增: # the entry would be mounted in every project, the project filter lost.
162新增: if [[ "$dst" == *:* ]]; then
163新增: echo "Warning: Mount entry '${raw}' (from ~/.agent-vm/volumes) does not read as source:destination:mode:project (the mode goes before the project, and is needed with one). Skipping." >&2
164新增: continue
165新增: fi
166新增: src="${src/#\~/$HOME}" # expand ~
167新增: # Reject characters that would break JSON interpolation below or the
168新增: # pipe-separated cache format used for file mounts.
169新增: if [[ "$src" == *[$'"\\\n|']* || "$dst" == *[$'"\\\n|']* ]]; then
170新增: echo "Warning: Mount entry '${raw}' (from ~/.agent-vm/volumes) contains invalid characters (quote/backslash/newline/pipe), skipping." >&2
171新增: continue
172新增: fi
173新增: if [[ ! -e "$src" ]]; then
174新增: echo "Warning: Mount path '${src}' (from ~/.agent-vm/volumes) does not exist, skipping." >&2
175新增: continue
176新增: fi
177新增: if [[ -n "$dst" && "$dst" != /* ]]; then
178新增: dst="$(_agent_vm_project_mountpoint "$host_dir" "$dst" "$src")" || continue
179新增: fi
180新增: if [[ -f "$src" ]]; then
181新增: if [[ "$mode" == "rw" ]]; then
182新增: echo "Warning: Mount entry '${line}' (from ~/.agent-vm/volumes) requests rw on a file; only directories support rw. Mount the parent directory instead. Skipping." >&2
183新增: continue
184新增: fi
185新增: # File mount: hardlink the source into a per-VM host staging dir so
186新增: # the VM sees only this file (never the source's parent). Lima mounts
187新增: # the staging dir; a bind mount inside the VM (applied after boot)
188新增: # exposes the file at its final destination.
189新增: local filename=""
190新增: filename="$(basename "$src")"
191新增: local file_staging_dir="$AGENT_VM_STATE_DIR/file-mounts/${vm_name}/${staging_idx}"
192新增: local host_staging="${file_staging_dir}/${filename}"
193新增: if ! _agent_vm_stage_file "$src" "$host_staging"; then
194新增: echo "Warning: Failed to stage '${src}', skipping." >&2
195新增: rm -rf "$file_staging_dir"
196新增: continue
197新增: fi
198新增: local staging_mount="/tmp/.agent-vm-file-mounts/${staging_idx}"
199新增: local bind_dst="${dst:-${src}}"
200新增: file_mount_entries+=("${src}|${host_staging}|${staging_mount}/${filename}|${bind_dst}")
201新增: mounts_json+=", {\"location\": \"$(_agent_vm_host_path "$file_staging_dir")\", \"mountPoint\": \"${staging_mount}\", \"writable\": false${sshfs}}"
202新增: staging_idx=$((staging_idx + 1))
203新增: continue
204新增: fi
205新增: if [[ ! -d "$src" ]]; then
206新增: echo "Warning: Mount path '${src}' (from ~/.agent-vm/volumes) is not a regular file or directory, skipping." >&2
207新增: continue
208新增: fi
209新增: local writable="false"
210新增: if [[ "$mode" == "rw" ]]; then
211新增: if [[ "$project_writable" == "true" ]]; then
212新增: writable="true"
213新增: else
214新增: echo "Note: --readonly: '${src}' (rw in ~/.agent-vm/volumes) is mounted read-only too." >&2
215新增: fi
216新增: fi
217新增: mounts_json+=", {\"location\": \"$(_agent_vm_host_path "$src")\", \"mountPoint\": \"${dst:-$src}\", \"writable\": ${writable}${sshfs}}"
218新增: done < "$mounts_file"
219新增: fi
220新增: mounts_json+="]"
221新增:
222新增: rm -f "$file_mounts_cache"
223新增: if [[ ${#file_mount_entries[@]} -gt 0 ]]; then
224新增: printf '%s\n' "${file_mount_entries[@]}" >| "$file_mounts_cache"
225新增: fi
226新增:
227新增: printf '%s' "$mounts_json"
228新增:}
229新增:
230新增:# The mounts JSON last applied to <vm>, kept so --readonly can tell whether
231新增:# any share is still writable: the guest cannot be asked, since after a mode
232新增:# change it still believes the old one (see _agent_vm_push_env_and_probe).
233新增:# A record that could not be written goes: an old one would keep claiming the
234新增:# protection or the mode the VM had before (a protected .git, read-only
235新增:# shares), and the next start would trust it. With none, it rebuilds them.
236新增:_agent_vm_record_mounts() {
237新增: local record="$AGENT_VM_STATE_DIR/.agent-vm-mounts-$1"
238新增: mkdir -p "$AGENT_VM_STATE_DIR" 2>/dev/null && printf '%s\n' "$2" >| "$record" && return 0
239新增: rm -f "$record"
240新增: echo "Error: could not record the shares of VM '$1' in $record." >&2
241新增: return 1
242新增:}
243新增:
244新增:# 0 when <vm> is recorded with no writable share at all. A missing record
245新增:# counts as "not known to be read-only".
246新增:_agent_vm_mounts_all_readonly() {
247新增: local record="$AGENT_VM_STATE_DIR/.agent-vm-mounts-$1" mounts
248新增: [[ -f "$record" ]] || return 1
249新增: mounts="$(cat "$record")"
250新增: [[ "$mounts" != *'"writable": true'* ]]
251新增:}
252新增:
253新增:# 0 when <vm> is recorded with every .git read-only (see
254新增:# _agent_vm_build_mounts_json). A missing record counts as "not protected".
255新增:_agent_vm_mounts_protect_git() {
256新增: local record="$AGENT_VM_STATE_DIR/.agent-vm-mounts-$1"
257新增: [[ -f "$record" ]] && grep -q '"readonlyNames"' "$record"
258新增:}
259新增:
260新增:# 0 when <vm> is recorded with readonlyNames <names> (a JSON array, as
261新增:# _agent_vm_readonly_names prints it).
262新增:_agent_vm_mounts_have_readonly_names() {
263新增: local record="$AGENT_VM_STATE_DIR/.agent-vm-mounts-$1"
264新增: [[ -f "$record" ]] && grep -qF "\"readonlyNames\": $2" "$record"
265新增:}
266新增:
267新增:# _agent_vm_push_env_and_probe <vm> <dir> <payload> [<env> [<runtime>]], in
268新增:# one round trip:
269新增:# - writes ~/.agent-vm.env in the VM (mode 600, sourced by its ~/.zshenv):
270新增:# <payload> (see _agent_vm_env_payload), then the project's <env>, read by
271新增:# the VM, CRs dropped; empty too, so env removed on the host goes. Prints
272新增:# env-ok.
273新增:# - prints runtime-found when the project's <runtime> is there.
274新增:# - returns whether a write into the project <dir> succeeds. A real write, not
275新增:# `test -w`: after a mode change the guest's fstab still shows the old one.
276新增:_agent_vm_push_env_and_probe() {
277新增: local vm_name="$1" host_dir="$2" payload="$3"
278新增: { [ -z "$payload" ] || printf '%s\n' "$payload"; } \
279新增: | limactl shell "$vm_name" sh -c '
280新增: (umask 077 && rm -f "$HOME/.agent-vm.env" && { cat; [ -z "$2" ] || [ ! -f "$2" ] || awk "{ sub(/\r\$/, \"\"); print }" "$2"; } > "$HOME/.agent-vm.env") && echo env-ok
281新增: [ -z "$3" ] || [ ! -f "$3" ] || echo runtime-found
282新增: p="$1/.agent-vm-write-probe.$$"; touch "$p" 2>/dev/null || exit 1; rm -f "$p"' \
283新增: sh "$host_dir" "${4:-}" "${5:-}" 2>/dev/null
284新增:}
285新增:
286新增:# Are <vm>'s shares ones whose read-only flag is enforced outside the guest?
287新增:# Answered on the host, from the VM type and mount type Lima has for the VM,
288新增:# never by asking the guest: a compromised one would say whatever passes.
289新增:# agent-vm only changes the mount type of a stopped VM, so the config is what
290新增:# the VM runs with. 9p is enforced by QEMU (`readonly=on` on -virtfs).
291新增:# virtiofs is enforced on vz only, by Virtualization.framework: under QEMU,
292新增:# virtiofsd has no read-only mode and Lima passes none
293新增:# (virtio-fs/virtiofsd#97), so the flag only reaches the guest's fstab.
294新增:# reverse-sshfs is enforced only when served by the builtin SFTP server of a
295新增:# Lima with readonlyNames, which is answered from the mounts agent-vm last
296新增:# applied. Otherwise it only gets `-o ro` inside the guest, where root can
297新增:# remount it rw. Returns 0 (enforced), 1 (not enforced), or 2 (could not tell).
298新增:_agent_vm_mount_is_host_enforced() {
299新增: local types vmtype mtype
300新增: types="$(limactl list --format '{{.VMType}} {{.Config.MountType}}' "$1" 2>/dev/null)" || return 2
301新增: vmtype="${types%% *}"
302新增: mtype="${types#* }"
303新增: [[ "$types" == *" "* ]] || mtype=""
304新增: case "$mtype" in
305新增: ""|default|"<nil>"|"<no value>") mtype="$(_agent_vm_default_mount_type "$1" "$vmtype")" ;;
306新增: esac
307新增: case "$vmtype $mtype" in
308新增: "vz virtiofs"|"qemu 9p") return 0 ;;
309新增: "qemu virtiofs") return 1 ;;
310新增: # The record says agent-vm gave it readonlyNames, and the Lima installed
311新增: # now serves them: a stock limactl started by hand would not.
312新增: ?*" reverse-sshfs")
313新增: _agent_vm_mounts_protect_git "$1" && _agent_vm_lima_protects_git && return 0
314新增: return 1 ;;
315新增: *) return 2 ;;
316新增: esac
317新增:}
318新增:
319新增:# The mount type Lima gives <vm> (of VM type <vmtype>) when its config leaves
320新增:# it unset, as agent-vm does without the .git protection: the one Lima's
321新增:# _config/override.yaml or default.yaml sets, if any, else the one its driver
322新增:# picks at start (and `limactl list` shows unset): virtiofs on vz, 9p on QEMU
323新增:# except on Windows or for a VM made by a Lima before 1.0 (no lima-version
324新增:# file before 0.20). Nothing for another.
325新增:_agent_vm_default_mount_type() {
326新增: local ver f t
327新增: for f in override default; do
328新增: t="$(awk '/^mountType:/ { v = $2; gsub(/["\047]/, "", v); print v; exit }' \
329新增: "$(_agent_vm_lima_home)/_config/$f.yaml" 2>/dev/null)"
330新增: if [[ -n "$t" ]]; then
331新增: echo "$t"
332新增: return 0
333新增: fi
334新增: done
335新增: case "$2" in
336新增: vz) echo virtiofs ;;
337新增: qemu)
338新增: ver="$(cat "$(_agent_vm_lima_home)/$1/lima-version" 2>/dev/null)"
339新增: if _agent_vm_on_windows || [[ -z "$ver" ]] || ! _agent_vm_ver_ge "$ver" 1.0.0; then
340新增: echo reverse-sshfs
341新增: else
342新增: echo 9p
343新增: fi ;;
344新增: esac
345新增:}
346新增:
347新增:# 0 when <vm>, without the .git protection, would share through reverse-sshfs
348新增:# served by a Lima without readonlyNames. Lima's mount documentation says a
349新增:# compromised guest may then reach host paths outside the shares, through the
350新增:# SFTP server: not only .git is at stake, the rest of the disk is. On Windows
351新增:# always; elsewhere for a QEMU VM made by a Lima before 1.0. A VM not made yet
352新增:# is asked about the base template it is cloned from.
353新增:_agent_vm_unprotected_mount_is_sshfs() {
354新增: local vm="$1" vmtype
355新增: _agent_vm_on_windows && return 0
356新增: _agent_vm_exists "$vm" || vm="$AGENT_VM_TEMPLATE"
357新增: vmtype="$(limactl list --format '{{.VMType}}' "$vm" 2>/dev/null)" || return 1
358新增: [[ "$(_agent_vm_default_mount_type "$vm" "${vmtype%% *}")" == reverse-sshfs ]]
359新增:}
新增lib/options.sh+82 −0看文件
@@ -0,0 +1,82 @@
1新增:# --- options: agent-vm's own, for the commands that start a VM ----------------
2新增:
3新增:# Validate a positive-integer arg from the CLI (no retry: fail fast).
4新增:_agent_vm_validate_int() {
5新增: local name="$1" val="$2"
6新增: if [[ ! "$val" =~ ^[1-9][0-9]*$ ]]; then
7新增: echo "Error: $name must be a positive integer (got: '$val')" >&2
8新增: return 1
9新增: fi
10新增:}
11新增:
12新增:# --ssh-port: 0 gives the port back to Lima (a new one on each start). Below
13新增:# 1024 the host agent, which runs as the user, could not bind it.
14新增:_agent_vm_validate_port() {
15新增: local val="${1:-}"
16新增: if [[ "$val" == 0 ]] || { [[ "$val" =~ ^[1-9][0-9]*$ ]] && (( val >= 1024 && val <= 65535 )); }; then
17新增: return 0
18新增: fi
19新增: echo "Error: --ssh-port must be 0 or a port from 1024 to 65535 (got: '$val')" >&2
20新增: return 1
21新增:}
22新增:
23新增:# Reads the option at the start of "$@", if it is one of agent-vm's, and sets
24新增:# in the caller's scope (bash scopes locals dynamically):
25新增:# taken the number of words it used, 0 when "$1" is not an option
26新增:# vm_opts the option appended, as _agent_vm_ensure_running takes it
27新增:# rm 1 for --rm
28新增:# Values are checked here, so a typo like `--disk 10G` is one clear error and
29新增:# not a bash diagnostic later on. Returns 1 when a value is missing or wrong.
30新增:_agent_vm_take_opt() {
31新增: local opt="$1" val
32新增: taken=0
33新增: case "$opt" in
34新增: --disk|--memory|--ram|--cpus|--ssh-port)
35新增: if [[ $# -lt 2 ]]; then
36新增: echo "Error: $opt needs a value." >&2
37新增: return 1
38新增: fi
39新增: val="$2"; taken=2 ;;
40新增: --disk=*|--memory=*|--ram=*|--cpus=*|--ssh-port=*)
41新增: val="${opt#*=}"; opt="${opt%%=*}"; taken=1 ;;
42新增: --reset|--readonly|--scratch)
43新增: vm_opts+=("$opt"); taken=1; return 0 ;;
44新增: --unsafe-writable-git|--unsafe-writable-git=1)
45新增: vm_opts+=(--unsafe-writable-git); taken=1; return 0 ;;
46新增: --unsafe-disable-security-prompts)
47新增: vm_opts+=(--unsafe-disable-security-prompts); taken=1; return 0 ;;
48新增: --rm)
49新增: rm=1; taken=1; return 0 ;;
50新增: *)
51新增: return 0 ;;
52新增: esac
53新增: [[ "$opt" == --ram ]] && opt=--memory
54新增: if [[ "$opt" == --ssh-port ]]; then
55新增: _agent_vm_validate_port "$val" || return 1
56新增: else
57新增: _agent_vm_validate_int "$opt" "$val" || return 1
58新增: fi
59新增: vm_opts+=("$opt" "$val")
60新增:}
61新增:
62新增:# Splits "$@" into agent-vm's options (see _agent_vm_take_opt) and the
63新增:# command's own words, set as args in the caller's scope. Options are only read
64新增:# before the command: from the first other word on, everything belongs to it,
65新增:# so `run docker run --rm x` keeps its --rm. `--` ends the options, and --tty
66新增:# sets tty=1.
67新增:_agent_vm_split_args() {
68新增: local taken
69新增: while [[ $# -gt 0 ]]; do
70新增: _agent_vm_take_opt "$@" || return 1
71新增: if [[ $taken -gt 0 ]]; then
72新增: shift "$taken"
73新增: continue
74新增: fi
75新增: case "$1" in
76新增: --tty) tty=1; shift ;;
77新增: --) shift; break ;;
78新增: *) break ;;
79新增: esac
80新增: done
81新增: args=("$@")
82新增:}
新增lib/runtime.sh+57 −0看文件
@@ -0,0 +1,57 @@
1新增:# --- runtime scripts ----------------------------------------------------------
2新增:# Interpreter a runtime script asks for, read from its shebang: bash or sh,
3新增:# zsh otherwise. Only shells: the script is fed on stdin, read with -s. The
4新增:# program is the shebang's first word ("#!/bin/bash -e"), or after env, its
5新增:# options and assignments ("#!/usr/bin/env -S bash -e"). An awk program, so
6新增:# the VM runs the same one on a project's script, which only it reads (see
7新增:# _agent_vm_run_project_runtime).
8新增:_AGENT_VM_SHEBANG_AWK='
9新增: NR == 1 {
10新增: sub(/\r$/, "")
11新增: if (substr($0, 1, 2) == "#!") {
12新增: n = split(substr($0, 3), w)
13新增: for (i = 1; i < n; i++)
14新增: if (w[i] != "env" && w[i] !~ /\/env$/ && w[i] !~ /^-/ && w[i] !~ /=/) break
15新增: p = w[i]
16新增: sub(/.*\//, "", p)
17新增: }
18新增: exit
19新增: }
20新增: END { print ((p == "bash" || p == "sh") ? p : "zsh") }
21新增:'
22新增:_agent_vm_runtime_interpreter() {
23新增: awk "$_AGENT_VM_SHEBANG_AWK" "$1"
24新增:}
25新增:
26新增:# This project's runtime script (see _agent_vm_project_path).
27新增:_agent_vm_project_runtime_path() {
28新增: _agent_vm_project_path "$1" "${AGENT_VM_PROJECT_RUNTIME:-.agent-vm.runtime.sh}"
29新增:}
30新增:
31新增:# Run a runtime script the host reads (~/.agent-vm/runtime.sh, or a project's
32新增:# kept outside it) in the VM, piped in, CRs dropped (Git for Windows checks
33新增:# out CRLF), under the shell it declares, from a login zsh: the VM's PATH and
34新增:# ~/.agent-vm.env apply.
35新增:_agent_vm_run_runtime() {
36新增: local vm_name="$1" host_dir="$2" file="$3" interp
37新增: interp="$(_agent_vm_runtime_interpreter "$file")"
38新增: _agent_vm_strip_cr < "$file" \
39新增: | limactl shell --workdir "$host_dir" "$vm_name" zsh -lc "exec $interp -s"
40新增:}
41新增:
42新增:# A runtime script inside the project, run the same way but read by the VM, by
43新增:# its path: the host never reads it. The VM can make it a symlink, which on the
44新增:# host would lead to any file of the user's, and the content would go to the
45新增:# VM. In the VM, it resolves among the VM's own files. A script that is not
46新增:# there (any more) is skipped.
47新增:_agent_vm_run_project_runtime() {
48新增: local vm_name="$1" host_dir="$2" file="$3"
49新增: limactl shell --workdir "$host_dir" "$vm_name" zsh -lc \
50新增: '[ -f "$3" ] || exit 0; i="$(awk "$1" "$3")" && awk "$2" "$3" | "$i" -s' \
51新增: agent-vm "$_AGENT_VM_SHEBANG_AWK" '{ sub(/\r$/, ""); print }' "$file"
52新增:}
53新增:
54新增:# stdin to stdout without a CR at the end of each line.
55新增:_agent_vm_strip_cr() {
56新增: awk '{ sub(/\r$/, ""); print }'
57新增:}
新增lib/setup.sh+533 −0看文件
@@ -0,0 +1,533 @@
1新增:# --- setup: build the base template -------------------------------------------
2新增:
3新增:# Report a setup failure and leave nothing running. The half-provisioned
4新增:# template stays on disk on purpose (the next `setup` deletes and recreates
5新增:# it, and keeping it lets the user look inside), but it has no reason to keep
6新增:# burning CPU and RAM meanwhile.
7新增:_agent_vm_setup_aborted() {
8新增: echo "Error: $1" >&2
9新增: limactl stop "$AGENT_VM_TEMPLATE" &>/dev/null
10新增:}
11新增:
12新增:# _agent_vm_scroll_window <log>: copy stdin to <log>. On a terminal, show only
13新增:# the last 10 lines, redrawn in place and cleared at the end; otherwise pass
14新增:# every line through. Lines are cut to the terminal width, since a wrapped line
15新增:# would break the redraw, and colour codes are dropped, since a cut one would
16新增:# leave the terminal coloured. No fork per line: apt prints thousands of lines.
17新增:_agent_vm_scroll_window() {
18新增: local log="$1"
19新增: if [[ ! -t 1 ]]; then
20新增: tee -a "$log"
21新增: return 0
22新增: fi
23新增: local height=10 size width rows line rest buf="" n=0 drawn=0
24新增: # "rows cols". Not tput: with stdout captured and stderr silenced it has no
25新增: # terminal left to ask, and answers 80. Probed first, as in _agent_vm_box:
26新增: # without a terminal the open itself errors on stderr.
27新增: if _agent_vm_have_tty; then
28新增: size="$(stty size 2>/dev/null </dev/tty)"
29新增: else
30新增: size=""
31新增: fi
32新增: rows="${size% *}"; width="${size#* }"
33新增: [[ "$width" =~ ^[0-9]+$ && "$width" -gt 1 ]] || width=80
34新增: [[ "$rows" =~ ^[0-9]+$ ]] && [[ "$rows" -lt $((height + 2)) ]] && height=$((rows > 3 ? rows - 2 : 1))
35新增: while IFS= read -r line || [[ -n "$line" ]]; do
36新增: printf '%s\n' "$line" >&3
37新增: # A progress bar redraws with \r: keep what the last redraw left.
38新增: line="${line%$'\r'}"; line="${line##*$'\r'}"
39新增: # Lima logs `time="…" level=info msg="…" key=value`: the message is what
40新增: # fits and what says something.
41新增: if [[ "$line" == time=*' msg="'* ]]; then
42新增: line="${line#* msg=\"}"; line="${line%%\"*}"
43新增: fi
44新增: while [[ "$line" == *$'\e'* ]]; do
45新增: rest="${line#*$'\e'}"
46新增: line="${line%%$'\e'*}${rest#\[*[A-Za-z]}"
47新增: done
48新增: line="${line//$'\t'/ }"
49新增: line="${line:0:$((width - 1))}"
50新增: if [[ "$n" -lt "$height" ]]; then
51新增: n=$((n + 1))
52新增: else
53新增: buf="${buf#*$'\n'}"
54新增: fi
55新增: buf="$buf$line"$'\n'
56新增: [[ "$drawn" -gt 0 ]] && printf '\e[%dA' "$drawn"
57新增: printf '\r\e[J\e[2m%s\e[0m' "$buf"
58新增: drawn="$n"
59新增: done 3>>"$log"
60新增: [[ "$drawn" -gt 0 ]] && printf '\e[%dA\r\e[J' "$drawn"
61新增: return 0
62新增:}
63新增:
64新增:# _agent_vm_windowed <log> <command> [args...]: run the command, stdin
65新增:# included, with its output in _agent_vm_scroll_window and appended to <log>.
66新增:# Returns the command's status, which goes through a file: a pipeline returns
67新增:# its last command's. On failure,
68新增:# the end of the log is shown again, since the window is gone.
69新增:_agent_vm_windowed() {
70新增: local log="$1" status_file="$1.status" rc
71新增: shift
72新增: echo 1 >| "$status_file"
73新增: { "$@" 2>&1; echo $? >| "$status_file"; } | _agent_vm_scroll_window "$log"
74新增: rc="$(cat "$status_file" 2>/dev/null)"
75新增: rm -f "$status_file"
76新增: if [[ "$rc" != "0" ]]; then
77新增: [[ -t 1 ]] && tail -n 20 "$log" >&2
78新增: return 1
79新增: fi
80新增: return 0
81新增:}
82新增:
83新增:# Why the caller's install_* choices need Node.js, if they do: Codex and Pi
84新增:# install with npm, Chrome DevTools MCP runs with npx for the agents it is
85新增:# wired into.
86新增:_agent_vm_node_needed_by() {
87新增: if [[ "$install_codex" == 1 ]]; then
88新增: echo "Codex CLI requires npm"
89新增: elif [[ "$install_pi" == 1 ]]; then
90新增: echo "Pi requires npm"
91新增: elif [[ "$install_chromium" == 1 && "$install_mcp_chrome" == 1 \
92新增: && ( "$install_claude" == 1 || "$install_opencode" == 1 || "$install_vibe" == 1 ) ]]; then
93新增: echo "Chrome DevTools MCP uses npx"
94新增: fi
95新增: return 0
96新增:}
97新增:
98新增:_agent_vm_setup() {
99新增: local disk=10
100新增: local memory=3
101新增: local cpus=1
102新增: local preinstall=""
103新增: local preinstall_seen=""
104新增: # The default set, used without --preinstall when the wizard's first
105新增: # question is accepted or there is no terminal. Opt-in: Ruby, Rust, Go, Pi
106新增: # (0.x, released several times a week) and Playwright MCP (a second
107新增: # browser-driving server, whose tools cost context in every agent). Only MCP
108新增: # servers with something to bake into the image belong here; a remote one
109新增: # is per-project config.
110新增: local install_python=1 install_node=1
111新增: local install_ruby=0 install_rust=0 install_golang=0
112新增: local install_docker=1 install_chromium=1 install_gh=1
113新增: local install_claude=1 install_opencode=1 install_codex=1 install_vibe=1
114新增: local install_pi=0
115新增: local install_mcp_chrome=1 install_mcp_playwright=0
116新增:
117新增: local vm_opts=() rm="" taken
118新增: while [[ $# -gt 0 ]]; do
119新增: # The resources are read as for the other commands (see
120新增: # _agent_vm_take_opt); its other options are not setup's.
121新增: vm_opts=(); rm=""
122新增: _agent_vm_take_opt "$@" || return 1
123新增: if [[ $taken -gt 0 ]]; then
124新增: local opt="${vm_opts[*]-}"
125新增: case "$opt" in
126新增: "--disk "*) disk="${opt#--disk }" ;;
127新增: "--memory "*) memory="${opt#--memory }" ;;
128新增: "--cpus "*) cpus="${opt#--cpus }" ;;
129新增: *)
130新增: echo "Unknown option: ${1%%=*}" >&2
131新增: echo "Usage: agent-vm setup [--disk GB] [--memory GB] [--cpus N] [--preinstall=LIST]" >&2
132新增: return 1 ;;
133新增: esac
134新增: shift "$taken"
135新增: continue
136新增: fi
137新增: case "$1" in
138新增: --help|-h)
139新增: cat << 'EOF'
140新增:Usage: agent-vm setup [options]
141新增:
142新增:Create a base VM template with dev tools and agents pre-installed. Runs an
143新增:interactive wizard by default; the first prompt offers a "default install"
144新增:(everything except the opt-in Ruby, Rust, Go, Pi, Playwright MCP). Answer 'n' for
145新增:per-component prompts. Pass --preinstall=... to skip the wizard and pick a
146新增:specific subset non-interactively. When no terminal is available (e.g. CI),
147新增:the wizard is skipped automatically and the default set is installed.
148新增:
149新增:Options:
150新增: --disk GB VM disk size (default: 10)
151新增: --memory GB VM memory (default: 3)
152新增: --cpus N Number of CPUs (default: 1)
153新增: --preinstall=LIST Comma-separated list of tools to preinstall in the base
154新增: VM image (skips the wizard). Anything not listed is
155新增: skipped. Use:
156新增: 'default' for the default set
157新增: (everything except Ruby, Rust, Go, Pi,
158新增: mcp-playwright),
159新增: 'all' for everything,
160新增: 'none' for nothing.
161新增: Available names:
162新增: python, node, ruby, rust, golang, docker, chromium,
163新增: gh, claude, opencode, codex, vibe, pi, mcp-chrome,
164新增: mcp-playwright
165新增: Selecting codex or pi also installs node (npm). So does
166新增: mcp-chrome when chromium and an agent are selected
167新增: (npx). mcp-playwright does not: list node yourself.
168新增: The mcp-* names wire an MCP server into each installed
169新增: agent's config. Both 'mcp-chrome' (Chrome DevTools) and
170新增: 'mcp-playwright' drive the preinstalled Chromium, so
171新增: both need node and chromium and are skipped, with a
172新增: notice, without them. Pi has no MCP support, so they
173新增: are not wired into it. 'mcp-playwright' is opt-in and not
174新增: part of 'default': a second browser-driving server is
175新增: redundant for most users. Omit them to leave the agents'
176新增: MCP config untouched, for when MCP servers are
177新增: managed per project rather than baked into the image.
178新增: Examples:
179新增: --preinstall=default,rust # default set plus Rust
180新增: --preinstall=python,docker,claude
181新增: --preinstall=node,chromium,opencode # no chrome MCP
182新增: --help Show this help
183新增:EOF
184新增: return 0
185新增: ;;
186新增: --preinstall)
187新增: preinstall_seen=1
188新增: # Only consume the next argument as the value when it is an actual
189新增: # value, not another option. Bare `--preinstall` falls back to the
190新增: # default set (handled below) without swallowing e.g. a following
191新增: # `--disk`.
192新增: if [[ -n "${2:-}" && "$2" != -* ]]; then
193新增: preinstall="$2"
194新增: shift 2
195新增: else
196新增: shift
197新增: fi
198新增: ;;
199新增: --preinstall=*)
200新增: preinstall="${1#*=}"
201新增: preinstall_seen=1
202新增: shift
203新增: ;;
204新增: *)
205新增: echo "Unknown option: $1" >&2
206新增: echo "Usage: agent-vm setup [--disk GB] [--memory GB] [--cpus N] [--preinstall=LIST]" >&2
207新增: return 1
208新增: ;;
209新增: esac
210新增: done
211新增:
212新增: # Apply --preinstall=LIST: start with everything OFF and turn on what's
213新增: # listed. 'default' / 'all' / 'none' are shortcuts. Setting this also
214新增: # bypasses the interactive wizard below. `--preinstall=` with no value
215新增: # (or `--preinstall` swallowed by a following flag) falls back to the
216新增: # default set, explicitly opting into the wizard's recommended install.
217新增: # Pass `--preinstall=none` if you really want nothing.
218新增: if [[ -n "$preinstall_seen" ]]; then
219新增: install_python=0 install_node=0 install_ruby=0 install_rust=0 install_golang=0
220新增: install_docker=0 install_chromium=0 install_gh=0
221新增: install_claude=0 install_opencode=0 install_codex=0 install_vibe=0
222新增: install_pi=0
223新增: install_mcp_chrome=0 install_mcp_playwright=0
224新增: [[ -z "$preinstall" ]] && preinstall="default"
225新增: # Iterate the comma-list by appending a trailing comma and peeling off
226新增: # one token per iteration.
227新增: local rest="${preinstall}," f
228新增: while [[ -n "$rest" ]]; do
229新增: f="${rest%%,*}"
230新增: rest="${rest#*,}"
231新增: # Trim whitespace.
232新增: f="${f# }"; f="${f% }"
233新增: [[ -z "$f" ]] && continue
234新增: case "$f" in
235新增: all)
236新增: install_python=1 install_node=1 install_ruby=1
237新增: install_rust=1 install_golang=1
238新增: install_docker=1 install_chromium=1 install_gh=1
239新增: install_claude=1 install_opencode=1 install_codex=1 install_vibe=1
240新增: install_pi=1
241新增: install_mcp_chrome=1 install_mcp_playwright=1
242新增: ;;
243新增: default)
244新增: install_python=1 install_node=1
245新增: install_docker=1 install_chromium=1 install_gh=1
246新增: install_claude=1 install_opencode=1 install_codex=1 install_vibe=1
247新增: install_mcp_chrome=1
248新增: ;;
249新增: none) ;; # explicit no-op token; with the all-off reset above,
250新增: # `--preinstall=none` ships nothing.
251新增: python) install_python=1 ;;
252新增: node) install_node=1 ;;
253新增: ruby) install_ruby=1 ;;
254新增: rust) install_rust=1 ;;
255新增: golang) install_golang=1 ;;
256新增: docker) install_docker=1 ;;
257新增: chromium) install_chromium=1 ;;
258新增: gh) install_gh=1 ;;
259新增: claude) install_claude=1 ;;
260新增: opencode) install_opencode=1 ;;
261新增: codex) install_codex=1 ;;
262新增: vibe) install_vibe=1 ;;
263新增: pi) install_pi=1 ;;
264新增: mcp-chrome) install_mcp_chrome=1 ;;
265新增: mcp-playwright) install_mcp_playwright=1 ;;
266新增: *)
267新增: echo "Unknown preinstall name: $f (names are lowercase)" >&2
268新增: echo "Valid: python, node, ruby, rust, golang, docker, chromium, gh, claude, opencode, codex, vibe, pi, mcp-chrome, mcp-playwright, default, all, none" >&2
269新增: return 1
270新增: ;;
271新增: esac
272新增: done
273新增: fi
274新增:
275新增: # Fail-fast checks before the (potentially long) wizard so the user doesn't
276新增: # answer 15 prompts only to be told their host is missing Lima or KVM.
277新增: # Installing software on the host is asked, never assumed. Without a
278新增: # terminal to ask on, say what to run instead.
279新增: # The Lima that keeps .git read-only is offered first, so that it is not
280新增: # brew's lima installed now and replaced a minute later.
281新增: echo "Starting agent-vm setup..."
282新增: local declined_protection=""
283新增: if [[ -z "$(_agent_vm_limactl_path)" ]]; then
284新增: if _agent_vm_on_windows && _agent_vm_have_tty; then
285新增: if [[ "$(_agent_vm_ask_yn "Lima is not installed. Download the Lima build for Windows that keeps .git read-only (both zips, about 60 MB)?" Y)" == "1" ]]; then
286新增: _agent_vm_install_fork_windows || return 1
287新增: hash -r 2>/dev/null
288新增: fi
289新增: elif command -v brew &>/dev/null && _agent_vm_have_tty; then
290新增: if [[ "$(_agent_vm_ask_yn "Lima is not installed. Install it now with 'brew install $AGENT_VM_LIMA_FORMULA' (keeps .git read-only for the VMs, built from source)?" Y)" == "1" ]]; then
291新增: brew install "$AGENT_VM_LIMA_FORMULA" || return 1
292新增: else
293新增: declined_protection=1
294新增: if [[ "$(_agent_vm_ask_yn "Install brew's lima instead, which lets the VMs write .git?" Y)" == "1" ]]; then
295新增: brew install lima || return 1
296新增: echo "With this Lima, every start with writable shares will ask first ('agent-vm doctor' says why)." >&2
297新增: fi
298新增: fi
299新增: fi
300新增: if [[ -z "$(_agent_vm_limactl_path)" ]]; then
301新增: echo "Error: Lima is required." >&2
302新增: if _agent_vm_on_windows; then
303新增: echo " Run 'agent-vm setup' in a terminal: it offers the Lima build for Windows." >&2
304新增: echo " Or get it by hand at $(_agent_vm_lima_fork_release)" >&2
305新增: echo " (both Windows zips, verified, unpacked on PATH)." >&2
306新增: elif command -v brew &>/dev/null; then
307新增: echo " Install it with: brew install $AGENT_VM_LIMA_FORMULA" >&2
308新增: echo " (or brew install lima, which lets the VMs write .git)" >&2
309新增: else
310新增: echo " Install it from https://lima-vm.io/docs/installation/" >&2
311新增: fi
312新增: return 1
313新增: fi
314新增: fi
315新增:
316新增: _agent_vm_check_linux_prereqs || return 1
317新增: _agent_vm_check_windows_prereqs || return 1
318新增:
319新增: # Interactive wizard, unless --preinstall was passed or no terminal is
320新增: # attached (e.g. running under CI). Defaults shown in [] are prefilled from
321新增: # any --disk/--memory/--cpus flags the user already passed, so they can
322新增: # confirm or override. Components default to the "default install" set
323新增: # (everything except Ruby/Rust/Go). The first prompt offers that whole set
324新增: # as a one-tap shortcut; 'n' gives per-component prompts.
325新增: if [[ -z "$preinstall_seen" ]] && _agent_vm_have_tty; then
326新增: printf '\nagent-vm setup wizard\n' >&2
327新增: printf '─────────────────────\n\n' >&2
328新增: printf 'These settings apply to the base VM image. Every per-project VM is\n' >&2
329新增: printf 'cloned from it, so anything preinstalled here is available in all\n' >&2
330新增: printf 'future agent VMs. You can still install extra tools inside any\n' >&2
331新增: printf 'individual VM later (e.g. via `agent-vm shell`).\n\n' >&2
332新增: printf 'For more: https://www.agent-vm.org/\n\n' >&2
333新增:
334新增: # Software first: the more interesting choice for most users.
335新增: printf 'Software\n' >&2
336新增: printf '────────\n' >&2
337新增: printf ' Agents: Claude Code, OpenCode, Codex CLI, Mistral Vibe\n' >&2
338新增: printf ' Tools: Python, Node.js, Docker, Chromium, gh,\n' >&2
339新增: printf ' Chrome DevTools MCP\n' >&2
340新增: printf ' Skip: Pi, Ruby, Rust, Go, Playwright MCP\n\n' >&2
341新增: local use_default_software
342新增: use_default_software=$(_agent_vm_ask_yn "Use this default" Y)
343新增: if [[ "$use_default_software" != "1" ]]; then
344新增: printf '\nAI coding agents\n' >&2
345新增: printf '────────────────\n' >&2
346新增: install_claude=$(_agent_vm_ask_yn "Claude Code" Y)
347新增: install_opencode=$(_agent_vm_ask_yn "OpenCode" Y)
348新增: install_codex=$(_agent_vm_ask_yn "Codex CLI" Y)
349新增: install_vibe=$(_agent_vm_ask_yn "Mistral Vibe" Y)
350新增: install_pi=$(_agent_vm_ask_yn "Pi" N)
351新增:
352新增: printf '\nSystem tools\n' >&2
353新增: printf '────────────\n' >&2
354新增: install_docker=$(_agent_vm_ask_yn "Docker" Y)
355新增: install_chromium=$(_agent_vm_ask_yn "Chromium (headless browser)" Y)
356新增: install_gh=$(_agent_vm_ask_yn "GitHub CLI (gh)" Y)
357新增:
358新增: # MCP servers, wired into each installed agent's config. Chrome DevTools
359新增: # drives the Chromium above, so it is only worth asking when that is on.
360新增: # Playwright brings its own browser download, hence the N default.
361新增: install_mcp_chrome=0 install_mcp_playwright=0
362新增: if [[ "$install_chromium" == "1" ]]; then
363新增: install_mcp_chrome=$(_agent_vm_ask_yn "Chrome DevTools MCP (wired into each agent's config)" Y)
364新增: install_mcp_playwright=$(_agent_vm_ask_yn "Playwright MCP (also drives that Chromium)" N)
365新增: fi
366新增:
367新增: local node_forced_reason
368新增: node_forced_reason="$(_agent_vm_node_needed_by)"
369新增:
370新增: printf '\nLanguages\n' >&2
371新增: printf '─────────\n' >&2
372新增: install_python=$(_agent_vm_ask_yn "Python 3" Y)
373新增: if [[ -n "$node_forced_reason" ]]; then
374新增: install_node=1
375新增: printf 'Node.js 24: yes (%s)\n' "$node_forced_reason" >&2
376新增: else
377新增: install_node=$(_agent_vm_ask_yn "Node.js 24" Y)
378新增: fi
379新增: # Opt-in, like Pi and Playwright MCP: N unless asked for.
380新增: install_ruby=$(_agent_vm_ask_yn "Ruby" N)
381新增: install_rust=$(_agent_vm_ask_yn "Rust" N)
382新增: install_golang=$(_agent_vm_ask_yn "Go" N)
383新增: fi
384新增:
385新增: # Resources second, the same way, accepted in one go or not. Current
386新增: # values reflect any --disk/--memory/--cpus already passed on the CLI.
387新增: # These are starting values: any later `agent-vm` command can resize the
388新增: # per-project VM with --disk/--memory/--cpus.
389新增: printf '\nDefault resources\n' >&2
390新增: printf '─────────────────\n' >&2
391新增: printf '(per-VM override with --disk / --memory / --cpus on any agent-vm command)\n\n' >&2
392新增: printf ' Disk %s GB\n' "$disk" >&2
393新增: printf ' Memory %s GB\n' "$memory" >&2
394新增: printf ' CPUs %s\n\n' "$cpus" >&2
395新增: local use_default_resources
396新增: use_default_resources=$(_agent_vm_ask_yn "Use these defaults" Y)
397新增: if [[ "$use_default_resources" != "1" ]]; then
398新增: disk=$(_agent_vm_ask_int "Disk size in GB" "$disk")
399新增: memory=$(_agent_vm_ask_int "Memory in GB" "$memory")
400新增: cpus=$(_agent_vm_ask_int "Number of CPUs" "$cpus")
401新增: fi
402新增: printf '\n' >&2
403新增: fi
404新增:
405新增: # After the wizard: its questions are the familiar ones (which agents, how
406新增: # much RAM), this one is not, and a first run should not open on it. Still
407新增: # before the VM is created, since it can replace Lima. Announced, so a
408新增: # warning reads as the result of a check and not out of the blue.
409新增: # safe.bareRepository is checked on every start instead (see
410新增: # _agent_vm_check_bare_repo_setting).
411新增: echo "Running security checks..."
412新增: [[ -n "$declined_protection" ]] || _agent_vm_offer_git_protection
413新增:
414新增: # --preinstall can name what needs node without node.
415新增: local node_reason
416新增: node_reason="$(_agent_vm_node_needed_by)"
417新增: if [[ -n "$node_reason" && "$install_node" != "1" ]]; then
418新增: echo "Enabling Node.js because $node_reason." >&2
419新增: install_node=1
420新增: fi
421新增:
422新增: _agent_vm_clean_partial_state "$AGENT_VM_TEMPLATE"
423新增:
424新增: # Retire the marker with the base it describes, before anything can fail.
425新增: # It is only rewritten at the end of a successful setup, so leaving the old
426新增: # one in place would make an interrupted re-setup look like a ready base.
427新增: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-base-version" "$AGENT_VM_STATE_DIR/.agent-vm-base-built-by"
428新增:
429新增: limactl stop "$AGENT_VM_TEMPLATE" &>/dev/null
430新增: limactl delete "$AGENT_VM_TEMPLATE" --force &>/dev/null
431新增:
432新增: # Same clamp as the per-project path. Done here rather than at parse time so
433新增: # the wizard above still shows what was asked for.
434新增: cpus="$(_agent_vm_cap_resource cpus "$cpus")"
435新增: memory="$(_agent_vm_cap_resource memory "$memory")"
436新增: _agent_vm_warn_disk_space "$disk"
437新增:
438新增: echo "Creating base VM..."
439新增: local create_args=(
440新增: --set '.mounts=[]'
441新增: --disk="$disk"
442新增: --memory="$memory"
443新增: --cpus="$cpus"
444新增: --tty=false
445新增: # No Lima containerd: Docker (optional) ships its own, and Lima's unit in
446新增: # /usr/local shadows Docker's. Also skips unpacking nerdctl on every boot.
447新增: --containerd=none
448新增: )
449新增: # Every step from here shows its output in a 10-line window, all of it kept
450新增: # in one log for when something fails.
451新增: mkdir -p "$AGENT_VM_STATE_DIR"
452新增: local setup_log="$AGENT_VM_STATE_DIR/setup.log"
453新增: : >| "$setup_log"
454新增: if ! _agent_vm_windowed "$setup_log" \
455新增: limactl create --name="$AGENT_VM_TEMPLATE" template:debian-13 "${create_args[@]}" </dev/null; then
456新增: echo "Error: Failed to create base VM. Full log: $setup_log" >&2
457新增: return 1
458新增: fi
459新增:
460新增: _agent_vm_print_resources "$AGENT_VM_TEMPLATE"
461新增:
462新增: echo "Starting base VM (the first run downloads a Debian image)..."
463新增: if ! _agent_vm_windowed "$setup_log" limactl start "$AGENT_VM_TEMPLATE" </dev/null; then
464新增: echo "Error: Failed to start base VM. Full log: $setup_log" >&2
465新增: echo "Lima's own log: $(_agent_vm_lima_home)/$AGENT_VM_TEMPLATE/ha.stderr.log" >&2
466新增: _agent_vm_windows_start_hint "$setup_log" "$(_agent_vm_lima_home)/$AGENT_VM_TEMPLATE/ha.stderr.log"
467新增: return 1
468新增: fi
469新增:
470新增: # The setup script runs in the VM, the choices as `export` lines put before
471新增: # it on stdin. Without them, it installs the default set.
472新增: echo "Installing packages inside VM..."
473新增: if [[ ! -r "${AGENT_VM_SCRIPT_DIR}/agent-vm.setup.sh" ]]; then
474新增: echo "Error: Setup script not found at ${AGENT_VM_SCRIPT_DIR}/agent-vm.setup.sh" >&2
475新增: return 1
476新增: fi
477新增: {
478新增: printf 'export AGENT_VM_INSTALL_PYTHON=%s\n' "$install_python"
479新增: printf 'export AGENT_VM_INSTALL_NODE=%s\n' "$install_node"
480新增: printf 'export AGENT_VM_INSTALL_RUBY=%s\n' "$install_ruby"
481新增: printf 'export AGENT_VM_INSTALL_RUST=%s\n' "$install_rust"
482新增: printf 'export AGENT_VM_INSTALL_GOLANG=%s\n' "$install_golang"
483新增: printf 'export AGENT_VM_INSTALL_DOCKER=%s\n' "$install_docker"
484新增: printf 'export AGENT_VM_INSTALL_CHROMIUM=%s\n' "$install_chromium"
485新增: printf 'export AGENT_VM_INSTALL_GH=%s\n' "$install_gh"
486新增: printf 'export AGENT_VM_INSTALL_CLAUDE=%s\n' "$install_claude"
487新增: printf 'export AGENT_VM_INSTALL_OPENCODE=%s\n' "$install_opencode"
488新增: printf 'export AGENT_VM_INSTALL_CODEX=%s\n' "$install_codex"
489新增: printf 'export AGENT_VM_INSTALL_VIBE=%s\n' "$install_vibe"
490新增: printf 'export AGENT_VM_INSTALL_PI=%s\n' "$install_pi"
491新增: printf 'export AGENT_VM_INSTALL_MCP_CHROME=%s\n' "$install_mcp_chrome"
492新增: printf 'export AGENT_VM_INSTALL_MCP_PLAYWRIGHT=%s\n' "$install_mcp_playwright"
493新增: cat "${AGENT_VM_SCRIPT_DIR}/agent-vm.setup.sh"
494新增: } | _agent_vm_windowed "$setup_log" limactl shell "$AGENT_VM_TEMPLATE" bash -l \
495新增: || { _agent_vm_setup_aborted "Setup script failed. Full log: $setup_log"; return 1; }
496新增:
497新增: # Run user's custom setup script if it exists
498新增: local user_setup="$AGENT_VM_STATE_DIR/setup.sh"
499新增: if [ -f "$user_setup" ]; then
500新增: echo "Running custom setup from $user_setup..."
501新增: _agent_vm_strip_cr < "$user_setup" | limactl shell "$AGENT_VM_TEMPLATE" zsh -l \
502新增: || { _agent_vm_setup_aborted "Custom setup script failed."; return 1; }
503新增: fi
504新增:
505新增: # The ready marker only for a stopped template: Lima clones only a stopped
506新增: # instance, so every new project VM would fail on a base still running.
507新增: if ! _agent_vm_stop_vm "$AGENT_VM_TEMPLATE"; then
508新增: echo "Error: the base VM is set up but did not stop: 'limactl stop $AGENT_VM_TEMPLATE', then 'agent-vm setup' again." >&2
509新增: return 1
510新增: fi
511新增:
512新增: # Record base VM version so we can warn about stale clones
513新增: mkdir -p "$AGENT_VM_STATE_DIR"
514新增: # And which agent-vm built it, for `list` and the bases of 0.1.0, which
515新增: # wrote none (see _agent_vm_migrate_0_1).
516新增: printf '%s\n' "$AGENT_VM_VERSION" >| "$AGENT_VM_STATE_DIR/.agent-vm-base-built-by"
517新增: date +%s >| "$AGENT_VM_STATE_DIR/.agent-vm-base-version"
518新增:
519新增: echo ""
520新增: echo "Base VM ready. Try one of these in any project directory:"
521新增: echo " agent-vm shell"
522新增: [[ "$install_claude" == "1" ]] && echo " agent-vm claude"
523新增: [[ "$install_opencode" == "1" ]] && echo " agent-vm opencode"
524新增: [[ "$install_codex" == "1" ]] && echo " agent-vm codex"
525新增: [[ "$install_vibe" == "1" ]] && echo " agent-vm vibe"
526新增: [[ "$install_pi" == "1" ]] && echo " agent-vm pi"
527新增: # Only worth saying to someone who has a VM to re-clone: on a first install
528新增: # there is nothing to reset, and the advice reads like a missed step.
529新增: if [[ -n "$(_agent_vm_project_vms)" ]]; then
530新增: echo ""
531新增: echo "Note: Existing VMs were not updated. Use --reset to re-clone them from the new base."
532新增: fi
533新增:}
新增lib/ui.sh+144 −0看文件
@@ -0,0 +1,144 @@
1新增:# --- ui: prompts, boxes, terminal detection -----------------------------------
2新增:
3新增:# Can a terminal actually be opened? `-r /dev/tty` does not answer that: the
4新增:# device node is world-readable even with no controlling terminal (CI, cron),
5新增:# and only opening it fails.
6新增:_agent_vm_have_tty() {
7新增: ( exec </dev/tty ) 2>/dev/null
8新增:}
9新增:
10新增:# Prompt for a value with a default. Reads from /dev/tty so this still works
11新增:# when called inside command substitution. Writes the prompt to stderr and the
12新增:# answer (or the default if the user just pressed Enter) to stdout.
13新增:#
14新增:# `2>/dev/null` comes before `</dev/tty` in every read below: redirections
15新增:# apply left to right, so the other order prints the open error first.
16新增:_agent_vm_ask() {
17新增: local prompt="$1" default="$2" reply=""
18新增: printf ' %s [%s]: ' "$prompt" "$default" >&2
19新增: IFS= read -r reply 2>/dev/null </dev/tty || reply=""
20新增: printf '%s\n' "${reply:-$default}"
21新增:}
22新增:
23新增:# Yes/no prompt. Second arg is the default: Y or N (case-insensitive). Prints
24新增:# 1 (yes) or 0 (no) to stdout. Empty input picks the default.
25新增:_agent_vm_ask_yn() {
26新增: local prompt="$1" default="${2:-Y}" reply="" indicator
27新增: case "$default" in
28新增: [Yy]*) indicator="[Y/n]"; default=Y ;;
29新增: *) indicator="[y/N]"; default=N ;;
30新增: esac
31新增: printf ' %s %s: ' "$prompt" "$indicator" >&2
32新增: IFS= read -r reply 2>/dev/null </dev/tty || reply=""
33新增: reply="${reply:-$default}"
34新增: case "$reply" in
35新增: [Yy]*) printf '1\n' ;;
36新增: *) printf '0\n' ;;
37新增: esac
38新增:}
39新增:
40新增:# Can a question be asked, and seen? A terminal to read the answer from, and
41新增:# stderr, where the question goes, on a terminal too: a caller capturing
42新增:# stderr would otherwise wait on a question nobody sees.
43新增:_agent_vm_can_ask() {
44新增: _agent_vm_have_tty && [[ -t 2 ]]
45新增:}
46新增:
47新增:# Turn off the input modes a full-screen program in the VM may have left on
48新增:# the terminal, when it was killed or the SSH session dropped before it
49新增:# restored them: mouse tracking (1000, 1002, 1003, with the 1006 and 1015
50新增:# encodings), focus reports (1004), bracketed paste (2004), the kitty keyboard
51新增:# protocol (a pop, which resets the flags when it empties the stack) and
52新增:# xterm's modifyOtherKeys. Each one types escape sequences into the host
53新增:# shell otherwise. Also shows the cursor. No clear, no leaving the alternate
54新增:# screen: 1049l restores a saved cursor position, which moves the prompt.
55新增:_agent_vm_reset_term_modes() {
56新增: [[ -t 1 ]] || return 0
57新增: printf '\033[?1000l\033[?1002l\033[?1003l\033[?1006l\033[?1015l\033[?1004l\033[?2004l\033[<u\033[>4;0m\033[?25h'
58新增:}
59新增:
60新增:# What turned the security questions off, when something did:
61新增:# --unsafe-disable-security-prompts (_agent_vm_ensure_running sets
62新增:# _agent_vm_unsafe_no_prompts, as a local, for the flag), or
63新增:# AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1 in the shell. Never a file of
64新增:# the project, which the VM can write. Fails when they are on.
65新增:_agent_vm_prompts_disabled_by() {
66新增: if [[ -n "${_agent_vm_unsafe_no_prompts:-}" ]]; then
67新增: printf '%s\n' "--unsafe-disable-security-prompts"
68新增: elif [[ "${AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS:-}" == 1 ]]; then
69新增: printf '%s\n' "AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1"
70新增: else
71新增: return 1
72新增: fi
73新增:}
74新增:
75新增:# The question after a security warning: 0 to go on. No by default, and when
76新增:# it cannot be asked (_agent_vm_can_ask); yes when the questions are off.
77新增:_agent_vm_confirm_unsafe() {
78新增: local by
79新增: if by="$(_agent_vm_prompts_disabled_by)"; then
80新增: echo "Continuing: $by." >&2
81新增: return 0
82新增: fi
83新增: _agent_vm_can_ask && [[ "$(_agent_vm_ask_yn "Continue anyway?" N)" == "1" ]]
84新增:}
85新增:
86新增:# _agent_vm_wrap <width>: word-wrap stdin to <width> columns. Lines indented
87新增:# by two spaces are commands, kept whole so they can be copied.
88新增:_agent_vm_wrap() {
89新增: awk -v w="$1" '
90新增: /^ / || length($0) <= w { print; next }
91新增: {
92新增: line = ""; n = split($0, word, " ")
93新增: for (i = 1; i <= n; i++) {
94新增: if (line == "") line = word[i]
95新增: else if (length(line) + 1 + length(word[i]) <= w) line = line " " word[i]
96新增: else { print line; line = word[i] }
97新增: }
98新增: print line
99新增: }'
100新增:}
101新增:
102新增:# _agent_vm_box <title>: print stdin on stderr as a boxed notice, for the
103新增:# warnings and offers of setup and of a start: one paragraph per line,
104新增:# wrapped to the terminal (72 columns at most). A question asked right after reads as being about the box.
105新增:# No right border: it would need every line padded to its display width, which
106新增:# the shell does not know for non-ASCII text.
107新增:_agent_vm_box() {
108新增: local title="$1" size width rule n
109新增: # Probed first: asking stty outright prints the shell's own open error on
110新增: # stderr when there is no terminal, which a bare 2>/dev/null
111新增: # does not silence, since it is the redirection itself that fails.
112新增: if _agent_vm_have_tty; then
113新增: size="$(stty size 2>/dev/null </dev/tty)"
114新增: else
115新增: size=""
116新增: fi
117新增: width="${size#* }"
118新增: [[ "$width" =~ ^[0-9]+$ ]] || width=72
119新增: [[ "$width" -gt 72 ]] && width=72
120新增: [[ "$width" -lt 30 ]] && width=30
121新增: rule="$(printf '%*s' "$width" '' | tr ' ' '-')"
122新增: n=$((width - ${#title} - 4))
123新增: [[ "$n" -lt 1 ]] && n=1
124新增: {
125新增: printf '\n+- %s %s\n|\n' "$title" "${rule:0:$n}"
126新增: _agent_vm_wrap $((width - 2)) | sed 's/^/| /; s/ *$//'
127新增: printf '|\n+%s\n' "${rule:0:$((width - 1))}"
128新增: } >&2
129新增:}
130新增:
131新增:# Prompt for a positive integer with default. Re-prompts on invalid input.
132新增:# Used for disk/memory/cpus where a typo (e.g. "10G") would otherwise produce
133新增:# a cryptic limactl error several seconds later.
134新增:_agent_vm_ask_int() {
135新增: local prompt="$1" default="$2" reply
136新增: while true; do
137新增: reply=$(_agent_vm_ask "$prompt" "$default")
138新增: if [[ "$reply" =~ ^[1-9][0-9]*$ ]]; then
139新增: printf '%s\n' "$reply"
140新增: return 0
141新增: fi
142新增: printf ' (must be a positive integer, e.g. 10; got: %s)\n' "$reply" >&2
143新增: done
144新增:}
新增lib/vm.sh+474 −0看文件
@@ -0,0 +1,474 @@
1新增:# --- vm: naming, state, resources, SSH port -----------------------------------
2新增:
3新增:# An interrupted `limactl create` leaves ~/.lima/<vm> without lima.yaml, and
4新增:# every later limactl call on that name fails: removed first.
5新增:_agent_vm_clean_partial_state() {
6新增: local vm_name="$1"
7新增: local lima_dir
8新增: lima_dir="$(_agent_vm_lima_home)/$vm_name"
9新增: if [[ -d "$lima_dir" ]] && [[ ! -f "$lima_dir/lima.yaml" ]]; then
10新增: echo "Detected partial VM state at $lima_dir (no lima.yaml): cleaning up." >&2
11新增: rm -rf "$lima_dir"
12新增: fi
13新增:}
14新增:
15新增:# The directory argument of `name` and `info` as the other commands spell
16新增:# theirs, `$(pwd)` (logical): the VM name hashes that string, so `/tmp/` and
17新增:# `/tmp` must give one. A directory that does not exist is refused.
18新增:_agent_vm_abs_dir() {
19新增: local dir="${1:-$(pwd)}"
20新增: if [[ ! -d "$dir" ]]; then
21新增: echo "Error: no such directory: $dir" >&2
22新增: return 1
23新增: fi
24新增: dir="$(CDPATH= cd -- "$dir" >/dev/null && pwd)" || return 1
25新增: # A newline in it would forge lines of `info`'s key=value output (a folder
26新增: # the VM made, named "x<newline>security_questions=none"). Checked on the
27新增: # whole path, the current directory's included. Starting a VM there is
28新增: # refused anyway.
29新增: if [[ "$dir" == *[[:cntrl:]]* ]]; then
30新增: echo "Error: the directory name contains a control character." >&2
31新增: return 1
32新增: fi
33新增: printf '%s\n' "$dir"
34新增:}
35新增:
36新增:# Why Lima cannot be given <dir> as a share, on stdout; fails when it can.
37新增:# Whitespace: the mount fails silently, leaving a bare, root-owned mount
38新增:# point where every write fails. A quote, a backslash or a control character:
39新增:# the path is spliced into the mounts JSON of `limactl edit --set`, where it
40新增:# would end the string and add mounts of its own.
41新增:_agent_vm_unmountable_path() {
42新增: if [[ "$1" == *[[:space:]]* ]]; then
43新增: echo "contains whitespace, which Lima cannot mount"
44新增: elif [[ "$1" == *[\"\\]* || "$1" == *[[:cntrl:]]* ]]; then
45新增: echo "contains a quote, a backslash or a control character"
46新增: else
47新增: return 1
48新增: fi
49新增:}
50新增:
51新增:# Prints why <dir> must not be shared with a VM ("is, or contains, ..." or "is
52新增:# inside ..."), and returns 0, when it is or contains your home directory
53新增:# (dotfiles, SSH keys, every other project), or is, contains or is inside
54新增:# agent-vm itself (the host runs its files), agent-vm's state (every VM's env)
55新增:# or Lima's (the VMs' SSH key and disks, override.yaml adding mounts to every
56新增:# VM). A project inside the home directory is what is expected. Returns 1
57新增:# when it is none of them.
58新增:# Compared as physical paths: a share is the directory a path resolves to.
59新增:# And whatever the case where the file system ignores it: `cd /c/users/me`
60新增:# reaches the home directory in Git Bash, which keeps the spelling typed.
61新增:_agent_vm_unsafe_project() {
62新增: local dir p rp what
63新增: dir="$(CDPATH= cd -P -- "$1" 2>/dev/null && pwd)" || dir="$1"
64新增: dir="$(_agent_vm_fold "$dir")"
65新增: for what in "your home directory" "agent-vm itself" "agent-vm's state" "Lima's state"; do
66新增: case "$what" in
67新增: "your home directory") p="$HOME" ;;
68新增: "agent-vm itself") p="$AGENT_VM_SCRIPT_DIR" ;;
69新增: "agent-vm's state") p="$AGENT_VM_STATE_DIR" ;;
70新增: *) p="$(_agent_vm_lima_home)" ;;
71新增: esac
72新增: [[ -n "$p" ]] || continue
73新增: # Not resolved when it does not exist: as typed, never emptied, or every
74新增: # path would be inside it.
75新增: if rp="$(CDPATH= cd -P -- "$p" 2>/dev/null && pwd)" && [[ -n "$rp" ]]; then
76新增: p="$rp"
77新增: else
78新增: p="${p%/}"
79新增: fi
80新增: [[ -n "$p" ]] || continue
81新增: p="$(_agent_vm_fold "$p")"
82新增: case "${p%/}/" in
83新增: "${dir%/}/"*)
84新增: printf 'is, or contains, %s\n' "$what"
85新增: return 0 ;;
86新增: esac
87新增: [[ "$what" == "your home directory" ]] && continue
88新增: case "${dir%/}/" in
89新增: "${p%/}/"*)
90新增: printf 'is inside %s\n' "$what"
91新增: return 0 ;;
92新增: esac
93新增: done
94新增: return 1
95新增:}
96新增:
97新增:# Stop <vm> and check that it did: limactl's status does not say (it fails on
98新增:# a VM that was already stopped). 1 when it still runs or Lima cannot tell.
99新增:_agent_vm_stop_vm() {
100新增: local st=0
101新增: limactl stop "$1" </dev/null &>/dev/null
102新增: _agent_vm_running "$1" || st=$?
103新增: [[ "$st" -eq 1 ]]
104新增:}
105新增:
106新增:# SHA-256 of stdin, hex first. shasum ships with macOS and with perl on most
107新增:# Linux systems; minimal ones (Fedora, Arch containers) only have sha256sum.
108新增:# Both print the same digest, so a VM keeps its name across the two.
109新增:_agent_vm_sha256() {
110新增: if command -v shasum >/dev/null 2>&1; then
111新增: shasum -a 256
112新增: elif command -v sha256sum >/dev/null 2>&1; then
113新增: sha256sum
114新增: else
115新增: return 1
116新增: fi
117新增:}
118新增:
119新增:# Generate a deterministic VM name for a directory. Fails rather than print a
120新增:# name without its hash: two projects with the same basename would then share
121新增:# one VM, and see each other's files.
122新增:_agent_vm_name() {
123新增: local dir="${1:-$(pwd)}"
124新增: local hash
125新增: hash=$(echo -n "$dir" | _agent_vm_sha256 | cut -c1-8)
126新增: if [[ ! "$hash" =~ ^[0-9a-f]{8}$ ]]; then
127新增: echo "Error: cannot hash the directory name: install shasum or sha256sum." >&2
128新增: return 1
129新增: fi
130新增: local base
131新增: base=$(basename "$dir" | tr -cs 'a-zA-Z0-9' '-' | sed 's/^-//;s/-$//')
132新增: echo "agent-vm-${base}-${hash}"
133新增:}
134新增:
135新增:# A name for a --scratch VM started in <dir>: its own, so it is never the
136新增:# folder's VM and several can run at once. Short enough for Lima (76
137新增:# characters, and a socket path under ~/.lima of at most 104 on macOS).
138新增:_agent_vm_scratch_name() {
139新增: local base rand
140新增: base=$(basename "$1" | tr -cs 'a-zA-Z0-9' '-' | cut -c1-20 | sed 's/^-*//;s/-*$//')
141新增: rand="$(od -An -N4 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n')"
142新增: if [[ ! "$rand" =~ ^[0-9a-f]{8}$ ]]; then
143新增: echo "Error: cannot read /dev/urandom to name the VM." >&2
144新增: return 1
145新增: fi
146新增: echo "agent-vm-${base:-project}-scratch-$rand"
147新增:}
148新增:
149新增:# Where a --scratch run records its VM, with the pid of the shell running it.
150新增:_agent_vm_scratch_marker() {
151新增: printf '%s/.agent-vm-scratch-%s\n' "$AGENT_VM_STATE_DIR" "$1"
152新增:}
153新增:
154新增:# --scratch VMs a run could not delete (killed, its terminal closed), one per
155新增:# line: recorded by a run whose pid is gone. A reused pid only delays the
156新增:# cleanup. Only names _agent_vm_scratch_name makes: these are deleted unasked.
157新增:_agent_vm_scratch_leftovers() {
158新增: local f pid vm
159新增: find "$AGENT_VM_STATE_DIR" -maxdepth 1 -name '.agent-vm-scratch-*' 2>/dev/null \
160新增: | while IFS= read -r f; do
161新增: vm="${f##*/.agent-vm-scratch-}"
162新增: [[ "$vm" =~ ^agent-vm-[A-Za-z0-9-]+-scratch-[0-9a-f]{8}$ ]] || continue
163新增: pid="$(cat "$f" 2>/dev/null)"
164新增: [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null && continue
165新增: printf '%s\n' "$vm"
166新增: done
167新增:}
168新增:
169新增:# Exact-line match against an already-captured string, with no pipe: under a
170新增:# caller's pipefail, `limactl list | grep -q` fails when grep exits before
171新增:# limactl is done (SIGPIPE), a VM then read as missing.
172新增:_agent_vm_has_line() {
173新增: case $'\n'"$1"$'\n' in
174新增: *$'\n'"$2"$'\n'*) return 0 ;;
175新增: *) return 1 ;;
176新增: esac
177新增:}
178新增:
179新增:# Check if a VM exists (any state).
180新增:# 0 = yes · 1 = no · 2 = could not ask (limactl itself failed).
181新增:# The third status matters: an empty answer from a failed query is otherwise
182新增:# indistinguishable from "no such VM", and `info` would report a confident 0.
183新增:_agent_vm_exists() {
184新增: local list
185新增: list="$(limactl list -q 2>/dev/null)" || return 2
186新增: _agent_vm_has_line "$list" "$1"
187新增:}
188新增:
189新增:# Check if a VM is running. Same three statuses as _agent_vm_exists.
190新增:_agent_vm_running() {
191新增: local list
192新增: list="$(limactl list --format '{{.Name}} {{.Status}}' 2>/dev/null)" || return 2
193新增: _agent_vm_has_line "$list" "$1 Running"
194新增:}
195新增:
196新增:# Whether the base template exists and can be cloned from, with the statuses
197新增:# of _agent_vm_exists. An interrupted setup leaves a template without its
198新增:# packages: only its marker, written at the very end, says it is usable.
199新增:_agent_vm_base_exists() {
200新增: _agent_vm_exists "$AGENT_VM_TEMPLATE" || return $?
201新增: [[ -f "$AGENT_VM_STATE_DIR/.agent-vm-base-version" ]]
202新增:}
203新增:
204新增:# Turn one of those exit statuses into the value `info` publishes.
205新增:_agent_vm_tristate() {
206新增: case "$1" in
207新增: 0) echo 1 ;;
208新增: 1) echo 0 ;;
209新增: *) echo unknown ;;
210新增: esac
211新增:}
212新增:
213新增:# Was <vm_name> cloned from an older base than the current one?
214新增:# Prints 1 (stale), 0 (up to date), or "unknown" when there is nothing recorded
215新增:# to compare against, never a guess from a missing file. A VM with no version
216新增:# marker but a known base predates the marker, which makes it stale.
217新增:_agent_vm_stale_state() {
218新增: local vm_name="$1"
219新增: local base_ver="$AGENT_VM_STATE_DIR/.agent-vm-base-version"
220新增: local vm_ver="$AGENT_VM_STATE_DIR/.agent-vm-version-${vm_name}"
221新增: if [[ ! -f "$base_ver" ]]; then
222新增: echo unknown
223新增: elif [[ ! -f "$vm_ver" ]]; then
224新增: echo 1
225新增: elif [[ "$(cat "$base_ver" 2>/dev/null)" != "$(cat "$vm_ver" 2>/dev/null)" ]]; then
226新增: echo 1
227新增: else
228新增: echo 0
229新增: fi
230新增:}
231新增:
232新增:# Remove all per-VM state files (version marker, terminfo cache, file mount
233新增:# cache, staging dirs). Called after a VM is deleted or before it is re-cloned
234新增:# via --reset.
235新增:_agent_vm_cleanup_state() {
236新增: local vm_name="$1"
237新增: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-version-${vm_name}"
238新增: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-built-by-${vm_name}"
239新增: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-sshfs-${vm_name}"
240新增: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-term-${vm_name}"
241新增: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-file-mounts-${vm_name}"
242新增: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-mounts-${vm_name}"
243新增: rm -f "$(_agent_vm_scratch_marker "$vm_name")"
244新增: rm -rf "$AGENT_VM_STATE_DIR/file-mounts/${vm_name}"
245新增: # Deleting the template retires the marker that says it is usable.
246新增: if [[ "$vm_name" == "$AGENT_VM_TEMPLATE" ]]; then
247新增: rm -f "$AGENT_VM_STATE_DIR/.agent-vm-base-version" "$AGENT_VM_STATE_DIR/.agent-vm-base-built-by"
248新增: fi
249新增:}
250新增:
251新增:# Stop and delete <vm_name>, then forget its state. Fails, saying so, when
252新增:# Lima still lists it (or cannot be asked): --reset would otherwise go on with
253新增:# the old VM and the shares it was given, which a changed ~/.agent-vm/volumes
254新增:# may no longer allow. limactl gets /dev/null as stdin, for callers reading
255新增:# names from theirs.
256新增:_agent_vm_delete_vm() {
257新增: local vm_name="$1" st=0
258新增: limactl stop "$vm_name" </dev/null &>/dev/null
259新增: limactl delete "$vm_name" --force </dev/null &>/dev/null
260新增: _agent_vm_exists "$vm_name" || st=$?
261新增: if [[ "$st" -ne 1 ]]; then
262新增: echo "Error: could not delete VM '$vm_name'. See 'limactl list', then retry." >&2
263新增: return 1
264新增: fi
265新增: _agent_vm_cleanup_state "$vm_name"
266新增:}
267新增:
268新增:# Current resources of <vm_name> as "cpus|memory_bytes|disk_bytes".
269新增:# Prints nothing (and returns 1) when the VM is unknown to Lima or answers
270新增:# non-numeric values. No pipe into grep/head: see _agent_vm_has_line for why
271新增:# that is unsafe under pipefail.
272新增:_agent_vm_resources_bytes() {
273新增: local vm_name="$1" all line
274新增: all="$(limactl list --format '{{.Name}}|{{.CPUs}}|{{.Memory}}|{{.Disk}}' 2>/dev/null || true)"
275新增: while IFS= read -r line; do
276新增: case "$line" in
277新增: "${vm_name}|"*)
278新增: local cpus mem_bytes disk_bytes
279新增: IFS='|' read -r _ cpus mem_bytes disk_bytes <<< "$line"
280新增: [[ "$cpus" =~ ^[0-9]+$ ]] || return 1
281新增: [[ "$mem_bytes" =~ ^[0-9]+$ ]] || return 1
282新增: [[ "$disk_bytes" =~ ^[0-9]+$ ]] || return 1
283新增: printf '%s|%s|%s\n' "$cpus" "$mem_bytes" "$disk_bytes"
284新增: return 0 ;;
285新增: esac
286新增: done <<< "$all"
287新增: return 1
288新增:}
289新增:
290新增:# Current resources of <vm_name> as "cpus|memory_gib|disk_gib", for display.
291新增:# GiB values are truncated: only use this for printing, never for comparing
292新增:# (see _agent_vm_resources_differ).
293新增:_agent_vm_resources() {
294新增: local raw cpus mem_bytes disk_bytes
295新增: raw="$(_agent_vm_resources_bytes "$1")" || return 1
296新增: IFS='|' read -r cpus mem_bytes disk_bytes <<< "$raw"
297新增: printf '%s|%s|%s\n' "$cpus" "$((mem_bytes / 1073741824))" "$((disk_bytes / 1073741824))"
298新增:}
299新增:
300新增:# Print VM resource details (CPUs, memory, disk), and when the base the VM was
301新增:# cloned from was built: its agents and packages are that old.
302新增:_agent_vm_print_resources() {
303新增: local res cpus mem_gib disk_gib built day
304新增: if res="$(_agent_vm_resources "$1")"; then
305新增: IFS='|' read -r cpus mem_gib disk_gib <<< "$res"
306新增: echo " Resources: CPUs: ${cpus}, Memory: ${mem_gib} GiB, Disk: ${disk_gib} GiB"
307新增: fi
308新增: # The base's timestamp, copied when this VM was cloned. None for the base
309新增: # itself, or for a VM cloned before it was recorded.
310新增: built="$(cat "$AGENT_VM_STATE_DIR/.agent-vm-version-$1" 2>/dev/null)"
311新增: [[ "$built" =~ ^[0-9]+$ ]] || return 0
312新增: day="$(_agent_vm_epoch_date "$built" +%F)" || return 0
313新增: echo " Base VM: built $day"
314新增:}
315新增:
316新增:# Epoch <t> formatted with <format>, in the local zone. GNU date takes -r for
317新增:# a file: a file named <t> in the current directory, which the VM can write,
318新增:# would answer. So -d there, -r for BSD date, and either for busybox.
319新增:_agent_vm_epoch_date() {
320新增: if date --version >/dev/null 2>&1; then
321新增: date -d "@$1" "$2" 2>/dev/null
322新增: else
323新增: date -r "$1" "$2" 2>/dev/null || date -d "@$1" "$2" 2>/dev/null
324新增: fi
325新增:}
326新增:
327新增:# The base <vm> was cloned from, for `list`: the agent-vm version that built
328新增:# it and the day. The base template describes itself. 0.1.0 recorded no
329新增:# version: a base without one was built by it.
330新增:_agent_vm_base_label() {
331新增: local ver_file="$AGENT_VM_STATE_DIR/.agent-vm-version-$1"
332新增: local by_file="$AGENT_VM_STATE_DIR/.agent-vm-built-by-$1"
333新增: local built by day=""
334新增: if [[ "$1" == "$AGENT_VM_TEMPLATE" ]]; then
335新增: ver_file="$AGENT_VM_STATE_DIR/.agent-vm-base-version"
336新增: by_file="$AGENT_VM_STATE_DIR/.agent-vm-base-built-by"
337新增: fi
338新增: built="$(cat "$ver_file" 2>/dev/null)"
339新增: by="$(cat "$by_file" 2>/dev/null)"
340新增: [[ "$by" =~ ^[0-9A-Za-z.+-]+$ ]] || by=0.1.0
341新增: [[ "$built" =~ ^[0-9]+$ ]] && day="$(_agent_vm_epoch_date "$built" +%F)"
342新增: printf '%s %s\n' "$by" "${day:--}"
343新增:}
344新增:
345新增:# agent-vm 0.1.0 made its VMs, and its bases, without sshfs and without the
346新增:# wrapper agent-vm.setup.sh installs, and gave them Lima's default mount type.
347新增:# Moved to reverse-sshfs to keep .git read-only, such a VM would get Debian's
348新增:# sshfs from Lima's boot scripts, which refuses absolute and ".." symlinks
349新增:# (node_modules/.bin), and only with apt reachable during the boot. So it
350新增:# boots once with no shares (nothing writable before its shares are
351新增:# protected), gets both, and stops. To be removed in a future release.
352新增:_agent_vm_migrate_0_1() {
353新增: local vm_name="$1" out
354新增: if ! out=$(cd /tmp && limactl edit "$vm_name" --set 'del(.mountType) | .mounts = []' 2>&1); then
355新增: echo "Error: could not remove the shares of '$vm_name' to install sshfs:" >&2
356新增: echo "$out" >&2
357新增: return 1
358新增: fi
359新增: echo "Starting VM '$vm_name' without shares to install sshfs..."
360新增: if ! out=$(limactl start "$vm_name" 2>&1); then
361新增: echo "Error: Failed to start VM '$vm_name' to install sshfs:" >&2
362新增: echo "$out" >&2
363新增: return 1
364新增: fi
365新增: # The same wrapper as agent-vm.setup.sh. sudo drops the proxy settings on
366新增: # these VMs (no env_keep before 0.2.0), so they are passed to apt by name.
367新增: # shellcheck disable=SC2016
368新增: if ! out=$(limactl shell --workdir / "$vm_name" sh -c '
369新增: set -e
370新增: if [ ! -x /usr/bin/sshfs ]; then
371新增: set -- DEBIAN_FRONTEND=noninteractive
372新增: for v in http_proxy https_proxy no_proxy HTTP_PROXY HTTPS_PROXY NO_PROXY; do
373新增: eval "x=\${$v-}"
374新增: [ -z "$x" ] || set -- "$@" "$v=$x"
375新增: done
376新增: sudo env "$@" apt-get -o DPkg::Lock::Timeout=120 update
377新增: sudo env "$@" apt-get -o DPkg::Lock::Timeout=120 install -y --no-install-recommends sshfs
378新增: fi
379新增: sudo tee /usr/local/bin/sshfs > /dev/null <<"EOF"
380新增:#!/bin/sh
381新增:# Installed by agent-vm: see agent-vm.setup.sh.
382新增:if /usr/bin/sshfs -h 2>&1 | grep -q no_contain_symlinks; then
383新增: exec /usr/bin/sshfs "$@" -o no_contain_symlinks
384新增:fi
385新增:exec /usr/bin/sshfs "$@"
386新增:EOF
387新增: sudo chmod 755 /usr/local/bin/sshfs' </dev/null 2>&1); then
388新增: echo "Error: could not install sshfs in VM '$vm_name':" >&2
389新增: echo "$out" | tail -n 20 >&2
390新增: _agent_vm_stop_vm "$vm_name"
391新增: return 1
392新增: fi
393新增: if ! _agent_vm_stop_vm "$vm_name"; then
394新增: echo "Error: could not stop VM '$vm_name' after installing sshfs." >&2
395新增: return 1
396新增: fi
397新增:}
398新增:
399新增:# Called on the stopped <vm> before it is given protected shares: migrates it
400新增:# (see above) when it comes from a base built by 0.1.0, which recorded no
401新增:# version, and was not migrated yet. Made by 0.1.0 or cloned by 0.2.0 from
402新增:# such a base: neither has the version of its base recorded.
403新增:_agent_vm_migrate_0_1_if_needed() {
404新增: local vm_name="$1"
405新增: [[ -f "$AGENT_VM_STATE_DIR/.agent-vm-built-by-$vm_name" ]] && return 0
406新增: [[ -f "$AGENT_VM_STATE_DIR/.agent-vm-sshfs-$vm_name" ]] && return 0
407新增: echo "Warning: VM '$vm_name' comes from a base built by agent-vm 0.1.0, without the sshfs of the shares that keep .git read-only. It boots once without shares to install it. This migration will be removed in a future release: 'agent-vm setup', then '--reset', gives a VM from a current base." >&2
408新增: _agent_vm_migrate_0_1 "$vm_name" || return 1
409新增: mkdir -p "$AGENT_VM_STATE_DIR" && : > "$AGENT_VM_STATE_DIR/.agent-vm-sshfs-$vm_name"
410新增:}
411新增:
412新增:# Would the requested resources actually change anything on <vm_name>?
413新增:# Empty request fields mean "not specified". Returns 0 when something differs
414新增:# (or when the current values can't be read: never claim "no change" from
415新增:# missing information), 1 when the VM already matches the request.
416新增:#
417新增:# Compared in bytes, not in truncated GiB: a VM holding a fractional size
418新增:# (set outside agent-vm, or by an older agent-vm) must converge to the
419新增:# requested integer GiB with one apply, not be misread as already matching
420新增:# it on every call.
421新增:#
422新增:# Disk is compared one-way on purpose: Lima can grow a disk but not shrink it,
423新增:# so a request below the current size is not a change that stopping could apply.
424新增:_agent_vm_resources_differ() {
425新增: local vm_name="$1" want_cpus="$2" want_mem="$3" want_disk="$4"
426新增: local cur cur_cpus cur_mem_bytes cur_disk_bytes
427新增: if ! cur="$(_agent_vm_resources_bytes "$vm_name")"; then
428新增: return 0
429新增: fi
430新增: IFS='|' read -r cur_cpus cur_mem_bytes cur_disk_bytes <<< "$cur"
431新增: if [[ -n "$want_cpus" && "$want_cpus" != "$cur_cpus" ]]; then
432新增: return 0
433新增: fi
434新增: # Requested values are validated integers where they are parsed, so a
435新增: # non-integer here is treated as "cannot tell", not as "no change".
436新增: if [[ -n "$want_mem" ]]; then
437新增: [[ "$want_mem" =~ ^[0-9]+$ ]] || return 0
438新增: [[ "$((10#$want_mem * 1073741824))" != "$cur_mem_bytes" ]] && return 0
439新增: fi
440新增: if [[ -n "$want_disk" ]]; then
441新增: [[ "$want_disk" =~ ^[0-9]+$ ]] || return 0
442新增: [[ "$((10#$want_disk * 1073741824))" -gt "$cur_disk_bytes" ]] && return 0
443新增: fi
444新增: return 1
445新增:}
446新增:
447新增:# The SSH port set in <vm_name>'s config, 0 when Lima picks one on each start.
448新增:# Empty when it cannot be read.
449新增:_agent_vm_ssh_port_config() {
450新增: local port
451新增: port="$(limactl list "$1" --format '{{.Config.SSH.LocalPort}}' 2>/dev/null)" || return 1
452新增: [[ "$port" =~ ^[0-9]+$ ]] || return 1
453新增: echo "$port"
454新增:}
455新增:
456新增:# 0 when --ssh-port <port> asks for a change to <vm_name>. A config that cannot
457新增:# be read is left alone, with a warning, rather than stopping the VM each run.
458新增:_agent_vm_ssh_port_differs() {
459新增: local vm_name="$1" want="$2" have
460新增: [[ -n "$want" ]] || return 1
461新增: if ! have="$(_agent_vm_ssh_port_config "$vm_name")"; then
462新增: echo "Warning: cannot read the SSH port of VM '$vm_name'; --ssh-port $want is not applied." >&2
463新增: return 1
464新增: fi
465新增: [[ "$have" != "$want" ]]
466新增:}
467新增:
468新增:# The agent-vm VMs other than the base template, one per line. Empty when
469新增:# there are none, or when limactl cannot answer.
470新增:_agent_vm_project_vms() {
471新增: local list
472新增: list="$(limactl list -q 2>/dev/null)" || return 0
473新增: printf '%s\n' "$list" | grep "^agent-vm-" | grep -v "^${AGENT_VM_TEMPLATE}\$" || true
474新增:}
新增release.sh+269 −0看文件
@@ -0,0 +1,269 @@
1新增:#!/usr/bin/env bash
2新增:#
3新增:# Cut an agent-vm release.
4新增:#
5新增:# ./release.sh X.Y.Z check, then tag, push and publish
6新增:# ./release.sh X.Y.Z --dry-run run every check, change nothing
7新增:# ./release.sh X.Y.Z --yes no confirmation prompt
8新增:# ./release.sh notes X.Y.Z print that version's CHANGELOG.md section
9新增:#
10新增:# It bumps and commits nothing. First, in an ordinary commit on main: set
11新增:# AGENT_VM_VERSION in agent-vm.sh and add a "## X.Y.Z" section to CHANGELOG.md.
12新增:# Push it and let CI pass. This script then checks that commit and publishes it:
13新增:#
14新增:# 1. clean tree, on main, level with origin/main, tag vX.Y.Z not taken (or
15新增:# already on this commit with no release: a failed run, resumed at 5)
16新增:# 2. agent-vm.sh reports X.Y.Z, CHANGELOG.md has a non-empty X.Y.Z section
17新增:# 3. the test workflow passed on this commit, and ./test.sh passes here
18新增:# 4. annotated tag vX.Y.Z, pushed
19新增:# 5. GitHub release: the CHANGELOG section as notes, plus a tarball made by
20新增:# `git archive` (without www/ and the tests) and its SHA256SUMS. The tarball is built here, so its
21新增:# checksum does not depend on how GitHub generates archives.
22新增:# 6. the url and sha256 lines for the Homebrew formula. With
23新增:# AGENT_VM_TAP=<path to a homebrew-tap clone>, Formula/agent-vm.rb there
24新增:# (checked to exist before step 1) is updated too, and the commands to
25新增:# commit it are printed.
26新增:#
27新增:# Needs git, gh (logged in) and shasum or sha256sum. A dry run reads origin
28新增:# without fetching, and without gh skips the checks that need it, with a
29新增:# warning.
30新增:
31新增:set -euo pipefail
32新增:
33新增:REPO_DIR="$(CDPATH= cd -P -- "$(dirname "${BASH_SOURCE[0]:-$0}")" >/dev/null && pwd)"
34新增:BRANCH="${RELEASE_BRANCH:-main}"
35新增:
36新增:c_g=''; c_y=''; c_r=''; c_0=''
37新增:if [ -t 1 ]; then c_g=$'\033[32m'; c_y=$'\033[33m'; c_r=$'\033[31m'; c_0=$'\033[0m'; fi
38新增:ok() { printf '%s✓%s %s\n' "$c_g" "$c_0" "$*"; }
39新增:warn() { printf '%s!%s %s\n' "$c_y" "$c_0" "$*"; }
40新增:die() { printf '%s✗%s %s\n' "$c_r" "$c_0" "$*" >&2; exit 1; }
41新增:
42新增:usage() {
43新增: sed -n '5,8p' "$0" | sed 's/^# \{0,1\}//' >&2
44新增: exit 2
45新增:}
46新增:
47新增:valid_version() {
48新增: [[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]
49新增:}
50新增:
51新增:# The "## X.Y.Z" section of CHANGELOG.md, without its heading and without
52新增:# leading or trailing blank lines. Empty when there is none.
53新增:changelog_notes() {
54新增: awk -v v="$1" '
55新增: /^## / { if (inside) exit; inside = ($2 == v); next }
56新增: inside { lines[++n] = $0 }
57新增: END {
58新增: first = 1; while (first <= n && lines[first] ~ /^[ \t]*$/) first++
59新增: last = n; while (last >= first && lines[last] ~ /^[ \t]*$/) last--
60新增: for (i = first; i <= last; i++) print lines[i]
61新增: }
62新增: ' "$REPO_DIR/CHANGELOG.md"
63新增:}
64新增:
65新增:sha256_of() {
66新增: if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1
67新增: elif command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
68新增: else die "neither shasum nor sha256sum is installed"
69新增: fi
70新增:}
71新增:
72新增:# Show a command, then run it, unless this is a dry run.
73新增:run() {
74新增: printf ' $ %s\n' "$*"
75新增: [ -n "$DRY_RUN" ] || "$@"
76新增:}
77新增:
78新增:# --- arguments -----------------------------------------------------------------
79新增:[ $# -ge 1 ] || usage
80新增:if [ "$1" = "notes" ]; then
81新增: [ $# -eq 2 ] && valid_version "$2" || usage
82新增: notes="$(changelog_notes "$2")"
83新增: [ -n "$notes" ] || die "CHANGELOG.md has no '## $2' section, or it is empty"
84新增: printf '%s\n' "$notes"
85新增: exit 0
86新增:fi
87新增:
88新增:VERSION="$1"; shift
89新增:valid_version "$VERSION" || die "not a version: '$VERSION' (expected X.Y.Z)"
90新增:TAG="v$VERSION"
91新增:DRY_RUN=""; ASSUME_YES=""
92新增:while [ $# -gt 0 ]; do
93新增: case "$1" in
94新增: --dry-run) DRY_RUN=1 ;;
95新增: --yes) ASSUME_YES=1 ;;
96新增: *) usage ;;
97新增: esac
98新增: shift
99新增:done
100新增:
101新增:cd "$REPO_DIR"
102新增:command -v git >/dev/null 2>&1 || die "git is required"
103新增:# A dry run changes nothing, here included: no fetch (origin is read with
104新增:# ls-remote), and gh only for reading, skipped with a warning when it is
105新增:# missing or not logged in.
106新增:GH=1
107新增:if ! command -v gh >/dev/null 2>&1 || ! gh auth status >/dev/null 2>&1; then
108新增: [ -n "$DRY_RUN" ] || die "gh is required, and logged in"
109新增: GH=""
110新增: warn "gh is missing or not logged in: the checks that need it are skipped"
111新增:fi
112新增:
113新增:# Checked now, not at step 6: by then the tag is pushed and the release out.
114新增:if [ -n "${AGENT_VM_TAP:-}" ]; then
115新增: FORMULA="$AGENT_VM_TAP/Formula/agent-vm.rb"
116新增: [ -f "$FORMULA" ] || die "no formula at $FORMULA (AGENT_VM_TAP): create it first, or unset AGENT_VM_TAP"
117新增:fi
118新增:
119新增:# --- 1. the repository ---------------------------------------------------------
120新增:echo "Checking the repository"
121新增:dirty="$(git status --porcelain)"
122新增:[ -z "$dirty" ] || die "the working tree is not clean:
123新增:$dirty"
124新增:ok "working tree is clean"
125新增:
126新增:current="$(git rev-parse --abbrev-ref HEAD)"
127新增:[ "$current" = "$BRANCH" ] || die "on branch '$current', not '$BRANCH' (RELEASE_BRANCH overrides)"
128新增:ok "on $BRANCH"
129新增:
130新增:head="$(git rev-parse HEAD)"
131新增:# `|| true`: under set -e and pipefail, a failed ls-remote would exit here
132新增:# without a word; the check below says what went wrong.
133新增:remote_head="$(git ls-remote origin "refs/heads/$BRANCH" | cut -f1)" || true
134新增:[ -n "$remote_head" ] || die "could not read origin/$BRANCH"
135新增:[ "$head" = "$remote_head" ] \
136新增: || die "HEAD is not origin/$BRANCH: push or pull first"
137新增:ok "level with origin/$BRANCH (${head:0:12})"
138新增:
139新增:# A tag already at HEAD with no release behind it is a previous run that
140新增:# pushed the tag and then failed: pick up from the release. The commit a tag
141新增:# names: the peeled line of an annotated tag, or the tag itself.
142新增:tag_commit() {
143新增: local local_c remote
144新增: if local_c="$(git rev-parse -q --verify "refs/tags/$TAG^{commit}")"; then
145新增: printf '%s\n' "$local_c"
146新增: return
147新增: fi
148新增: remote="$(git ls-remote --tags origin "refs/tags/$TAG" "refs/tags/$TAG^{}")"
149新增: printf '%s\n' "$remote" | awk -v t="refs/tags/$TAG" '$2 == t "^{}" { p = $1 } $2 == t { l = $1 } END { print (p != "" ? p : l) }'
150新增:}
151新增:RESUME=""
152新增:if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null \
153新增: || [ -n "$(git ls-remote --tags origin "refs/tags/$TAG")" ]; then
154新增: if [ -z "$GH" ]; then
155新增: die "tag $TAG already exists (without gh, whether it has a release cannot be checked)"
156新增: elif [ "$(tag_commit)" = "$head" ] && ! gh release view "$TAG" >/dev/null 2>&1; then
157新增: RESUME=1
158新增: warn "tag $TAG is already at ${head:0:12}, with no release: resuming from the release"
159新增: else
160新增: die "tag $TAG already exists"
161新增: fi
162新增:else
163新增: ok "tag $TAG is free"
164新增:fi
165新增:
166新增:# --- 2. version and changelog --------------------------------------------------
167新增:echo "Checking the version"
168新增:reported="$(bash ./agent-vm.sh version)"
169新增:[ "$reported" = "$VERSION" ] \
170新增: || die "agent-vm.sh reports $reported: set AGENT_VM_VERSION=\"$VERSION\" and commit"
171新增:ok "agent-vm.sh reports $VERSION"
172新增:
173新增:NOTES="$(changelog_notes "$VERSION")"
174新增:[ -n "$NOTES" ] || die "CHANGELOG.md has no '## $VERSION' section, or it is empty"
175新增:ok "CHANGELOG.md has a $VERSION section ($(printf '%s\n' "$NOTES" | wc -l | tr -d ' ') lines)"
176新增:
177新增:# --- 3. tests ------------------------------------------------------------------
178新增:# CI is the authority: it runs bash 3.2, which this machine may lack.
179新增:echo "Checking the tests"
180新增:ci="skipped"
181新增:[ -z "$GH" ] || ci="$(gh run list --workflow test.yml --commit "$head" --limit 1 \
182新增: --json status,conclusion --jq '.[0] | "\(.status) \(.conclusion)"' 2>/dev/null || true)"
183新增:case "$ci" in
184新增: skipped) warn "the test workflow on ${head:0:12} was not checked (no gh)" ;;
185新增: "completed success") ok "the test workflow passed on ${head:0:12}" ;;
186新增: "") die "no test workflow run for ${head:0:12}: push and wait for CI" ;;
187新增: completed*) die "the test workflow did not pass on ${head:0:12} ($ci)" ;;
188新增: *) die "the test workflow is still running on ${head:0:12} ($ci)" ;;
189新增:esac
190新增:for f in agent-vm.sh lib/*.sh agent-vm.setup.sh install.sh runtime.example.sh test.sh tests/*.sh test-e2e.sh release.sh; do
191新增: bash -n "$f" || die "syntax error in $f"
192新增:done
193新增:sh -n www/public/install.sh || die "syntax error in www/public/install.sh"
194新增:./test.sh >/dev/null 2>&1 || die "./test.sh fails here: run it to see why"
195新增:ok "./test.sh passes here"
196新增:
197新增:# --- confirmation --------------------------------------------------------------
198新增:echo
199新增:if [ -n "$DRY_RUN" ]; then
200新增: echo "Dry run: everything checks out. A real run would do:"
201新增:elif [ -z "$ASSUME_YES" ]; then
202新增: printf 'Tag %s at %s, push it and publish the release? [y/N] ' "$TAG" "${head:0:12}"
203新增: reply=''
204新增: IFS= read -r reply 2>/dev/null </dev/tty || reply=''
205新增: case "$reply" in [Yy]*) ;; *) echo "Aborted, nothing was changed."; exit 1 ;; esac
206新增:fi
207新增:
208新增:# --- 4-5. tag, push, release ---------------------------------------------------
209新增:WORK="$(mktemp -d)"
210新增:trap 'rm -rf "$WORK"' EXIT
211新增:printf '%s\n' "$NOTES" > "$WORK/notes.md"
212新增:TARBALL="agent-vm-$VERSION.tar.gz"
213新增:
214新增:if [ -z "$RESUME" ]; then
215新增: run git tag -a "$TAG" -m "agent-vm $VERSION"
216新增: run git push origin "refs/tags/$TAG"
217新增:elif [ -z "$(git ls-remote --tags origin "refs/tags/$TAG")" ]; then
218新增: # Resumed from a tag that only exists here: `gh release create --verify-tag`
219新增: # needs it on origin.
220新增: run git push origin "refs/tags/$TAG"
221新增:elif ! git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
222新增: # Resumed from a tag that only exists on origin: the tarball is built from it.
223新增: run git fetch --quiet origin "refs/tags/$TAG:refs/tags/$TAG"
224新增:fi
225新增:# Built from the tag, not the working tree, so the asset is what was tagged.
226新增:# It only writes into $WORK, so a dry run builds it too (from HEAD, which is
227新增:# what the tag points at, or would) to show the checksum. www/ and the tests
228新增:# are left out by export-ignore in .gitattributes.
229新增:ref="$TAG"
230新增:[ -z "$DRY_RUN" ] || ref="HEAD"
231新增:git archive --format=tar.gz --prefix="agent-vm-$VERSION/" -o "$WORK/$TARBALL" "$ref"
232新增:SHA="$(sha256_of "$WORK/$TARBALL")"
233新增:printf '%s %s\n' "$SHA" "$TARBALL" > "$WORK/SHA256SUMS"
234新增:run gh release create "$TAG" --verify-tag --title "agent-vm $VERSION" \
235新增: --notes-file "$WORK/notes.md" "$WORK/$TARBALL" "$WORK/SHA256SUMS"
236新增:
237新增:# --- 6. Homebrew -----------------------------------------------------------------
238新增:if [ -n "$GH" ]; then
239新增: SLUG="$(gh repo view --json nameWithOwner --jq .nameWithOwner)"
240新增:else
241新增: # owner/repo from the origin URL, https or ssh.
242新增: SLUG="$(git remote get-url origin | sed -E 's#^.*github\.com[:/]##; s#\.git$##')"
243新增:fi
244新增:URL="https://github.com/$SLUG/releases/download/$TAG/$TARBALL"
245新增:echo
246新增:echo "Homebrew formula:"
247新增:echo " url \"$URL\""
248新增:echo " sha256 \"$SHA\""
249新增:
250新增:if [ -n "${AGENT_VM_TAP:-}" ]; then
251新增: if [ -n "$DRY_RUN" ]; then
252新增: echo "Dry run: $FORMULA would be updated."
253新增: else
254新增: # The first url and sha256 only: those of the source. A `bottle do`
255新增: # block below has sha256 lines of its own.
256新增: awk -v url="$URL" -v sha="$SHA" '
257新增: !u && /^[[:space:]]*url / { sub(/url .*/, "url \"" url "\""); u = 1 }
258新增: !s && /^[[:space:]]*sha256 / { sub(/sha256 .*/, "sha256 \"" sha "\""); s = 1 }
259新增: { print }' "$FORMULA" > "$WORK/formula.rb"
260新增: mv "$WORK/formula.rb" "$FORMULA"
261新增: ok "updated $FORMULA"
262新增: echo " Review and publish it:"
263新增: echo " git -C \"$AGENT_VM_TAP\" diff"
264新增: echo " git -C \"$AGENT_VM_TAP\" commit -am \"agent-vm $VERSION\" && git -C \"$AGENT_VM_TAP\" push"
265新增: fi
266新增:fi
267新增:
268新增:echo
269新增:[ -n "$DRY_RUN" ] && ok "dry run complete, nothing was changed" || ok "agent-vm $VERSION is released"
修改runtime.example.sh+37 −47看文件
@@ -3,88 +3,78 @@
33# runtime.example.sh — Template for ~/.agent-vm/runtime.sh
44# =============================================================================
55#
6删除:# This file runs inside every agent-vm on each start, before the per-project
7删除:# .agent-vm.runtime.sh script. Copy it to ~/.agent-vm/runtime.sh and uncomment
8删除:# the sections you need.
6新增:# This file runs inside the VM on every agent-vm command that enters one,
7新增:# before the per-project .agent-vm.runtime.sh script, so keep it safe to run
8新增:# again. Copy it to ~/.agent-vm/runtime.sh and uncomment the sections you
9新增:# need.
910#
1011# To get started:
1112# cp runtime.example.sh ~/.agent-vm/runtime.sh
1213# # Edit the file with your own values
13删除:# chmod +x ~/.agent-vm/runtime.sh
14删除:
15删除:
16删除:# =============================================================================
17删除:# 1. SSH authentication for GitHub
18删除:# =============================================================================
19删除:#
20删除:# Embed your SSH private key (base64-encoded) so the VM can push/pull over SSH.
2114#
22删除:# To encode your key:
23删除:# cat ~/.ssh/id_ed25519 | base64
15新增:# It is piped into the interpreter its first line names (bash, sh or zsh), so
16新增:# it needs no execute bit. It runs in the project directory.
2417#
25删除:# Paste the output below:
26删除:
27删除:# SSH_KEY_B64="<your-base64-encoded-private-key>"
28删除:# mkdir -p ~/.ssh && chmod 700 ~/.ssh
29删除:# echo "$SSH_KEY_B64" | base64 -d > ~/.ssh/id_ed25519
30删除:# chmod 600 ~/.ssh/id_ed25519
31删除:# ssh-keyscan github.com >> ~/.ssh/known_hosts 2>/dev/null
18新增:# Keep private keys out of this file: it runs in every VM, where the agent can
19新增:# read whatever it sets up. For GitHub, a fine-grained GH_TOKEN in
20新增:# ~/.agent-vm/env is revocable in one click; an SSH key is not.
3221
3322
3423# =============================================================================
35删除:# 2. Git configuration
24新增:# 1. Git configuration
3625# =============================================================================
26新增:#
27新增:# The identity can also come from GIT_AUTHOR_* / GIT_COMMITTER_* in
28新增:# ~/.agent-vm/env: https://www.agent-vm.org/#letting-the-agent-commit
3729
3830# git config --global user.name "Your Name"
3931# git config --global user.email "[email protected]"
4032
41删除:# Force SSH for all GitHub remotes (avoids HTTPS credential prompts)
42删除:# git config --global url."[email protected]:".insteadOf "https://github.com/"
43删除:
4433
4534# =============================================================================
46删除:# 3. GitHub CLI authentication
35新增:# 2. Pushing over HTTPS with GH_TOKEN
4736# =============================================================================
4837#
49删除:# Required for creating PRs, commenting on issues, etc. from inside the VM.
50删除:# (If you only need `gh` for CLI calls, setting GH_TOKEN in ~/.agent-vm/env is
51删除:# simpler — see "Sharing tokens" in the README.)
52删除:#
53删除:# To create a token: https://github.com/settings/tokens
54删除:# Scopes needed: repo, read:org
38新增:# `gh` reads GH_TOKEN from ~/.agent-vm/env on its own. Plain `git push` over
39新增:# HTTPS needs a credential helper, which `gh` knows how to install.
5540#
56删除:# echo "<your-github-pat>" | gh auth login --with-token
41新增:# gh auth setup-git
5742
5843
5944# =============================================================================
60删除:# 4. Claude Code skills
45新增:# 3. Claude Code skills
6146# =============================================================================
6247#
63删除:# Clone shared skills into the global skills directory.
48新增:# Clone shared skills into the global skills directory, once per VM (this
49新增:# script runs again on every command), and update them after that.
6450# These will be available in all projects.
6551
6652# mkdir -p ~/.claude/skills
67删除:# git clone [email protected]:your-org/claude-skills.git ~/.claude/skills/your-org-skills
68删除:
69删除:# You can also install skills into the current project's directory.
70删除:# These will only be available when working in that project.
53新增:# if [ -d ~/.claude/skills/your-org-skills ]; then
54新增:# git -C ~/.claude/skills/your-org-skills pull --ff-only --quiet
55新增:# else
56新增:# git clone https://github.com/your-org/claude-skills.git ~/.claude/skills/your-org-skills
57新增:# fi
7158
72删除:# PROJECT_DIR="$(pwd)"
73删除:# mkdir -p "$PROJECT_DIR/.claude/skills"
74删除:# git clone [email protected]:your-org/project-skills.git "$PROJECT_DIR/.claude/skills/project-skills"
59新增:# Skills for the current project only belong in that project's
60新增:# .agent-vm.runtime.sh: this file runs in every project. There, the same
61新增:# pattern, in "$PWD/.claude/skills/project-skills" (which fails under
62新增:# --readonly, where the project cannot be written).
7563
7664
7765# =============================================================================
78删除:# 5. MCP servers
66新增:# 4. MCP servers
7967# =============================================================================
8068#
8169# Add MCP servers available to Claude Code in all projects (--scope user).
70新增:# `add` fails on a name that exists, so only when it is not there yet.
8271#
83删除:# claude mcp add --scope user my-mcp-server npx -y my-mcp-server@latest
72新增:# claude mcp get my-mcp-server >/dev/null 2>&1 \
73新增:# || claude mcp add --scope user my-mcp-server npx -y my-mcp-server@latest
8474
8575
8676# =============================================================================
87删除:# 6. Claude Code status line
77新增:# 5. Claude Code status line
8878# =============================================================================
8979#
9080# Install a custom status line command in ~/.claude/settings.json.
@@ -93,12 +83,12 @@
9383# For example, to show the current git branch:
9484#
9585# cat > /tmp/statusline-patch.json << 'PATCH'
96删除:# {"statusLine": {"command": "git branch --show-current 2>/dev/null || echo ''"}}
86新增:# {"statusLine": {"type": "command", "command": "git branch --show-current 2>/dev/null || echo ''"}}
9787# PATCH
9888#
9989# if [ -f ~/.claude/settings.json ]; then
100删除:# jq -s '.[0] * .[1]' ~/.claude/settings.json /tmp/statusline-patch.json > /tmp/settings-merged.json
101删除:# mv /tmp/settings-merged.json ~/.claude/settings.json
90新增:# jq -s '.[0] * .[1]' ~/.claude/settings.json /tmp/statusline-patch.json > /tmp/settings-merged.json \
91新增:# && mv /tmp/settings-merged.json ~/.claude/settings.json
10292# else
10393# mkdir -p ~/.claude
10494# cp /tmp/statusline-patch.json ~/.claude/settings.json
新增test-e2e.sh+358 −0看文件
@@ -0,0 +1,358 @@
1新增:#!/usr/bin/env bash
2新增:#
3新增:# agent-vm end-to-end tests. Run this ON A HOST that has Lima.
4新增:#
5新增:# ./test-e2e.sh
6新增:#
7新增:# Unlike ./test.sh, this one builds a real VM and boots it. It is here for the
8新增:# claims that a stub limactl cannot check — above all that --readonly and the
9新增:# read-only .git are enforced on the host and not by a rule the guest could
10新增:# lift.
11新增:#
12新增:# It does not touch anything of yours. LIMA_HOME and the state directory are
13新增:# throwaways, so your `agent-vm-base` and your project VMs are never read,
14新增:# edited or deleted, and everything is removed on exit, Ctrl-C included.
15新增:#
16新增:# The .git checks run when this Lima has sshfs.readonlyNames (see
17新增:# `agent-vm doctor`), and are reported as skipped otherwise.
18新增:#
19新增:# Cost: one Debian image download (the throwaway LIMA_HOME starts with an
20新增:# empty cache) and a few minutes. `--preinstall=none` keeps the template to the
21新增:# base system.
22新增:
23新增:set -uo pipefail
24新增:
25新增:SELF_DIR="$(CDPATH= cd -- "$(dirname "${BASH_SOURCE[0]:-$0}")" >/dev/null && pwd)"
26新增:AGENT_VM="${AGENT_VM:-$SELF_DIR/agent-vm.sh}"
27新增:
28新增:FAIL=0
29新增:PASSED=0
30新增:pass() { PASSED=$((PASSED + 1)); printf ' ok %s\n' "$1"; }
31新增:fail() { FAIL=$((FAIL + 1)); printf ' FAIL %s\n' "$1"; }
32新增:info() { printf ' %s\n' "$1"; }
33新增:section() { printf '\n%s\n' "$1"; }
34新增:
35新增:if ! command -v limactl >/dev/null 2>&1; then
36新增: echo "This suite needs Lima on the host. Install it, or run ./test.sh instead." >&2
37新增: exit 2
38新增:fi
39新增:
40新增:# --- isolation ----------------------------------------------------------------
41新增:# LIMA_HOME moves every instance out of ~/.lima; otherwise `agent-vm setup`
42新增:# would rebuild the `agent-vm-base` you actually use, since that name is not
43新增:# configurable.
44新增:# Under /tmp, not $TMPDIR: Lima puts a socket under LIMA_HOME/<vm>/, and macOS's
45新增:# $TMPDIR (/var/folders/...) is long enough to push its path past the 104
46新增:# bytes a Unix socket path may have, which fails `limactl create`.
47新增:SB="$(mktemp -d /tmp/agent-vm-e2e.XXXXXX)"
48新增:export AGENT_VM_STATE_DIR="$SB/state"
49新增:export LIMA_HOME="$SB/lima"
50新增:PROJ="$SB/project"
51新增:mkdir -p "$AGENT_VM_STATE_DIR" "$LIMA_HOME" "$PROJ"
52新增:git -C "$PROJ" init -q
53新增:
54新增:cleanup() {
55新增: printf '\nCleaning up (%s)...\n' "$SB"
56新增: # Best effort: the VMs are in our own LIMA_HOME, so a stray one cannot
57新增: # collide with the user's.
58新增: for vm in $(limactl list -q 2>/dev/null); do
59新增: limactl stop --force "$vm" >/dev/null 2>&1
60新增: limactl delete --force "$vm" >/dev/null 2>&1
61新增: done
62新增: rm -rf "$SB"
63新增:}
64新增:trap cleanup EXIT
65新增:# Exiting runs the EXIT trap. A trap on INT that only cleaned up let the suite
66新增:# carry on against the deleted sandbox, reporting failures (and passes) that
67新增:# meant nothing.
68新增:trap 'exit 130' INT TERM
69新增:
70新增:# The same probe agent-vm uses to decide.
71新增:PROTECTS_GIT=""
72新增:bash -c 'source "$1"; _agent_vm_lima_protects_git' _ "$AGENT_VM" && PROTECTS_GIT=1
73新增:# A start asks before going on when this Lima has no readonlyNames, or when
74新增:# your git config lacks safe.bareRepository, and offers to change that config.
75新增:# The output is captured here, so a question would wait unseen: they are
76新增:# answered yes, and nothing is offered. The suite is about what the VM can
77新增:# reach, not about those questions (./test.sh covers them).
78新增:export AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1
79新增:
80新增:printf 'agent-vm end-to-end suite\n'
81新增:printf ' agent-vm: %s\n' "$AGENT_VM"
82新增:printf ' LIMA_HOME: %s\n' "$LIMA_HOME"
83新增:printf ' project: %s\n' "$PROJ"
84新增:if [[ -n "$PROTECTS_GIT" ]]; then
85新增: printf ' .git: read-only for the VMs (this Lima has readonlyNames)\n'
86新增:else
87新增: printf ' .git: writable (this Lima has no readonlyNames)\n'
88新增:fi
89新增:printf ' your own VMs, ~/.lima and ~/.agent-vm are not touched.\n'
90新增:
91新增:vm_name="$("$AGENT_VM" name "$PROJ")"
92新增:
93新增:# Changing the mount mode of a RUNNING VM asks on the terminal first, and the
94新增:# output is captured here, so the question would wait unseen. Stop it first.
95新增:stop_vm() { (cd "$PROJ" && "$AGENT_VM" stop >/dev/null 2>&1); }
96新增:
97新增:# A --readonly run. Its output ends up in $ro_out; a check on a missing file
98新增:# proves nothing unless agent-vm also said the mode is in force, since an
99新增:# aborted run leaves no file either.
100新增:ro_run() { ro_out="$(cd "$PROJ" && "$AGENT_VM" --readonly "$@" 2>&1)"; }
101新增:ro_applied() { case "$ro_out" in *"Read-only: the project"*) return 0 ;; esac; return 1; }
102新增:
103新增:# =============================================================================
104新增:section "build the base template (--preinstall=none)"
105新增:# =============================================================================
106新增:printf ' this downloads a Debian image on the first run; be patient\n'
107新增:if "$AGENT_VM" setup --preinstall=none </dev/null; then
108新增: pass "setup completed"
109新增:else
110新增: fail "setup failed — nothing below can run"
111新增: exit 1
112新增:fi
113新增:
114新增:# =============================================================================
115新增:section "first run in a project directory"
116新增:# =============================================================================
117新增:echo "hello" > "$PROJ/host-file.txt"
118新增:
119新增:if grep -q hello <<< "$(cd "$PROJ" && "$AGENT_VM" run cat "$PROJ/host-file.txt" 2>/dev/null)"; then
120新增: pass "the project directory is mounted and readable in the VM"
121新增:else
122新增: fail "the project directory is not readable in the VM"
123新增:fi
124新增:
125新增:if (cd "$PROJ" && "$AGENT_VM" run sh -c "echo from-vm > '$PROJ/vm-file.txt'") \
126新增: && [ "$(cat "$PROJ/vm-file.txt" 2>/dev/null)" = "from-vm" ]; then
127新增: pass "a write from the VM lands on the host"
128新增:else
129新增: fail "a write from the VM did not reach the host"
130新增:fi
131新增:
132新增:# Last line: `run` prints the VM's resources first. reverse-sshfs is only
133新增:# host-enforced when it is the one agent-vm sets up for readonlyNames.
134新增:fstype="$(cd "$PROJ" && "$AGENT_VM" run findmnt -no FSTYPE "$PROJ" 2>/dev/null | tail -1)"
135新增:case "$fstype:$PROTECTS_GIT" in
136新增: virtiofs:|9p:) pass "the share uses a host-enforced mount type ($fstype)" ;;
137新增: fuse.sshfs:1) pass "the share is reverse-sshfs, as readonlyNames needs" ;;
138新增: fuse.sshfs:) fail "reverse-sshfs without readonlyNames: --readonly cannot be a boundary here" ;;
139新增: *) fail "unexpected project mount type: '$fstype'" ;;
140新增:esac
141新增:
142新增:# =============================================================================
143新增:section ".git is read-only for the VM, root included"
144新增:# =============================================================================
145新增:# Git on the host runs what .git/config and hooks name. Enforced by Lima's
146新增:# SFTP server on the host, so root in the guest cannot lift it, at any depth,
147新增:# whatever the case of the name. The rest of the working tree stays writable.
148新增:# Repository layouts are made with plain shell: the template has no git.
149新增:if [ -n "$PROTECTS_GIT" ]; then
150新增: git -C "$PROJ" init -q nested
151新增: config_sum="$(cksum < "$PROJ/.git/config")"
152新增: (cd "$PROJ" && "$AGENT_VM" run sudo sh -c 'echo "# e2e" >> .git/config' >/dev/null 2>&1)
153新增: [ "$(cksum < "$PROJ/.git/config")" = "$config_sum" ] && pass "root in the VM cannot change .git/config" \
154新增: || fail "root in the VM changed .git/config"
155新增: (cd "$PROJ" && "$AGENT_VM" run sudo touch .git/hooks/e2e-hook >/dev/null 2>&1)
156新增: [ ! -e "$PROJ/.git/hooks/e2e-hook" ] && pass "root in the VM cannot add a hook" || fail "root in the VM added a hook"
157新增: (cd "$PROJ" && "$AGENT_VM" run sudo sh -c 'mv .git .git-moved' >/dev/null 2>&1)
158新增: [ -d "$PROJ/.git" ] && [ ! -e "$PROJ/.git-moved" ] && pass "root in the VM cannot move .git away" \
159新增: || fail "root in the VM moved .git"
160新增: (cd "$PROJ" && "$AGENT_VM" run sudo sh -c 'echo x >> nested/.git/config' >/dev/null 2>&1)
161新增: grep -q '^x$' "$PROJ/nested/.git/config" && fail "root in the VM changed a nested repository" \
162新增: || pass "a nested repository is protected too"
163新增: (cd "$PROJ" && "$AGENT_VM" run sh -c 'mkdir -p planted/.GIT' >/dev/null 2>&1)
164新增: [ ! -e "$PROJ/planted/.GIT" ] && pass "the VM cannot plant a .git, whatever the case" \
165新增: || fail "the VM planted planted/.GIT"
166新增: (cd "$PROJ" && "$AGENT_VM" run sh -c "echo still > '$PROJ/worktree-file.txt'") \
167新增: && [ "$(cat "$PROJ/worktree-file.txt" 2>/dev/null)" = "still" ] \
168新增: && pass "the working tree stays writable" || fail "the working tree is not writable"
169新增: grep -q '^ref:' <<< "$(cd "$PROJ" && "$AGENT_VM" run cat .git/HEAD 2>/dev/null)" \
170新增: && pass "the VM can still read .git" || fail "the VM cannot read .git"
171新增: (cd "$PROJ" && "$AGENT_VM" run sh -c 'mkdir -p planted/.hg' >/dev/null 2>&1)
172新增: [ ! -e "$PROJ/planted/.hg" ] && pass "the VM cannot plant a .hg" || fail "the VM planted planted/.hg"
173新增: # core.hooksPath in the project: its folder joins the names at the next start.
174新增: git -C "$PROJ" config core.hooksPath .husky/_
175新增: stop_vm
176新增: (cd "$PROJ" && "$AGENT_VM" run sh -c 'mkdir -p .husky/_ && echo x > .husky/pre-commit' >/dev/null 2>&1)
177新增: [ ! -e "$PROJ/.husky" ] && pass "the VM cannot write the core.hooksPath folder" \
178新增: || fail "the VM wrote .husky although core.hooksPath points there"
179新增: git -C "$PROJ" config --unset core.hooksPath
180新增: rm -rf "$PROJ/.husky"
181新增: stop_vm
182新增:else
183新增: info "skipped: this Lima has no sshfs.readonlyNames, the VM can write .git"
184新增:fi
185新增:
186新增:# =============================================================================
187新增:section "--readonly is enforced outside the guest"
188新增:# =============================================================================
189新增:# The whole point. A guest-side restriction would pass the first check and fail
190新增:# the second, which is what --offline and --git-read-only did before they were
191新增:# removed.
192新增:stop_vm
193新增:ro_run run sh -c "echo nope > '$PROJ/should-not-exist.txt'"
194新增:ro_status=$?
195新增:
196新增:if ! ro_applied; then
197新增: fail "--readonly was not applied"
198新增: info "$ro_out"
199新增:elif [ "$ro_status" -ne 0 ] && [ ! -e "$PROJ/should-not-exist.txt" ]; then
200新增: pass "a write from the VM is refused under --readonly"
201新增:else
202新增: fail "the VM could write under --readonly"
203新增: info "$ro_out"
204新增: rm -f "$PROJ/should-not-exist.txt"
205新增:fi
206新增:
207新增:# root in the VM tries to lift it. Under a bind-mount or an fstab flag this
208新增:# succeeds; under a host-side share it cannot.
209新增:#
210新增:# Verified on macOS/M2 + vz + virtiofs: the `remount,rw` itself SUCCEEDS (the
211新增:# guest kernel happily flips its own mount flag) and the write still fails with
212新增:# EPERM. Note the errno: a guest-side read-only mount would give EROFS, so
213新增:# EPERM is the signature of the backend refusing. Which is why this test writes
214新增:# after the remount instead of trusting the remount's exit status.
215新增:ro_run run sudo sh -c \
216新增: "mount -o remount,rw '$PROJ' 2>/dev/null; echo escaped > '$PROJ/escaped.txt'"
217新增:
218新增:if ! ro_applied; then
219新增: fail "--readonly was not applied for the remount attempt"
220新增: info "$ro_out"
221新增:elif [ ! -e "$PROJ/escaped.txt" ]; then
222新增: pass "root in the VM cannot remount the project read-write"
223新增:else
224新增: fail "root in the VM lifted --readonly: it is NOT a boundary"
225新增: info "$ro_out"
226新增: rm -f "$PROJ/escaped.txt"
227新增:fi
228新增:
229新增:# The host side is unaffected: you keep editing while the agent cannot.
230新增:if echo "still mine" > "$PROJ/host-write.txt" 2>/dev/null; then
231新增: pass "the host can still write while the VM is read-only"
232新增:else
233新增: fail "the host lost write access to its own directory"
234新增:fi
235新增:
236新增:# =============================================================================
237新增:section "--readonly covers every share, not just the project"
238新增:# =============================================================================
239新增:# A writable volume that contains the project is a second path to the same
240新增:# files, and the hypervisor enforces read-only per share. Under --readonly it
241新增:# has to be read-only as well. $SB is the project's parent.
242新增:#
243新增:# Volumes are mounted when a VM is created, so --reset: on the existing VM the
244新增:# volume would simply be absent, and the write would fail for that reason.
245新增:printf '%s:/mnt/sb:rw\n' "$SB" > "$AGENT_VM_STATE_DIR/volumes"
246新增:ro_run --reset run sudo sh -c \
247新增: "test -d /mnt/sb/project || exit 3; echo x > /mnt/sb/project/via-volume.txt"
248新增:via_status=$?
249新增:if ! ro_applied; then
250新增: fail "--readonly was not applied with the volume"
251新增: info "$ro_out"
252新增:elif [ "$via_status" -eq 3 ]; then
253新增: fail "the rw volume is not mounted in the VM: nothing was tested"
254新增:elif [ ! -e "$PROJ/via-volume.txt" ]; then
255新增: pass "root cannot write the project through an rw volume under --readonly"
256新增:else
257新增: fail "the project was written through a volume under --readonly"
258新增: info "$ro_out"
259新增: rm -f "$PROJ/via-volume.txt"
260新增:fi
261新增:
262新增:# =============================================================================
263新增:section "the mode goes back"
264新增:# =============================================================================
265新增:if (cd "$PROJ" && "$AGENT_VM" run sh -c "echo back > '$PROJ/writable-again.txt'") \
266新增: && [ -e "$PROJ/writable-again.txt" ]; then
267新增: pass "dropping --readonly restores write access"
268新增:else
269新增: fail "the project stayed read-only after --readonly was dropped"
270新增:fi
271新增:if (cd "$PROJ" && "$AGENT_VM" run sh -c "echo back > /mnt/sb/volume-again.txt") \
272新增: && [ -e "$SB/volume-again.txt" ]; then
273新增: pass "and an rw volume is writable again"
274新增:else
275新增: fail "the rw volume stayed read-only after --readonly was dropped"
276新增:fi
277新增:rm -f "$AGENT_VM_STATE_DIR/volumes"
278新增:
279新增:# =============================================================================
280新增:section "the rest of the VM stays writable under --readonly"
281新增:# =============================================================================
282新增:# --readonly is about the project share only: an agent still needs to install
283新增:# packages and write its own state.
284新增:stop_vm
285新增:if ro_run run sh -c 'touch /tmp/probe && touch "$HOME/probe"' && ro_applied; then
286新增: pass "/tmp and \$HOME in the VM are writable under --readonly"
287新增:else
288新增: fail "--readonly made the whole VM read-only"
289新增:fi
290新增:
291新增:# =============================================================================
292新增:section "what the VM can reach on the host"
293新增:# =============================================================================
294新增:# Not a pass/fail: it reports a documented Lima behaviour that the site
295新增:# discloses. Lima NATs the guest's gateway to the host's 127.0.0.1, so
296新增:# whatever you have listening on localhost answers from inside the VM.
297新增:reachable=""
298新增:for port in 5432 6379 3306 11434; do
299新增: if (cd "$PROJ" && "$AGENT_VM" run timeout 2 bash -c "echo > /dev/tcp/192.168.5.2/$port") >/dev/null 2>&1; then
300新增: reachable="$reachable $port"
301新增: fi
302新增:done
303新增:if [ -n "$reachable" ]; then
304新增: info "host services reachable from the VM on 192.168.5.2:$reachable"
305新增: info "expected, and disclosed. Put auth on local dev services."
306新增:else
307新增: info "no common host service answered on 192.168.5.2 (nothing listening)"
308新增:fi
309新增:
310新增:# =============================================================================
311新增:section "--scratch: nothing of the host mounted, deleted after"
312新增:# =============================================================================
313新增:# stderr captured: the question before the deletion is not asked, so the VM
314新增:# goes, as for any caller without a terminal.
315新增:echo "host-only" > "$PROJ/scratch-probe.txt"
316新增:scr_out="$(cd "$PROJ" && "$AGENT_VM" --scratch run sh -c \
317新增: "test ! -e '$PROJ/scratch-probe.txt' && echo no-host-file; touch '$PROJ/from-scratch.txt' && echo wrote-own-disk; echo \"shares=\$(findmnt -rn -t virtiofs,9p,fuse.sshfs | wc -l | tr -d ' ')\"" 2>&1)"
318新增:case "$scr_out" in *no-host-file*) pass "the project's files are not in a scratch VM" ;; *) fail "a scratch VM sees the project: $scr_out" ;; esac
319新增:case "$scr_out" in *wrote-own-disk*) pass "it works at the project's path, on its own disk" ;; *) fail "the scratch folder is not writable: $scr_out" ;; esac
320新增:[ ! -e "$PROJ/from-scratch.txt" ] && pass "what it writes there does not reach the host" || fail "a scratch VM wrote into the project"
321新增:case "$scr_out" in *shares=0*) pass "no share is mounted in it" ;; *) fail "a share is mounted in a scratch VM: $scr_out" ;; esac
322新增:if grep -q -- '-scratch-' <<< "$(limactl list -q 2>/dev/null)"; then
323新增: fail "the scratch VM is still there: $(limactl list -q | grep -- '-scratch-')"
324新增:else
325新增: pass "the scratch VM is deleted"
326新增:fi
327新增:grep -qx "vm_exists=1" <<< "$("$AGENT_VM" info "$PROJ")" && pass "the folder's own VM is still there" || fail "the folder's own VM went"
328新增:rm -f "$PROJ/scratch-probe.txt"
329新增:
330新增:# =============================================================================
331新增:section "the integrator surface against a real VM"
332新增:# =============================================================================
333新增:info_out="$(cd "$PROJ" && "$AGENT_VM" info "$PROJ")"
334新增:get() { printf '%s\n' "$info_out" | grep "^$1=" | cut -d= -f2-; }
335新增:
336新增:[ "$(get vm_exists)" = "1" ] && pass "info: vm_exists=1" || fail "info: vm_exists is $(get vm_exists)"
337新增:[ "$(get base_exists)" = "1" ] && pass "info: base_exists=1" || fail "info: base_exists is $(get base_exists)"
338新增:[ "$(get vm_name)" = "$vm_name" ] && pass "info: vm_name agrees with name" || fail "info: vm_name disagrees with name"
339新增:
340新增:if "$AGENT_VM" version --min 0.2.0 >/dev/null 2>&1; then
341新增: pass "version --min 0.2.0 is satisfied"
342新增:else
343新增: fail "version --min 0.2.0 refused this build"
344新增:fi
345新增:
346新增:# =============================================================================
347新增:section "teardown"
348新增:# =============================================================================
349新增:if (cd "$PROJ" && "$AGENT_VM" rm >/dev/null 2>&1) \
350新增: && grep -qx "vm_exists=0" <<< "$("$AGENT_VM" info "$PROJ")"; then
351新增: pass "rm deletes the project VM"
352新增:else
353新增: fail "the project VM survived rm"
354新增:fi
355新增:
356新增:# =============================================================================
357新增:printf '\n%s passed, %s failed\n' "$PASSED" "$FAIL"
358新增:[ "$FAIL" -eq 0 ] || exit 1
修改test.sh+7 −421看文件
@@ -6,11 +6,11 @@
66#
77# Runs against a stub limactl in a throwaway HOME, so it never creates, starts
88# or deletes a VM and never touches your real ~/.agent-vm. No network needed.
9新增:# What needs a real VM is in test-e2e.sh.
910#
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.
11新增:# tests/helpers.sh sets up the sandbox and the stubs, then every tests/NN-*.sh
12新增:# runs in order, in this one shell: later files use what earlier ones set up
13新增:# (the recording limactl of 11-recorded-commands.sh, for one).
1414#
1515# Also worth running under bash 3.2 (what macOS ships), which is stricter about
1616# empty array expansion under `set -u`:
@@ -19,425 +19,11 @@
1919set -uo pipefail
2020
2121SELF_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}"
2422
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
23新增:. "$SELF_DIR/tests/helpers.sh"
24新增:for _test_file in "$SELF_DIR"/tests/[0-9]*.sh; do
25新增: . "$_test_file"
36826done
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
44027
441删除:# =============================================================================
44228printf '\n%s passed, %s failed\n' "$PASSED" "$FAIL"
44329[ "$FAIL" -eq 0 ] || exit 1
新增tests/01-basics.sh+215 −0看文件
@@ -0,0 +1,215 @@
1新增:# =============================================================================
2新增:section "sourcing under a strict caller"
3新增:# =============================================================================
4新增:# agent-vm is meant to be sourced by other tools. Empty array expansion under
5新增:# `set -u` is an error on bash 3.2, and `cmd | grep -q` under `pipefail` can
6新增:# fail from a SIGPIPE race — both would show up here.
7新增:( set -u; set -o pipefail
8新增: _agent_vm_exists agent-vm-base >/dev/null
9新增: _agent_vm_running agent-vm-proj-deadbeef >/dev/null
10新增: _agent_vm_base_exists >/dev/null
11新增: _agent_vm_project_vms >/dev/null
12新增: agent-vm version >/dev/null
13新增: agent-vm info "$PROJ" >/dev/null
14新增:) 2>"$SB/strict.err"
15新增:if [ -s "$SB/strict.err" ]; then
16新增: fail "no diagnostics under set -u / pipefail"; sed 's/^/ /' "$SB/strict.err"
17新增:else
18新增: pass "no diagnostics under set -u / pipefail"
19新增:fi
20新增:
21新增:# =============================================================================
22新增:section "VM naming"
23新增:# =============================================================================
24新增:n1="$(_agent_vm_name /tmp/some-project)"
25新增:n2="$(_agent_vm_name /tmp/some-project)"
26新增:check "deterministic for the same directory" "$n1" "$n2"
27新增:if [ "$(_agent_vm_name /tmp/a)" != "$(_agent_vm_name /tmp/b)" ]; then
28新增: pass "different directories get different names"
29新增:else
30新增: fail "different directories collide"
31新增:fi
32新增:case "$(_agent_vm_name /tmp/some-project)" in
33新增: agent-vm-some-project-*) pass "name carries the directory basename" ;;
34新增: *) fail "unexpected name shape: $(_agent_vm_name /tmp/some-project)" ;;
35新增:esac
36新增:case "$(_agent_vm_name '/tmp/Weird Name!')" in
37新增: *[!a-zA-Z0-9-]*) fail "name not sanitised: $(_agent_vm_name '/tmp/Weird Name!')" ;;
38新增: *) pass "odd characters are sanitised out of the name" ;;
39新增:esac
40新增:
41新增:# =============================================================================
42新增:section "exact line matching (no pipe into grep -q)"
43新增:# =============================================================================
44新增:if _agent_vm_has_line "$(printf 'alpha\nbeta\n')" beta; then pass "finds an exact line"
45新增:else fail "missed an exact line"; fi
46新增:if _agent_vm_has_line "$(printf 'alphabet\n')" alpha; then fail "matched a prefix"
47新增:else pass "does not match a prefix"; fi
48新增:if _agent_vm_has_line "" alpha; then fail "matched in empty input"
49新增:else pass "no match in empty input"; fi
50新增:
51新增:# =============================================================================
52新增:section "resource comparison (only prompt on a real change)"
53新增:# =============================================================================
54新增:VM=agent-vm-proj-deadbeef
55新增:check "reads current resources" "$(_agent_vm_resources "$VM")" "4|8|32"
56新增:if _agent_vm_resources_differ "$VM" 4 8 32; then
57新增: fail "identical request (4/8/32) seen as a change"
58新增:else
59新增: pass "identical request (4/8/32) is not a change"
60新增:fi
61新增:_agent_vm_resources_differ "$VM" 8 8 32 && pass "cpus 4->8 detected" || fail "cpus 4->8 missed"
62新增:_agent_vm_resources_differ "$VM" 4 16 32 && pass "memory 8->16 detected" || fail "memory 8->16 missed"
63新增:_agent_vm_resources_differ "$VM" 4 8 64 && pass "disk grow 32->64 detected" || fail "disk grow missed"
64新增:if _agent_vm_resources_differ "$VM" 4 8 10; then
65新增: fail "disk shrink 32->10 treated as a change (Lima cannot shrink)"
66新增:else
67新增: pass "disk shrink 32->10 ignored (Lima cannot shrink)"
68新增:fi
69新增:if _agent_vm_resources_differ "$VM" "" "" ""; then
70新增: fail "empty request seen as a change"
71新增:else
72新增: pass "empty request is not a change"
73新增:fi
74新增:_agent_vm_resources_differ agent-vm-unknown 4 8 32 \
75新增: && pass "unknown VM does not claim 'no change'" \
76新增: || fail "unknown VM treated as identical"
77新增:
78新增:# =============================================================================
79新增:section "staleness (never guess from a missing file)"
80新增:# =============================================================================
81新增:mkdir -p "$HOME/.agent-vm"
82新增:check "no markers at all -> unknown" "$(_agent_vm_stale_state vmx)" "unknown"
83新增:echo 111 > "$HOME/.agent-vm/.agent-vm-base-version"
84新增:check "base known, VM unmarked -> stale" "$(_agent_vm_stale_state vmx)" "1"
85新增:echo 111 > "$HOME/.agent-vm/.agent-vm-version-vmx"
86新增:check "same version -> up to date" "$(_agent_vm_stale_state vmx)" "0"
87新增:echo 222 > "$HOME/.agent-vm/.agent-vm-base-version"
88新增:check "base newer -> stale" "$(_agent_vm_stale_state vmx)" "1"
89新增:rm -f "$HOME/.agent-vm/.agent-vm-base-version" "$HOME/.agent-vm/.agent-vm-version-vmx"
90新增:
91新增:# =============================================================================
92新增:section "base readiness (a half-provisioned template is not a base)"
93新增:# =============================================================================
94新增:# The stub always lists agent-vm-base, so what changes below is only the
95新增:# marker, which is exactly the state a setup interrupted while provisioning
96新增:# leaves: the template is in Lima, nothing is installed in it.
97新增:if _agent_vm_base_exists; then
98新增: fail "template listed but no version marker -> treated as a usable base"
99新增:else
100新增: pass "template listed but no version marker -> not a usable base"
101新增:fi
102新增:echo 111 > "$HOME/.agent-vm/.agent-vm-base-version"
103新增:if _agent_vm_base_exists; then
104新增: pass "template listed and marked -> usable base"
105新增:else
106新增: fail "a completed setup is not recognised"
107新增:fi
108新增:# And a failed query still answers "could not ask", not "no base": info turns
109新增:# that status into `unknown`, and a caller told 0 would offer to rebuild a
110新增:# base VM that exists.
111新增:mkdir -p "$SB/brokenlima"
112新增:printf '#!/usr/bin/env bash\nexit 1\n' > "$SB/brokenlima/limactl"
113新增:chmod +x "$SB/brokenlima/limactl"
114新增:( PATH="$SB/brokenlima:$PATH"; _agent_vm_base_exists; [ "$?" = 2 ] ) \
115新增: && pass "a failing limactl keeps the 'unknown' status" \
116新增: || fail "a failing limactl no longer reports status 2"
117新增:
118新增:# =============================================================================
119新增:section "project VMs (who the post-setup --reset note is for)"
120新增:# =============================================================================
121新增:check "the template is not a project VM" \
122新增: "$(_agent_vm_project_vms)" "agent-vm-proj-deadbeef"
123新增:# A first install: the base is there, nothing has been cloned from it yet, and
124新增:# suggesting --reset would point at nothing.
125新增:mkdir -p "$SB/baseonly"
126新增:cat > "$SB/baseonly/limactl" <<'STUB'
127新增:#!/usr/bin/env bash
128新增:[ "$1" = list ] && echo "agent-vm-base"
129新增:exit 0
130新增:STUB
131新增:chmod +x "$SB/baseonly/limactl"
132新增:check "nothing cloned yet -> no project VM" \
133新增: "$( PATH="$SB/baseonly:$PATH"; _agent_vm_project_vms )" ""
134新增:check "a failing limactl lists nothing rather than erroring" \
135新增: "$( PATH="$SB/brokenlima:$PATH"; _agent_vm_project_vms )" ""
136新增:
137新增:# =============================================================================
138新增:section "machine-readable surface"
139新增:# =============================================================================
140新增:check "version" "$(agent-vm version)" "$AGENT_VM_VERSION"
141新增:check "--version" "$(agent-vm --version)" "$AGENT_VM_VERSION"
142新增:check "name matches the internal helper" "$(agent-vm name "$PROJ")" "$(_agent_vm_name "$PROJ")"
143新增:
144新增:info_out="$(agent-vm info "$PROJ")"
145新增:get() { printf '%s\n' "$info_out" | grep "^$1=" | cut -d= -f2-; }
146新增:check "info: version" "$(get version)" "$AGENT_VM_VERSION"
147新增:check "info: template" "$(get template)" "agent-vm-base"
148新增:check "info: dir" "$(get dir)" "$PROJ"
149新增:check "info: base_exists" "$(get base_exists)" "1"
150新增:check "info: vm_exists" "$(get vm_exists)" "0"
151新增:check "info: vm_stale unknown with no VM" "$(get vm_stale)" "unknown"
152新增:check "info: ssh_host is Lima's alias" "$(get ssh_host)" "lima-$(_agent_vm_name "$PROJ")"
153新增:check "info: ssh_config unknown with no VM" "$(get ssh_config)" "unknown"
154新增:# This limactl answers `validate` with nothing: a Lima agent-vm cannot read.
155新增:check "info: git_protected unknown when Lima cannot tell" "$(get git_protected)" "unknown"
156新增:case "$(get security_questions)" in
157新增: lima-unknown|lima-unknown,*) pass "info: security_questions names the Lima that cannot tell" ;;
158新增: *) fail "info: security_questions: $(get security_questions)" ;;
159新增:esac
160新增:check "info: key count" "$(printf '%s\n' "$info_out" | grep -c '^[a-z_]*=')" "14"
161新增:
162新增:# Every key must be present even with no Lima on the box. Build a PATH with the
163新增:# limactl-bearing directories dropped rather than a hardcoded one, so this also
164新增:# holds on a machine where Lima is genuinely installed.
165新增:nolima_path=""
166新增:_rest="$PATH:"
167新增:while [ -n "$_rest" ]; do
168新增: _d="${_rest%%:*}"
169新增: _rest="${_rest#*:}"
170新增: [ -z "$_d" ] && continue
171新增: [ -x "$_d/limactl" ] && continue
172新增: nolima_path="${nolima_path:+$nolima_path:}$_d"
173新增:done
174新增:nolima="$(PATH="$nolima_path" bash -c 'source "$1"; agent-vm info "$2"' _ "$AGENT_VM_SH" "$PROJ" 2>/dev/null)"
175新增:check "info without limactl still prints 14 keys" \
176新增: "$(printf '%s\n' "$nolima" | grep -c '^[a-z_]*=')" "14"
177新增:case "$nolima" in
178新增: *"base_exists=unknown"*) pass "info without limactl says unknown, not 0" ;;
179新增: *) fail "info without limactl should report unknown" ;;
180新增:esac
181新增:
182新增:# =============================================================================
183新增:section "directory arguments are normalised"
184新增:# =============================================================================
185新增:# The VM name is a hash of the directory STRING, and the VM-running commands
186新增:# always feed it `$(pwd)`. Without normalising, `name /tmp` and `name /tmp/`
187新增:# would be two different VMs for one directory, and neither need match what
188新增:# `cd /tmp && agent-vm opencode` produces.
189新增:canon="$(agent-vm name "$PROJ")"
190新增:check "trailing slash agrees" "$(agent-vm name "$PROJ/")" "$canon"
191新增:check "relative path agrees" "$(cd "$PROJ" && agent-vm name .)" "$canon"
192新增:check "no argument means cwd" "$(cd "$PROJ" && agent-vm name)" "$canon"
193新增:check "info agrees with name" "$(agent-vm info "$PROJ/" | grep '^vm_name=' | cut -d= -f2)" "$canon"
194新增:if agent-vm name "$SB/does-not-exist" >/dev/null 2>&1; then
195新增: fail "a nonexistent directory should be rejected, not hashed"
196新增:else
197新增: pass "a nonexistent directory is rejected"
198新增:fi
199新增:
200新增:# CDPATH must not leak into the resolution. With it set, `cd <relative>` searches
201新增:# it before the current directory AND prints where it landed — so an unprotected
202新增:# `cd "$dir" && pwd` both emits a stray line and resolves a different directory
203新增:# than the `-d` test validated. Two decoys with the same basename make the
204新增:# difference observable.
205新增:mkdir -p "$SB/decoy/twin" "$SB/real/twin"
206新增:check "CDPATH does not redirect the lookup" \
207新增: "$(cd "$SB/real" && CDPATH="$SB/decoy" agent-vm name twin)" \
208新增: "$(agent-vm name "$SB/real/twin")"
209新增:
210新增:# Stray `cd` output has to be observed on `info`, not on `name`: the name is run
211新增:# through `tr -cs 'a-zA-Z0-9' '-'`, which would quietly turn the extra newline
212新增:# into a dash. `info` prints the resolved path raw, so a leaked line shows up as
213新增:# one line too many among the key=value pairs.
214新增:check "no stray cd output leaks into info" \
215新增: "$(cd "$SB/real" && CDPATH="$SB/decoy" agent-vm info twin | wc -l | tr -d ' ')" "14"
新增tests/02-setup-output.sh+123 −0看文件
@@ -0,0 +1,123 @@
1新增:# =============================================================================
2新增:section "--preinstall parsing"
3新增:# =============================================================================
4新增:preinstall_exports() {
5新增: export AGENT_VM_TEST_CAPTURE="$SB/piped.sh"
6新增: : > "$AGENT_VM_TEST_CAPTURE"
7新增: _agent_vm_setup --preinstall="$1" >/dev/null 2>&1
8新增: grep -E "^export AGENT_VM_INSTALL_$2=" "$AGENT_VM_TEST_CAPTURE" | cut -d= -f2
9新增:}
10新增:check "default: node on" "$(preinstall_exports default NODE)" "1"
11新增:check "default: ruby off" "$(preinstall_exports default RUBY)" "0"
12新增:check "all: ruby on" "$(preinstall_exports all RUBY)" "1"
13新增:check "none: node off" "$(preinstall_exports none NODE)" "0"
14新增:check "explicit subset: gh on" "$(preinstall_exports node,gh GH)" "1"
15新增:check "explicit subset: docker off" "$(preinstall_exports node,gh DOCKER)" "0"
16新增:check "default leaves pi out" "$(preinstall_exports default PI)" "0"
17新增:check "all installs pi" "$(preinstall_exports all PI)" "1"
18新增:check "naming pi installs it" "$(preinstall_exports default,pi PI)" "1"
19新增:check "pi pulls node in" "$(preinstall_exports pi NODE)" "1"
20新增:
21新增:section "--preinstall: MCP names"
22新增:check "default wires the chrome MCP" "$(preinstall_exports default MCP_CHROME)" "1"
23新增:check "default leaves playwright out" "$(preinstall_exports default MCP_PLAYWRIGHT)" "0"
24新增:check "all wires both" "$(preinstall_exports all MCP_CHROME)" "1"
25新增:check "all wires playwright too" "$(preinstall_exports all MCP_PLAYWRIGHT)" "1"
26新增:# The point of the mcp-* names: a caller that manages MCP servers per project
27新增:# just omits them. Nothing new has to be passed, so older builds stay compatible.
28新增:check "omitting mcp-chrome disables it" "$(preinstall_exports node,gh,chromium,opencode MCP_CHROME)" "0"
29新增:check "naming mcp-chrome enables it" "$(preinstall_exports node,chromium,opencode,mcp-chrome MCP_CHROME)" "1"
30新增:check "naming mcp-playwright enables it" "$(preinstall_exports node,chromium,opencode,mcp-playwright MCP_PLAYWRIGHT)" "1"
31新增:
32新增:section "startup: when the VM's base was built"
33新增:( AGENT_VM_STATE_DIR="$SB/base-age"; mkdir -p "$AGENT_VM_STATE_DIR"
34新增: _agent_vm_resources() { echo '1|3|10'; }
35新增: echo 1790803800 > "$AGENT_VM_STATE_DIR/.agent-vm-version-vmx"
36新增: out="$(_agent_vm_print_resources vmx)"
37新增: case "$out" in *"Base VM: built $(_agent_vm_epoch_date 1790803800 +%F)") echo ok ;; *) echo "date: $out" ;; esac
38新增: case "$(_agent_vm_print_resources agent-vm-base)" in *"Base VM"*) echo "base: said" ;; *) echo ok ;; esac
39新增: echo junk > "$AGENT_VM_STATE_DIR/.agent-vm-version-vmx"
40新增: case "$(_agent_vm_print_resources vmx)" in *"Base VM"*) echo "junk: said" ;; *) echo ok ;; esac
41新增:) > "$SB/base-age.out" 2>&1
42新增:check "the date of the VM's base, nothing without a record" \
43新增: "$(cat "$SB/base-age.out")" "$(printf 'ok\nok\nok')"
44新增:
45新增:section "terminal modes after a session"
46新增:check "nothing written when stdout is not a terminal" "$(_agent_vm_reset_term_modes | wc -c | tr -d ' ')" "0"
47新增:if command -v script >/dev/null 2>&1 && script -qc true /dev/null >/dev/null 2>&1; then
48新增: check "mouse tracking and kitty keyboard turned off on a terminal" \
49新增: "$(AGENT_VM_SH="$AGENT_VM_SH" script -qc 'bash -c ". \"\$AGENT_VM_SH\"; _agent_vm_reset_term_modes"' /dev/null | grep -c $'\033\\[?1003l.*\033\\[<u')" "1"
50新增:fi
51新增:
52新增:section "boxed notices"
53新增:check "a paragraph wraps at the width" \
54新增: "$(printf 'aaa bbb ccc ddd\n' | _agent_vm_wrap 8)" "$(printf 'aaa bbb\nccc ddd')"
55新增:check "an indented command is kept whole" \
56新增: "$(printf ' git config --global x y\n' | _agent_vm_wrap 8)" " git config --global x y"
57新增:box="$(printf 'one two\n\n cmd --flag\n' | _agent_vm_box "Title" 2>&1)"
58新增:check "the box: title rule, body, bottom rule, on stderr" "$box" "$(printf '\n+- Title %s\n|\n| one two\n|\n| cmd --flag\n|\n+%s' \
59新增: "$(printf '%*s' 63 '' | tr ' ' -)" "$(printf '%*s' 71 '' | tr ' ' -)")"
60新增:check "nothing on stdout" "$(printf 'x\n' | _agent_vm_box "T" 2>/dev/null)" ""
61新增:if script -qec true /dev/null >/dev/null 2>&1; then
62新增: narrow="$(script -qec "stty rows 40 cols 40; bash -c 'source \"$AGENT_VM_SH\"; _agent_vm_bare_repo_hint | _agent_vm_box \"Git: repositories not named .git\"'" /dev/null 2>&1 | tr -d '\r')"
63新增: # Wider lines than the terminal are only the commands, kept whole.
64新增: wide="$(printf '%s\n' "$narrow" | awk 'length($0) > 40 && $0 !~ /^\| /')"
65新增: check "a 40-column terminal gets a 40-column box" "$wide" ""
66新增:else
67新增: printf ' skip narrow box test (no util-linux script)\n'
68新增:fi
69新增:
70新增:section "setup: the install output"
71新增:# A pipe into the output window must not swallow the install's failure, and
72新增:# the log must keep what the window drops.
73新增:out="$(AGENT_VM_TEST_SHELL_FAIL=1 _agent_vm_setup --preinstall=none 2>&1)"
74新增:check "a failed install still fails setup" "$?" "1"
75新增:case "$out" in
76新增: *"Setup script failed. Full log: $HOME/.agent-vm/setup.log"*) pass "the failure names the log" ;;
77新增: *) fail "no log named: $out" ;;
78新增:esac
79新增:case "$(cat "$HOME/.agent-vm/setup.log")" in
80新增: *"Attempting to download the image"*"E: boom") pass "one log, every step in order: the start, then the install" ;;
81新增: *) fail "setup.log: $(cat "$HOME/.agent-vm/setup.log")" ;;
82新增:esac
83新增:out="$(AGENT_VM_TEST_START_FAIL=1 _agent_vm_setup --preinstall=none 2>&1)"
84新增:check "a failed start fails setup" "$?" "1"
85新增:case "$out" in
86新增: *"Failed to start base VM. Full log: $HOME/.agent-vm/setup.log"*) pass "and names the log" ;;
87新增: *) fail "start failure: $out" ;;
88新增:esac
89新增:case "$(cat "$HOME/.agent-vm/setup.log")" in
90新增: *'msg="no start"'*) pass "which has Lima's error" ;;
91新增: *) fail "setup.log after a failed start: $(cat "$HOME/.agent-vm/setup.log")" ;;
92新增:esac
93新增:_agent_vm_setup --preinstall=none >/dev/null 2>&1
94新增:check "a good install passes" "$?" "0"
95新增:check "no status file is left behind" "$([ -e "$HOME/.agent-vm/setup.log.status" ] && echo left || echo gone)" "gone"
96新增:check "without a terminal, every line passes through" \
97新增: "$(printf 'a\nb' | _agent_vm_scroll_window "$SB/window.log")" "$(printf 'a\nb')"
98新增:check "and reaches the log" "$(cat "$SB/window.log")" "$(printf 'a\nb')"
99新增:# On a terminal: never more than 10 lines redrawn, and cleared at the end.
100新增:if script -qec true /dev/null >/dev/null 2>&1; then
101新增: win="$(script -qec "stty rows 40 cols 80; bash -c 'source \"$AGENT_VM_SH\"; seq 1 30 | _agent_vm_scroll_window \"$SB/tty.log\"'" /dev/null 2>&1 | cat -v)"
102新增: case "$win" in
103新增: *'^[[11A'*) fail "the window grew past 10 lines" ;;
104新增: *'^[[10A'*'^[[10A^M^[[J') pass "a 10-line window, cleared at the end" ;;
105新增: *) fail "unexpected window output: $(printf '%s' "$win" | tail -c 200)" ;;
106新增: esac
107新增: check "the log keeps all 30 lines" "$(wc -l < "$SB/tty.log" | tr -d ' ')" "30"
108新增: lima_line='time="2026-01-01T00:00:00Z" level=info msg="Attempting to download the image" arch=aarch64 digest=sha256:0123'
109新增: win="$(script -qec "stty rows 40 cols 80; bash -c 'source \"$AGENT_VM_SH\"; printf \"%s\\n\" '\''$lima_line'\'' | _agent_vm_scroll_window \"$SB/lima.log\"'" /dev/null 2>&1 | cat -v)"
110新增: case "$win" in
111新增: *'[2mAttempting to download the image^M'*) pass "a Lima log line shows its message only" ;;
112新增: *) fail "Lima line in the window: $win" ;;
113新增: esac
114新增: check "and the log keeps it whole" "$(cat "$SB/lima.log")" "$lima_line"
115新增:else
116新增: printf ' skip terminal window test (no util-linux script)\n'
117新增:fi
118新增:
119新增:if _agent_vm_setup --preinstall=node,not-a-real-name >/dev/null 2>&1; then
120新增: fail "an unknown --preinstall name should be fatal"
121新增:else
122新增: pass "an unknown --preinstall name is fatal"
123新增:fi
新增tests/03-install.sh+200 −0看文件
@@ -0,0 +1,200 @@
1新增:# =============================================================================
2新增:section "script dir resolves through symlinks"
3新增:# =============================================================================
4新增:# `agent-vm install` puts a symlink on PATH. Without following it, AGENT_VM_SCRIPT_DIR
5新增:# points at the link's directory and `agent-vm setup` cannot find
6新增:# agent-vm.setup.sh, which lives next to the real file.
7新增:REALDIR="$(CDPATH= cd -P -- "$(dirname "$AGENT_VM_SH")" >/dev/null && pwd)"
8新增:mkdir -p "$SB/link1" "$SB/link2"
9新增:ln -sf "$AGENT_VM_SH" "$SB/link1/agent-vm"
10新增:ln -sf "$SB/link1/agent-vm" "$SB/link2/agent-vm"
11新增:# Paths go in as positional parameters: interpolating them into single-quoted
12新增:# shell text would break on a path containing a single quote.
13新增:script_dir_of() {
14新增: bash -c 'source "$1" 2>/dev/null; printf "%s" "$AGENT_VM_SCRIPT_DIR"' _ "$1"
15新增:}
16新增:# Link resolution has nothing to resolve where ln -s plants copies (Windows
17新增:# runners lack the privilege): those checks skip, with the reason printed.
18新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
19新增:check "direct symlink" "$(script_dir_of "$SB/link1/agent-vm")" "$REALDIR"
20新增:check "chain of two symlinks" "$(script_dir_of "$SB/link2/agent-vm")" "$REALDIR"
21新增:else
22新增: printf ' skip symlink resolution (ln -s plants copies on this machine)\n'
23新增:fi
24新增:check "no symlink (the historical sourcing)" "$(script_dir_of "$AGENT_VM_SH")" "$REALDIR"
25新增:
26新增:# Sourced from a shell rc, the current directory is anyone's: a project where
27新增:# the agent may have written a lib/ui.sh.
28新增:ELSEWHERE="$SB/elsewhere"; mkdir -p "$ELSEWHERE/lib"
29新增:printf 'touch "%s/planted-lib-ran"\n' "$SB" > "$ELSEWHERE/lib/ui.sh"
30新增:source_from_elsewhere() { # <file>
31新增: ( cd "$ELSEWHERE" && bash -c '. "$1" >/dev/null 2>&1; printf "%s" "$AGENT_VM_SCRIPT_DIR"' _ "$1" )
32新增:}
33新增:check "sourced by bash from another directory: lib/ next to agent-vm.sh" \
34新增: "$(source_from_elsewhere "$AGENT_VM_SH")" "$REALDIR"
35新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
36新增: check "sourced by bash through a symlink, from another directory" \
37新增: "$(source_from_elsewhere "$SB/link2/agent-vm")" "$REALDIR"
38新增:fi
39新增:check "sourced by bash: a lib/ in the current directory never runs" \
40新增: "$([ -e "$SB/planted-lib-ran" ] && echo ran || echo no)" "no"
41新增:rm -f "$SB/planted-lib-ran"
42新增:
43新增:# zsh (the ~/.zshrc line of 0.1.0's installer): a function running the file
44新增:# with bash, and nothing else, whatever the user's options. From another
45新增:# directory, through links, and from a path with a space and a quote.
46新增:if command -v zsh >/dev/null 2>&1; then
47新增: zsh_source() { # <file>: sourced, then `agent-vm version`
48新增: ( cd "$ELSEWHERE" && zsh -fc 'setopt noclobber ksh_arrays sh_word_split nounset
49新增: . "$1"; print -r -- "${AGENT_VM_SCRIPT_DIR-unset} $(whence -w agent-vm)"; agent-vm version' _ "$1" 2>&1 )
50新增: }
51新增: check "sourced by zsh: only an agent-vm function, which runs the command" \
52新增: "$(zsh_source "$AGENT_VM_SH")" "unset agent-vm: function
53新增:$AGENT_VM_VERSION"
54新增: if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
55新增: check "sourced by zsh through a symlink, from another directory" \
56新增: "$(zsh_source "$SB/link2/agent-vm")" "unset agent-vm: function
57新增:$AGENT_VM_VERSION"
58新增: fi
59新增: ODD="$SB/it's odd"; mkdir -p "$ODD"; cp -R "$REALDIR/agent-vm.sh" "$REALDIR/lib" "$ODD/"
60新增: check "sourced by zsh from a path with a space and a quote" \
61新增: "$(zsh_source "$ODD/agent-vm.sh")" "unset agent-vm: function
62新增:$AGENT_VM_VERSION"
63新增: rm -rf "$ODD"
64新增: check "sourced by zsh by a relative path: still found from another directory" \
65新增: "$(cd "$REALDIR" && zsh -fc '. ./agent-vm.sh; cd "$1" && agent-vm version' _ "$ELSEWHERE" 2>&1)" "$AGENT_VM_VERSION"
66新增: out="$(cd "$ELSEWHERE" && zsh -fc '. "$1"; agent-vm nosuchcmd' _ "$AGENT_VM_SH" 2>&1; echo "st=$?")"
67新增: case "$out" in *"st=0") fail "sourced by zsh: a failing command returns 0: $out" ;;
68新增: *) pass "sourced by zsh: a failing command's status comes back" ;; esac
69新增: check "sourced by zsh: a lib/ in the current directory never runs" \
70新增: "$([ -e "$SB/planted-lib-ran" ] && echo ran || echo no)" "no"
71新增: rm -f "$SB/planted-lib-ran"
72新增: check "run by zsh: runs under bash" "$(zsh "$AGENT_VM_SH" version 2>&1)" "$AGENT_VM_VERSION"
73新增:else
74新增: printf ' skip sourced by zsh (zsh is not installed)\n'
75新增:fi
76新增:
77新增:# lib/ is found next to the real file; a copy without it says so and stops.
78新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
79新增:check "through a symlink, lib/ loads too" \
80新增: "$(bash "$SB/link2/agent-vm" version 2>&1)" "$AGENT_VM_VERSION"
81新增:else
82新增: printf ' skip through a symlink (ln -s plants copies on this machine)\n'
83新增:fi
84新增:mkdir -p "$SB/lone"; cp "$AGENT_VM_SH" "$SB/lone/"
85新增:out="$(bash "$SB/lone/agent-vm.sh" version 2>&1)"
86新增:case "$?:$out" in
87新增: 1:"agent-vm: cannot load $SB/lone/lib/ui.sh") pass "run without lib/: says which file, exits 1" ;;
88新增: *) fail "run without lib/: $out" ;;
89新增:esac
90新增:out="$(bash -c 'source "$1" 2>/dev/null; echo "returned $?"; type agent-vm >/dev/null 2>&1 || echo "no agent-vm"' _ "$SB/lone/agent-vm.sh")"
91新增:check "sourced without lib/: returns 1, defines no half-loaded agent-vm" "$out" "returned 1
92新增:no agent-vm"
93新增:
94新增:# =============================================================================
95新增:section "install / uninstall"
96新增:# =============================================================================
97新增:# A throwaway HOME and bin directory. TTY=1 stands for a terminal to ask on,
98新增:# ANSWER for the reply (1 yes, 0 no), BASE=1 for a base VM already built.
99新增:IH="$SB/ihome"; IBIN="$SB/ibin"
100新增:mkdir -p "$IH"
101新增:inst() {
102新增: ( export HOME="$IH" AGENT_VM_BIN_DIR="$IBIN" SHELL=/bin/zsh PATH="$IBIN:$PATH"
103新增: _agent_vm_have_tty() { [ -n "${TTY:-}" ]; }
104新增: _agent_vm_ask_yn() { echo "${ANSWER:-1}"; }
105新增: _agent_vm_base_exists() { [ -n "${BASE:-}" ]; }
106新增: _agent_vm_setup() { echo "SETUP RAN $#"; return "${SETUP_RC:-0}"; }
107新增: agent-vm "$@" ) 2>&1
108新增:}
109新增:out="$(inst install)"
110新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
111新增:check "install: the link points at this agent-vm.sh" "$(readlink "$IBIN/agent-vm" 2>/dev/null)" "$REALDIR/agent-vm.sh"
112新增:else
113新增: printf ' skip install: readlink (ln -s plants copies on this machine)\n'
114新增: # A copy stands where the link would: clear it so the installs below start
115新增: # clean instead of tripping over it.
116新增: rm -f "$IBIN/agent-vm"
117新增:fi
118新增:case "$out" in *"not on your PATH"*) fail "install: PATH hint while the directory is on PATH" ;; *) pass "install: no PATH hint when the directory is on PATH" ;; esac
119新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
120新增:out="$( ( export HOME="$IH" AGENT_VM_BIN_DIR="$IBIN"; _agent_vm_have_tty() { return 1; }; agent-vm install ) 2>&1)"
121新增:case "$out" in *"already linked"*"$IBIN is not on your PATH"*'export PATH="'"$IBIN"':$PATH"'*) pass "install again: already linked, and the PATH line to add" ;; *) fail "install again: $out" ;; esac
122新增:else
123新增: printf ' skip install again (ln -s plants copies on this machine)\n'
124新增:fi
125新增:# The link is all install puts in place: no shell rc is written, whatever the
126新增:# shell. A `source agent-vm.sh` line in ~/.profile broke every sh login (dash
127新增:# has no `source`, and the file is bash).
128新增:for sh in /bin/zsh /bin/bash /usr/bin/fish; do
129新增: rm -f "$IBIN/agent-vm"
130新增: ( export SHELL="$sh"; TTY=1 BASE=1 inst install ) >/dev/null
131新增:done
132新增:check "install writes no shell rc, for zsh, bash or fish" "$(ls -A "$IH")" ""
133新增:rm -f "$IBIN/agent-vm"
134新增:# An rc line from before 0.2.0 is named, not edited.
135新增:printf 'source "%s"\n' "$REALDIR/agent-vm.sh" > "$IH/.zshrc"
136新增:out="$(BASE=1 inst install)"
137新增:case "$out" in *"still sources agent-vm.sh"*"can remove"*) pass "an old rc line is named as no longer needed" ;; *) fail "old rc line: $out" ;; esac
138新增:check "and left as it was" "$(cat "$IH/.zshrc")" "source \"$REALDIR/agent-vm.sh\""
139新增:rm -f "$IH/.zshrc" "$IBIN/agent-vm"
140新增:check "install takes no argument (exit 2)" "$(inst install --force >/dev/null; echo $?)" "2"
141新增:
142新增:# Then setup, when there is no base yet and a terminal to ask on.
143新增:# Each install below starts from a clean bin dir: without symlink privilege
144新增:# an install leaves a copy behind, which the next one would read as a foreign
145新增:# file. Recreating the link each time is harmless where links are real.
146新增:clean_bin() { rm -f "$IBIN/agent-vm"; }
147新增:clean_bin
148新增:case "$(TTY=1 inst install)" in *"SETUP RAN 0"*) pass "no base, yes: setup runs" ;; *) fail "no base, yes: setup did not run" ;; esac
149新增:clean_bin
150新增:check "no base, setup fails: install says so" "$(TTY=1 SETUP_RC=3 inst install >/dev/null; echo $?)" "3"
151新增:clean_bin
152新增:out="$(TTY=1 ANSWER=0 inst install)"
153新增:case "$out" in *"SETUP RAN"*) fail "no base, no: setup ran" ;; *"agent-vm setup "*) pass "no base, no: setup is named, not run" ;; *) fail "no base, no: $out" ;; esac
154新增:clean_bin
155新增:out="$(inst install)"
156新增:case "$out" in *"SETUP RAN"*) fail "no terminal: setup ran" ;; *"agent-vm setup "*) pass "no terminal: setup is named, not run" ;; *) fail "no terminal: $out" ;; esac
157新增:clean_bin
158新增:out="$(TTY=1 BASE=1 inst install)"
159新增:case "$out" in *"SETUP RAN"*|*"agent-vm setup "*) fail "base built: setup offered again" ;; *"agent-vm claude"*) pass "base built: points at an agent instead" ;; *) fail "base built: $out" ;; esac
160新增:
161新增:# Someone else's file or link at that path is never replaced.
162新增:rm -f "$IBIN/agent-vm"; echo mine > "$IBIN/agent-vm"
163新增:check "a file of the user's: refused" "$(inst install >/dev/null; echo $?)" "1"
164新增:check "and left as it was" "$(cat "$IBIN/agent-vm")" "mine"
165新增:out="$(inst uninstall)"
166新增:check "uninstall: a file of the user's is left" "$(cat "$IBIN/agent-vm")" "mine"
167新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
168新增:rm -f "$IBIN/agent-vm"; ln -s "$SB/nowhere" "$IBIN/agent-vm"
169新增:out="$(inst install)"
170新增:check "a dangling link: refused, not overwritten" "$(inst install >/dev/null; echo $?):$(readlink "$IBIN/agent-vm")" "1:$SB/nowhere"
171新增:case "$out" in *"already exists and is not a link to"*"AGENT_VM_BIN_DIR"*) pass "and says why, with the way out" ;; *) fail "dangling link: $out" ;; esac
172新增:else
173新增: printf ' skip dangling link (ln -s plants copies on this machine)\n'
174新增:fi
175新增:rm -f "$IBIN/agent-vm"
176新增:
177新增:# uninstall removes our link and names the rc line it leaves.
178新增:inst install >/dev/null
179新增:printf 'source "%s"\n' "$REALDIR/agent-vm.sh" > "$IH/.zshrc"
180新增:out="$(inst uninstall)"
181新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
182新增:[ ! -e "$IBIN/agent-vm" ] && [ ! -L "$IBIN/agent-vm" ] && pass "uninstall: our link is removed" || fail "uninstall: the link is still there"
183新增:else
184新增: printf ' skip uninstall: link removal (ln -s plants copies on this machine)\n'
185新增: rm -f "$IBIN/agent-vm"
186新增:fi
187新增:case "$out" in *"still sources agent-vm.sh"*) pass "uninstall: names the rc line it leaves" ;; *) fail "uninstall: $out" ;; esac
188新增:check "uninstall: the rc is not edited" "$(cat "$IH/.zshrc")" "source \"$REALDIR/agent-vm.sh\""
189新增:case "$(inst uninstall)" in *"No link to remove"*) pass "uninstall again: nothing to remove, said" ;; *) fail "uninstall twice" ;; esac
190新增:
191新增:# The wrapper kept for the previous way: install.sh, and --uninstall. The rc
192新增:# already sources agent-vm.sh here, so nothing asks on a terminal.
193新增:( export HOME="$IH" AGENT_VM_BIN_DIR="$IBIN"; bash "$REALDIR/install.sh" >/dev/null 2>&1 )
194新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
195新增:check "install.sh: installs" "$(readlink "$IBIN/agent-vm" 2>/dev/null)" "$REALDIR/agent-vm.sh"
196新增:else
197新增: printf ' skip install.sh: readlink (ln -s plants copies on this machine)\n'
198新增:fi
199新增:( export HOME="$IH" AGENT_VM_BIN_DIR="$IBIN"; bash "$REALDIR/install.sh" --uninstall >/dev/null 2>&1 )
200新增:[ ! -L "$IBIN/agent-vm" ] && pass "install.sh --uninstall: uninstalls" || fail "install.sh --uninstall left the link"
新增tests/04-env.sh+304 −0看文件
@@ -0,0 +1,304 @@
1新增:# =============================================================================
2新增:section "env: the shared secrets file"
3新增:# =============================================================================
4新增:# This file is SOURCED by the VM's shell, so one bad escape costs every secret
5新增:# in it — not just the one that was mis-quoted. That is why the quoting lives
6新增:# here rather than in each integrator.
7新增:ENVHOME="$SB/envhome"; mkdir -p "$ENVHOME"
8新增:avenv() { HOME="$ENVHOME" bash "$AGENT_VM_SH" env "$@"; }
9新增:
10新增:avenv set ALBERT_API_KEY "k1" >/dev/null
11新增:avenv set AC_GIT_USER_NAME "O'Brien" >/dev/null
12新增:check "get returns the value" "$(avenv get ALBERT_API_KEY)" "k1"
13新增:check "a single quote survives" "$(avenv get AC_GIT_USER_NAME)" "O'Brien"
14新增:avenv set ALBERT_API_KEY "k2" >/dev/null
15新增:check "rotation replaces, not appends" "$(grep -c '^ALBERT_API_KEY=' "$ENVHOME/.agent-vm/env")" "1"
16新增:check "rotation keeps the fresh value" "$(avenv get ALBERT_API_KEY)" "k2"
17新增:check "the quoted entry still reads back" "$(avenv get AC_GIT_USER_NAME)" "O'Brien"
18新增:
19新增:# Without VALUE, set reads it from stdin: a secret on the command line lands
20新增:# in the shell history and in `ps`. One trailing newline goes, as echo adds
21新增:# it; the rest of the value is kept.
22新增:printf 'from-stdin\n' | avenv set STDIN_KEY >/dev/null
23新增:check "set without VALUE reads stdin" "$(avenv get STDIN_KEY)" "from-stdin"
24新增:printf 'two\nlines\n' | avenv set STDIN_KEY >/dev/null
25新增:check "a value on stdin keeps its inner newline" "$(avenv get STDIN_KEY)" "two
26新增:lines"
27新增:if avenv set STDIN_KEY </dev/null >/dev/null 2>&1; then
28新增: fail "set with no VALUE and nothing on stdin succeeded"
29新增:else
30新增: pass "set with no VALUE and nothing on stdin is refused"
31新增:fi
32新增:check "and the value is kept" "$(avenv get STDIN_KEY)" "two
33新增:lines"
34新增:avenv unset STDIN_KEY
35新增:
36新增:printf 'SOMEONE_ELSE=keep-me\n' >> "$ENVHOME/.agent-vm/env"
37新增:avenv set ALBERT_API_KEY "k3" >/dev/null
38新增:check "unmanaged lines are preserved" "$(grep -c '^SOMEONE_ELSE=keep-me$' "$ENVHOME/.agent-vm/env")" "1"
39新增:
40新增:avenv has ALBERT_API_KEY && pass "has: present key" || fail "has: present key"
41新增:avenv has NOPE_NOT_HERE && fail "has: absent key" || pass "has: absent key"
42新增:
43新增:# `has`/`get` must answer about the FILE. The subshell inherits this shell's
44新增:# environment, so without unsetting first, a merely-exported variable reads as
45新增:# stored — and agent-vm's own callers often run inside a VM that exports these.
46新增:if HOME="$ENVHOME" AMBIENT_ONLY=x bash "$AGENT_VM_SH" env has AMBIENT_ONLY; then
47新增: fail "has must ignore the ambient environment"
48新增:else
49新增: pass "has ignores the ambient environment"
50新增:fi
51新增:
52新增:check "list prints names only" "$(avenv list | sort | tr '\n' ' ')" "AC_GIT_USER_NAME ALBERT_API_KEY SOMEONE_ELSE "
53新增:if grep -q "O'Brien\|k3" <<< "$(avenv list)"; then fail "list must never print values"; else pass "list never prints values"; fi
54新增:
55新增:avenv unset ALBERT_API_KEY >/dev/null
56新增:avenv has ALBERT_API_KEY && fail "unset removed the key" || pass "unset removes the key"
57新增:check "unset keeps the others" "$(grep -c '^SOMEONE_ELSE=' "$ENVHOME/.agent-vm/env")" "1"
58新增:# Permission bits are emulated on Windows: the engine still chmods, but
59新增:# ls cannot show a mode the filesystem does not have.
60新增:if _agent_vm_on_windows; then
61新增: printf ' skip file is mode 600 (permission bits are emulated on Windows)\n'
62新增:else
63新增:check "file is mode 600" "$(ls -l "$ENVHOME/.agent-vm/env" | cut -c2-10)" "rw-------"
64新增:fi
65新增:
66新增:if avenv set "not-a-name" x >/dev/null 2>&1; then
67新增: fail "an invalid variable name must be rejected"
68新增:else
69新增: pass "an invalid variable name is rejected"
70新增:fi
71新增:
72新增:# The file has to survive being sourced the way the VM sources it.
73新增:val="$(set -a; . "$ENVHOME/.agent-vm/env"; set +a; printf '%s' "${AC_GIT_USER_NAME:-BROKEN}")"
74新增:check "the file sources cleanly in a shell" "$val" "O'Brien"
75新增:
76新增:# =============================================================================
77新增:section "state dir: overridable, and published"
78新增:# =============================================================================
79新增:# Integrators must not rebuild this path from $HOME. They can only stop doing
80新增:# that if the engine both publishes it and honours an override.
81新增:STATE_ALT="$SB/state-alt"
82新增:check "AGENT_VM_STATE_DIR is honoured" \
83新增: "$(AGENT_VM_STATE_DIR="$STATE_ALT" bash "$AGENT_VM_SH" info "$SB" | sed -n 's/^state_dir=//p')" \
84新增: "$STATE_ALT"
85新增:AGENT_VM_STATE_DIR="$STATE_ALT" bash "$AGENT_VM_SH" env set SOME_KEY v >/dev/null
86新增:if [ -f "$STATE_ALT/env" ]; then
87新增: pass "writes land in the overridden state dir"
88新增:else
89新增: fail "the override is published but not used for writes"
90新增:fi
91新增:
92新增:# =============================================================================
93新增:section "project-env: one env per project"
94新增:# =============================================================================
95新增:# Same file format and same quoting as the shared env — deliberately the same
96新增:# code — but it lives WITH the project, like the project runtime script, and
97新增:# moves, clones and disappears with it.
98新增:PENV="$SB/penv"; mkdir -p "$PENV/pa/.mytool" "$PENV/pb" "$PENV/state"
99新增:pe() { ( cd "$1" && AGENT_VM_STATE_DIR="$PENV/state" bash "$AGENT_VM_SH" project-env "${@:2}" ); }
100新增:if [[ -z "$AGENT_VM_HAS_PERL" ]]; then
101新增: printf ' skip project-env in the project (perl is not installed)\n'
102新增:else
103新增:
104新增:pe "$PENV/pa" set OPENCODE_CONFIG "/a/.albert-code/opencode.json" >/dev/null
105新增:pe "$PENV/pb" set OPENCODE_CONFIG "/b/.albert-code/opencode.json" >/dev/null
106新增:check "each project keeps its own value (a)" "$(pe "$PENV/pa" get OPENCODE_CONFIG)" "/a/.albert-code/opencode.json"
107新增:check "each project keeps its own value (b)" "$(pe "$PENV/pb" get OPENCODE_CONFIG)" "/b/.albert-code/opencode.json"
108新增:check "the file sits in the project, at the documented default" \
109新增: "$(ls -A "$PENV/pa" | grep '^\.agent-vm\.env$')" ".agent-vm.env"
110新增:if [ -z "$(ls -A "$PENV/state" 2>/dev/null)" ]; then
111新增: pass "nothing about a project is written into the state dir"
112新增:else
113新增: fail "project state leaked outside the project: $(ls -A "$PENV/state" | tr '\n' ' ')"
114新增:fi
115新增:pe "$PENV/pa" set NAME "O'Brien" >/dev/null
116新增:check "the shared quoting applies here too" "$(pe "$PENV/pa" get NAME)" "O'Brien"
117新增:if _agent_vm_on_windows; then
118新增: printf ' skip file is mode 600 (permission bits are emulated on Windows)\n'
119新增:else
120新增:check "the file is mode 600" "$(ls -l "$PENV/pa/.agent-vm.env" | cut -c2-10)" "rw-------"
121新增:fi
122新增:if grep -q "O'Brien" <<< "$(pe "$PENV/pa" list)"; then fail "list must never print values"; else pass "list never prints values"; fi
123新增:
124新增:# AGENT_VM_PROJECT_ENV, like AGENT_VM_PROJECT_RUNTIME: an integrator keeps its
125新增:# files in its own directory instead of cluttering the project root.
126新增:_pe_alt() { ( cd "$PENV/pa" && AGENT_VM_PROJECT_ENV=.mytool/env AGENT_VM_STATE_DIR="$PENV/state" bash "$AGENT_VM_SH" project-env "$@" ); }
127新增:_pe_alt set OPENCODE_CONFIG "/elsewhere" >/dev/null
128新增:check "AGENT_VM_PROJECT_ENV relocates the file" "$(cat "$PENV/pa/.mytool/env")" "OPENCODE_CONFIG='/elsewhere'"
129新增:check "and the default file is untouched by it" "$(pe "$PENV/pa" get OPENCODE_CONFIG)" "/a/.albert-code/opencode.json"
130新增:check "info publishes the path, so nobody rebuilds it" \
131新增: "$( ( cd "$PENV/pa" && AGENT_VM_PROJECT_ENV=.mytool/env AGENT_VM_STATE_DIR="$PENV/state" bash "$AGENT_VM_SH" info | sed -n 's/^project_env=//p' ) )" \
132新增: "$PENV/pa/.mytool/env"
133新增:fi
134新增:
135新增:# Precedence: the payload pushed into the VM is shared-then-project, because it
136新增:# is sourced — so a key set in both ends up with the project's value. Without
137新增:# this order, "per project" would mean nothing. The host only reads a project
138新增:# file kept outside the project; one inside is appended by the VM, after the
139新增:# payload (tests/20-project-files.sh).
140新增:( AGENT_VM_STATE_DIR="$PENV/state"
141新增: export AGENT_VM_PROJECT_ENV="$PENV/outside.env"
142新增: mkdir -p "$AGENT_VM_STATE_DIR"
143新增: printf "SHARED_ONLY='s'\nBOTH='shared'\n" > "$AGENT_VM_STATE_DIR/env"
144新增: printf "BOTH='project'\n" > "$PENV/outside.env"
145新增: payload="$(_agent_vm_env_payload "$PENV/pa")"
146新增: val="$(set -a; eval "$payload"; set +a; printf '%s' "${BOTH:-MISSING}")"
147新增: shared="$(set -a; eval "$payload"; set +a; printf '%s' "${SHARED_ONLY:-MISSING}")"
148新增: [ "$val" = "project" ] || { echo " BOTH=$val" >&2; exit 1; }
149新增: [ "$shared" = "s" ] || { echo " SHARED_ONLY=$shared" >&2; exit 1; } )
150新增:if [ $? -eq 0 ]; then
151新增: pass "the project's value wins, and shared keys still come through"
152新增:else
153新增: fail "wrong precedence between the shared env and the project env"
154新增:fi
155新增:# A shared file without a trailing newline must not glue onto the project's.
156新增:( AGENT_VM_STATE_DIR="$PENV/state"
157新增: export AGENT_VM_PROJECT_ENV="$PENV/outside.env"
158新增: printf "SHARED_LAST='s'" > "$AGENT_VM_STATE_DIR/env"
159新增: printf "BOTH='project'\n" > "$PENV/outside.env"
160新增: payload="$(_agent_vm_env_payload "$PENV/pa")"
161新增: grep -qx "BOTH='project'" <<< "$payload" )
162新增:check "a shared file with no final newline stays separate" "$?" "0"
163新增:( AGENT_VM_STATE_DIR="$PENV/state"
164新增: printf "S='s'\n" > "$AGENT_VM_STATE_DIR/env"
165新增: printf "IN_PROJECT='p'\n" > "$PENV/pa/.agent-vm.env"
166新增: _agent_vm_env_payload "$PENV/pa" ) > "$SB/payload-in-project"
167新增:check "a project file inside the project is not read by the host" "$(cat "$SB/payload-in-project")" "S='s'"
168新增:rm -f "$PENV/state/env" "$PENV/outside.env"
169新增:
170新增:# =============================================================================
171新增:section "project-env: the file is in a repository, so say so"
172新增:# =============================================================================
173新增:# The failure that matters for this file is committing it. The warning has to
174新增:# name the fix, and the fix has to work — a printed line nobody can apply is
175新增:# worse than no warning.
176新增:if [[ -z "$AGENT_VM_HAS_PERL" ]]; then
177新增: printf ' skip project-env set in a repository (perl is not installed)\n'
178新增:elif command -v git >/dev/null 2>&1; then
179新增: GI="$SB/gitrepo"; mkdir -p "$GI"
180新增: ( cd "$GI" && git init -q && git config user.email t@t && git config user.name t )
181新增: gpe() { ( cd "$GI" && AGENT_VM_STATE_DIR="$PENV/state" bash "$AGENT_VM_SH" project-env "$@" ); }
182新增:
183新增: err_out="$(gpe set K v 2>&1 >/dev/null)"
184新增: case "$err_out" in
185新增: *"not ignored by git"*) pass "warns when the file is not ignored" ;;
186新增: *) fail "no warning on an unignored file: $err_out" ;;
187新增: esac
188新增: check "the warning stays on stderr" "$(gpe set K v 2>/dev/null)" ""
189新增:
190新增: # The printed line, applied verbatim, must silence the warning.
191新增: line="$(printf '%s\n' "$err_out" | sed -n 's/^ *echo //p' | sed "s/ >>.*//; s/^'//; s/'$//")"
192新增: printf '%s\n' "$line" >> "$GI/.gitignore"
193新增: if [ -n "$(gpe set K v2 2>&1 >/dev/null)" ]; then
194新增: fail "the suggested line does not silence the warning: $(gpe set K v2 2>&1 >/dev/null)"
195新增: else
196新增: pass "the suggested line is the one that fixes it"
197新增: fi
198新增:
199新增: # .git/info/exclude counts too — a grep over .gitignore would miss it.
200新增: rm -f "$GI/.gitignore"
201新增: printf '.agent-vm.env\n' >> "$GI/.git/info/exclude"
202新增: if [ -n "$(gpe set K v3 2>&1 >/dev/null)" ]; then
203新增: fail "warns although .git/info/exclude covers the file"
204新增: else
205新增: pass "an exclude outside .gitignore is honoured"
206新增: fi
207新增:
208新增: # Already tracked: ignoring changes nothing, so the advice must differ.
209新增: : > "$GI/.git/info/exclude"
210新增: ( cd "$GI" && git add -f .agent-vm.env >/dev/null 2>&1 )
211新增: case "$(gpe set K v4 2>&1 >/dev/null)" in
212新增: *"tracked by git"*) pass "a tracked file gets the fix that actually applies" ;;
213新增: *) fail "a tracked file must not be told to add a gitignore line" ;;
214新增: esac
215新增:
216新增: # The printed fixes work as printed, run from the project, which can be a
217新增: # directory below the top of the repository, whose path can hold a space.
218新增: GS="$SB/git space"; mkdir -p "$GS/sub"
219新增: ( cd "$GS" && git init -q && git config user.email t@t && git config user.name t )
220新增: gspe() { ( cd "$GS/sub" && AGENT_VM_STATE_DIR="$PENV/state" bash "$AGENT_VM_SH" project-env "$@" ); }
221新增: fix_of() { printf '%s\n' "$1" | sed -n 's/^ *\(git -C .*\)$/\1/p; s/^ *\(echo .*\)$/\1/p'; }
222新增: out="$(gspe set K v 2>&1 >/dev/null)"
223新增: ( cd "$GS/sub" && eval "$(fix_of "$out")" )
224新增: check "untracked, from a subdirectory, a path with a space: the printed line fixes it" \
225新增: "$(gspe set K v2 2>&1 >/dev/null)" ""
226新增: rm -f "$GS/.gitignore"
227新增: ( cd "$GS" && git add -f sub/.agent-vm.env && git commit -qm t ) >/dev/null 2>&1
228新增: out="$(gspe set K v3 2>&1 >/dev/null)"
229新增: ( cd "$GS/sub" && eval "$(fix_of "$out")" ) >/dev/null 2>&1
230新增: check "tracked, from a subdirectory: the printed command untracks and ignores it" \
231新增: "$( cd "$GS" && git ls-files sub/.agent-vm.env; git check-ignore -q sub/.agent-vm.env && echo ignored )" "ignored"
232新增:
233新增: # The VM can plant a bare repository in the project, whose config names a
234新增: # command git runs on the host (core.fsmonitor, on reading the index). The
235新增: # warning runs git there: it must refuse that repository, whatever the
236新增: # user's safe.bareRepository, and run nothing it names.
237新增: PLANT="$SB/planted"; mkdir -p "$PLANT"
238新增: ( cd "$PLANT" && git init -q --bare . \
239新增: && git config core.bare false && git config core.worktree "$PLANT" \
240新增: && git config core.fsmonitor "touch '$SB/pwned-fsmonitor'" ) 2>/dev/null
241新增: : > "$PLANT/.agent-vm.env"
242新增: ( HOME="$SB/nogitconfig"; export GIT_CONFIG_NOSYSTEM=1; _agent_vm_warn_unignored "$PLANT/.agent-vm.env" ) >/dev/null 2>&1
243新增: check "a planted bare repository runs nothing on the host" \
244新增: "$(ls "$SB" | grep -c '^pwned-')" "0"
245新增: rm -rf "$PLANT" "$SB"/pwned-*
246新增:
247新增: # Outside a repository there is nothing to warn about.
248新增: OUTSIDE="$SB/outside"; mkdir -p "$OUTSIDE"
249新增: if [ -n "$( ( cd "$OUTSIDE" && AGENT_VM_STATE_DIR="$PENV/state" bash "$AGENT_VM_SH" project-env set K v ) 2>&1 >/dev/null )" ]; then
250新增: fail "warns outside a git repository"
251新增: else
252新增: pass "silent outside a git repository"
253新增: fi
254新增:else
255新增: echo " (git absent: gitignore warning not exercised)"
256新增:fi
257新增:
258新增:# =============================================================================
259新增:section "project-env: Git Bash drive-letter spellings"
260新增:# =============================================================================
261新增:# git spells the top C:/... while the shell spells the file /c/.... A fake git
262新增:# answers all three invocations with canned replies, so this runs everywhere:
263新增:# untracked, then unignored, so the warning must fire with the repo-relative
264新增:# name and a suggestion line that names it too.
265新增:mkdir -p "$SB/fakedrive"
266新增:cat > "$SB/fakedrive/git" <<'STUB'
267新增:#!/bin/sh
268新增:case "$*" in
269新增: *rev-parse*) echo "C:/proj" ;;
270新增: *ls-files*) exit 1 ;;
271新增: *check-ignore*) exit 1 ;;
272新增:esac
273新增:STUB
274新增:chmod +x "$SB/fakedrive/git"
275新增:drive_err="$(PATH="$SB/fakedrive:$PATH" _agent_vm_warn_unignored "/c/proj/.agent-vm.env" 2>&1 >/dev/null)"
276新增:case "$drive_err" in
277新增: *"Warning: .agent-vm.env is not ignored"*) pass "C:/ top over a /c/ file still warns, with the relative name" ;;
278新增: *) fail "drive-letter mismatch silenced the warning: $drive_err" ;;
279新增:esac
280新增:case "$drive_err" in
281新增: *"echo '/.agent-vm.env' >> 'C:/proj/.gitignore'"*) pass "the suggested line names the relative file" ;;
282新增: *) fail "the suggested line is not applicable: $drive_err" ;;
283新增:esac
284新增:
285新增:section "files rewritten under the caller's noclobber"
286新增:# agent-vm is sourced into the user's shell, set -C (noclobber) included: a
287新增:# plain > on a file that exists fails there. The env file went unwritable, and
288新增:# the record of a VM's shares kept claiming what they were before.
289新增:( set -C
290新增: AGENT_VM_STATE_DIR="$SB/noclobber"
291新增: agent-vm env set NC 1 >/dev/null 2>&1 && agent-vm env set NC 2 >/dev/null 2>&1 && agent-vm env get NC
292新增: _agent_vm_record_mounts vmnc '[{"a": 1}]' && _agent_vm_record_mounts vmnc '[{"b": 2}]' && cat "$AGENT_VM_STATE_DIR/.agent-vm-mounts-vmnc"
293新增:) > "$SB/noclobber.out" 2>&1
294新增:check "noclobber: the env file and the shares record are rewritten" "$(cat "$SB/noclobber.out")" "$(printf '2\n[{"b": 2}]')"
295新增:# A record that cannot be written stops the start, and says so.
296新增:mkdir -p "$SB/ro-state"; printf 'old\n' > "$SB/ro-state/.agent-vm-mounts-vmro"
297新增:chmod 400 "$SB/ro-state/.agent-vm-mounts-vmro"
298新增:if ( printf 'x\n' >| "$SB/ro-state/.agent-vm-mounts-vmro" ) 2>/dev/null; then
299新增: printf ' skip an unwritable record (this user writes anyway)\n'
300新增:else
301新增: out="$(AGENT_VM_STATE_DIR="$SB/ro-state"; _agent_vm_record_mounts vmro '[]' 2>&1; echo "rc=$?")"
302新增: case "$out" in *"could not record the shares of VM 'vmro'"*"rc=1") pass "an unwritable record: an error" ;; *) fail "an unwritable record: $out" ;; esac
303新增: [ -e "$SB/ro-state/.agent-vm-mounts-vmro" ] && fail "the old record is still there" || pass "and the old record goes"
304新增:fi
新增tests/05-host-version-runtime.sh+179 −0看文件
@@ -0,0 +1,179 @@
1新增:# =============================================================================
2新增:section "host capacity: clamping"
3新增:# =============================================================================
4新增:# The policy is "a VM must not starve the host it runs on". These assertions
5新增:# pin the arithmetic, the floors, and the two cases where the value must be
6新增:# left alone: nothing asked, and an unreadable host.
7新增:check "half of 8 CPUs" "$(_agent_vm_host_share 8 1)" "4"
8新增:check "floor of 1 CPU on a 1-CPU host" "$(_agent_vm_host_share 1 1)" "1"
9新增:check "floor of 2 GiB on a 3 GiB host" "$(_agent_vm_host_share 3 2)" "2"
10新增:
11新增:# A known host: 8 CPUs / 16 GiB.
12新增:_agent_vm_host_cpus() { echo 8; }
13新增:_agent_vm_host_mem_gib() { echo 16; }
14新增:
15新增:check "nothing asked stays nothing" "$(_agent_vm_cap_resource cpus '')" ""
16新增:check "a value under the share passes" "$(_agent_vm_cap_resource cpus 2)" "2"
17新增:check "a value at the share passes" "$(_agent_vm_cap_resource cpus 4)" "4"
18新增:check "a value above the share is clamped" \
19新增: "$(_agent_vm_cap_resource cpus 16 2>/dev/null)" "4"
20新增:check "memory is clamped too" \
21新增: "$(_agent_vm_cap_resource memory 64 2>/dev/null)" "8"
22新增:# Clamping must be said, not done behind the user's back.
23新增:clamp_msg="$(_agent_vm_cap_resource cpus 16 2>&1 >/dev/null)"
24新增:case "$clamp_msg" in
25新增: *"exceeds this host's share"*) pass "clamping is announced on stderr" ;;
26新增: *) fail "clamping was silent (got: '$clamp_msg')" ;;
27新增:esac
28新增:# The share is a policy, so it is overridable.
29新增:check "AGENT_VM_HOST_SHARE=1 gives the whole host" \
30新增: "$(AGENT_VM_HOST_SHARE=1 _agent_vm_cap_resource cpus 8)" "8"
31新增:check "AGENT_VM_HOST_SHARE=4 clamps to a quarter" \
32新增: "$(AGENT_VM_HOST_SHARE=4 _agent_vm_cap_resource cpus 8 2>/dev/null)" "2"
33新增:# It goes into arithmetic: anything but a positive integer falls back to 2,
34新增:# never to a division error, an empty value or an evaluated name.
35新增:# HOME and not an unset name: under set -u that aborts before the subscript runs.
36新增:for bad in 0 08 abc -1 '' 'HOME[$(touch '"$SB"'/pwned-share)]'; do
37新增: check "AGENT_VM_HOST_SHARE='$bad' falls back to half" \
38新增: "$(AGENT_VM_HOST_SHARE="$bad" _agent_vm_cap_resource cpus 8 2>/dev/null)" "4"
39新增:done
40新增:check "and nothing in it was evaluated" "$([ -e "$SB/pwned-share" ] && echo yes || echo no)" "no"
41新增:case "$(AGENT_VM_HOST_SHARE=0 _agent_vm_host_share 8 1 2>&1 >/dev/null)" in
42新增: *"not a positive integer"*) pass "an invalid AGENT_VM_HOST_SHARE is reported" ;;
43新增: *) fail "an invalid AGENT_VM_HOST_SHARE was silent" ;;
44新增:esac
45新增:
46新增:# An unreadable host must never shrink anything.
47新增:_agent_vm_host_cpus() { echo ""; }
48新增:_agent_vm_host_mem_gib() { echo ""; }
49新增:check "unknown host: the value is honoured as asked" \
50新增: "$(_agent_vm_cap_resource cpus 16)" "16"
51新增:
52新增:# Free space: measured where Lima keeps the disks, through a link to another
53新增:# disk; in HOME before Lima has made its directory. A stub df names the path.
54新增:free_at() { # <LIMA_HOME or empty>: the path df was given, then the GiB
55新增: ( df() { printf '%s ' "$2" > "$SB/df-arg"; printf 'h\nfs 1 1 2097152 0%% /\n'; }
56新增: if [[ -n "$1" ]]; then export LIMA_HOME="$1"; else unset LIMA_HOME; fi
57新增: gib="$(_agent_vm_free_gib)"
58新增: printf '%s%s' "$(cat "$SB/df-arg")" "$gib" )
59新增:}
60新增:mkdir -p "$SB/lima-disk"
61新增:ln -s "$SB/lima-disk" "$SB/lima-link" 2>/dev/null
62新增:check "free space: in Lima's directory, a link followed" "$(free_at "$SB/lima-link")" "$SB/lima-link/. 2"
63新增:check "free space: in HOME before Lima's directory exists" "$(free_at "$SB/no-lima")" "$HOME/. 2"
64新增:check "free space: ~/.lima without LIMA_HOME" "$(mkdir -p "$HOME/.lima"; free_at "")" "$HOME/.lima/. 2"
65新增:rmdir "$HOME/.lima"; rm -rf "$SB/lima-link" "$SB/lima-disk" "$SB/df-arg"
66新增:
67新增:# Restore the real probes for anything running after this section.
68新增:unset -f _agent_vm_host_cpus _agent_vm_host_mem_gib
69新增:# shellcheck source=./agent-vm.sh
70新增:source "$AGENT_VM_SH"
71新增:
72新增:# The flags stay plain integers — no new value to learn, no new way to be wrong.
73新增:check "a resource value is taken as a plain integer" \
74新增: "$( vm_opts=(); rm=""; taken=""; _agent_vm_take_opt --cpus 4 && echo "${vm_opts[*]}" )" "--cpus 4"
75新增:
76新增:# =============================================================================
77新增:section "version --min: a floor an integrator can oppose"
78新增:# =============================================================================
79新增:# Without this, every integrator reimplements the comparison — and some get
80新增:# "1.10.0 > 1.9.0" wrong, which a string comparison does.
81新增:vge() { if _agent_vm_ver_ge "$1" "$2" 2>/dev/null; then echo yes; else echo no; fi; }
82新增:check "1.10.0 outranks 1.9.0" "$(vge 1.10.0 1.9.0)" "yes"
83新增:check "1.9.0 does not reach 1.10.0" "$(vge 1.9.0 1.10.0)" "no"
84新增:check "equal versions pass" "$(vge 1.2.3 1.2.3)" "yes"
85新增:check "a short version is padded" "$(vge 1 1.0.0)" "yes"
86新增:check "and compared once padded" "$(vge 1 1.0.1)" "no"
87新增:check "a -rc suffix is ignored" "$(vge 2.0.0-rc1 2.0.0)" "yes"
88新增:check "0.08.0 is decimal, not octal" "$(vge 0.8.0 0.08.0)" "yes"
89新增:check "0.09.0 outranks 0.8.0" "$(vge 0.09.0 0.8.0)" "yes"
90新增:check "a component past 999 still orders" "$(vge 1.1000.0 2.0.0)" "no"
91新增:check "and does not spill into the next" "$(vge 1.0.1000 1.1.0)" "no"
92新增:# Past what shell arithmetic holds.
93新增:check "a 20-digit floor is not met" "$(vge 0.2.0 18446744073709551616)" "no"
94新增:check "a 20-digit version meets a 19-digit one" "$(vge 18446744073709551616 9223372036854775807)" "yes"
95新增:check "leading zeros are dropped" "$(vge 0010 9)" "yes"
96新增:
97新增:check "plain version still prints" "$(agent-vm version)" "$AGENT_VM_VERSION"
98新增:
99新增:if agent-vm version --min 0.0.1 >/dev/null 2>&1; then
100新增: pass "a floor below the installed version passes"
101新增:else
102新增: fail "a satisfied floor was rejected"
103新增:fi
104新增:check "a satisfied floor prints nothing" "$(agent-vm version --min 0.0.1 2>/dev/null)" ""
105新增:check "--min= spelling works too" \
106新增: "$( (agent-vm version --min=0.0.1 >/dev/null 2>&1) && echo yes )" "yes"
107新增:
108新增:agent-vm version --min 99.0.0 >/dev/null 2>&1
109新增:check "an unmet floor exits 1" "$?" "1"
110新增:# The case that separates a numeric comparison from a lexical one: against
111新增:# 0.2.0, "0.10.0" is higher as a number and lower as a string. A lexical
112新增:# implementation passes every other assertion in this section.
113新增:agent-vm version --min 0.10.0 >/dev/null 2>&1
114新增:check "0.10.0 is a higher floor than 0.2.0" "$?" "1"
115新增:too_old="$(agent-vm version --min 99.0.0 2>&1 >/dev/null)"
116新增:case "$too_old" in
117新增: *"older than the required 99.0.0"*"Update it: "*) pass "an unmet floor says what to do" ;;
118新增: *) fail "unhelpful message for an unmet floor: $too_old" ;;
119新增:esac
120新增:mkdir -p "$SB/upd/clone/.git" "$SB/upd/Cellar/agent-vm/1.0.0/libexec" "$SB/upd/release"
121新增:update_of() { ( AGENT_VM_SCRIPT_DIR="$1"; _agent_vm_update_command ); }
122新增:check "update: a clone pulls" "$(update_of "$SB/upd/clone")" "git -C '$SB/upd/clone' pull"
123新增:mkdir -p "$SB/upd/it's/.git"
124新增:check "update: a clone path is quoted for the shell" "$(update_of "$SB/upd/it's")" "git -C '$SB/upd/it'\"'\"'s' pull"
125新增:check "update: a keg upgrades" "$(update_of "$SB/upd/Cellar/agent-vm/1.0.0/libexec")" "brew upgrade agent-vm"
126新增:mkdir -p "$HOME/.local/share/agent-vm" "$SB/upd/agent-vm"
127新增:check "update: a release reinstalls" "$(update_of "$HOME/.local/share/agent-vm")" "curl -fsSL https://www.agent-vm.org/install.sh | sh"
128新增:check "update: a release installed elsewhere reinstalls there" \
129新增: "$(update_of "$SB/upd/release")" "curl -fsSL https://www.agent-vm.org/install.sh | sh -s -- --dir '$SB/upd/release'"
130新增:check "update: XDG_DATA_HOME moves the default" \
131新增: "$(XDG_DATA_HOME="$SB/upd"; update_of "$SB/upd/agent-vm")" "curl -fsSL https://www.agent-vm.org/install.sh | sh"
132新增:rm -rf "$HOME/.local/share/agent-vm"
133新增:
134新增:# A malformed call must be distinguishable from "too old": a typo in the
135新增:# caller's own code should not send a user chasing an upgrade.
136新增:agent-vm version --min oups >/dev/null 2>&1
137新增:check "a malformed version exits 2" "$?" "2"
138新增:agent-vm version --min >/dev/null 2>&1
139新增:check "a missing value exits 2" "$?" "2"
140新增:agent-vm version --max 1 >/dev/null 2>&1
141新增:check "an unknown option exits 2" "$?" "2"
142新增:
143新增:# =============================================================================
144新增:section "runtime scripts: location and interpreter"
145新增:# =============================================================================
146新增:# Before this, every runtime ran under zsh whatever its shebang said — a bash
147新增:# script silently got zsh's arrays and globbing.
148新增:RT="$SB/rt"; mkdir -p "$RT"
149新增:printf '#!/usr/bin/env bash\ntrue\n' > "$RT/env-bash.sh"
150新增:printf '#!/bin/bash\ntrue\n' > "$RT/bin-bash.sh"
151新增:printf '#!/bin/sh\ntrue\n' > "$RT/sh.sh"
152新增:printf '#!/usr/bin/env python3\n' > "$RT/py.sh"
153新增:printf 'echo no shebang\n' > "$RT/none.sh"
154新增:: > "$RT/empty.sh"
155新增:check "#!/usr/bin/env bash → bash" "$(_agent_vm_runtime_interpreter "$RT/env-bash.sh")" "bash"
156新增:check "#!/bin/bash → bash" "$(_agent_vm_runtime_interpreter "$RT/bin-bash.sh")" "bash"
157新增:check "#!/bin/sh → sh" "$(_agent_vm_runtime_interpreter "$RT/sh.sh")" "sh"
158新增:check "another language → zsh (unchanged behaviour)" \
159新增: "$(_agent_vm_runtime_interpreter "$RT/py.sh")" "zsh"
160新增:check "no shebang → zsh" "$(_agent_vm_runtime_interpreter "$RT/none.sh")" "zsh"
161新增:check "empty file → zsh" "$(_agent_vm_runtime_interpreter "$RT/empty.sh")" "zsh"
162新增:
163新增:# Where the project runtime is looked up.
164新增:check "default location is the project root" \
165新增: "$(_agent_vm_project_runtime_path "$PROJ")" "$PROJ/.agent-vm.runtime.sh"
166新增:check "a relative override resolves against the project" \
167新增: "$(AGENT_VM_PROJECT_RUNTIME=.mytool/runtime.sh _agent_vm_project_runtime_path "$PROJ")" \
168新增: "$PROJ/.mytool/runtime.sh"
169新增:check "an absolute override is used as-is" \
170新增: "$(AGENT_VM_PROJECT_RUNTIME=/tmp/elsewhere.sh _agent_vm_project_runtime_path "$PROJ")" \
171新增: "/tmp/elsewhere.sh"
172新增:
173新增:# The script still reaches the VM whole: it is piped, because the per-user
174新增:# runtime lives outside the mount and its path means nothing inside the VM.
175新增:export AGENT_VM_TEST_CAPTURE="$SB/runtime-stdin"
176新增:_agent_vm_run_runtime agent-vm-proj-deadbeef "$PROJ" "$RT/env-bash.sh"
177新增:unset AGENT_VM_TEST_CAPTURE
178新增:check "the runtime is piped into the VM intact" \
179新增: "$(cat "$SB/runtime-stdin")" "$(cat "$RT/env-bash.sh")"
新增tests/06-help-and-setup-script.sh+213 −0看文件
@@ -0,0 +1,213 @@
1新增:# =============================================================================
2新增:section "release hygiene"
3新增:# =============================================================================
4新增:# Every dispatched command must appear in `help`: a command nobody can discover
5新增:# is a command nobody uses. (`sh`/`destroy`/`status` are aliases documented inline.)
6新增:help_text="$(agent-vm help)"
7新增:missing=""
8新增:for verb in setup claude opencode codex vibe pi shell run stop rm destroy-all \
9新增: list name info env version help; do
10新增: case "$help_text" in
11新增: *" $verb"*) ;;
12新增: *) missing="$missing $verb" ;;
13新增: esac
14新增:done
15新增:# One verdict, not a pass that fires whatever the loop found.
16新增:if [ -n "$missing" ]; then
17新增: fail "dispatched but missing from help:$missing"
18新增:else
19新增: pass "every dispatched command appears in help"
20新增:fi
21新增:check "help lists each customisation file once" \
22新增: "$(printf '%s\n' "$help_text" | grep -c '^ ~/.agent-vm/env ')" "1"
23新增:# Every key info prints, named in help.
24新增:missing=""
25新增:for key in $(agent-vm info "$PROJ" | cut -d= -f1); do
26新增: case "$help_text" in *"$key"*) ;; *) missing="$missing $key" ;; esac
27新增:done
28新增:check "help names every info key" "$missing" ""
29新增:check "the version in help output matches the constant" \
30新增: "$(agent-vm version)" "$AGENT_VM_VERSION"
31新增:
32新增:# A bad resource value must produce an actionable message, not a raw bash
33新增:# arithmetic diagnostic leaking from the comparison helper.
34新增:bad="$( (agent-vm --disk 10G version) 2>&1 )" || true
35新增:case "$bad" in
36新增: *"must be a positive integer"*) pass "a non-numeric --disk is rejected clearly" ;;
37新增: *"value too great for base"*) fail "raw bash arithmetic error leaked: $bad" ;;
38新增: *) fail "unexpected output for --disk 10G: $bad" ;;
39新增:esac
40新增:# A command that starts no VM refuses them instead of dropping them: `agent-vm
41新增:# --readonly stop` must not read as if something had been made read-only.
42新增:for c in version stop status help env; do
43新增: out="$( (agent-vm --readonly "$c") 2>&1 )"
44新增: case "$?:$out" in
45新增: 1:*"--readonly is an option for the commands that start a VM"*"not for '$c'"*) pass "--readonly before '$c' is refused" ;;
46新增: *) fail "--readonly before '$c': $out" ;;
47新增: esac
48新增:done
49新增:out="$( (agent-vm --disk 32 --cpus 4 version) 2>&1 )"
50新增:case "$out" in
51新增: *"--disk is an option for the commands that start a VM"*) pass "valid values too: the option is named" ;;
52新增: *) fail "--disk 32 --cpus 4 version: $out" ;;
53新增:esac
54新增:
55新增:# A failed write of the secrets file must not be reported as success: a caller
56新增:# told the secret was stored when it was not is the worst outcome for this file.
57新增:# Root ignores permission bits, so the condition cannot be staged as root —
58新增:# which is exactly what the bash 3.2 container runs as.
59新增:if [ "$(id -u)" -eq 0 ] || _agent_vm_on_windows; then
60新增: printf ' skip env-set-failure test (running as root, or on Windows where chmod bits are emulated)\n'
61新增:else
62新增: RO="$SB/readonly-home"
63新增: mkdir -p "$RO/.agent-vm"
64新增: printf "K='v'\n" > "$RO/.agent-vm/env"
65新增: chmod 500 "$RO/.agent-vm"
66新增: if HOME="$RO" bash "$AGENT_VM_SH" env set OTHER x >/dev/null 2>&1; then
67新增: fail "env set reported success on an unwritable directory"
68新增: else
69新增: pass "env set fails loudly when the write cannot happen"
70新增: fi
71新增: chmod 700 "$RO/.agent-vm"
72新增:fi
73新增:
74新增:# =============================================================================
75新增:section "setup script: apt runs with a working debconf frontend"
76新增:# =============================================================================
77新增:# `export DEBIAN_FRONTEND=noninteractive` does not survive sudo's env_reset,
78新增:# so an apt call that does not carry the variable itself prints debconf's
79新增:# "unable to initialize frontend: Dialog" block on every install step.
80新增:if grep -qE '^[^#]*sudo apt-get' "$SETUP_SH"; then
81新增: fail "an apt call bypasses apt_get: $(grep -nE '^[^#]*sudo apt-get' "$SETUP_SH" | head -1)"
82新增:else
83新增: pass "every apt call goes through apt_get"
84新增:fi
85新增:# The script reaches bash on its stdin: a command that reads stdin swallows the
86新增:# lines after it. Here sudo stands for a dpkg prompt, reading all it can.
87新增:apt_fn="$(sed -n '/^apt_get() {/,/^}/p' "$SETUP_SH")"
88新增:check "apt_get does not read the script's stdin" \
89新增: "$({ printf 'sudo() { cat >/dev/null; }\n%s\napt_get update\necho after\n' "$apt_fn"; } | bash 2>/dev/null)" "after"
90新增:check "npm installs do not read it either" \
91新增: "$(grep -E '^[^#]*npm i ' "$SETUP_SH" | grep -vc '</dev/null$')" "0"
92新增:if grep -q 'sudo env DEBIAN_FRONTEND=noninteractive apt-get' "$SETUP_SH"; then
93新增: pass "apt_get hands the frontend to sudo"
94新增:else
95新增: fail "apt_get no longer passes DEBIAN_FRONTEND through sudo"
96新增:fi
97新增:# Recommends pull in Samba, avahi-daemon, printer config... via Chromium.
98新增:if grep -qv -- '--no-install-recommends' <<< "$(grep -E '^[^#]*apt_get install' "$SETUP_SH")"; then
99新增: fail "an install pulls in Recommends: $(grep -nE '^[^#]*apt_get install' "$SETUP_SH" | grep -v -- '--no-install-recommends' | head -1)"
100新增:else
101新增: pass "every apt install skips Recommends"
102新增:fi
103新增:if grep -qE '^[^#]*\| *sudo( -E)? bash' "$SETUP_SH"; then
104新增: fail "a remote script is piped to a root shell: $(grep -nE '^[^#]*\| *sudo( -E)? bash' "$SETUP_SH" | head -1)"
105新增:else
106新增: pass "no remote script runs as root"
107新增:fi
108新增:
109新增:# Behind a proxy, sudo must keep the proxy settings Lima puts in the guest's
110新增:# environment (#25): installed before the first apt call, and checked by
111新增:# visudo first, since a broken sudoers file breaks sudo.
112新增:proxy_line="$(grep -n '/etc/sudoers.d/10-agent-vm-proxy' "$SETUP_SH" | head -1 | cut -d: -f1)"
113新增:visudo_line="$(grep -n 'sudo visudo -cqf /tmp/agent-vm-proxy.sudoers' "$SETUP_SH" | head -1 | cut -d: -f1)"
114新增:apt_line="$(grep -nE '^[^#]*apt_get (update|install)' "$SETUP_SH" | head -1 | cut -d: -f1)"
115新增:if [ -n "$proxy_line" ] && [ -n "$visudo_line" ] && [ "$visudo_line" -lt "$proxy_line" ] && [ "$proxy_line" -lt "$apt_line" ]; then
116新增: pass "sudo keeps the proxy settings from before the first apt call, checked by visudo"
117新增:else
118新增: fail "proxy sudoers drop-in: visudo at ${visudo_line:-none}, install at ${proxy_line:-none}, first apt at ${apt_line:-none}"
119新增:fi
120新增:kept=" $(grep -o 'env_keep += "[^"]*"' "$SETUP_SH" | cut -d'"' -f2) "
121新增:dropped=""
122新增:for v in http_proxy https_proxy ftp_proxy no_proxy HTTP_PROXY HTTPS_PROXY FTP_PROXY NO_PROXY; do
123新增: case "$kept" in *" $v "*) ;; *) dropped="$dropped $v" ;; esac
124新增:done
125新增:check "sudo keeps every proxy variable, both cases" "$dropped" ""
126新增:
127新增:# Shell history in the VM (#20): the block setup appends to ~/.zshrc, run by
128新增:# zsh itself.
129新增:sed -n "/^cat >> ~\/.zshrc <<'ZSHRC'/,/^ZSHRC\$/p" "$SETUP_SH" | sed '1d;$d' > "$SB/zshrc-history"
130新增:if command -v zsh >/dev/null 2>&1; then
131新增: check "zsh history: saved to a file, space-prefixed commands left out" \
132新增: "$(HOME="$SB" zsh -fc '. "$1"; print -r -- "$HISTFILE $SAVEHIST"; [[ -o histignorespace && -o incappendhistory ]] && print opts' _ "$SB/zshrc-history")" \
133新增: "$SB/.zsh_history 10000
134新增:opts"
135新增:else
136新增: printf ' skip zsh history (zsh not installed)\n'
137新增:fi
138新增:
139新增:# The sshfs wrapper, run against a stub that stands for /usr/bin/sshfs:
140新增:# no_contain_symlinks is added only when that sshfs knows it (#22).
141新增:sed -n '/^sudo tee \/usr\/local\/bin\/sshfs/,/^EOF$/p' "$SETUP_SH" | sed '1d;$d' \
142新增: | sed "s|/usr/bin/sshfs|$SB/sshfs-real|g" > "$SB/sshfs-wrapper"
143新增:sshfs_stub() { # <help text>
144新增: printf '#!/bin/sh\n[ "$1" = -h ] && { echo "%s"; exit 1; }\necho "$*"\n' "$1" > "$SB/sshfs-real"
145新增: chmod +x "$SB/sshfs-real"
146新增:}
147新增:sshfs_stub ' -o no_contain_symlinks allow all symlink targets'
148新增:check "sshfs wrapper: turns contain_symlinks off where it exists" \
149新增: "$(sh "$SB/sshfs-wrapper" ':/p' /p -o slave -o allow_other)" ":/p /p -o slave -o allow_other -o no_contain_symlinks"
150新增:sshfs_stub ' -o follow_symlinks'
151新增:check "sshfs wrapper: an older sshfs gets the arguments unchanged" \
152新增: "$(sh "$SB/sshfs-wrapper" ':/p' /p -o slave)" ":/p /p -o slave"
153新增:
154新增:# =============================================================================
155新增:section "MCP config writer"
156新增:# =============================================================================
157新增:# configure_mcp lives in the in-VM setup script, whose top level performs the
158新增:# actual installs — so lift just that function out rather than sourcing it.
159新增:if ! command -v jq >/dev/null 2>&1; then
160新增: printf ' skip configure_mcp tests (jq not installed)\n'
161新增:else
162新增: MCPHOME="$SB/mcp"; mkdir -p "$MCPHOME"
163新增: (
164新增: HOME="$MCPHOME"
165新增: eval "$(awk '/^configure_mcp\(\) \{/,/^\}/' "$SETUP_SH")"
166新增: INSTALL_CLAUDE=1 INSTALL_OPENCODE=1 INSTALL_VIBE=1 INSTALL_CODEX=1
167新增: for _ in 1 2; do # twice: the writer must be idempotent
168新增: configure_mcp chrome-devtools npx -y chrome-devtools-mcp@latest --headless=true
169新增: configure_mcp playwright env PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npx -y @playwright/mcp@latest
170新增: done
171新增: ) >/dev/null 2>&1
172新增:
173新增: oc="$MCPHOME/.config/opencode/opencode.json"
174新增: check "opencode: two servers" "$(jq '.mcp | length' "$oc")" "2"
175新增: check "opencode: \$schema kept" "$(jq -r '."$schema"' "$oc")" "https://opencode.ai/config.json"
176新增: check "opencode: command starts with the launcher" \
177新增: "$(jq -r '.mcp.playwright.command[0]' "$oc")" "env"
178新增: check "opencode: env assignment survives as its own argv entry" \
179新增: "$(jq -r '.mcp.playwright.command[1]' "$oc")" "PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1"
180新增: check "claude: two servers" \
181新增: "$(jq '.mcpServers | length' "$MCPHOME/.claude.json")" "2"
182新增: check "codex: no duplicate table after two runs" \
183新增: "$(grep -cF '[mcp_servers.playwright]' "$MCPHOME/.codex/config.toml")" "1"
184新增: check "vibe: no duplicate entry after two runs" \
185新增: "$(grep -c '^\[\[mcp_servers\]\]' "$MCPHOME/.vibe/config.toml")" "2"
186新增:fi
187新增:
188新增:# =============================================================================
189新增:section "Pi install block"
190新增:# =============================================================================
191新增:# Lifted out like configure_mcp, with sudo recorded instead of run.
192新增:if ! command -v jq >/dev/null 2>&1; then
193新增: printf ' skip Pi install tests (jq not installed)\n'
194新增:else
195新增: pi_block="$(awk '/^if \[\[ "\$INSTALL_PI" == "1" \]\]; then/,/^fi$/' "$SETUP_SH")"
196新增: run_pi_block() {
197新增: ( HOME="$1"; INSTALL_PI=1 INSTALL_NODE="$2"
198新增: sudo() { echo "sudo $*" >> "$HOME/sudo.log"; }
199新增: eval "$pi_block" ) >/dev/null 2>&1
200新增: }
201新增: PIH="$SB/pi-home"; mkdir -p "$PIH"
202新增: run_pi_block "$PIH" 1
203新增: check "pi: the maintained package, without install scripts" "$(cat "$PIH/sudo.log" 2>/dev/null)" \
204新增: "sudo npm i -g --ignore-scripts @earendil-works/pi-coding-agent"
205新增: # (The </dev/null is a redirection, which the recording sudo does not see.)
206新增: check "pi: project files trusted" \
207新增: "$(jq -r .defaultProjectTrust "$PIH/.pi/agent/settings.json" 2>/dev/null)" "always"
208新增: check "pi: telemetry off" \
209新增: "$(jq -r .enableInstallTelemetry "$PIH/.pi/agent/settings.json" 2>/dev/null)" "false"
210新增: PIH0="$SB/pi-home-nonode"; mkdir -p "$PIH0"
211新增: run_pi_block "$PIH0" 0
212新增: check "pi: skipped without node" "$( [ -e "$PIH0/sudo.log" ] || [ -e "$PIH0/.pi" ]; echo $?)" "1"
213新增:fi
新增tests/07-stop-rm.sh+79 −0看文件
@@ -0,0 +1,79 @@
1新增:# =============================================================================
2新增:section "stop / rm target selection"
3新增:# =============================================================================
4新增:# The whole point of the optional name is the orphan case: a directory that was
5新增:# renamed or deleted leaves a VM no `cd` can reach, because the name hashes the
6新增:# old path. So the argument is a VM name, and it has to reach limactl untouched.
7新增:CALLS="$SB/calls"
8新增:
9新增:: > "$CALLS"
10新增:out="$( export AGENT_VM_TEST_CALLS="$CALLS"; agent-vm stop agent-vm-proj-deadbeef 2>&1 )"
11新增:check "stop <name> stops the named VM" "$(cat "$CALLS")" "stop agent-vm-proj-deadbeef"
12新增:
13新增:: > "$CALLS"; : > "$SB/deleted"
14新增:out="$( export AGENT_VM_TEST_CALLS="$CALLS" AGENT_VM_TEST_DELETED="$SB/deleted"; agent-vm rm agent-vm-proj-deadbeef 2>&1 )"
15新增:check "rm <name> stops then deletes the named VM" \
16新增: "$(cat "$CALLS")" "$(printf 'stop agent-vm-proj-deadbeef\ndelete agent-vm-proj-deadbeef --force')"
17新增:case "$out" in *"VM destroyed."*) pass "rm: says it is done once Lima no longer lists it" ;; *) fail "rm: $out" ;; esac
18新增:
19新增:# A delete that did not take is said, not reported as done.
20新增:out="$( export AGENT_VM_TEST_CALLS="$CALLS"; agent-vm rm agent-vm-proj-deadbeef 2>&1 )"
21新增:case "$?:$out" in
22新增: 1:*"could not delete VM 'agent-vm-proj-deadbeef'"*) pass "rm: a VM Lima still lists is an error" ;;
23新增: *) fail "rm, delete did not take: $out" ;;
24新增:esac
25新增:case "$out" in *"VM destroyed."*) fail "rm: a failed delete was reported as done" ;; *) pass "rm: and not reported as done" ;; esac
26新增:
27新增:# A name that is not ours must not reach limactl at all: `agent-vm rm` is not a
28新增:# way to delete someone else's Lima instance by typo.
29新增:: > "$CALLS"
30新增:if out="$( export AGENT_VM_TEST_CALLS="$CALLS"; agent-vm rm some-other-lima-vm 2>&1 )"; then
31新增: fail "rm accepted a non-agent-vm name"
32新增:else
33新增: case "$out" in
34新增: *"not an agent-vm VM name"*) pass "rm rejects a name outside the agent-vm- namespace" ;;
35新增: *) fail "unexpected rejection message: $out" ;;
36新增: esac
37新增:fi
38新增:check "the rejected name never reached limactl" "$(cat "$CALLS")" ""
39新增:
40新增:: > "$CALLS"
41新增:if out="$( export AGENT_VM_TEST_CALLS="$CALLS"; agent-vm stop agent-vm-does-not-exist 2>&1 )"; then
42新增: fail "stop accepted a VM that does not exist"
43新增:else
44新增: case "$out" in
45新增: *"no such VM: agent-vm-does-not-exist"*) pass "stop reports an unknown VM by name" ;;
46新增: *) fail "unexpected message for an unknown VM: $out" ;;
47新增: esac
48新增:fi
49新增:check "the unknown name never reached limactl" "$(cat "$CALLS")" ""
50新增:
51新增:if out="$( agent-vm stop agent-vm-proj-deadbeef agent-vm-base 2>&1 )"; then
52新增: fail "stop accepted two names"
53新增:else
54新增: case "$out" in
55新增: *"Usage: agent-vm stop [vm-name]"*) pass "stop refuses more than one name" ;;
56新增: *) fail "unexpected message for two names: $out" ;;
57新增: esac
58新增:fi
59新增:
60新增:# Without an argument, the current directory still selects the VM.
61新增:PROJ_VM="$(_agent_vm_name "$PROJ")"
62新增:: > "$CALLS"
63新增:out="$( cd "$PROJ" || exit 1
64新增: export AGENT_VM_TEST_CALLS="$CALLS" AGENT_VM_TEST_EXTRA_VM="$PROJ_VM"
65新增: agent-vm stop 2>&1 )"
66新增:check "stop with no argument targets the current directory's VM" \
67新增: "$(cat "$CALLS")" "stop $PROJ_VM"
68新增:
69新增:: > "$CALLS"
70新增:if out="$( cd "$PROJ" || exit 1
71新增: export AGENT_VM_TEST_CALLS="$CALLS"
72新增: agent-vm stop 2>&1 )"; then
73新增: fail "stop succeeded with no VM for the current directory"
74新增:else
75新增: case "$out" in
76新增: *"No VM found for this directory."*) pass "stop with no argument reports the empty directory" ;;
77新增: *) fail "unexpected message for a directory with no VM: $out" ;;
78新增: esac
79新增:fi
新增tests/08-mount-mode.sh+126 −0看文件
@@ -0,0 +1,126 @@
1新增:# =============================================================================
2新增:section "project mount mode (--readonly is a host-side flag)"
3新增:# =============================================================================
4新增:# The read-only decision has to reach Lima's mount config, the only place the
5新增:# guest cannot undo it. Assert on the JSON handed to limactl, so a revert to a
6新增:# guest-side `mount -o remount,ro` fails here instead of passing quietly.
7新增:mounts_default="$(_agent_vm_build_mounts_json agent-vm-t "$PROJ")"
8新增:mounts_rw="$(_agent_vm_build_mounts_json agent-vm-t "$PROJ" true)"
9新增:mounts_ro="$(_agent_vm_build_mounts_json agent-vm-t "$PROJ" false)"
10新增:
11新增:check "default is a writable project mount" \
12新增: "$mounts_default" "[{$(mnt "$PROJ"), \"writable\": true}]"
13新增:check "an explicit true agrees with the default" "$mounts_rw" "$mounts_default"
14新增:check "false marks the project mount read-only" \
15新增: "$mounts_ro" "[{$(mnt "$PROJ"), \"writable\": false}]"
16新增:
17新增:# The mode must ride on the project entry, not on whatever happens to be first
18新增:# once ~/.agent-vm/volumes contributes extra mounts.
19新增:mkdir -p "$SB/extra-vol"
20新增:printf '%s:ro\n' "$SB/extra-vol" > "$HOME/.agent-vm/volumes"
21新增:mounts_ro_vols="$(_agent_vm_build_mounts_json agent-vm-t "$PROJ" false)"
22新增:rm -f "$HOME/.agent-vm/volumes"
23新增:case "$mounts_ro_vols" in
24新增: "[{$(mnt "$PROJ"), \"writable\": false},"*"extra-vol"*)
25新增: pass "read-only project mount keeps the ~/.agent-vm/volumes entries" ;;
26新增: *) fail "volumes entries lost or reordered: $mounts_ro_vols" ;;
27新增:esac
28新增:
29新增:# .git protection: Lima refuses readonlyNames unless EVERY mount uses the
30新增:# builtin driver, so the volumes entries need it as much as the project.
31新增:SSHFS_RO='"sshfs": {"sftpDriver": "builtin", "readonlyNames": [".git", ".hg"]}'
32新增:printf '%s:/mnt/v:rw\n' "$SB/extra-vol" > "$HOME/.agent-vm/volumes"
33新增:mounts_prot="$(_agent_vm_build_mounts_json agent-vm-t "$PROJ" true 1)"
34新增:rm -f "$HOME/.agent-vm/volumes"
35新增:case "$mounts_prot" in
36新增: "[{$(mnt "$PROJ"), \"writable\": true, $SSHFS_RO}, "*) pass "protected: the project entry carries readonlyNames" ;;
37新增: *) fail "protected project entry: $mounts_prot" ;;
38新增:esac
39新增:check "protected: every entry has the builtin driver" \
40新增: "$(printf '%s' "$mounts_prot" | grep -o '"sftpDriver": "builtin"' | wc -l | tr -d ' ')" "2"
41新增:case "$(_agent_vm_mounts_expr '[]' 1)" in
42新增: '.mountType = "reverse-sshfs" | .mounts = []') pass "protected: the mount type is reverse-sshfs" ;;
43新增: *) fail "protected expression: $(_agent_vm_mounts_expr '[]' 1)" ;;
44新增:esac
45新增:# Without the protection, a reverse-sshfs left by a Lima that had it must go:
46新增:# without readonlyNames it is the weaker mount type.
47新增:case "$(_agent_vm_mounts_expr '[]' '')" in
48新增: 'del(.mountType) | .mounts = []') pass "unprotected: back to Lima's default mount type" ;;
49新增: *) fail "unprotected expression: $(_agent_vm_mounts_expr '[]' '')" ;;
50新增:esac
51新增:
52新增:# Read-only is only a real boundary for mount types the host enforces. Lima
53新增:# applies it inside the guest for reverse-sshfs and for virtiofs under QEMU,
54新增:# where root can remount it rw. Answered from what `limactl list` reports for
55新增:# the VM, "<VM type> <mount type>" ($1), never from the guest: this stub's
56新增:# guest claims 9p, which must not count.
57新增:mount_types() {
58新增: cat > "$SB/bin/limactl" <<STUB
59新增:#!/usr/bin/env bash
60新增:[ "\$1" = shell ] && { echo 9p; exit 0; }
61新增:[ "\$1" = list ] && { printf '%s\n' "$1"; exit 0; }
62新增:[ "\$1" = validate ] && [ -n "\${MT_PROTECTS:-}" ] && { echo 'field mounts[*].sshfs.readonlyNames requires mountType to be reverse-sshfs' >&2; exit 1; }
63新增:exit 1
64新增:STUB
65新增: chmod +x "$SB/bin/limactl"
66新增: _agent_vm_mount_is_host_enforced agent-vm-t
67新增: printf '%s' "$?"
68新增:}
69新增:check "virtiofs on vz is host-enforced" "$(mount_types 'vz virtiofs')" "0"
70新增:check "virtiofs under QEMU is not" "$(mount_types 'qemu virtiofs')" "1"
71新增:check "virtiofs, VM type unknown: undecided" "$(mount_types ' virtiofs')" "2"
72新增:check "9p on QEMU is host-enforced" "$(mount_types 'qemu 9p')" "0"
73新增:check "reverse-sshfs is not" "$(mount_types 'vz reverse-sshfs')" "1"
74新增:check "an empty answer is undecided" "$(mount_types '')" "2"
75新增:check "an unknown VM type is undecided" "$(mount_types 'wsl2 wsl2')" "2"
76新增:# Left unset, Lima's driver picks it at start: virtiofs on vz, 9p on QEMU for
77新增:# a VM made by Lima 1.0 or later (its lima-version file), reverse-sshfs before.
78新增:check "unset on vz: virtiofs, enforced" "$(mount_types 'vz <nil>')" "0"
79新增:mkdir -p "$SB/lima-home/agent-vm-t"
80新增:echo 2.1.0 > "$SB/lima-home/agent-vm-t/lima-version"
81新增:# Not on a Windows host, where QEMU has no 9p (tests/18-windows.sh).
82新增:if _agent_vm_on_windows; then
83新增: printf ' skip unset on QEMU, Lima >= 1.0: 9p (a Windows host has no 9p)\n'
84新增:else
85新增: check "unset on QEMU, Lima >= 1.0: 9p, enforced" "$(LIMA_HOME="$SB/lima-home" mount_types 'qemu <nil>')" "0"
86新增:fi
87新增:echo 0.23.2 > "$SB/lima-home/agent-vm-t/lima-version"
88新增:check "unset on QEMU, Lima < 1.0: reverse-sshfs, not" "$(LIMA_HOME="$SB/lima-home" mount_types 'qemu <nil>')" "1"
89新增:rm -f "$SB/lima-home/agent-vm-t/lima-version"
90新增:check "unset on QEMU, no lima-version: reverse-sshfs, not" "$(LIMA_HOME="$SB/lima-home" mount_types 'qemu')" "1"
91新增:# Served by the builtin server of a Lima with readonlyNames, it is. The guest
92新增:# cannot tell the servers apart: the record of the applied mounts does.
93新增:mkdir -p "$HOME/.agent-vm"
94新增:printf '[{"location": "%s", "writable": false, %s}]\n' "$PROJ" "$SSHFS_RO" > "$HOME/.agent-vm/.agent-vm-mounts-agent-vm-t"
95新增:check "reverse-sshfs with readonlyNames is" "$(MT_PROTECTS=1 mount_types 'qemu reverse-sshfs')" "0"
96新增:# Recorded so, but served by a Lima without them (a stock limactl started it
97新增:# since): not.
98新增:check "recorded with readonlyNames, a Lima without them: not" "$(mount_types 'qemu reverse-sshfs')" "1"
99新增:rm -f "$HOME/.agent-vm/.agent-vm-mounts-agent-vm-t"
100新增:# Restore the shared stub: mount_fstype replaced it with its own.
101新增:cat > "$SB/bin/limactl" <<'STUB'
102新增:#!/usr/bin/env bash
103新增:exit 0
104新增:STUB
105新增:chmod +x "$SB/bin/limactl"
106新增:
107新增:# =============================================================================
108新增:section "unenforceable flags are gone, not just hidden"
109新增:# =============================================================================
110新增:# Both were removed for the same reason: they were applied inside the VM, where
111新增:# the agent has passwordless sudo and could undo them. --offline was iptables
112新增:# rules, --git-read-only a bind mount. Neither can come back without the
113新增:# enforcement moving to the host, so fail here if one reappears — including as
114新增:# a silently-ignored argument, which reads to a caller like it worked.
115新增:for flag in --offline --git-read-only --git-ro; do
116新增: if grep -q -- "$flag" "$AGENT_VM_SH" "$SELF_DIR"/lib/*.sh; then
117新增: fail "$flag still referenced in agent-vm.sh or lib/"
118新增: else
119新增: pass "no $flag left in agent-vm.sh or lib/"
120新增: fi
121新增: if agent-vm "$flag" shell >/dev/null 2>&1; then
122新增: fail "$flag was silently accepted"
123新增: else
124新增: pass "$flag is rejected rather than ignored"
125新增: fi
126新增:done
新增tests/09-env-read.sh+143 −0看文件
@@ -0,0 +1,143 @@
1新增:# =============================================================================
2新增:section "env get/has read the file, they never run it"
3新增:# =============================================================================
4新增:# The project env file sits in a directory the VM can write to, and can arrive
5新增:# with a cloned repository. Sourcing it on the host to answer `get` ran
6新增:# whatever it contained, as the user, outside the sandbox.
7新增:RD="$SB/envread"; mkdir -p "$RD" "$SB/envread-cwd"
8新增:# Without perl, the same file is named from outside its directory, where the
9新增:# host reads it as is: the reader under test is the same.
10新增:if [[ -n "$AGENT_VM_HAS_PERL" ]]; then
11新增: rd() { ( cd "$RD" && AGENT_VM_STATE_DIR="$SB/envread-state" bash "$AGENT_VM_SH" project-env "$@" ); }
12新增:else
13新增: printf ' note: no perl, the project env file is read from outside the project\n'
14新增: rd() { ( cd "$SB/envread-cwd" && AGENT_VM_PROJECT_ENV="$RD/.agent-vm.env" AGENT_VM_STATE_DIR="$SB/envread-state" bash "$AGENT_VM_SH" project-env "$@" ); }
15新增:fi
16新增:
17新增:printf 'X=$(touch %s/pwned-dollar)\nY=`touch %s/pwned-tick`\n' "$SB" "$SB" > "$RD/.agent-vm.env"
18新增:rd get X >/dev/null 2>&1
19新增:check "get refuses a \$(...) value (exit 2)" "$?" "2"
20新增:rd has Y >/dev/null 2>&1
21新增:check "has refuses a backquoted value (exit 2)" "$?" "2"
22新增:if [ -e "$SB/pwned-dollar" ] || [ -e "$SB/pwned-tick" ]; then
23新增: fail "a value in the project env file was executed on the host"
24新增:else
25新增: pass "nothing in the project env file was executed on the host"
26新增:fi
27新增:case "$(rd get X 2>&1)" in
28新增: *"Rewrite it with 'agent-vm project-env set'"*) pass "the refusal says how to fix the entry" ;;
29新增: *) fail "the refusal does not say what to do" ;;
30新增:esac
31新增:
32新增:# Everything `set` can write must read back unchanged, including the values
33新增:# that would be code if the reader evaluated them.
34新增:: > "$RD/.agent-vm.env"
35新增:for v in "O'Brien" '$(echo hi)' '`id`' 'a\b' 'two words' '"dq"' '~/x' "line1
36新增:line2"; do
37新增: rd set K "$v" >/dev/null 2>&1
38新增: check "set/get round trip: $(printf '%s' "$v" | tr '\n' '|')" "$(rd get K)" "$v"
39新增:done
40新增:rd set EMPTY "" >/dev/null 2>&1
41新增:rd has EMPTY && pass "an empty value is present" || fail "an empty value reads as absent"
42新增:check "an empty value reads back empty" "$(rd get EMPTY)" ""
43新增:
44新增:# A value spanning lines must not create keys out of its own content.
45新增:rd set MULTI "first
46新增:PHANTOM=injected" >/dev/null 2>&1
47新增:rd has PHANTOM && fail "a line inside a quoted value was read as a key" \
48新增: || pass "a line inside a quoted value is not a key"
49新增:
50新增:# Plain dotenv lines written by hand.
51新增:cat > "$RD/.agent-vm.env" <<'EOF'
52新增:# a comment
53新增:A=plain
54新增:
55新增:export B=exported
56新增: C="double quoted"
57新增:D=value # trailing comment
58新增:E='a'"b"c
59新增:F=first
60新增:F=second
61新增:EOF
62新增:printf 'G=crlf\r\n\r\n' >> "$RD/.agent-vm.env"
63新增:check "plain value" "$(rd get A)" "plain"
64新增:check "export prefix" "$(rd get B)" "exported"
65新增:check "leading blanks, double quotes" "$(rd get C)" "double quoted"
66新增:check "trailing comment" "$(rd get D)" "value"
67新增:check "concatenated quoting" "$(rd get E)" "abc"
68新增:check "the last assignment wins" "$(rd get F)" "second"
69新增:check "a CRLF line ending is dropped" "$(rd get G)" "crlf"
70新增:rd get NOT_THERE >/dev/null 2>&1
71新增:check "an absent key exits 1" "$?" "1"
72新增:# One line each: a refused line makes the whole file unreadable.
73新增:refused() { printf '%s\nOK=1\n' "$1" > "$RD/.agent-vm.env"; rd get "${2:-K}" >/dev/null 2>&1; echo "$?"; }
74新增:check "an unquoted ~ (host-dependent) is refused" "$(refused 'K=~/somewhere')" "2"
75新增:check "an expansion inside double quotes is refused" "$(refused 'K="$HOME"')" "2"
76新增:
77新增:# One refused line, and no key reads: the shell may read the next lines as
78新增:# part of that value, or run them as code, which can assign any key, one
79新增:# before it included.
80新增:printf 'A=before\nX="line1\nY=evil\n"\nZ=a\\\nW=b\n' > "$RD/.agent-vm.env"
81新增:check "the shell reads Y as part of X's value" \
82新增: "$(set -a; . "$RD/.agent-vm.env" 2>/dev/null; printf '%s' "${Y:-unset}")" "unset"
83新增:rd get Y >/dev/null 2>&1
84新增:check "a key inside an open double quote is refused" "$?" "2"
85新增:rd get W >/dev/null 2>&1
86新增:check "a key after a backslash continuation is refused" "$?" "2"
87新增:rd get A >/dev/null 2>&1
88新增:check "a key before the refused line is refused too" "$?" "2"
89新增:rd get NOT_THERE >/dev/null 2>&1
90新增:check "a key named nowhere is refused, not absent" "$?" "2"
91新增:printf 'A=1\nsource ./other\nunset A\n' > "$RD/.agent-vm.env"
92新增:rd get A >/dev/null 2>&1
93新增:check "a line of code counts as refused" "$?" "2"
94新增:printf 'A=1\nB=2;A=3\n' > "$RD/.agent-vm.env"
95新增:rd get A >/dev/null 2>&1
96新增:check "a key assigned later on a refused line is refused" "$?" "2"
97新增:printf "KEY='good'\neval KE\"\"Y=evil\n" > "$RD/.agent-vm.env"
98新增:rd get KEY >/dev/null 2>&1
99新增:check "a key a later line assigns without naming it is refused" "$?" "2"
100新增:
101新增:# =============================================================================
102新增:section "env set/unset replace a multi-line value whole"
103新增:# =============================================================================
104新增:# Dropping only the first line of a value spanning lines left its tail, an
105新增:# unterminated quote: the file then failed to source in the VM, losing every
106新增:# key after it, while `get` still answered.
107新增:: > "$RD/.agent-vm.env"
108新增:rd set A 'a' >/dev/null 2>&1
109新增:rd set K "line1
110新增:PHANTOM=x" >/dev/null 2>&1
111新增:rd set B 'b' >/dev/null 2>&1
112新增:rd set K new >/dev/null 2>&1
113新增:sourced="$(set -a; . "$RD/.agent-vm.env" 2>&1; set +a; printf '%s|%s|%s' "${A:-}" "${B:-}" "${K:-}")"
114新增:check "set over a multi-line value: the file still sources, every key intact" "$sourced" "a|b|new"
115新增:check "list: a line inside a value is not a key" "$(rd list | tr '\n' ' ')" "A B K "
116新增:rd set K "line1
117新增:line2" >/dev/null 2>&1
118新增:rd unset K >/dev/null 2>&1
119新增:check "unset of a multi-line value leaves nothing behind" "$(cat "$RD/.agent-vm.env")" "A='a'
120新增:B='b'"
121新增:printf 'export E=1\nE2="two\nlines"\n' >> "$RD/.agent-vm.env"
122新增:rd unset E >/dev/null 2>&1
123新增:rd has E && fail "unset left an 'export E=' line" || pass "unset removes an 'export KEY=' line too"
124新增:rd unset E2 >/dev/null 2>&1
125新增:check "a double-quoted value over two lines goes whole" "$(cat "$RD/.agent-vm.env")" "A='a'
126新增:B='b'"
127新增:# $'...' takes backslash escapes, an escaped quote included: it does not
128新增:# leave a quote open over the next lines.
129新增:printf "A=\$'it\\\\'s'\nB=1\n" > "$RD/.agent-vm.env"
130新增:check "a \$'...' value: the shell sets both" "$(bash -c "set -a; . '$RD/.agent-vm.env'; printf '%s' \"\$A|\$B\"" 2>/dev/null)" "it's|1"
131新增:check "list: the key after a \$'...' value" "$(rd list | tr '\n' ' ')" "A B "
132新增:rd unset B >/dev/null 2>&1
133新增:check "unset: the key after a \$'...' value goes" "$(cat "$RD/.agent-vm.env")" "A=\$'it\\'s'"
134新增:# A word too many is refused, not dropped.
135新增:: > "$RD/.agent-vm.env"
136新增:case "$(rd set TOKEN my secret value 2>&1; echo "rc=$?")" in *"too many arguments"*"rc=1") pass "set: a value in several words is refused" ;; *) fail "set with extra words accepted" ;; esac
137新增:check "and nothing is stored" "$(cat "$RD/.agent-vm.env")" ""
138新增:for a in get has unset; do
139新增: case "$(rd "$a" K x 2>&1; echo "rc=$?")" in *"too many arguments"*"rc=1") pass "$a K x: refused" ;; *) fail "$a K x: accepted" ;; esac
140新增:done
141新增:case "$(rd list x 2>&1; echo "rc=$?")" in *"too many arguments"*"rc=1") pass "list x: refused" ;; *) fail "list x: accepted" ;; esac
142新增:check "list names each key once" \
143新增: "$(printf "X=1\nX=2\nexport Y=3\n" > "$SB/envlist"; _agent_vm_env env "$SB/envlist" "" list | tr '\n' ' ')" "X Y "
新增tests/10-names-and-paths.sh+59 −0看文件
@@ -0,0 +1,59 @@
1新增:# =============================================================================
2新增:section "project paths that would rewrite the mount config are refused"
3新增:# =============================================================================
4新增:# The path is spliced into the yq expression given to `limactl edit --set`. A
5新增:# quote in a directory name used to end the string and let the name add mounts
6新增:# of its own: `a","writable":true},{"location":"~",...` mounted the home
7新增:# directory read-write, --readonly or not.
8新增:for d in "$SB/"'q"uote' "$SB/"'back\slash'; do
9新增: mkdir -p "$d"
10新增: out="$(_agent_vm_ensure_running agent-vm-x "$d" 2>&1)"
11新增: rc=$?
12新增: case "$rc:$out" in
13新增: 1:*"a quote, a backslash or a control character"*) pass "refused: $(basename "$d")" ;;
14新增: *) fail "not refused: $(basename "$d") ($rc: $out)" ;;
15新增: esac
16新增:done
17新增:
18新增:# =============================================================================
19新增:section "VM names need a hash, and get one without shasum"
20新增:# =============================================================================
21新增:# Without a hash, every directory named `proj` shared the VM `agent-vm-proj-`.
22新增:HB="$SB/hashbin"; mkdir -p "$HB/none" "$HB/sha256sum-only"
23新增:# Wrapper scripts, not symlinks: where the machine makes no real links
24新增:# (Windows runners plant copies), a copied binary cannot find its libraries
25新增:# under the restricted PATH below, while a wrapper execs the real tool by
26新增:# absolute path. /bin/sh exists everywhere these tests run.
27新增:for t in cut basename tr sed; do
28新增: tool="$(command -v "$t")"
29新增: printf '#!/bin/sh\nexec "%s" "$@"\n' "$tool" > "$HB/none/$t"
30新增: printf '#!/bin/sh\nexec "%s" "$@"\n' "$tool" > "$HB/sha256sum-only/$t"
31新增: chmod +x "$HB/none/$t" "$HB/sha256sum-only/$t"
32新增:done
33新增:out="$(PATH="$HB/none"; _agent_vm_name /x/proj 2>&1)"
34新增:rc=$?
35新增:case "$rc:$out" in
36新增: 1:*"install shasum or sha256sum"*) pass "no hash tool: naming fails instead of dropping the hash" ;;
37新增: *) fail "no hash tool: got $rc '$out'" ;;
38新增:esac
39新增:if command -v sha256sum >/dev/null 2>&1; then
40新增: printf '#!/bin/sh\nexec "%s" "$@"\n' "$(command -v sha256sum)" > "$HB/sha256sum-only/sha256sum"
41新增: chmod +x "$HB/sha256sum-only/sha256sum"
42新增: check "sha256sum gives the same name as shasum" \
43新增: "$(PATH="$HB/sha256sum-only"; _agent_vm_name /x/proj)" "$(_agent_vm_name /x/proj)"
44新增:else
45新增: printf ' skip sha256sum fallback (not installed here)\n'
46新增:fi
47新增:
48新增:# =============================================================================
49新增:section "Lima's state directory follows LIMA_HOME"
50新增:# =============================================================================
51新增:# A leftover without lima.yaml is cleaned where Lima keeps its VMs, and only
52新增:# there: with LIMA_HOME set, ~/.lima is someone else's.
53新增:mkdir -p "$SB/limahome/agent-vm-partial" "$HOME/.lima/agent-vm-partial"
54新增:( LIMA_HOME="$SB/limahome"; _agent_vm_clean_partial_state agent-vm-partial ) 2>/dev/null
55新增:check "LIMA_HOME: the leftover there goes, ~/.lima is not touched" \
56新增: "$([ -d "$SB/limahome/agent-vm-partial" ] && echo kept || echo cleaned) $([ -d "$HOME/.lima/agent-vm-partial" ] && echo kept || echo cleaned)" \
57新增: "cleaned kept"
58新增:_agent_vm_clean_partial_state agent-vm-partial 2>/dev/null
59新增:check "without LIMA_HOME: ~/.lima" "$([ -d "$HOME/.lima/agent-vm-partial" ] && echo kept || echo cleaned)" "cleaned"
新增tests/11-recorded-commands.sh+183 −0看文件
@@ -0,0 +1,183 @@
1新增:# =============================================================================
2新增:section "commands against a recording limactl"
3新增:# =============================================================================
4新增:# One stub for the sections below. It logs every call, lists the base template
5新增:# and the VM named by AGENT_VM_TEST_VM, and reports its mount type as
6新增:# virtiofs (AGENT_VM_TEST_MOUNTTYPE to change it) on vz (AGENT_VM_TEST_VMTYPE). With AGENT_VM_TEST_CLONED set,
7新增:# that VM only exists once `clone` has created the file. AGENT_VM_TEST_STOPPED
8新增:# lists it as stopped, as does a `stop` until the next `start`, and
9新增:# AGENT_VM_TEST_RO makes the project write probe fail, as a read-only share
10新增:# would. AGENT_VM_TEST_STOP_FAIL makes `stop` leave it running.
11新增:# AGENT_VM_TEST_SSHFS_FAIL fails the sshfs install of a 0.1.0 VM.
12新增:# AGENT_VM_TEST_RUNTIME_FOUND makes the probe find the project's runtime
13新增:# script. What is piped into the env push goes to AGENT_VM_TEST_STDIN.
14新增:# `validate` answers like stock Lima 2.2 does to readonlyNames, or, while the
15新增:# file $PROTECTS exists, like a Lima that has it (both messages copied from
16新增:# the real binaries). AGENT_VM_TEST_VALIDATE_SILENT makes it accept the file
17新增:# without a word, an answer agent-vm cannot read.
18新增:REC="$SB/rec.log"
19新增:PROTECTS="$SB/lima-protects"
20新增:cat > "$SB/bin/limactl" <<'STUB'
21新增:#!/usr/bin/env bash
22新增:printf '%s\n' "$*" >> "$AGENT_VM_TEST_REC"
23新增:listed() { [ -z "${AGENT_VM_TEST_CLONED:-}" ] || [ -e "$AGENT_VM_TEST_CLONED" ]; }
24新增:case "$1" in
25新增: --version) echo "limactl version 2.0.3" ;;
26新增: validate)
27新增: [ -z "${AGENT_VM_TEST_VALIDATE_SILENT:-}" ] || exit 0
28新增: if [ -e "${AGENT_VM_TEST_PROTECTS:-/nonexistent}" ]; then
29新增: echo 'level=fatal msg="failed to validate YAML file `probe.yaml`: field `mounts[*].sshfs.readonlyNames` requires `mountType` to be `reverse-sshfs`"' >&2
30新增: exit 1
31新增: fi
32新增: echo 'level=warning msg="Non-strict YAML detected; please check for typos" error="[3:158] unknown field \"readonlyNames\""' >&2
33新增: echo 'level=info msg="`probe.yaml`: OK"' >&2 ;;
34新增: clone)
35新增: [ -z "${AGENT_VM_TEST_CLONE_FAIL:-}" ] || { echo 'level=fatal msg="clone boom"' >&2; exit 1; }
36新增: [ -n "${AGENT_VM_TEST_CLONED:-}" ] && touch "$AGENT_VM_TEST_CLONED" ;;
37新增: edit) [ -z "${AGENT_VM_TEST_EDIT_FAIL:-}" ] || { echo 'level=fatal msg="edit boom"' >&2; exit 1; } ;;
38新增: list)
39新增: case "$*" in
40新增: *"{{.Name}} {{.Config.SSH.LocalPort}}"*)
41新增: echo "agent-vm-base 0"
42新增: [ -z "${AGENT_VM_TEST_OTHER_PORT:-}" ] || echo "agent-vm-other-00000000 $AGENT_VM_TEST_OTHER_PORT"
43新增: listed && echo "$AGENT_VM_TEST_VM ${AGENT_VM_TEST_SSH_PORT:-0}" ;;
44新增: *"{{.Config.SSH.LocalPort}}"*) listed && echo "${AGENT_VM_TEST_SSH_PORT:-0}" ;;
45新增: *"{{.SSHConfigFile}}"*) listed && echo "/lima/$AGENT_VM_TEST_VM/ssh.config" ;;
46新增: *"{{.VMType}}"*) echo "${AGENT_VM_TEST_VMTYPE:-vz} ${AGENT_VM_TEST_MOUNTTYPE:-virtiofs}" ;;
47新增: *"{{.CPUs}}"*"{{.Disk}}"*) listed && echo "$AGENT_VM_TEST_VM|1|3221225472|10737418240" ;;
48新增: *"{{.Status}}|"*) listed && echo "$AGENT_VM_TEST_VM|Running|1|3221225472" ;;
49新增: *"{{.Status}}"*)
50新增: if [ -n "${AGENT_VM_TEST_BASE_RUNNING:-}" ]; then echo "agent-vm-base Running"; else echo "agent-vm-base Stopped"; fi
51新增: if [ -n "${AGENT_VM_TEST_STOPPED:-}" ] || [ -e "$AGENT_VM_TEST_REC.stopped" ]; then st=Stopped; else st=Running; fi
52新增: listed && echo "$AGENT_VM_TEST_VM $st" ;;
53新增: *-q*) echo "agent-vm-base"; listed && echo "$AGENT_VM_TEST_VM" ;;
54新增: *)
55新增: echo "NAME STATUS"
56新增: [ -n "${AGENT_VM_TEST_NOVMS:-}" ] && exit 0
57新增: echo "agent-vm-base Stopped"; listed && echo "$AGENT_VM_TEST_VM Running" ;;
58新增: esac ;;
59新增: shell)
60新增: case "$*" in
61新增: # A guest asked for its mount type lies: agent-vm must not ask it.
62新增: *findmnt*) echo 9p ;;
63新增: *"/usr/local/bin/sshfs"*) [ -z "${AGENT_VM_TEST_SSHFS_FAIL:-}" ] || { echo "E: no sshfs" >&2; exit 1; } ;;
64新增: *agent-vm-write-probe*)
65新增: case "$*" in *'.agent-vm.env'*)
66新增: cat >> "${AGENT_VM_TEST_STDIN:-/dev/null}"
67新增: [ -n "${AGENT_VM_TEST_ENV_FAIL:-}" ] || echo env-ok
68新增: [ -z "${AGENT_VM_TEST_RUNTIME_FOUND:-}" ] || echo runtime-found ;;
69新增: esac
70新增: [ -z "${AGENT_VM_TEST_RO:-}" ] || exit 1 ;;
71新增: *"exec "*" -s"*) cat >> "${AGENT_VM_TEST_STDIN:-/dev/null}" ;;
72新增: esac ;;
73新增: start) rm -f "$AGENT_VM_TEST_REC.stopped" ;;
74新增: stop) cat >/dev/null; [ -n "${AGENT_VM_TEST_STOP_FAIL:-}" ] || touch "$AGENT_VM_TEST_REC.stopped" ;;
75新增: delete) [ -z "${AGENT_VM_TEST_CLONED:-}" ] || rm -f "$AGENT_VM_TEST_CLONED"; cat >/dev/null ;;
76新增:esac
77新增:exit 0
78新增:STUB
79新增:chmod +x "$SB/bin/limactl"
80新增:mkdir -p "$HOME/.agent-vm"
81新增:echo 1 > "$HOME/.agent-vm/.agent-vm-base-version"
82新增:echo 0.2.0 > "$HOME/.agent-vm/.agent-vm-base-built-by"
83新增:PV="$(_agent_vm_name "$PROJ")"
84新增:# Re-sourced by an earlier section, so stubbed again: no KVM and no QEMU on
85新增:# a test runner. Both checks: host probing is covered in lib/host.sh and
86新增:# tests/18-windows.sh, not here.
87新增:_agent_vm_check_linux_prereqs() { return 0; }
88新增:_agent_vm_check_windows_prereqs() { return 0; }
89新增:# The stub Lima runs its VMs on vz, which keeps them to their shares. On
90新增:# Windows a VM's shares are reverse-sshfs whatever Lima says: the tests of
91新增:# that case stub it, and tests/14 checks the real answer.
92新增:if _agent_vm_on_windows; then
93新增: _agent_vm_unprotected_mount_is_sshfs() { return 1; }
94新增:fi
95新增:rec() {
96新增: : > "$REC"
97新增: rm -f "$REC.stopped"
98新增: ( cd "$PROJ" || exit 1
99新增: export AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_VM="$PV" AGENT_VM_TEST_PROTECTS="$PROTECTS"
100新增: agent-vm "$@" </dev/null 2>&1 )
101新增:}
102新增:rec_has() { grep -qF -- "$1" "$REC"; }
103新增:
104新增:section "VM options are read before the command only"
105新增:# `agent-vm run docker run --rm x` used to take docker's --rm for its own: the
106新增:# container ran without it, and the VM was deleted afterwards.
107新增:rec run docker run --rm hello >/dev/null
108新增:rec_has "agent-vm docker run --rm hello" && pass "run: --rm reaches the command" \
109新增: || fail "run: --rm was taken from the command: $(grep ' zsh ' "$REC")"
110新增:rec_has "delete" && fail "run: the VM was deleted" || pass "run: the VM is kept"
111新增:
112新增:rec claude -p hi --rm >/dev/null
113新增:rec_has "claude --dangerously-skip-permissions -p hi --rm" && pass "claude: a later --rm is claude's" \
114新增: || fail "claude: arguments changed: $(grep ' zsh ' "$REC")"
115新增:rec_has "delete" && fail "claude: the VM was deleted" || pass "claude: the VM is kept"
116新增:
117新增:rec --rm run true >/dev/null
118新增:rec_has "delete $PV" && pass "--rm before the command still deletes the VM" \
119新增: || fail "--rm before the command was lost"
120新增:rec claude --rm >/dev/null
121新增:rec_has "delete $PV" && pass "--rm right after the agent name is still agent-vm's" \
122新增: || fail "--rm right after the agent name was passed to the agent"
123新增:rec run --tty htop >/dev/null
124新增:rec_has "shell --workdir $PROJ --tty $PV" && pass "run --tty still allocates a PTY" \
125新增: || fail "run --tty lost: $(grep ' zsh ' "$REC")"
126新增:rec run -- --weird-name >/dev/null
127新增:rec_has "agent-vm --weird-name" && pass "-- ends the options" || fail "-- not honoured"
128新增:rec_has "exec env -- \"\$@\"" && pass "the guest's env takes no option from the command (run -i foo)" \
129新增: || fail "env options reachable: $(grep ' zsh ' "$REC")"
130新增:
131新增:rec pi -p hi --rm >/dev/null
132新增:rec_has "shell --workdir $PROJ --tty $PV" && rec_has "agent-vm pi -p hi --rm" \
133新增: && pass "pi: a TTY, and the arguments are pi's" || fail "pi: $(grep 'zsh' "$REC")"
134新增:rec claude >/dev/null
135新增:rec_has "shell --workdir $PROJ $PV -- zsh" && pass "claude: no TTY forced" || fail "claude: $(grep 'zsh' "$REC")"
136新增:
137新增:# One reader for every command, before or right after its name.
138新增:take() { ( vm_opts=(); rm=""; taken=""; _agent_vm_take_opt "$@" || exit 1; echo "$taken:${vm_opts[*]-}:$rm" ); }
139新增:check "take: --disk 7" "$(take --disk 7 x)" "2:--disk 7:"
140新增:check "take: --disk=7" "$(take --disk=7 x)" "1:--disk 7:"
141新增:check "take: --ram is --memory" "$(take --ram 4)" "2:--memory 4:"
142新增:check "take: --rm" "$(take --rm x)" "1::1"
143新增:check "take: not an option" "$(take -p hi)" "0::"
144新增:check "take: a missing value" "$(take --disk 2>&1; echo $?)" "Error: --disk needs a value.
145新增:1"
146新增:AGENT_VM_TEST_STOPPED=1 rec claude --disk=50 -p hi >/dev/null
147新增:rec_has "edit $PV --disk 50" && rec_has "claude --dangerously-skip-permissions -p hi" \
148新增: && pass "claude --disk=50: agent-vm's, not claude's" || fail "claude --disk=50: $(grep -E '^edit|zsh' "$REC")"
149新增:out="$(rec claude --disk abc)"
150新增:case "$?:$out" in
151新增: 1:*"--disk must be a positive integer (got: 'abc')"*) pass "claude --disk abc: refused, and said" ;;
152新增: *) fail "claude --disk abc: $out" ;;
153新增:esac
154新增:rec_has "shell --workdir" && fail "claude ran anyway" || pass "and claude does not run"
155新增:
156新增:# With no env left on the host, the guest copy must go too, not keep old secrets.
157新增:rm -f "$HOME/.agent-vm/env" "$PROJ/.agent-vm.env"
158新增:rec run true >/dev/null
159新增:rec_has '> "$HOME/.agent-vm.env")' && pass "an empty env still replaces the guest file" \
160新增: || fail "an empty env left the guest file as it was"
161新增:
162新增:# Each `limactl shell` is a round trip: the env push and the write probe share one.
163新增:out="$(rec run true)"
164新增:# The script is multi-line, so one call spans lines of the record: from the
165新增:# push's line to the probe's, no new `shell …` call starts.
166新增:check "one round trip for the env push and the probe" \
167新增: "$(grep -c 'rm -f "$HOME/.agent-vm.env"' "$REC") $(grep -c 'agent-vm-write-probe' "$REC") $(sed -n '/rm -f "$HOME\/.agent-vm.env"/,/agent-vm-write-probe/p' "$REC" | grep -c '^shell ')" "1 1 0"
168新增:check "a push that worked is not warned about" \
169新增: "$(printf '%s\n' "$out" | grep -c 'failed to push the env')" "0"
170新增:out="$(AGENT_VM_TEST_ENV_FAIL=1 rec run true)"
171新增:case "$out" in
172新增: *"Warning: failed to push the env files"*) pass "a failed push is still said" ;;
173新增: *) fail "a failed push went unsaid: $out" ;;
174新增:esac
175新增:
176新增:# `shell` takes no command, so a word it does not know is a mistake: it used to
177新增:# be skipped, which reads to the caller as if the flag had applied.
178新增:out="$(rec shell --offline)"
179新增:case "$out" in
180新增: *"unknown argument for shell: --offline"*) pass "shell rejects an unknown argument" ;;
181新增: *) fail "shell accepted --offline: $out" ;;
182新增:esac
183新增:rec_has "shell --workdir" && fail "shell opened a session anyway" || pass "no session is opened"
新增tests/12-ssh-port-and-creation.sh+76 −0看文件
@@ -0,0 +1,76 @@
1新增:section "--ssh-port and the SSH alias"
2新增:check "info: ssh_config once the VM exists" \
3新增: "$(rec info | grep '^ssh_config=')" "ssh_config=/lima/$PV/ssh.config"
4新增:out="$(AGENT_VM_TEST_STOPPED=1 rec --ssh-port 2222 run true)"
5新增:rec_has "edit $PV --set .ssh.localPort = 2222" && pass "--ssh-port: set on a stopped VM" \
6新增: || fail "--ssh-port not set: $(grep '^edit' "$REC") $out"
7新增:AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_SSH_PORT=2222 rec --ssh-port 2222 run true >/dev/null
8新增:rec_has "localPort" && fail "--ssh-port: the same port was set again" || pass "--ssh-port: the same port is left alone"
9新增:AGENT_VM_TEST_STOPPED=1 rec run claude --ssh-port 2222 >/dev/null
10新增:rec_has "localPort" && fail "--ssh-port after the command was taken" || pass "--ssh-port after the command is the command's"
11新增:AGENT_VM_TEST_STOPPED=1 rec claude --ssh-port 2223 >/dev/null
12新增:rec_has "edit $PV --set .ssh.localPort = 2223" && pass "--ssh-port right after the agent name is agent-vm's" \
13新增: || fail "claude --ssh-port lost: $(grep '^edit' "$REC")"
14新增:AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_SSH_PORT=2222 rec --ssh-port 0 run true >/dev/null
15新增:rec_has "edit $PV --set .ssh.localPort = 0" && pass "--ssh-port 0: back to a port Lima picks" \
16新增: || fail "--ssh-port 0 not set: $(grep '^edit' "$REC")"
17新增:out="$(AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_OTHER_PORT=2222 rec --ssh-port 2222 run true)"
18新增:case "$?:$out" in
19新增: 1:*"SSH port 2222 is already set for VM 'agent-vm-other-00000000'"*) pass "--ssh-port: a port another VM has is refused" ;;
20新增: *) fail "--ssh-port: taken port not refused: $out" ;;
21新增:esac
22新增:rec_has "localPort =" && fail "a taken port was set anyway" || pass "and nothing is changed"
23新增:for bad in 80 70000 abc ""; do
24新增: out="$(rec --ssh-port "$bad" run true)"
25新增: case "$?:$out" in
26新增: 1:*"--ssh-port must be 0 or a port from 1024 to 65535"*) pass "--ssh-port '$bad' refused" ;;
27新增: *) fail "--ssh-port '$bad' accepted: $out" ;;
28新增: esac
29新增:done
30新增:out="$(rec claude --ssh-port 80)"
31新增:case "$?:$out" in
32新增: 1:*"--ssh-port must be"*) pass "claude --ssh-port 80 refused too" ;;
33新增: *) fail "claude --ssh-port 80 accepted: $out" ;;
34新增:esac
35新增:CLONED="$SB/cloned-port"; rm -f "$CLONED"
36新增:AGENT_VM_TEST_CLONED="$CLONED" AGENT_VM_TEST_STOPPED=1 rec --ssh-port 2224 run true >/dev/null
37新增:p="$(grep -n -m1 -- "^edit $PV --set .ssh.localPort = 2224" "$REC" | cut -d: -f1)"
38新增:s="$(grep -n -m1 "^start $PV" "$REC" | cut -d: -f1)"
39新增:[ -n "$p" ] && [ -n "$s" ] && [ "$p" -lt "$s" ] \
40新增: && pass "new VM: the port is set before the first start" \
41新增: || fail "new VM: $(grep -E '^(edit|start)' "$REC")"
42新增:
43新增:section "a VM that cannot be configured is not kept (#21)"
44新增:# The edit giving a new VM its shares and resources used to fail in silence:
45新增:# the VM then ran with the template's config, ~/.agent-vm/volumes entries gone.
46新增:CLONED="$SB/cloned-fail"; rm -f "$CLONED"
47新增:out="$(AGENT_VM_TEST_CLONED="$CLONED" AGENT_VM_TEST_EDIT_FAIL=1 rec --memory 2 run true)"
48新增:case "$?:$out" in
49新增: 1:*"could not set the shares of VM '$PV'"*"edit boom"*) pass "a failed edit is said, with Lima's message" ;;
50新增: *) fail "a failed edit: $out" ;;
51新增:esac
52新增:rec_has "delete $PV --force" && pass "and the half-made VM is deleted" || fail "the half-made VM is kept"
53新增:rec_has "start $PV" && fail "the VM was started anyway" || pass "and it is not started"
54新增:[ -e "$HOME/.agent-vm/.agent-vm-mounts-$PV" ] && fail "its mounts are still recorded" \
55新增: || pass "and no mounts are recorded for it"
56新增:out="$(AGENT_VM_TEST_CLONED="$CLONED" AGENT_VM_TEST_CLONE_FAIL=1 rec run true)"
57新增:case "$?:$out" in
58新增: 1:*"could not clone the base template into '$PV'"*"clone boom"*) pass "a failed clone is said too" ;;
59新增: *) fail "a failed clone: $out" ;;
60新增:esac
61新增:rec_has "edit $PV" && fail "a failed clone was edited anyway" || pass "and nothing is done after it"
62新增:
63新增:section "--reset stops when the old VM cannot be deleted"
64新增:# Carrying on would reuse the old VM, with the shares it was given: a volumes
65新增:# entry since limited to another project would stay mounted in it.
66新增:out="$(rec --reset run true)"
67新增:case "$?:$out" in
68新增: 1:*"could not delete VM '$PV'"*) pass "a VM Lima still lists after the delete: --reset fails" ;;
69新增: *) fail "--reset over an undeleted VM: $out" ;;
70新增:esac
71新增:rec_has "agent-vm true" && fail "the command ran on the old VM" || pass "and the command does not run"
72新增:CLONED="$SB/cloned-reset"; touch "$CLONED"
73新增:AGENT_VM_TEST_CLONED="$CLONED" rec --reset run true >/dev/null
74新增:rec_has "delete $PV --force" && rec_has "clone agent-vm-base $PV" && rec_has "agent-vm true" \
75新增: && pass "a delete that takes: re-cloned, then the command runs" || fail "--reset: $(grep -E '^(delete|clone)' "$REC")"
76新增:rm -f "$CLONED"
新增tests/13-volumes-and-readonly.sh+263 −0看文件
@@ -0,0 +1,263 @@
1新增:section "~/.agent-vm/volumes: entries limited to some projects"
2新增:mkdir -p "$SB/vol-f"
3新增:vols() { printf '%s\n' "$@" > "$HOME/.agent-vm/volumes"; _agent_vm_build_mounts_json "$PV" "$PROJ" true 2>"$SB/vols-err"; }
4新增:has_vol() { case "$1" in *"\"location\": \"$(_agent_vm_host_path "$SB/vol-f")\""*) echo yes ;; *) echo no ;; esac; }
5新增:check "filter: the project's own path" "$(has_vol "$(vols "$SB/vol-f:/mnt/f:ro:$PROJ")")" yes
6新增:check "filter: a trailing slash is the same path" "$(has_vol "$(vols "$SB/vol-f:/mnt/f:ro:$PROJ/")")" yes
7新增:check "filter: another project's path" "$(has_vol "$(vols "$SB/vol-f:/mnt/f:ro:$SB/other")")" no
8新增:check "filter: a parent is not a match" "$(has_vol "$(vols "$SB/vol-f:/mnt/f:ro:$SB")")" no
9新增:check "filter: * matches below a directory" "$(has_vol "$(vols "$SB/vol-f:/mnt/f:ro:$SB/*")")" yes
10新增:check "filter: * does not match elsewhere" "$(has_vol "$(vols "$SB/vol-f:/mnt/f:ro:/nowhere/*")")" no
11新增:check "filter: ~ is expanded" \
12新增: "$( HOME="$SB"; _agent_vm_volume_matches '~/proj' "$PROJ" && echo yes || echo no )" yes
13新增:check "filter: mode rw is kept" \
14新增: "$(vols "$SB/vol-f:/mnt/f:rw:$PROJ" | grep -oF "$(mnt "$SB/vol-f" /mnt/f), \"writable\": true")" \
15新增: "$(mnt "$SB/vol-f" /mnt/f), \"writable\": true"
16新增:check "filter: no destination mounts at the same path" \
17新增: "$(vols "$SB/vol-f::ro:$PROJ" | grep -cF "{$(mnt "$SB/vol-f"), \"writable\": false}")" 1
18新增:check "filter: no destination, short form" \
19新增: "$(vols "$SB/vol-f:ro:$PROJ" | grep -cF "{$(mnt "$SB/vol-f"), \"writable\": false}")" 1
20新增:# Entries that do not read as source:destination:mode:project are refused, not
21新增:# guessed: read as a destination, the project filter is lost and the entry
22新增:# mounted in every project (cases from #30).
23新增:for e in "$SB/vol-f:/mnt/f:rw:" \
24新增: "$SB/vol-f:/mnt/f:$SB/other" \
25新增: "$SB/vol-f:/mnt/f:$SB/other:rw" \
26新增: "$SB/vol-f:/mnt/f:rw:$SB/other:ro" \
27新增: "$SB/vol-f:/mnt/f:ro:$SB/other:x"; do
28新增: out="$(vols "$e")"
29新增: if [ "$(has_vol "$out")" = no ] && grep -q "Warning: Mount entry '$e'" "$SB/vols-err"; then
30新增: pass "refused, with a warning: ${e#"$SB"/}"
31新增: else
32新增: fail "not refused: ${e#"$SB"/} -> $out $(cat "$SB/vols-err")"
33新增: fi
34新增:done
35新增:out="$(vols "$SB/vol-f:/mnt/f:rw:")"
36新增:grep -q "empty project filter" "$SB/vols-err" && pass "an empty filter is named as such" || fail "empty filter: $(cat "$SB/vols-err")"
37新增:out="$(vols "$(printf '%s:/mnt/a\tb:ro' "$SB/vol-f")")"
38新增:check "a control character in an entry: refused" "$(has_vol "$out") $(grep -c 'control character' "$SB/vols-err")" "no 1"
39新增:out="$(vols "$SB/vol-f:/mnt/f:ro:~nobody/proj")"
40新增:check "a ~user filter is not an absolute path: refused" "$(has_vol "$out") $(grep -c 'not an absolute path' "$SB/vols-err")" "no 1"
41新增:check "the filter's ~/ still expands" \
42新增: "$( HOME="$SB"; _agent_vm_volume_matches '~/proj' "$PROJ" && echo yes || echo no )" yes
43新增:
44新增:out="$(vols "$SB/vol-f:/mnt/f:ro:relative/path")"
45新增:check "filter: a relative one matches nothing" "$(has_vol "$out")" no
46新增:grep -q "Project filter 'relative/path'.*not an absolute path" "$SB/vols-err" \
47新增: && pass "filter: and says why" || fail "filter: relative filter not reported: $(cat "$SB/vols-err")"
48新增:# A relative destination is inside the project, and made on the host, which
49新增:# needs perl (_agent_vm_nofollow). Without it the entry is skipped, and said.
50新增:if [[ -n "$AGENT_VM_HAS_PERL" ]]; then
51新增:out="$(vols "$SB/vol-f:.claude:ro:$PROJ")"
52新增:check "relative: inside the project" \
53新增: "$(printf '%s' "$out" | grep -cF "$(mnt "$SB/vol-f" "$PROJ/.claude")")" 1
54新增:[ -d "$PROJ/.claude" ] && pass "relative: the mount point is made on the host" || fail "relative: no $PROJ/.claude"
55新增:vols "$SB/vol-f:./a/b:ro" >/dev/null
56新增:[ -d "$PROJ/a/b" ] && pass "relative: ./ and subdirectories" || fail "relative: no $PROJ/a/b"
57新增:else
58新增: out="$(vols "$SB/vol-f:.claude:ro:$PROJ")"
59新增: check "relative, no perl: skipped, and said" \
60新增: "$(has_vol "$out") $(grep -c 'perl is needed' "$SB/vols-err") $([ -e "$PROJ/.claude" ] && echo made || echo none)" "no 1 none"
61新增:fi
62新增:mkdir -p "$SB/outside"
63新增:out="$(vols "$SB/vol-f:../outside/x:ro")"
64新增:check "relative: .. is refused" "$(has_vol "$out")" no
65新增:grep -q "goes out of the project with '..'" "$SB/vols-err" && [ ! -e "$SB/outside/x" ] \
66新增: && pass "relative: and nothing is made outside" || fail "relative ..: $(cat "$SB/vols-err")"
67新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
68新增:ln -s "$SB/outside" "$PROJ/planted"
69新增:out="$(vols "$SB/vol-f:planted/x:ro")"
70新增:check "relative: a symlink in the project is refused" "$(has_vol "$out")" no
71新增:grep -q "goes through a symlink in the project" "$SB/vols-err" && [ ! -e "$SB/outside/x" ] \
72新增: && pass "relative: and mkdir does not follow it" || fail "relative symlink: $(cat "$SB/vols-err"); $(ls "$SB/outside")"
73新增:rm -f "$PROJ/planted"
74新增:if [[ -n "$AGENT_VM_HAS_PERL" ]]; then
75新增:# The VM can plant the link after the check above: here, right before the
76新增:# mount point is made, for a directory and for a file source.
77新增:race_real="$(typeset -f _agent_vm_nofollow)"
78新增:mkdir -p "$SB/race-out"
79新增:for kind in dir file; do
80新增: src="$SB/vol-f"; [ "$kind" = file ] && { src="$SB/race-src.toml"; echo x > "$src"; }
81新增: out="$( eval "${race_real/_agent_vm_nofollow/_race_nofollow}"
82新增: _agent_vm_nofollow() { ln -s "$SB/race-out" "$PROJ/raced"; _race_nofollow "$@"; }
83新增: _agent_vm_project_mountpoint "$PROJ" raced/x "$src" 2>"$SB/race-err" )"
84新增: check "relative, a link planted after the check ($kind): refused, nothing made outside" \
85新增: "$out|$(ls -A "$SB/race-out")|$(grep -c 'goes through a symlink' "$SB/race-err")" "||1"
86新增: rm -f "$PROJ/raced" "$SB/race-src.toml"
87新增:done
88新增:rm -rf "$SB/race-out"
89新增:else
90新增: printf ' skip relative: a link planted after the check (perl is not installed)\n'
91新增:fi
92新增:else
93新增: printf ' skip relative: symlink in the project (ln -s plants copies on this machine)\n'
94新增:fi
95新增:out="$(vols "$SB/vol-f:.:ro")"
96新增:check "relative: the project itself is refused" "$(has_vol "$out")" no
97新增:echo x > "$SB/vol-file.toml"
98新增:if [[ -n "$AGENT_VM_HAS_PERL" ]]; then
99新增:vols "$SB/vol-file.toml:conf/app.toml" >/dev/null
100新增:[ -f "$PROJ/conf/app.toml" ] && pass "relative, a file: an empty file is its mount point" || fail "relative file: no placeholder"
101新增:grep -q "|$PROJ/conf/app.toml\$" "$HOME/.agent-vm/.agent-vm-file-mounts-$PV" \
102新增: && pass "relative, a file: bound at that path" || fail "relative file: $(cat "$HOME/.agent-vm/.agent-vm-file-mounts-$PV")"
103新增:fi
104新增:# Two file entries: the JSON is only JSON.
105新增:echo y > "$SB/vol-file2.toml"
106新增:out="$(vols "$SB/vol-file.toml:/etc/a.toml" "$SB/vol-file2.toml:/etc/b.toml")"
107新增:case "$out" in \[*\]) pass "two file entries: the mounts JSON alone" ;; *) fail "two file entries: $out" ;; esac
108新增:rm -rf "$PROJ/.claude" "$PROJ/a" "$PROJ/planted" "$PROJ/conf" "$SB/outside" "$SB/vol-file.toml" "$SB/vol-file2.toml"
109新增:check "no filter: every project, as before" "$(has_vol "$(vols "$SB/vol-f:/mnt/f:ro")")" yes
110新增:check "no filter, no mode: as before" \
111新增: "$(vols "$SB/vol-f:/mnt/f" | grep -c "\"mountPoint\": \"/mnt/f\", \"writable\": false")" 1
112新增:rm -f "$HOME/.agent-vm/volumes"
113新增:
114新增:section "--readonly makes every share read-only"
115新增:# The hypervisor enforces read-only per share, not per host file. A writable
116新增:# volume containing the project (~/work:/mnt/work:rw) was a way to write the
117新增:# project under --readonly without root.
118新增:mkdir -p "$SB/vol-rw" "$SB/vol-ro"
119新增:printf '%s:/mnt/rw:rw\n%s:/mnt/ro\n' "$SB/vol-rw" "$SB/vol-ro" > "$HOME/.agent-vm/volumes"
120新增:ro_json="$(_agent_vm_build_mounts_json "$PV" "$PROJ" false 2>"$SB/ro-notice")"
121新增:rw_json="$(_agent_vm_build_mounts_json "$PV" "$PROJ" true 2>/dev/null)"
122新增:case "$ro_json" in
123新增: *'"writable": true'*) fail "a share stays writable under --readonly: $ro_json" ;;
124新增: *) pass "no share is writable under --readonly" ;;
125新增:esac
126新增:case "$rw_json" in
127新增: *"$(mnt "$SB/vol-rw" /mnt/rw), \"writable\": true"*)
128新增: pass "without it, an rw volume is writable again" ;;
129新增: *) fail "rw volume not restored: $rw_json" ;;
130新增:esac
131新增:case "$(cat "$SB/ro-notice")" in
132新增: *"'$SB/vol-rw' (rw in ~/.agent-vm/volumes) is mounted read-only too"*) pass "the downgrade is announced" ;;
133新增: *) fail "no notice for the downgraded volume" ;;
134新增:esac
135新增:
136新增:# An existing VM whose project is already read-only: the probe agrees with
137新增:# --readonly, so only the record of applied mounts can say a volume is still
138新增:# writable. Stopped, so no prompt is needed.
139新增:REC_MOUNTS="$HOME/.agent-vm/.agent-vm-mounts-$PV"
140新增:ro_run() { AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_RO=1 rec --readonly run true >/dev/null; }
141新增:printf '%s\n' "[{\"location\": \"$PROJ\", \"writable\": false}, {\"location\": \"$SB/vol-rw\", \"writable\": true}]" > "$REC_MOUNTS"
142新增:ro_run
143新增:rec_has "edit $PV --set del(.mountType) | .mounts" && pass "a recorded writable volume forces a remount" \
144新增: || fail "a writable volume survived --readonly"
145新增:_agent_vm_mounts_all_readonly "$PV" && pass "the new record has no writable share" \
146新增: || fail "the record still has a writable share: $(cat "$REC_MOUNTS")"
147新增:ro_run
148新增:rec_has "edit $PV" && fail "an all read-only VM was remounted again" \
149新增: || pass "an all read-only VM is left alone"
150新增:# Back to writable while it runs: another terminal may be using it under
151新增:# --readonly, so it is asked (no by default), not taken for a broken mount.
152新增:out="$(AGENT_VM_TEST_RO=1 rec run true; echo "rc=$?")"
153新增:case "$out" in *"runs read-only (--readonly)"*"not restarted"*"rc=1") pass "after --readonly, running, no terminal: not restarted" ;; *) fail "after --readonly, running: $out" ;; esac
154新增:rec_has "stop $PV" && fail "after --readonly, running: stopped unasked" || pass "and it was not stopped"
155新增:out="$( _agent_vm_can_ask() { return 0; }; _agent_vm_ask_yn() { echo 1; }; AGENT_VM_TEST_RO=1 rec run true )"
156新增:rec_has "stop $PV" && rec_has "edit $PV" && pass "after --readonly, running, restart accepted: made writable" || fail "after --readonly, accepted: $out"
157新增:_agent_vm_mounts_all_readonly "$PV" && fail "after --readonly, accepted: still recorded read-only" || pass "and recorded writable"
158新增:# Stopped: the end of a --readonly session is said as such, not as a broken
159新增:# mount being repaired.
160新增:printf '%s\n' "[{\"location\": \"$PROJ\", \"writable\": false}]" > "$REC_MOUNTS"
161新增:out="$(AGENT_VM_TEST_STOPPED=1 rec run true)"
162新增:case "$out" in *"left read-only by --readonly; making it writable again"*) pass "after --readonly, stopped: says it is making the VM writable again" ;; *) fail "after --readonly, stopped: $out" ;; esac
163新增:printf '[{"location": "%s", "writable": true}]\n' "$PROJ" > "$REC_MOUNTS"
164新增:out="$(AGENT_VM_TEST_RO=1 rec run true)"
165新增:case "$out" in *"Project mount is not writable; repairing"*) pass "a writable VM that cannot write: a repair" ;; *) fail "broken mount: $out" ;; esac
166新增:# The first push ran on the broken mount, where the VM could not see the
167新增:# project's env file or runtime: the repaired VM gets them pushed again.
168新增:check "after a repair, the env is pushed again, with the project's files" \
169新增: "$(grep -c 'rm -f "$HOME/.agent-vm.env"' "$REC") $(grep -c "^shell $PV sh -c" "$REC")" "2 2"
170新增:rm -f "$REC_MOUNTS"
171新增:ro_run
172新增:rec_has "edit $PV --set del(.mountType) | .mounts" && pass "no record (an older VM): remounted to be sure" \
173新增: || fail "an unrecorded VM was trusted"
174新增:_agent_vm_cleanup_state "$PV"
175新增:[ -e "$REC_MOUNTS" ] && fail "rm/--reset left the mounts record" || pass "rm/--reset drops the mounts record"
176新增:
177新增:# Declining a resize of a running VM (or having no terminal to accept it on)
178新增:# used to return before anything else: --readonly was then never applied, and
179新增:# the command ran on a writable VM.
180新增:# --disk: unlike CPUs and memory, it is not clamped to this host's share.
181新增:out="$(rec --readonly --disk 20 run true)"
182新增:rc=$?
183新增:case "$rc:$out" in
184新增: 1:*"Not applied: the VM keeps its current settings"*"--readonly was requested but not applied"*)
185新增: pass "a declined resize does not skip --readonly" ;;
186新增: *) fail "a declined resize skipped --readonly ($rc): $out" ;;
187新增:esac
188新增:rec_has "agent-vm true" && fail "the command ran on a writable VM" || pass "and the command does not run"
189新增:rec_has "edit $PV --disk" && fail "the declined resize was applied" || pass "and the resize is not applied"
190新增:_agent_vm_cleanup_state "$PV"
191新增:rm -f "$HOME/.agent-vm/volumes"
192新增:
193新增:section "--readonly on a stopped VM: read-only from its first boot"
194新增:# A VM that last ran writable used to be started writable, then stopped and
195新增:# made read-only: whatever starts with the VM had a writable window.
196新增:printf '[{"location": "%s", "writable": true}]\n' "$PROJ" > "$REC_MOUNTS"
197新增:AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_RO=1 rec --readonly run true >/dev/null
198新增:e="$(grep -n "^edit $PV --set" "$REC" | head -1 | cut -d: -f1)"
199新增:s="$(grep -n "^start $PV" "$REC" | head -1 | cut -d: -f1)"
200新增:if [ -n "$e" ] && [ -n "$s" ] && [ "$e" -lt "$s" ]; then
201新增: pass "the shares are made read-only before the VM starts"
202新增:else
203新增: fail "read-only applied at '${e:-none}', start at '${s:-none}'"
204新增:fi
205新增:check "and it starts once" "$(grep -c "^start $PV" "$REC")" "1"
206新增:rec_has "stop $PV" && fail "the VM was stopped to apply --readonly" || pass "and is not stopped again"
207新增:# Back to writable: also before the start.
208新增:AGENT_VM_TEST_STOPPED=1 rec run true >/dev/null
209新增:check "the end of a --readonly session: changed first, then one start" \
210新增: "$(grep -c "^start $PV" "$REC") $(grep -E "^(edit $PV --set|start $PV)" "$REC" | head -1 | cut -d' ' -f1)" "1 edit"
211新增:# Whether --readonly holds is decided on the host: the guest is not asked.
212新增:rec_has "findmnt" && fail "the guest was asked for its mount type" || pass "the guest is not asked for its mount type"
213新增:
214新增:section "a stop that did not happen changes nothing"
215新增:# The shares were edited and recorded read-only while the VM still ran with
216新增:# its writable ones.
217新增:printf '[{"location": "%s", "writable": true}]\n' "$PROJ" > "$REC_MOUNTS"
218新增:out="$(AGENT_VM_TEST_STOP_FAIL=1 AGENT_VM_TEST_RO=1 rec run true)"
219新增:case "$?:$out" in
220新增: 1:*"could not stop VM '$PV'"*) pass "the repair stops only once the VM is down" ;;
221新增: *) fail "a failed stop went on: $out" ;;
222新增:esac
223新增:rec_has "edit $PV" && fail "the shares were edited on a running VM" || pass "and nothing is edited"
224新增:check "and the record is unchanged" "$(cat "$REC_MOUNTS")" "[{\"location\": \"$PROJ\", \"writable\": true}]"
225新增:_agent_vm_cleanup_state "$PV"
226新增:# `agent-vm stop` said "VM stopped." whatever happened.
227新增:out="$(rec stop)"
228新增:case "$?:$out" in 0:*"VM stopped."*) pass "stop: a VM that stops is said stopped" ;; *) fail "stop: $out" ;; esac
229新增:out="$(AGENT_VM_TEST_STOP_FAIL=1 rec stop)"
230新增:case "$?:$out" in
231新增: 1:*"is still running"*) pass "stop: a VM that keeps running is an error" ;;
232新增: *) fail "stop that did not take: $out" ;;
233新增:esac
234新增:case "$out" in *"VM stopped."*) fail "stop: reported stopped while running" ;; *) pass "stop: and not reported stopped" ;; esac
235新增:
236新增:section "directories that are never shared"
237新增:# `cd ~ && agent-vm shell` handed the VM every dotfile and SSH key, read-write.
238新增:refused() { # <dir>
239新增: local out
240新增: out="$( cd "$1" && export AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_VM="$PV"; : > "$REC"; agent-vm run true </dev/null 2>&1 )"
241新增: case "$?:$out" in
242新增: 1:*"refusing to share"*) grep -q '^clone\|^start\|^shell' "$REC" && echo "refused, but limactl ran" || echo refused ;;
243新增: *) echo "accepted: $out" ;;
244新增: esac
245新增:}
246新增:check "the home directory" "$(refused "$HOME")" "refused"
247新增:check "a parent of it" "$(refused "$SB")" "refused"
248新增:check "/" "$(refused /)" "refused"
249新增:check "agent-vm's own directory" "$(refused "$AGENT_VM_SCRIPT_DIR")" "refused"
250新增:check "a parent of agent-vm's" "$(refused "$(dirname "$AGENT_VM_SCRIPT_DIR")")" "refused"
251新增:check "agent-vm's state" "$(refused "$HOME/.agent-vm")" "refused"
252新增:# Inside them: the VM would write what the host runs (lib/), or every VM's
253新增:# config (Lima's _config/override.yaml).
254新增:mkdir -p "$HOME/.agent-vm/inside" "$(_agent_vm_lima_home)/_config"
255新增:check "a folder inside agent-vm" "$(refused "$AGENT_VM_SCRIPT_DIR/lib")" "refused"
256新增:check "a folder inside its state" "$(refused "$HOME/.agent-vm/inside")" "refused"
257新增:check "a folder inside Lima's" "$(refused "$(_agent_vm_lima_home)/_config")" "refused"
258新增:check "and says which" "$(_agent_vm_unsafe_project "$AGENT_VM_SCRIPT_DIR/lib")" "is inside agent-vm itself"
259新增:case "$(refused "$PROJ")" in accepted*) pass "a project directory is shared" ;; *) fail "a project directory was refused" ;; esac
260新增:case "$(_agent_vm_unsafe_project "$HOME/proj-under-home" 2>/dev/null || echo none)" in
261新增: none) pass "a project inside the home directory is fine" ;;
262新增: *) fail "a project inside the home directory was refused" ;;
263新增:esac
新增tests/14-git-protection.sh+570 −0看文件
@@ -0,0 +1,570 @@
1新增:section ".git protection follows what Lima can do"
2新增:# Stock Lima accepts readonlyNames with a warning and ignores it, so only a
3新增:# refusal that names the field counts. Stock Lima failing for another reason
4新增:# still names it, in its "unknown field" warning: that is not support either.
5新增:# An answer that says neither is "cannot tell", never "no".
6新增:probe() {
7新增: ( export AGENT_VM_TEST_REC="$SB/probe.log" AGENT_VM_TEST_PROTECTS="$PROTECTS" TMPDIR="$SB/probe-tmp"
8新增: _agent_vm_lima_protects_git; case $? in 0) echo yes ;; 1) echo no ;; *) echo unknown ;; esac )
9新增:}
10新增:mkdir -p "$SB/probe-tmp"
11新增:rm -f "$PROTECTS"
12新增:check "stock Lima: no protection" "$(probe)" "no"
13新增:touch "$PROTECTS"
14新增:check "a Lima with readonlyNames: protection" "$(probe)" "yes"
15新增:check "the probe leaves no temporary file" "$(ls -A "$SB/probe-tmp")" ""
16新增:mkdir -p "$SB/stock-err"
17新增:cat > "$SB/stock-err/limactl" <<'STUB'
18新增:#!/usr/bin/env bash
19新增:echo 'level=warning msg="Non-strict YAML detected" error="[2:47] unknown field \"readonlyNames\""' >&2
20新增:echo 'level=fatal msg="failed to validate YAML file `probe.yaml`: field `images` must be set"' >&2
21新增:exit 1
22新增:STUB
23新增:chmod +x "$SB/stock-err/limactl"
24新增:check "stock Lima failing for another reason: no protection" "$(PATH="$SB/stock-err:$PATH" probe)" "no"
25新增:mkdir -p "$SB/nolimactl"
26新增:# Wrappers, not symlinks (see 10-names-and-paths.sh): the probe must run its
27新增:# mktemp while limactl stays missing, on machines without link privilege too.
28新增:for t in mktemp rm; do
29新增: printf '#!/bin/sh\nexec "%s" "$@"\n' "$(command -v "$t")" > "$SB/nolimactl/$t"
30新增: chmod +x "$SB/nolimactl/$t"
31新增:done
32新增:check "no limactl: cannot tell" "$(PATH="$SB/nolimactl" probe)" "unknown"
33新增:check "a Lima accepting the probe without a word: cannot tell" \
34新增: "$(AGENT_VM_TEST_VALIDATE_SILENT=1 probe)" "unknown"
35新增:
36新增:# Cannot tell: the start stops before anything changes, even for a VM that is
37新增:# protected today, and whatever the security questions say. --readonly and
38新增:# --unsafe-writable-git still start it.
39新增:protected_rec_early() { printf '[{"location": "%s", "writable": true, %s}]\n' "$PROJ" "$SSHFS_RO" > "$REC_MOUNTS"; }
40新增:protected_rec_early
41新增:out="$(AGENT_VM_TEST_VALIDATE_SILENT=1 AGENT_VM_TEST_STOPPED=1 rec run true)"
42新增:case "$out" in *"Error: cannot tell whether this Lima keeps .git read-only"*) pass "cannot tell: the start stops, and says why" ;; *) fail "cannot tell: $out" ;; esac
43新增:if grep -Eq '^(edit|start|clone) ' "$REC"; then fail "cannot tell: the VM was touched: $(grep -E '^(edit|start)' "$REC" | head -1)"
44新增:else pass "cannot tell: the protected VM is left as it is"; fi
45新增:AGENT_VM_TEST_VALIDATE_SILENT=1 AGENT_VM_TEST_STOPPED=1 rec --unsafe-writable-git run true >/dev/null
46新增:rec_has "start $PV" && pass "cannot tell: --unsafe-writable-git still starts it" || fail "cannot tell: --unsafe-writable-git did not start it"
47新增:
48新增:# A new VM gets reverse-sshfs and readonlyNames on every share.
49新增:CLONED="$SB/cloned-prot"; rm -f "$CLONED" "$REC_MOUNTS"
50新增:AGENT_VM_TEST_CLONED="$CLONED" rec run true >/dev/null
51新增:rec_has "edit $PV --set .mountType = \"reverse-sshfs\" | .mounts = [{$(mnt "$PROJ"), \"writable\": true, $SSHFS_RO}]" \
52新增: && pass "new VM: reverse-sshfs, every .git read-only" || fail "new VM not protected: $(grep '^edit' "$REC")"
53新增:_agent_vm_mounts_protect_git "$PV" && pass "new VM: recorded as protected" || fail "new VM: record not protected"
54新增:
55新增:# An existing VM set up before: changed while it is stopped, before it starts,
56新增:# so it is not started a second time.
57新增:unprotected_rec() { printf '[{"location": "%s", "writable": true}]\n' "$PROJ" > "$REC_MOUNTS"; }
58新增:protected_rec() { printf '[{"location": "%s", "writable": %s, %s}]\n' "$PROJ" "${1:-true}" "$SSHFS_RO" > "$REC_MOUNTS"; }
59新增:unprotected_rec
60新增:out="$(AGENT_VM_TEST_STOPPED=1 rec run true)"
61新增:e="$(grep -n "^edit $PV --set .mountType = \"reverse-sshfs\"" "$REC" | head -1 | cut -d: -f1)"
62新增:s="$(grep -n "^start $PV" "$REC" | head -1 | cut -d: -f1)"
63新增:if [ -n "$e" ] && [ -n "$s" ] && [ "$e" -lt "$s" ]; then
64新增: pass "stopped VM from before: protected before it starts"
65新增:else
66新增: fail "stopped VM from before: edit at '${e:-none}', start at '${s:-none}'"
67新增:fi
68新增:check "stopped VM from before: started once" "$(grep -c "^start $PV" "$REC")" "1"
69新增:case "$out" in *"Making every .git read-only for VM '$PV'"*) pass "and it says so" ;; *) fail "no notice: $out" ;; esac
70新增:
71新增:# A running one is not restarted behind another session's back: asked, and
72新增:# with no one to answer, a risk that stops the start. With the questions off,
73新增:# warned and left running.
74新增:unprotected_rec
75新增:out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }; rec run true )"
76新增:rec_has "edit $PV" && fail "a running VM was changed" || pass "running VM from before: left running"
77新增:case "$out" in *"can still write .git"*"Aborted. 'agent-vm stop', then run again."*) pass "running VM from before, no terminal: stops, and says how to protect it" ;; *) fail "no abort: $out" ;; esac
78新增:rec_has "agent-vm-write-probe" && fail "running VM from before, no terminal: the command ran" || pass "and the command did not run"
79新增:unprotected_rec
80新增:out="$(rec run true)"
81新增:rec_has "edit $PV" && fail "questions off: a running VM was changed" || pass "questions off: left running"
82新增:case "$out" in *"can still write .git"*"Continuing: AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1."*) pass "questions off: warned, then on" ;; *) fail "questions off: $out" ;; esac
83新增:unprotected_rec
84新增:out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 0; }; _agent_vm_ask_yn() { echo 1; }; rec run true )"
85新增:s="$(grep -n "^stop $PV" "$REC" | head -1 | cut -d: -f1)"
86新增:e="$(grep -n "^edit $PV --set .mountType = \"reverse-sshfs\"" "$REC" | head -1 | cut -d: -f1)"
87新增:t="$(grep -n "^start $PV" "$REC" | head -1 | cut -d: -f1)"
88新增:if [ -n "$s" ] && [ -n "$e" ] && [ -n "$t" ] && [ "$s" -lt "$e" ] && [ "$e" -lt "$t" ]; then
89新增: pass "running VM from before, restart accepted: stopped, protected, started"
90新增:else
91新增: fail "restart accepted: stop '${s:-none}', edit '${e:-none}', start '${t:-none}': $out"
92新增:fi
93新增:
94新增:# From a base built by agent-vm 0.1.0 (no version of it recorded for the VM):
95新增:# no sshfs in it, so it boots once with no shares to get it, then gets the
96新增:# protected ones. Line numbers of the calls, in the order they must come.
97新增:BUILT_BY="$HOME/.agent-vm/.agent-vm-built-by-$PV"
98新增:MIGRATED="$HOME/.agent-vm/.agent-vm-sshfs-$PV"
99新增:old_vm() { rm -f "$BUILT_BY" "$MIGRATED" "$REC_MOUNTS"; }
100新增:at() { grep -n -- "$1" "$REC" | head -1 | cut -d: -f1; }
101新增:in_order() {
102新增: local prev=0 n
103新增: for n in "$@"; do
104新增: [ -n "$n" ] && [ "$n" -gt "$prev" ] || return 1
105新增: prev="$n"
106新增: done
107新增:}
108新增:migration_order() {
109新增: in_order "$(at "^edit $PV --set del(.mountType) | .mounts = \[\]")" "$(at "^start $PV")" \
110新增: "$(at "/usr/local/bin/sshfs")" "$(at "^stop $PV")" \
111新增: "$(at "^edit $PV --set .mountType = \"reverse-sshfs\"")"
112新增:}
113新增:old_vm
114新增:out="$(AGENT_VM_TEST_STOPPED=1 rec run true)"
115新增:migration_order && pass "0.1.0 VM: booted without shares, sshfs installed, stopped, then protected" \
116新增: || fail "0.1.0 VM: $(grep -E '^(edit|start|stop|shell)' "$REC" | cut -c1-80)"
117新增:check "0.1.0 VM: started twice in all" "$(grep -c "^start $PV" "$REC")" "2"
118新增:case "$out" in *"base built by agent-vm 0.1.0"*"removed in a future release"*) pass "0.1.0 VM: warned" ;; *) fail "0.1.0 VM: no warning: $out" ;; esac
119新增:_agent_vm_mounts_protect_git "$PV" && pass "0.1.0 VM: recorded as protected" || fail "0.1.0 VM: not recorded"
120新增:[ -e "$MIGRATED" ] && pass "0.1.0 VM: recorded as migrated" || fail "0.1.0 VM: not recorded as migrated"
121新增:unprotected_rec
122新增:AGENT_VM_TEST_STOPPED=1 rec run true >/dev/null
123新增:rec_has "/usr/local/bin/sshfs" && fail "0.1.0 VM: migrated again" || pass "0.1.0 VM: migrated once"
124新增:
125新增:old_vm
126新增:out="$(AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_SSHFS_FAIL=1 rec run true; echo "rc=$?")"
127新增:case "$out" in *"could not install sshfs"*"E: no sshfs"*"rc=1") pass "0.1.0 VM, install failed: stops with the reason" ;; *) fail "0.1.0 VM, install failed: $out" ;; esac
128新增:rec_has "reverse-sshfs" && fail "0.1.0 VM, install failed: shares changed" || pass "0.1.0 VM, install failed: no protected shares"
129新增:rec_has "agent-vm-write-probe" && fail "0.1.0 VM, install failed: the command ran" || pass "0.1.0 VM, install failed: the command did not run"
130新增:[ -e "$MIGRATED" ] && fail "0.1.0 VM, install failed: recorded as migrated" || pass "0.1.0 VM, install failed: tried again next time"
131新增:
132新增:old_vm
133新增:rm -f "$PROTECTS"
134新增:AGENT_VM_TEST_STOPPED=1 rec run true >/dev/null
135新增:touch "$PROTECTS"
136新增:rec_has "/usr/local/bin/sshfs" && fail "0.1.0 VM on stock Lima: migrated" || pass "0.1.0 VM on stock Lima: its shares stay as they were"
137新增:
138新增:# Cloned by 0.2.0 from a 0.1.0 base on stock Lima: its shares are recorded,
139新增:# unprotected. With readonlyNames later, it is migrated all the same.
140新增:old_vm
141新增:unprotected_rec
142新增:AGENT_VM_TEST_STOPPED=1 rec run true >/dev/null
143新增:migration_order && pass "recorded VM from a 0.1.0 base: migrated before it is protected" \
144新增: || fail "recorded VM from a 0.1.0 base: $(grep -E '^(edit|start|stop|shell)' "$REC" | cut -c1-80)"
145新增:
146新增:# Running, under --readonly: no question before the start, the shares change
147新增:# in the restart that applies --readonly. Migrated there too.
148新增:old_vm
149新增:out="$( _agent_vm_can_ask() { return 0; }; _agent_vm_ask_yn() { echo 1; }; AGENT_VM_TEST_RO=1 rec --readonly run true )"
150新增:in_order "$(at "^stop $PV")" "$(at "^edit $PV --set del(.mountType) | .mounts = \[\]")" \
151新增: "$(at "/usr/local/bin/sshfs")" "$(at "^edit $PV --set .mountType = \"reverse-sshfs\"")" \
152新增: && pass "running 0.1.0 VM, --readonly: migrated in the restart, before it is protected" \
153新增: || fail "running 0.1.0 VM, --readonly: $(grep -E '^(edit|start|stop|shell)' "$REC" | cut -c1-80): $out"
154新增:
155新增:# Its base recorded: no migration, with or without a record of its shares.
156新增:rm -f "$MIGRATED" "$REC_MOUNTS"
157新增:echo 0.2.0 > "$BUILT_BY"
158新增:AGENT_VM_TEST_STOPPED=1 rec run true >/dev/null
159新增:rec_has "/usr/local/bin/sshfs" && fail "VM from a current base: migrated" || pass "VM from a current base: not migrated"
160新增:
161新增:# A new VM from a base 0.1.0 built: the same, on the bare clone, before its
162新增:# shares are set.
163新增:mv "$HOME/.agent-vm/.agent-vm-base-built-by" "$SB/built-by.saved"
164新增:echo 0.2.0 > "$HOME/.agent-vm/.agent-vm-built-by-$PV"
165新增:CLONED="$SB/cloned-old-base"; rm -f "$CLONED" "$REC_MOUNTS"
166新增:out="$(AGENT_VM_TEST_CLONED="$CLONED" rec run true)"
167新增:in_order "$(at "^clone ")" "$(at "/usr/local/bin/sshfs")" "$(at "^edit $PV --set .mountType = \"reverse-sshfs\"")" \
168新增: && migration_order && pass "new VM from a 0.1.0 base: sshfs installed before its shares are set" \
169新增: || fail "new VM from a 0.1.0 base: $(grep -E '^(clone|edit|start|stop|shell)' "$REC" | cut -c1-80)"
170新增:case "$out" in *"base built by agent-vm 0.1.0"*"agent-vm setup"*) pass "new VM from a 0.1.0 base: warned" ;; *) fail "new VM from a 0.1.0 base: $out" ;; esac
171新增:[ -e "$HOME/.agent-vm/.agent-vm-built-by-$PV" ] && fail "new VM from a 0.1.0 base: given a version" || pass "new VM from a 0.1.0 base: no version of its own"
172新增:rm -f "$CLONED" "$REC_MOUNTS"
173新增:out="$(AGENT_VM_TEST_CLONED="$CLONED" AGENT_VM_TEST_SSHFS_FAIL=1 rec run true; echo "rc=$?")"
174新增:case "$out" in *"could not install sshfs"*"rc=1") pass "new VM from a 0.1.0 base, install failed: stops" ;; *) fail "new VM, install failed: $out" ;; esac
175新增:rec_has "delete $PV" && pass "and the clone is deleted" || fail "new VM, install failed: clone kept"
176新增:mv "$SB/built-by.saved" "$HOME/.agent-vm/.agent-vm-base-built-by"
177新增:rm -f "$CLONED" "$REC_MOUNTS"
178新增:AGENT_VM_TEST_CLONED="$CLONED" rec run true >/dev/null
179新增:rec_has "/usr/local/bin/sshfs" && fail "new VM from a current base: migrated" || pass "new VM from a current base: not migrated"
180新增:check "new VM from a current base: its base version recorded" "$(cat "$HOME/.agent-vm/.agent-vm-built-by-$PV" 2>/dev/null)" "0.2.0"
181新增:rm -f "$CLONED"
182新增:protected_rec
183新增:
184新增:# Back to a Lima without readonlyNames: reverse-sshfs goes, before the start.
185新增:rm -f "$PROTECTS"
186新增:protected_rec
187新增:AGENT_VM_TEST_STOPPED=1 rec run true >/dev/null
188新增:rec_has "edit $PV --set del(.mountType) | .mounts = [{$(mnt "$PROJ"), \"writable\": true}]" \
189新增: && pass "Lima without readonlyNames: the VM goes back to the default mount type" \
190新增: || fail "reverse-sshfs kept without readonlyNames: $(grep '^edit' "$REC")"
191新增:_agent_vm_mounts_protect_git "$PV" && fail "the record still says protected" || pass "and the record says so"
192新增:
193新增:# A running VM asks nothing at the start, but stopped to apply new settings,
194新增:# it boots again: asked then, as any VM about to boot. Declined, it stays
195新增:# stopped and unchanged.
196新增:protected_rec
197新增:out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 0; }
198新增: _agent_vm_ask_yn() { if [[ "$1" == "Stop the VM and apply changes?" ]]; then echo 1; else echo 0; fi; }
199新增: rec --ssh-port 2299 run true; echo "rc=$?" )"
200新增:case "$out" in *"Lima cannot keep .git read-only"*"Aborted."*"is stopped"*"rc=1") pass "resize of a running VM: the questions are asked once it is stopped" ;; *) fail "resize of a running VM: $out" ;; esac
201新增:rec_has "stop $PV" && ! rec_has "start $PV" && ! rec_has "edit $PV" \
202新增: && pass "declined: stopped, not changed, not started" || fail "declined: $(grep -E '^(stop|edit|start)' "$REC")"
203新增:
204新增:# Where the shares would be reverse-sshfs (Windows, a QEMU VM of a Lima before
205新增:# 1.0), a Lima without readonlyNames does not keep the VM to its shares: the
206新增:# box says so, not only .git.
207新增:out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }
208新增: _agent_vm_unprotected_mount_is_sshfs() { return 0; }
209新增: AGENT_VM_TEST_STOPPED=1 rec run true; echo "rc=$?" )"
210新增:case "$out" in *"Lima cannot keep the VM to its shares"*"SSH keys"*"Aborted."*"--scratch"*"rc=1") pass "reverse-sshfs without readonlyNames: the box says the disk is at stake" ;; *) fail "reverse-sshfs box: $out" ;; esac
211新增:# --unsafe-writable-git gives up .git, not the rest of the disk: still asked.
212新增:out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }
213新增: _agent_vm_unprotected_mount_is_sshfs() { return 0; }
214新增: AGENT_VM_TEST_STOPPED=1 rec --unsafe-writable-git run true; echo "rc=$?" )"
215新增:case "$out" in *"Lima cannot keep the VM to its shares"*"Aborted."*"rc=1") pass "reverse-sshfs, --unsafe-writable-git: still asked" ;; *) fail "reverse-sshfs opt-out: $out" ;; esac
216新增:case "$( _agent_vm_unprotected_mount_is_sshfs() { return 0; }; AGENT_VM_UNSAFE_WRITABLE_GIT=1 rec info | grep '^security_questions=' )" in
217新增: *lima*) pass "info: the same question with the opt-out" ;; *) fail "info: opt-out on reverse-sshfs asks nothing" ;;
218新增:esac
219新增:# --readonly cannot be enforced there: refused before the VM is touched.
220新增:out="$( _agent_vm_unprotected_mount_is_sshfs() { return 0; }
221新增: AGENT_VM_TEST_STOPPED=1 rec --readonly run true; echo "rc=$?" )"
222新增:case "$out" in *"--readonly cannot be enforced here"*"rc=1") pass "reverse-sshfs, --readonly: refused" ;; *) fail "reverse-sshfs --readonly: $out" ;; esac
223新增:grep -Eq '^(edit|start|clone) ' "$REC" && fail "reverse-sshfs --readonly: the VM was touched" || pass "and nothing was touched"
224新增:# The real function: tests/11 stubs it on Windows.
225新增:sshfs_default() {
226新增: ( . "$SELF_DIR/lib/mounts.sh"
227新增: export AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_VM="$PV" AGENT_VM_TEST_VMTYPE=qemu LIMA_HOME="$SB/old-lima"
228新增: mkdir -p "$SB/old-lima/$PV"; echo "$1" > "$SB/old-lima/$PV/lima-version"
229新增: _agent_vm_unprotected_mount_is_sshfs "$PV" && echo yes || echo no )
230新增:}
231新增:check "a QEMU VM of a Lima before 1.0: reverse-sshfs" "$(sshfs_default 0.23.2)" "yes"
232新增:check "a QEMU VM of Lima 2: 9p" "$(sshfs_default 2.1.0)" "$(_agent_vm_on_windows && echo yes || echo no)"
233新增:# Lima's own config can set the type for every VM: override.yaml first.
234新增:mkdir -p "$SB/old-lima/_config"
235新增:printf 'mountType: "reverse-sshfs"\n' > "$SB/old-lima/_config/default.yaml"
236新增:check "default.yaml setting reverse-sshfs" "$(sshfs_default 2.1.0)" "yes"
237新增:printf 'mountType: 9p # mine\n' > "$SB/old-lima/_config/override.yaml"
238新增:check "override.yaml wins over it" "$(sshfs_default 2.1.0)" "$(_agent_vm_on_windows && echo yes || echo no)"
239新增:rm -rf "$SB/old-lima/_config"
240新增:check "a VM on vz: not" \
241新增: "$( . "$SELF_DIR/lib/mounts.sh"
242新增: AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_VM="$PV" _agent_vm_unprotected_mount_is_sshfs "$PV" && echo yes || echo no )" \
243新增: "$(_agent_vm_on_windows && echo yes || echo no)"
244新增:
245新增:# --readonly on reverse-sshfs: enforced on the host by the builtin server of a
246新增:# Lima with readonlyNames, and refused otherwise.
247新增:touch "$PROTECTS"
248新增:protected_rec false
249新增:out="$(AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_RO=1 AGENT_VM_TEST_MOUNTTYPE=reverse-sshfs rec --readonly run true)"
250新增:case "$out" in *"enforced on the host"*) pass "--readonly on protected reverse-sshfs: accepted" ;; *) fail "--readonly on protected reverse-sshfs: $out" ;; esac
251新增:rm -f "$PROTECTS"
252新增:printf '[{"location": "%s", "writable": false}]\n' "$PROJ" > "$REC_MOUNTS"
253新增:out="$(AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_RO=1 AGENT_VM_TEST_MOUNTTYPE=reverse-sshfs rec --readonly run true)"
254新增:case "$out" in *"--readonly cannot be enforced"*) pass "--readonly on plain reverse-sshfs: refused" ;; *) fail "--readonly on plain reverse-sshfs: $out" ;; esac
255新增:
256新增:# The opt-out: .git writable although this Lima could protect it, said on
257新增:# every run.
258新增:touch "$PROTECTS"
259新增:protected_rec
260新增:out="$(AGENT_VM_UNSAFE_WRITABLE_GIT=1 rec run true)"
261新增:rec_has "edit $PV" && fail "opt-out: a running VM was changed" || pass "opt-out: a running VM is left running"
262新增:case "$out" in *"keeps .git read-only until it stops"*) pass "and it says .git stays read-only until then" ;; *) fail "opt-out, running VM: $out" ;; esac
263新增:out="$(AGENT_VM_UNSAFE_WRITABLE_GIT=1 AGENT_VM_TEST_STOPPED=1 rec run true)"
264新增:rec_has "edit $PV --set del(.mountType) | .mounts = [{$(mnt "$PROJ"), \"writable\": true}]" \
265新增: && pass "opt-out: a stopped protected VM gets .git writable, on the default mount type" \
266新增: || fail "opt-out: shares kept protected: $(grep '^edit' "$REC")"
267新增:case "$out" in *"WARNING: AGENT_VM_UNSAFE_WRITABLE_GIT=1"*) pass "opt-out: the warning is printed" ;; *) fail "opt-out: no warning: $out" ;; esac
268新增:out="$(AGENT_VM_UNSAFE_WRITABLE_GIT=1 rec run true)"
269新增:rec_has "edit $PV" && fail "opt-out: an unprotected VM was edited again" || pass "opt-out: nothing to change the next time"
270新增:case "$out" in *"WARNING: AGENT_VM_UNSAFE_WRITABLE_GIT=1"*) pass "opt-out: the warning is printed on every run" ;; *) fail "opt-out: no warning the next time: $out" ;; esac
271新增:AGENT_VM_UNSAFE_WRITABLE_GIT=yes AGENT_VM_TEST_STOPPED=1 rec run true >/dev/null
272新增:rec_has "edit $PV --set .mountType = \"reverse-sshfs\"" && pass "only 1 is the opt-out: 'yes' keeps .git protected" \
273新增: || fail "AGENT_VM_UNSAFE_WRITABLE_GIT=yes turned the protection off"
274新增:
275新增:# The same as a VM option, before the command or right after its name.
276新增:out="$(AGENT_VM_TEST_STOPPED=1 rec --unsafe-writable-git run true)"
277新增:rec_has "edit $PV --set del(.mountType) | .mounts = [{$(mnt "$PROJ"), \"writable\": true}]" \
278新增: && pass "--unsafe-writable-git: .git writable" || fail "--unsafe-writable-git ignored: $(grep '^edit' "$REC")"
279新增:case "$out" in *"WARNING: --unsafe-writable-git."*) pass "--unsafe-writable-git: the warning names the flag" ;; *) fail "--unsafe-writable-git: $out" ;; esac
280新增:protected_rec
281新增:AGENT_VM_TEST_STOPPED=1 rec run --unsafe-writable-git=1 true >/dev/null
282新增:rec_has "edit $PV --set del(.mountType)" && pass "run --unsafe-writable-git=1: .git writable" \
283新增: || fail "run --unsafe-writable-git=1 ignored: $(grep '^edit' "$REC")"
284新增:rec_has "agent-vm-write-probe" && ! rec_has "unsafe-writable-git" && pass "and the flag does not reach the command" \
285新增: || fail "the flag reached the command: $(grep -v '^edit' "$REC" | tail -2)"
286新增:# Without it, the next run protects again. agent-vm is a shell function too,
287新增:# where a flag leaking out of its call would stay on for the rest of the shell.
288新增:unset _agent_vm_unsafe_git_flag
289新增:( cd "$PROJ" && export AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_VM="$PV" AGENT_VM_TEST_PROTECTS="$PROTECTS" AGENT_VM_TEST_STOPPED=1
290新增: agent-vm --unsafe-writable-git run true >/dev/null 2>&1
291新增: [ -z "${_agent_vm_unsafe_git_flag:-}" ] || echo leaked
292新增: : > "$REC"
293新增: agent-vm run true >/dev/null 2>&1 ) > "$SB/leak.out"
294新增:check "the flag does not outlive its command" "$(cat "$SB/leak.out")" ""
295新增:rec_has "edit $PV --set .mountType = \"reverse-sshfs\"" && pass "the next run without it protects .git again" \
296新增: || fail "not protected after the flag: $(grep '^edit' "$REC")"
297新增:case "$(agent-vm setup --unsafe-writable-git 2>&1 </dev/null)" in
298新增: *"Unknown option: --unsafe-writable-git"*) pass "setup rejects --unsafe-writable-git" ;;
299新增: *) fail "setup accepted --unsafe-writable-git" ;;
300新增:esac
301新增:
302新增:# A VM from before .hg: the names change while it is stopped, and a running
303新增:# one is offered the restart (here with the questions off: warned, left
304新增:# running).
305新增:names_rec() { printf '[{"location": "%s", "writable": true, "sshfs": {"sftpDriver": "builtin", "readonlyNames": %s}}]\n' "$PROJ" "$1" > "$REC_MOUNTS"; }
306新增:names_rec '[".git"]'
307新增:out="$(rec run true)"
308新增:rec_has "edit $PV" && fail "names: a running VM was changed" || pass "names: a running VM is left running"
309新增:case "$out" in *"older list of read-only names (it needs .git, .hg)"*"Continuing"*) pass "names: and warned" ;; *) fail "names, running VM: $out" ;; esac
310新增:names_rec '[".git"]'
311新增:out="$(AGENT_VM_TEST_STOPPED=1 rec run true)"
312新增:rec_has "edit $PV --set .mountType = \"reverse-sshfs\" | .mounts = [{$(mnt "$PROJ"), \"writable\": true, $SSHFS_RO}]" \
313新增: && pass "names: a stopped VM from before .hg gets it" || fail "names: not updated: $(grep '^edit' "$REC")"
314新增:case "$out" in *"Making .git, .hg read-only for VM '$PV'"*) pass "names: and it says so" ;; *) fail "names: no notice: $out" ;; esac
315新增:_agent_vm_mounts_have_readonly_names "$PV" '[".git", ".hg"]' && pass "names: recorded" || fail "names: record: $(cat "$REC_MOUNTS")"
316新增:out="$(AGENT_VM_TEST_STOPPED=1 rec run true)"
317新增:rec_has "edit $PV" && fail "names: edited again with nothing to change" || pass "names: nothing to change the next time"
318新增:
319新增:# core.hooksPath in the project: its first component joins the names.
320新增:if command -v git >/dev/null 2>&1; then
321新增: # In subshells: bash 3.2 would keep git hashed for a later test that hides
322新增: # it with PATH.
323新增: ( git -C "$PROJ" init -q )
324新增: hp() { ( git -C "$PROJ" config core.hooksPath "$1" ); }
325新增: names() { _agent_vm_readonly_names "$PROJ"; }
326新增: check "hooks: git's default, in .git" "$(names)" '[".git", ".hg"]'
327新增: hp .husky/_
328新增: check "hooks: husky's .husky/_ adds .husky" "$(names)" '[".git", ".hg", ".husky"]'
329新增: hp tools/../.githooks
330新增: check "hooks: the path is normalized" "$(names)" '[".git", ".hg", ".githooks"]'
331新增: hp .Git/hooks
332新增: check "hooks: under .git, whatever the case, adds nothing" "$(names)" '[".git", ".hg"]'
333新增: hp "$SB/elsewhere"
334新增: check "hooks: outside the project, nothing" "$(names)" '[".git", ".hg"]'
335新增: hp .
336新增: check "hooks: the project itself cannot be a name" "$(names)" '[".git", ".hg"]'
337新增: hp 'a"b/x'
338新增: check "hooks: a name the JSON cannot carry is left out" "$(names)" '[".git", ".hg"]'
339新增: # The project below the top of the repository: paths are relative to it.
340新增: mkdir -p "$PROJ/sub"
341新增: hp .husky/_
342新增: check "hooks: in the repository, outside a subdirectory project" "$(_agent_vm_readonly_names "$PROJ/sub")" '[".git", ".hg"]'
343新增: hp sub/hooks
344新增: check "hooks: inside a subdirectory project" "$(_agent_vm_readonly_names "$PROJ/sub")" '[".git", ".hg", "hooks"]'
345新增: rmdir "$PROJ/sub"
346新增:
347新增: # A stopped VM gets the name before it starts, with a note; a running one
348新增: # is offered the restart (questions off here: warned).
349新增: hp .husky/_
350新增: names_rec '[".git", ".hg"]'
351新增: out="$(rec run true)"
352新增: rec_has "edit $PV" && fail "hooks: a running VM was changed" || pass "hooks: a running VM is left running"
353新增: case "$out" in *"older list of read-only names (it needs .git, .hg, .husky)"*) pass "hooks: and warned" ;; *) fail "hooks, running VM: $out" ;; esac
354新增: names_rec '[".git", ".hg"]'
355新增: out="$(AGENT_VM_TEST_STOPPED=1 rec run true)"
356新增: rec_has "\"readonlyNames\": [\".git\", \".hg\", \".husky\"]}}]" && pass "hooks: a stopped VM gets .husky read-only" \
357新增: || fail "hooks: not applied: $(grep '^edit' "$REC")"
358新增: case "$out" in *"hooks from .husky/_ (core.hooksPath): every '.husky' in the project is read-only"*) pass "hooks: and it says so" ;; *) fail "hooks: no note: $out" ;; esac
359新增: out="$(rec doctor)"
360新增: case "$out" in *"ok git runs hooks from .husky/_ (core.hooksPath): every '.husky' in the project is read-only for the VM"*) pass "doctor: protected hooks are ok" ;; *) fail "doctor: hooks: $out" ;; esac
361新增:
362新增: # Git before 2.31 has no --path-format: the hooks folder is still found.
363新增: mkdir -p "$SB/oldgit"
364新增: printf '#!/bin/sh\nfor a in "$@"; do [ "$a" = --path-format=absolute ] && { echo "unknown option" >&2; exit 129; }; done\nexec "%s" "$@"\n' \
365新增: "$(command -v git)" > "$SB/oldgit/git"
366新增: chmod +x "$SB/oldgit/git"
367新增: check "hooks: found without --path-format" "$(PATH="$SB/oldgit:$PATH" names)" '[".git", ".hg", ".husky"]'
368新增:
369新增: # Case: where the file system ignores it, a hooks path spelled with other
370新增: # capitals is still in the project.
371新增: check "a path in other capitals is inside, where case is ignored" \
372新增: "$( _agent_vm_fs_nocase() { return 0; }; _agent_vm_rel_in /Work/Proj/.Husky/_ /work/proj )" ".Husky/_"
373新增: ( _agent_vm_fs_nocase() { return 1; }; _agent_vm_rel_in /Work/Proj/x /work/proj ) >/dev/null \
374新增: && fail "a path in other capitals counted as inside where case matters" \
375新增: || pass "and not where case matters"
376新增:
377新增: # A repository below the project has hooks of its own.
378新增: mkdir -p "$PROJ/lib/inner"
379新增: ( git -C "$PROJ/lib/inner" init -q && git -C "$PROJ/lib/inner" config core.hooksPath .githooks )
380新增: check "hooks: a nested repository's folder joins the names" "$(names)" '[".git", ".hg", ".husky", ".githooks"]'
381新增: case "$(_agent_vm_project_hooks "$PROJ")" in *"lib/inner/.githooks"*) pass "hooks: named from the project" ;; *) fail "hooks: nested: $(_agent_vm_project_hooks "$PROJ")" ;; esac
382新增: names_rec '[".git", ".hg"]'
383新增: AGENT_VM_TEST_STOPPED=1 rec run true >/dev/null
384新增: rec_has "\"readonlyNames\": [\".git\", \".hg\", \".husky\", \".githooks\"]}}]" \
385新增: && pass "hooks: a start protects the nested folder by its own name, not the project's 'lib'" \
386新增: || fail "hooks: nested, start: $(grep '^edit' "$REC")"
387新增: rm -rf "$PROJ/lib"
388新增:
389新增: # A name that is not a dot-name is read-only in every folder of the
390新增: # project, so it is asked first: yes by default, and when no one can answer.
391新增: hp tools/hooks
392新增: names_rec '[".git", ".hg", "tools"]'
393新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }; AGENT_VM_TEST_STOPPED=1 rec run true )"
394新增: rec_has "start $PV" && pass "hooks: a plain name, no terminal: protected, started" || fail "hooks: plain name, no terminal: $out"
395新增: names_rec '[".git", ".hg"]'
396新增: # if, not case: bash 3.2 misreads a case pattern's ) inside $( ).
397新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 0; }
398新增: _agent_vm_ask_yn() { echo 0; }
399新增: AGENT_VM_TEST_STOPPED=1 rec run true; echo "rc=$?" )"
400新增: case "$out" in *"'tools' stays writable"*"Aborted."*"rc=1") pass "hooks: a plain name declined: a risk, stopped by default" ;; *) fail "hooks: plain name declined: $out" ;; esac
401新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 0; }
402新增: _agent_vm_ask_yn() { if [ "$1" = "Continue anyway?" ]; then echo 1; else echo 0; fi; }
403新增: AGENT_VM_TEST_STOPPED=1 rec run true )"
404新增: rec_has "start $PV" && ! grep -q '"tools"' "$REC_MOUNTS" && ! rec_has '"tools"' \
405新增: && pass "hooks: declined, then accepted as a risk: left writable" || fail "hooks: declined name: $(cat "$REC_MOUNTS") $out"
406新增:
407新增: # Hooks that cannot be protected stop the start, before anything changes,
408新增: # unless the user answers yes. No terminal, or the default answer, aborts.
409新增: hp .
410新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }; AGENT_VM_TEST_STOPPED=1 rec run true )"
411新增: rc=$?
412新增: case "$out" in *"Warning: git's core.hooksPath is the project directory itself"*"Aborted."*) pass "hooks: the project itself, no terminal: aborted" ;; *) fail "hooks: no abort for '.': $out" ;; esac
413新增: check "hooks: and it fails" "$rc" "1"
414新增: if grep -Eq '^(edit|start|clone) ' "$REC"; then fail "hooks: the VM was touched before the abort: $(grep -E '^(edit|start|clone) ' "$REC" | head -1)"
415新增: else pass "hooks: nothing touched before the abort"; fi
416新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 0; }; _agent_vm_ask_yn() { [ "$2" = N ] && echo 0 || echo 1; }; AGENT_VM_TEST_STOPPED=1 rec run true )"
417新增: case "$out" in *"Aborted."*) pass "hooks: the default answer aborts" ;; *) fail "hooks: default answer went on: $out" ;; esac
418新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 0; }; _agent_vm_ask_yn() { echo 1; }; AGENT_VM_TEST_STOPPED=1 rec run true )"
419新增: rc=$?
420新增: check "hooks: a yes goes on" "$rc" "0"
421新增: rec_has "start $PV" && pass "hooks: and the VM starts" || fail "hooks: not started after a yes: $out"
422新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }; AGENT_VM_TEST_STOPPED=1 rec --unsafe-disable-security-prompts run true )"
423新增: case "$out" in *"Continuing: --unsafe-disable-security-prompts."*) pass "hooks: --unsafe-disable-security-prompts goes on, and says so" ;; *) fail "hooks: the flag did not skip the question: $out" ;; esac
424新增: # A VM already running: stopping would protect nothing, so no question.
425新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }; rec run true )"
426新增: case "$out" in *"project directory itself"*"Aborted."*) fail "hooks: a running VM was stopped on: $out" ;; *"project directory itself"*) pass "hooks: a running VM: warned, not asked" ;; *) fail "hooks: running VM: $out" ;; esac
427新增: case "$(rec info | grep '^security_questions=')" in *hooks*) pass "info: security_questions names the hooks" ;; *) fail "info: hooks not named: $(rec info)" ;; esac
428新增: hp 'a"b/x'
429新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }; AGENT_VM_TEST_STOPPED=1 rec run true )"
430新增: case "$out" in *"its name cannot be made read-only"*"Aborted."*) pass "hooks: a name that cannot be carried, no terminal: aborted" ;; *) fail "hooks: no abort for a bad name: $out" ;; esac
431新增: hp .
432新增: out="$(rec doctor)"
433新增: case "$out" in *"warn git runs hooks from the project directory itself (core.hooksPath), which the VM can write"*) pass "doctor: and a warning there" ;; *) fail "doctor: '.' hooks: $out" ;; esac
434新增: hp .husky/_
435新增: names_rec '[".git", ".hg"]'
436新增: out="$(rec doctor)"
437新增: case "$out" in *"warn git runs hooks from .husky/_ (core.hooksPath), which the VM can still write"*) pass "doctor: a VM without the name yet is a warning" ;; *) fail "doctor: stale hooks: $out" ;; esac
438新增:
439新增: # Git config the VM can write: a file included from the project, and
440新增: # commands named by a path in it. Commands found on PATH, options and URLs
441新增: # are not paths in the project.
442新增: ( git -C "$PROJ" config --unset core.hooksPath
443新增: git -C "$PROJ" config core.pager less
444新增: git -C "$PROJ" config core.sshCommand "ssh -o ProxyCommand=/usr/bin/nc"
445新增: git -C "$PROJ" config alias.st status )
446新增: check "config: nothing in the project, nothing said" "$(_agent_vm_project_config_risks "$PROJ")" ""
447新增: ( printf '[core]\n\tfsmonitor = ./watch.sh\n' > "$PROJ/.gitconfig"
448新增: git -C "$PROJ" config include.path ../.gitconfig
449新增: git -C "$PROJ" config filter.x.clean "scripts/clean.sh %f"
450新增: git -C "$PROJ" config alias.t '!./t.sh' )
451新增: risks="$(_agent_vm_project_config_risks "$PROJ")"
452新增: case "$risks" in *"config file .gitconfig"*) pass "config: an included file in the project" ;; *) fail "config: include: $risks" ;; esac
453新增: case "$risks" in *"core.fsmonitor = ./watch.sh"*) pass "config: a command it sets" ;; *) fail "config: fsmonitor: $risks" ;; esac
454新增: case "$risks" in *"filter.x.clean = scripts/clean.sh %f"*) pass "config: a relative command path" ;; *) fail "config: filter: $risks" ;; esac
455新增: case "$risks" in *"alias.t = !./t.sh"*) pass "config: a shell alias" ;; *) fail "config: alias: $risks" ;; esac
456新增: case "$risks" in *"core.pager"*|*sshcommand*|*"alias.st"*) fail "config: false positive: $risks" ;; *) pass "config: PATH commands, options and plain aliases left out" ;; esac
457新增: check "config: an included file listed once" "$(grep -c 'config file .gitconfig' <<< "$risks")" "1"
458新增: # An include of a file not there yet: git skips it, and the VM can create
459新增: # it. includeIf too, and relative to the file holding it.
460新增: ( git -C "$PROJ" config includeIf.gitdir:/.path ../later.gitconfig
461新增: git -C "$PROJ" config --add include.path ../.git/x.gitconfig
462新增: git -C "$PROJ" config --add include.path "$SB/outside.gitconfig" )
463新增: risks="$(_agent_vm_project_config_risks "$PROJ")"
464新增: case "$risks" in *"config file later.gitconfig"*) pass "config: an include of a file not there yet" ;; *) fail "config: missing include: $risks" ;; esac
465新增: case "$risks" in *x.gitconfig*|*outside.gitconfig*) fail "config: an include in .git or outside the project listed: $risks" ;; *) pass "config: includes in .git or outside left out" ;; esac
466新增: ( git -C "$PROJ" config --unset-all includeIf.gitdir:/.path
467新增: git -C "$PROJ" config --unset-all include.path
468新增: git -C "$PROJ" config include.path ../.gitconfig )
469新增: names_rec '[".git", ".hg"]'
470新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }; AGENT_VM_TEST_STOPPED=1 rec run true )"
471新增: case "$out" in *"git on this machine uses these"*".gitconfig"*"Aborted."*) pass "config: a start stops on it" ;; *) fail "config: start: $out" ;; esac
472新增: grep -Eq '^(edit|start|clone) ' "$REC" && fail "config: the VM was touched before the abort" || pass "config: nothing touched"
473新增: case "$(rec info | grep '^security_questions=')" in *git-config*) pass "info: security_questions names the config" ;; *) fail "info: config not named: $(rec info)" ;; esac
474新增: out="$(rec doctor)"
475新增: case "$out" in *"warn git on this machine uses these, and the VM can write them:"*"config file .gitconfig"*) pass "doctor: the config is a warning" ;; *) fail "doctor: config: $out" ;; esac
476新增: # Under --readonly the VM writes none of it: no warning and no question,
477新增: # for hooks, git config, or the restart of a running VM, and the names
478新增: # are still given to the shares.
479新增: hp .
480新增: ro_names_rec() { printf '[{"location": "%s", "writable": false, "sshfs": {"sftpDriver": "builtin", "readonlyNames": %s}}]\n' "$PROJ" "$1" > "$REC_MOUNTS"; }
481新增: ro_names_rec '[".git", ".hg"]'
482新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }
483新增: AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_RO=1 AGENT_VM_TEST_MOUNTTYPE=reverse-sshfs rec --readonly run true; echo "rc=$?" )"
484新增: case "$out" in
485新增: *"Aborted"*|*"git on this machine uses these"*|*"core.hooksPath is the project directory"*) fail "--readonly: warned or asked about what the VM cannot write: $out" ;;
486新增: *"rc=0") pass "--readonly: no hooks or config question, and it starts" ;;
487新增: *) fail "--readonly: $out" ;;
488新增: esac
489新增: hp tools/hooks
490新增: ro_names_rec '[".git", ".hg"]'
491新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }
492新增: AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_RO=1 AGENT_VM_TEST_MOUNTTYPE=reverse-sshfs rec --readonly run true )"
493新增: rec_has "\"readonlyNames\": [\".git\", \".hg\", \"tools\"]}}]" && pass "--readonly: the hooks folder name still goes to the shares" \
494新增: || fail "--readonly: names: $(grep '^edit' "$REC")"
495新增: ro_names_rec '[".git", ".hg"]'
496新增: out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }
497新增: AGENT_VM_TEST_RO=1 AGENT_VM_TEST_MOUNTTYPE=reverse-sshfs rec --readonly run true; echo "rc=$?" )"
498新增: case "$out" in
499新增: *"Restart it now"*|*"Aborted"*) fail "--readonly, running VM: asked to restart for names it cannot write: $out" ;;
500新增: *"rc=0") pass "--readonly, running read-only VM with older names: no question" ;;
501新增: *) fail "--readonly, running VM: $out" ;;
502新增: esac
503新增: rm -f "$PROJ/.gitconfig"
504新增:
505新增: rm -f "$PROTECTS"
506新增: hp .husky/_
507新增: out="$(rec doctor)"
508新增: case "$out" in *"warn git runs hooks from .husky/_ (core.hooksPath), which the VM can write"*) pass "doctor: without the protection, a warning" ;; *) fail "doctor: unprotected hooks: $out" ;; esac
509新增: rm -rf "$PROJ/.git"
510新增:else
511新增: printf ' skip core.hooksPath (git is not installed)\n'
512新增:fi
513新增:rm -f "$PROTECTS"
514新增:
515新增:# A Lima without readonlyNames: a start with writable shares asks first, and
516新增:# stops before anything changes unless the answer is yes.
517新增:noprompt() { unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }; }
518新增:touched() { grep -Eq '^(edit|start|clone) ' "$REC"; }
519新增:# A question is only asked where it is seen: with stderr captured, it would
520新增:# wait unseen, so it counts as no terminal.
521新增:( _agent_vm_have_tty() { return 0; }; _agent_vm_can_ask ) 2>/dev/null \
522新增: && fail "a question asked with stderr captured" || pass "stderr captured: no question"
523新增:case "$(rec info | grep -E '^(git_protected|security_questions)=' | tr '\n' ' ')" in
524新增: "git_protected=0 security_questions=lima "*) pass "info: this Lima, named as a question" ;;
525新增: *) fail "info: $(rec info | grep -E '^(git_protected|security_questions)=')" ;;
526新增:esac
527新增:out="$( noprompt; AGENT_VM_TEST_STOPPED=1 rec run true )"
528新增:rc=$?
529新增:case "$out" in *"Lima cannot keep .git read-only"*"Aborted."*) pass "no readonlyNames, no terminal: aborted, with why" ;; *) fail "no readonlyNames: no abort: $out" ;; esac
530新增:check "no readonlyNames: and it fails" "$rc" "1"
531新增:touched && fail "no readonlyNames: the VM was touched before the abort" || pass "no readonlyNames: nothing touched"
532新增:rec_has "agent-vm-write-probe" && fail "no readonlyNames: the command ran" || pass "no readonlyNames: the command did not run"
533新增:out="$( noprompt; _agent_vm_can_ask() { return 0; }; _agent_vm_ask_yn() { [ "$2" = N ] && echo 0 || echo 1; }; AGENT_VM_TEST_STOPPED=1 rec run true )"
534新增:case "$out" in *"Aborted."*) pass "no readonlyNames: the default answer aborts" ;; *) fail "no readonlyNames: default answer went on: $out" ;; esac
535新增:out="$( noprompt; _agent_vm_can_ask() { return 0; }; _agent_vm_ask_yn() { echo 1; }; AGENT_VM_TEST_STOPPED=1 rec run true )"
536新增:check "no readonlyNames: a yes goes on" "$?" "0"
537新增:rec_has "start $PV" && pass "no readonlyNames: and the VM starts" || fail "no readonlyNames: not started after a yes: $out"
538新增:# A VM already running: the risk is there already, so a warning, no question.
539新增:out="$( noprompt; rec run true )"
540新增:case "$out" in *"Aborted."*) fail "running VM: stopped on the question: $out" ;; *"this Lima cannot keep .git read-only, so the VM can write .git"*) pass "running VM: warned, not asked" ;; *) fail "running VM: $out" ;; esac
541新增:# No question where nothing is at stake, or where it was already answered.
542新增:printf '[{"location": "%s", "writable": false}]\n' "$PROJ" > "$REC_MOUNTS"
543新增:out="$( noprompt; AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_RO=1 rec --readonly run true )"
544新增:case "$out" in *"Continue anyway"*|*"Aborted."*) fail "--readonly: asked anyway: $out" ;; *) pass "--readonly: no question" ;; esac
545新增:rec_has "start $PV" && pass "--readonly: the VM starts" || fail "--readonly: not started: $out"
546新增:out="$( noprompt; AGENT_VM_TEST_STOPPED=1 rec --unsafe-writable-git run true )"
547新增:case "$out" in *"Aborted."*) fail "--unsafe-writable-git: asked anyway: $out" ;; *) pass "--unsafe-writable-git: no question, .git writable was asked for" ;; esac
548新增:# The way past it: the flag, before the command or right after its name, or
549新增:# exactly 1 in the environment.
550新增:out="$( noprompt; AGENT_VM_TEST_STOPPED=1 rec --unsafe-disable-security-prompts run true )"
551新增:case "$out" in *"Lima cannot keep .git read-only"*"Continuing: --unsafe-disable-security-prompts."*) pass "--unsafe-disable-security-prompts: the warning, then on" ;; *) fail "--unsafe-disable-security-prompts: $out" ;; esac
552新增:out="$( noprompt; AGENT_VM_TEST_STOPPED=1 rec run --unsafe-disable-security-prompts true )"
553新增:case "$out" in *"Aborted."*) fail "run --unsafe-disable-security-prompts: not taken: $out" ;; *) pass "run --unsafe-disable-security-prompts: taken" ;; esac
554新增:rec_has "agent-vm-write-probe" && ! rec_has " true --unsafe" && ! grep -q "unsafe-disable-security-prompts" <<< "$(grep -v '^edit' "$REC")" \
555新增: && pass "and the flag does not reach the command" || fail "the flag reached the command: $(grep -v '^edit' "$REC" | tail -2)"
556新增:out="$( noprompt; export AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1; AGENT_VM_TEST_STOPPED=1 rec run true )"
557新增:case "$out" in *"Continuing: AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1."*) pass "AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1: on, and says so" ;; *) fail "the env var: $out" ;; esac
558新增:out="$( noprompt; export AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=yes; AGENT_VM_TEST_STOPPED=1 rec run true )"
559新增:case "$out" in *"Aborted."*) pass "only 1 disables the prompts: 'yes' still asks" ;; *) fail "AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=yes went on: $out" ;; esac
560新增:case "$(agent-vm setup --unsafe-disable-security-prompts 2>&1 </dev/null)" in
561新增: *"Unknown option: --unsafe-disable-security-prompts"*) pass "setup rejects --unsafe-disable-security-prompts" ;;
562新增: *) fail "setup accepted --unsafe-disable-security-prompts" ;;
563新增:esac
564新增:
565新增:# Home, in other capitals where case is ignored (Git Bash keeps the spelling
566新增:# typed), is still refused.
567新增:upper_home="$(printf '%s' "$HOME" | tr '[:lower:]' '[:upper:]')"
568新增:check "the home directory in other capitals is refused where case is ignored" \
569新增: "$( _agent_vm_fs_nocase() { return 0; }; _agent_vm_unsafe_project "$upper_home" )" "is, or contains, your home directory"
570新增:_agent_vm_cleanup_state "$PV"
新增tests/15-status-and-doctor.sh+183 −0看文件
@@ -0,0 +1,183 @@
1新增:section "a new VM prints its resources once"
2新增:CLONED="$SB/cloned"; rm -f "$CLONED"
3新增:out="$(AGENT_VM_TEST_CLONED="$CLONED" rec run true)"
4新增:check "one Resources line on the first run" "$(printf '%s\n' "$out" | grep -c 'Resources:')" "1"
5新增:
6新增:section "status"
7新增:out="$(rec status)"
8新增:case "$out" in
9新增: *"> $PV Running"*) pass "the current directory's VM is marked" ;;
10新增: *) fail "current VM not marked: $out" ;;
11新增:esac
12新增:case "$out" in *"(no VMs)"*) fail "(no VMs) printed next to VMs" ;; *) pass "no '(no VMs)' when there are VMs" ;; esac
13新增:# Without pipefail, as in an interactive shell: the old piped loop only said
14新增:# "(no VMs)" when the caller happened to have pipefail on.
15新增:out="$(set +o pipefail; AGENT_VM_TEST_NOVMS=1 rec status)"
16新增:case "$out" in
17新增: *"(no VMs)"*) pass "no VM: says so" ;;
18新增: *) fail "no VM: nothing said: $out" ;;
19新增:esac
20新增:
21新增:section "list"
22新增:echo 1790803800 > "$HOME/.agent-vm/.agent-vm-base-version"
23新增:echo 0.2.0 > "$HOME/.agent-vm/.agent-vm-base-built-by"
24新增:echo 1790803800 > "$HOME/.agent-vm/.agent-vm-version-$PV"
25新增:rm -f "$HOME/.agent-vm/.agent-vm-built-by-$PV"
26新增:day="$(_agent_vm_epoch_date 1790803800 +%F)"
27新增:out="$(rec list)"
28新增:w=$((${#PV} + 8))
29新增:check "list: the base of each VM, aligned, this folder's marked" "$out" "$(printf '%s %-*s %s\n' " " "$w" "NAME STATUS" BASE \
30新增: " " "$w" "agent-vm-base Stopped" "0.2.0 $day" ">" "$w" "$PV Running" "0.1.0 $day")"
31新增:check "status is list" "$(rec status)" "$out"
32新增:rm -f "$HOME/.agent-vm/.agent-vm-version-$PV"
33新增:case "$(rec list)" in *"$PV Running 0.1.0 -") pass "list: a VM with no record of its base" ;; *) fail "list: $(rec list)" ;; esac
34新增:case "$(AGENT_VM_TEST_NOVMS=1 rec list)" in *"(no VMs)") pass "list: no VM, says so" ;; *) fail "list, no VM: $(AGENT_VM_TEST_NOVMS=1 rec list)" ;; esac
35新增:echo 1 > "$HOME/.agent-vm/.agent-vm-base-version"
36新增:mkdir -p "$SB/faillima"; printf '#!/bin/sh\nexit 1\n' > "$SB/faillima/limactl"; chmod +x "$SB/faillima/limactl"
37新增:case "$(PATH="$SB/faillima:$PATH" agent-vm list 2>&1; echo "rc=$?")" in
38新增: *"could not query Lima"*"rc=1") pass "list: a Lima that fails is an error, not '(no VMs)'" ;;
39新增: *) fail "list: failing Lima: $(PATH="$SB/faillima:$PATH" agent-vm list 2>&1)" ;;
40新增:esac
41新增:# A name with a newline would add lines to info's output.
42新增:forged="$SB/p
43新增:security_questions=none"
44新增:mkdir -p "$forged"
45新增:case "$(agent-vm info "$forged" 2>&1; echo "rc=$?")" in
46新增: *"control character"*"rc=1") pass "info: a directory name with a newline is refused" ;;
47新增: *) fail "info: forged name accepted" ;;
48新增:esac
49新增:case "$(agent-vm name "$forged" 2>&1; echo "rc=$?")" in *"control character"*"rc=1") pass "name: the same" ;; *) fail "name: forged name accepted" ;; esac
50新增:mkdir -p "$forged/sub"
51新增:case "$(cd "$forged" && agent-vm info . 2>&1; echo "rc=$?")" in *"control character"*"rc=1") pass "info .: from inside it, the same" ;; *) fail "info .: forged cwd accepted" ;; esac
52新增:case "$(cd "$forged" && agent-vm name sub 2>&1; echo "rc=$?")" in *"control character"*"rc=1") pass "name sub: below it, the same" ;; *) fail "name sub: forged parent accepted" ;; esac
53新增:rm -rf "$forged"
54新增:
55新增:section "destroy-all"
56新增:# The names are read on stdin; each limactl call must not eat the next ones.
57新增:# This limactl reads its stdin, and a VM it deleted leaves its listing, except
58新增:# the one named by STUCK.
59新增:mkdir -p "$SB/destroylima"
60新增:cat > "$SB/destroylima/limactl" <<STUB
61新增:#!/bin/sh
62新增:case "\$1" in
63新增: list) printf 'agent-vm-a\nagent-vm-b\nagent-vm-base\n' \
64新增: | if [ -s "$SB/destroyed" ]; then grep -vxF -f "$SB/destroyed"; else cat; fi ;;
65新增: delete) cat >/dev/null; echo "delete \$2" >> "$SB/destroy.log"
66新增: [ "\$2" = "\${STUCK:-}" ] || echo "\$2" >> "$SB/destroyed" ;;
67新增: stop) cat >/dev/null ;;
68新增:esac
69新增:exit 0
70新增:STUB
71新增:chmod +x "$SB/destroylima/limactl"
72新增:destroy_three() {
73新增: : > "$SB/destroyed"; : > "$SB/destroy.log"
74新增: echo 1 > "$HOME/.agent-vm/.agent-vm-base-version"
75新增: ( PATH="$SB/destroylima:$PATH"; _agent_vm_destroy_vms "$(printf 'agent-vm-a\nagent-vm-b\nagent-vm-base\n')" ) 2>&1
76新增:}
77新增:out="$(destroy_three)"; rc=$?
78新增:check "every listed VM is deleted" "$rc $(grep -c '^delete' "$SB/destroy.log")" "0 3"
79新增:if [ -e "$HOME/.agent-vm/.agent-vm-base-version" ]; then
80新增: fail "deleting the base template left its ready marker"
81新增:else
82新增: pass "deleting the base template retires its ready marker"
83新增:fi
84新增:out="$(STUCK=agent-vm-a destroy_three)"; rc=$?
85新增:case "$rc:$out" in
86新增: 1:*"could not delete VM 'agent-vm-a'"*) pass "a VM that stays is said, and fails destroy-all" ;;
87新增: *) fail "a VM that stays: $rc $out" ;;
88新增:esac
89新增:check "the others are still deleted" "$(grep -c '^delete' "$SB/destroy.log")" "3"
90新增:[ -e "$HOME/.agent-vm/.agent-vm-base-built-by" ] && fail "deleting the base template left its version" \
91新增: || pass "deleting the base template forgets which agent-vm built it"
92新增:echo 1 > "$HOME/.agent-vm/.agent-vm-base-version"
93新增:echo 0.2.0 > "$HOME/.agent-vm/.agent-vm-base-built-by"
94新增:
95新增:section "doctor"
96新增:date +%s > "$HOME/.agent-vm/.agent-vm-base-version"
97新增:# A stub git that keeps safe.bareRepository in a file; FAKE_GIT_VERSION and
98新增:# FAKE_GIT_SET_FAILS change its answers. Used here and by the setup offer.
99新增:mkdir -p "$SB/fakegit"
100新增:cat > "$SB/fakegit/git" <<STUB
101新增:#!/usr/bin/env bash
102新增:echo "git \$*" >> "$SB/git.log"
103新增:case "\$*" in
104新增: --version) echo "git version \${FAKE_GIT_VERSION:-2.47.0}" ;;
105新增: "config --get safe.bareRepository") cat "$SB/git-bare" 2>/dev/null || exit 1 ;;
106新增: "config --global safe.bareRepository explicit")
107新增: [ -n "\${FAKE_GIT_SET_FAILS:-}" ] && exit 1
108新增: echo explicit > "$SB/git-bare" ;;
109新增: *) exit 1 ;;
110新增:esac
111新增:STUB
112新增:chmod +x "$SB/fakegit/git"
113新增:# With the setting made: a healthy host has it.
114新增:DOCTOR_OLD_PATH="$PATH"
115新增:export PATH="$SB/fakegit:$PATH"
116新增:echo explicit > "$SB/git-bare"
117新增:out="$(rec doctor)"
118新增:rc=$?
119新增:check "doctor exits 0 on a healthy setup" "$rc" "0"
120新增:[ "$rc" = 0 ] || printf '%s\n' "$out" | sed 's/^/ /'
121新增:for want in "ok Lima 2.0.3" "ok agent-vm-base is ready" "(--readonly works)" "No problems found"; do
122新增: case "$out" in
123新增: *"$want"*) pass "doctor: $want" ;;
124新增: *) fail "doctor: missing '$want'"; printf '%s\n' "$out" | tail -3 | sed 's/^/ /' ;;
125新增: esac
126新增:done
127新增:if grep -Eq '^(start|stop|delete|clone|create|edit)( |$)' "$REC"; then
128新增: fail "doctor changed something: $(grep -E '^(start|stop|delete|clone|create|edit)' "$REC" | head -1)"
129新增:else
130新增: pass "doctor is read-only"
131新增:fi
132新增:case "$out" in
133新增: *"warn this Lima cannot keep .git read-only"*"$AGENT_VM_LIMA_ISSUE"*) pass "doctor: a Lima without readonlyNames is a warning, with the way out" ;;
134新增: *) fail "doctor: no warning about .git protection" ;;
135新增:esac
136新增:case "$out" in *"warn its shares leave .git writable"*) pass "doctor: a VM with a writable .git is a warning" ;; *) fail "doctor: VM shares not reported" ;; esac
137新增:case "$out" in *"built by agent-vm 0.1.0"*) fail "doctor: a current base taken for 0.1.0's" ;; *) pass "doctor: a current base is not 0.1.0's" ;; esac
138新增:case "$out" in *"to their shares"*) fail "doctor: reverse-sshfs exposure reported on vz" ;; *) pass "doctor: no reverse-sshfs exposure on vz" ;; esac
139新增:case "$( _agent_vm_unprotected_mount_is_sshfs() { return 0; }; rec doctor )" in
140新增: *"warn it cannot keep the VMs to their shares either"*"SSH keys"*) pass "doctor: reverse-sshfs exposure reported where a start would ask" ;;
141新增: *) fail "doctor: reverse-sshfs exposure not reported" ;;
142新增:esac
143新增:mv "$HOME/.agent-vm/.agent-vm-base-built-by" "$SB/built-by.saved"
144新增:case "$(rec doctor)" in *"warn the base template was built by agent-vm 0.1.0"*"'agent-vm setup' rebuilds it"*) pass "doctor: a base of 0.1.0 is a warning, with the way out" ;; *) fail "doctor: base of 0.1.0 not reported" ;; esac
145新增:mv "$SB/built-by.saved" "$HOME/.agent-vm/.agent-vm-base-built-by"
146新增:touch "$PROTECTS"
147新增:printf '[{"location": "%s", "writable": true, %s}]\n' "$PROJ" "$SSHFS_RO" > "$HOME/.agent-vm/.agent-vm-mounts-$PV"
148新增:out="$(rec doctor)"
149新增:case "$out" in *"ok Lima keeps every .git read-only"*) pass "doctor: a Lima with readonlyNames is ok" ;; *) fail "doctor: protection not reported" ;; esac
150新增:case "$out" in *"ok its shares keep every .git read-only"*) pass "doctor: a protected VM is ok" ;; *) fail "doctor: protected VM not reported" ;; esac
151新增:case "$out" in *"AGENT_VM_UNSAFE_WRITABLE_GIT"*) fail "doctor: opt-out reported while unset" ;; *) pass "doctor: no opt-out reported while unset" ;; esac
152新增:out="$(AGENT_VM_UNSAFE_WRITABLE_GIT=1 rec doctor)"
153新增:case "$out" in *"warn AGENT_VM_UNSAFE_WRITABLE_GIT=1: the VMs can write .git"*) pass "doctor: the opt-out is a warning" ;; *) fail "doctor: opt-out not reported" ;; esac
154新增:rm -f "$PROTECTS" "$HOME/.agent-vm/.agent-vm-mounts-$PV"
155新增:case "$out" in *"ok safe.bareRepository = explicit"*) pass "doctor: safe.bareRepository set is ok" ;; *) fail "doctor: safe.bareRepository not reported" ;; esac
156新增:rm -f "$SB/git-bare"
157新增:out="$(rec doctor)"
158新增:case "$out" in
159新增: *"warn safe.bareRepository is not 'explicit'"*"git config --global safe.bareRepository explicit"*) pass "doctor: safe.bareRepository unset is a warning, with the command" ;;
160新增: *) fail "doctor: unset safe.bareRepository not a warning" ;;
161新增:esac
162新增:out="$(FAKE_GIT_VERSION=2.30.1 rec doctor)"
163新增:case "$out" in *"warn git version 2.30.1 is older than 2.38"*) pass "doctor: a git older than 2.38 is a warning" ;; *) fail "doctor: old git not reported" ;; esac
164新增:export PATH="$DOCTOR_OLD_PATH"
165新增:# PATH without any limactl. Commands run under it are called by absolute path,
166新增:# in case the directory that held limactl also held them.
167新增:nolima_path() {
168新增: local rest="$PATH:" p out=""
169新增: while [ -n "$rest" ]; do
170新增: p="${rest%%:*}"; rest="${rest#*:}"
171新增: [ -x "$p/limactl" ] || out="${out:+$out:}$p"
172新增: done
173新增: printf '%s' "$out"
174新增:}
175新增:BASH_BIN="$(command -v bash)"
176新增:out="$(cd "$PROJ" && PATH="$(nolima_path)" "$BASH_BIN" "$AGENT_VM_SH" doctor 2>&1)"
177新增:rc=$?
178新增:case "$rc:$out" in
179新增: 1:*"FAIL Lima is not installed"*) pass "doctor without Lima: fails and says so" ;;
180新增: *) fail "doctor without Lima: $rc" ;;
181新增:esac
182新增:agent-vm doctor extra >/dev/null 2>&1
183新增:check "doctor takes no argument (exit 2)" "$?" "2"
新增tests/16-setup.sh+358 −0看文件
@@ -0,0 +1,358 @@
1新增:section "setup options"
2新增:case "$(agent-vm setup --reset 2>&1 </dev/null)" in
3新增: *"Unknown option: --reset"*) pass "setup rejects --reset instead of ignoring it" ;;
4新增: *) fail "setup accepted --reset" ;;
5新增:esac
6新增:for opt in --rm --scratch "--ssh-port=2300"; do
7新增: case "$(agent-vm setup "$opt" 2>&1 </dev/null)" in
8新增: *"Unknown option: ${opt%%=*}"*) pass "setup rejects $opt" ;;
9新增: *) fail "setup accepted $opt" ;;
10新增: esac
11新增:done
12新增:case "$(agent-vm setup --disk 10G 2>&1 </dev/null)" in *"--disk must be a positive integer"*) pass "setup: a bad value is said" ;; *) fail "setup --disk 10G accepted" ;; esac
13新增:
14新增:# A value option at the end is one clear error, also under a caller's set -u.
15新增:for opt in --disk --memory --cpus; do
16新增: out="$( (set -u; agent-vm setup "$opt") 2>&1 </dev/null)"
17新增: case "$?:$out" in
18新增: 1:"Error: $opt needs a value.") pass "setup $opt without a value: said" ;;
19新增: *) fail "setup $opt without a value: $out" ;;
20新增: esac
21新增:done
22新增:
23新增:section "setup wizard: the opt-in components default to no"
24新增:# Pressing Enter at every per-component prompt must give the default set's
25新增:# languages: Ruby, Rust and Go stay out, like Pi and Playwright MCP.
26新增:mkdir -p "$SB/wizlima"
27新增:cat > "$SB/wizlima/limactl" <<STUB
28新增:#!/bin/sh
29新增:case "\$1" in
30新增: shell) cat > "$SB/wizard.stdin" ;;
31新增: list) [ "\$2" = -q ] && echo agent-vm-base ;;
32新增:esac
33新增:exit 0
34新增:STUB
35新增:chmod +x "$SB/wizlima/limactl"
36新增:( PATH="$SB/wizlima:$PATH"; AGENT_VM_STATE_DIR="$SB/wizstate"
37新增: _agent_vm_have_tty() { return 0; }
38新增: _agent_vm_ask_yn() {
39新增: case "$1" in
40新增: "Use this default") echo 0 ;;
41新增: "Use these defaults") echo 1 ;;
42新增: *) case "$2" in [Yy]) echo 1 ;; *) echo 0 ;; esac ;;
43新增: esac
44新增: }
45新增: _agent_vm_offer_git_protection() { :; }
46新增: _agent_vm_setup ) >/dev/null 2>&1
47新增:check "wizard defaults: Ruby, Rust, Go, Pi and Playwright MCP off; Claude on" \
48新增: "$(grep -E '^export AGENT_VM_INSTALL_(RUBY|RUST|GOLANG|PI|MCP_PLAYWRIGHT|CLAUDE)=' "$SB/wizard.stdin" 2>/dev/null | cut -d_ -f4- | tr '\n' ' ')" \
49新增: "RUBY=0 RUST=0 GOLANG=0 CLAUDE=1 PI=0 MCP_PLAYWRIGHT=0 "
50新增:
51新增:section "release.sh"
52新增:REL="$SELF_DIR/release.sh"
53新增:notes="$("$REL" notes "$AGENT_VM_VERSION" 2>&1)"
54新增:case "$notes" in
55新增: ""|*"has no '## "*) fail "CHANGELOG.md has no section for $AGENT_VM_VERSION, the version agent-vm.sh reports" ;;
56新增: *) pass "CHANGELOG.md has a section for $AGENT_VM_VERSION" ;;
57新增:esac
58新增:# On a changelog of our own: the section stops at the next heading and loses
59新增:# its surrounding blank lines.
60新增:mkdir -p "$SB/rel"
61新增:cp "$REL" "$SB/rel/release.sh"
62新增:printf '# Changelog\n\n## 2.0.0\n\n- two\n\n## 1.0.0\n\n- one\n' > "$SB/rel/CHANGELOG.md"
63新增:check "notes: only that version's section" "$("$SB/rel/release.sh" notes 2.0.0)" "- two"
64新增:check "notes: the last section too" "$("$SB/rel/release.sh" notes 1.0.0)" "- one"
65新增:"$SB/rel/release.sh" notes 3.0.0 >/dev/null 2>&1
66新增:check "notes: an absent version fails" "$?" "1"
67新增:"$REL" 1.2 >/dev/null 2>&1
68新增:check "a malformed version is refused before anything else" "$?" "1"
69新增:"$REL" >/dev/null 2>&1
70新增:check "no argument prints the usage (exit 2)" "$?" "2"
71新增:
72新增:# The tarball is what an install runs: not the site, not the tests. Worktree
73新增:# attributes, so this checks the .gitattributes being committed.
74新增:if git -C "$SELF_DIR" rev-parse --verify -q HEAD >/dev/null 2>&1; then
75新增: listing="$(git -C "$SELF_DIR" archive --worktree-attributes --format=tar --prefix=x/ HEAD | tar -tf - 2>/dev/null)"
76新增: check "release tarball: no www/, tests/, test.sh or test-e2e.sh" \
77新增: "$(printf '%s\n' "$listing" | grep -cE '^x/(www/|tests/|test\.sh$|test-e2e\.sh$)')" "0"
78新增: check "release tarball: agent-vm.sh, lib/ and the setup script" \
79新增: "$(printf '%s\n' "$listing" | grep -cxE 'x/(agent-vm\.sh|lib/env\.sh|agent-vm\.setup\.sh)')" "3"
80新增:else
81新增: printf ' skip release tarball contents (not a git checkout)\n'
82新增:fi
83新增:
84新增:# A run that pushed the tag and then failed to publish is picked up again,
85新增:# rather than stuck on "tag already exists". Against a throwaway repository,
86新增:# its origin a bare one, and a stub gh.
87新增:if command -v git >/dev/null 2>&1; then
88新增: RR="$SB/relrepo"; RO="$SB/relorigin.git"; RB="$SB/relbin"
89新增: mkdir -p "$RR/www/public" "$RR/tests" "$RB"
90新增: cp -R "$SELF_DIR/agent-vm.sh" "$SELF_DIR/lib" "$SELF_DIR/agent-vm.setup.sh" "$SELF_DIR/install.sh" \
91新增: "$SELF_DIR/runtime.example.sh" "$SELF_DIR/test-e2e.sh" "$SELF_DIR/release.sh" "$SELF_DIR/CHANGELOG.md" "$RR/"
92新增: cp "$SELF_DIR/www/public/install.sh" "$RR/www/public/"
93新增: printf '#!/bin/sh\nexit 0\n' > "$RR/test.sh"; chmod +x "$RR/test.sh"
94新增: : > "$RR/tests/helpers.sh"
95新增: cat > "$RB/gh" <<STUB
96新增:#!/bin/sh
97新增:case "\$1 \$2" in
98新增: "run list") echo "completed success" ;;
99新增: "release view") [ -e "$SB/rel-released" ] ;;
100新增: "repo view") echo "o/r" ;;
101新增:esac
102新增:STUB
103新增: chmod +x "$RB/gh"
104新增: ( cd "$RR" && git init -q && git checkout -q -b main && git add -A \
105新增: && git -c user.name=t -c user.email=t@t commit -qm r \
106新增: && git init -q --bare "$RO" && git remote add origin "$RO" && git push -q origin main \
107新增: && git -c user.name=t -c user.email=t@t tag -a "v$AGENT_VM_VERSION" -m t && git push -q origin "v$AGENT_VM_VERSION" ) >/dev/null 2>&1
108新增: relrun() { ( cd "$RR" && PATH="$RB:$PATH" bash ./release.sh "$AGENT_VM_VERSION" --dry-run ) 2>&1; }
109新增: rm -f "$SB/rel-released"
110新增: out="$(relrun)"
111新增: case "$out" in
112新增: *"with no release: resuming"*"dry run complete"*) pass "release.sh: a tag with no release is resumed" ;;
113新增: *) fail "release.sh resume: $out" ;;
114新增: esac
115新增: case "$out" in *'$ git tag'*|*'$ git push'*) fail "release.sh resume: tags or pushes again" ;; *) pass "release.sh resume: neither tags nor pushes again" ;; esac
116新增: # A missing formula stops the run before it tags or publishes anything.
117新增: case "$(AGENT_VM_TAP="$SB/no-tap" relrun; echo "rc=$?")" in
118新增: *"no formula at $SB/no-tap/Formula/agent-vm.rb"*"rc=1")
119新增: case "$(AGENT_VM_TAP="$SB/no-tap" relrun)" in *"Checking the repository"*) fail "release.sh: the formula is checked after the repository" ;; *) pass "release.sh: a missing formula stops it first" ;; esac ;;
120新增: *) fail "release.sh: missing formula: $(AGENT_VM_TAP="$SB/no-tap" relrun)" ;;
121新增: esac
122新增: touch "$SB/rel-released"
123新增: case "$(relrun)" in *"tag v$AGENT_VM_VERSION already exists"*) pass "release.sh: a released tag is still refused" ;; *) fail "release.sh: a released tag was not refused" ;; esac
124新增: # The tag made here but never pushed: resumed too, and pushed before the
125新增: # release, which `gh release create --verify-tag` needs on origin.
126新增: rm -f "$SB/rel-released"
127新增: git -C "$RR" push -q origin ":refs/tags/v$AGENT_VM_VERSION" >/dev/null 2>&1
128新增: out="$(relrun)"
129新增: case "$out" in
130新增: *"resuming"*"\$ git push origin refs/tags/v$AGENT_VM_VERSION"*"\$ gh release create"*) pass "release.sh resume: a tag only made here is pushed first" ;;
131新增: *) fail "release.sh resume, local tag: $out" ;;
132新增: esac
133新增: case "$out" in *'$ git tag'*) fail "release.sh resume: tags again" ;; *) pass "release.sh resume: and not tagged again" ;; esac
134新增:else
135新增: printf ' skip release.sh resume (no git)\n'
136新增:fi
137新增:
138新增:section "no terminal: detected by opening it"
139新增:# `-r /dev/tty` is true with no controlling terminal; only opening it fails.
140新增:# setsid gives a process no controlling terminal, which is the CI case.
141新增:if command -v setsid >/dev/null 2>&1; then
142新增: SETSID="$(command -v setsid)"
143新增: # Runs $1 in bash with no controlling terminal. The exit status comes back as
144新增: # a last `rc=N` line: busybox setsid has no -w to wait and pass it through.
145新增: notty() {
146新增: "$SETSID" "$BASH_BIN" -c "source '$AGENT_VM_SH'; $1"'; echo "rc=$?"' </dev/null 2>&1
147新增: }
148新增:
149新增: out="$(notty '_agent_vm_have_tty')"
150新增: check "no controlling terminal: _agent_vm_have_tty says no" "${out##*rc=}" "1"
151新增:
152新增: # Lima missing, brew present, nobody to ask: say what to run, install nothing.
153新增: mkdir -p "$SB/fakebrew"
154新增: printf '#!/bin/sh\necho "brew $*" >> "%s/brew.log"\n' "$SB" > "$SB/fakebrew/brew"
155新增: chmod +x "$SB/fakebrew/brew"
156新增: rm -f "$SB/brew.log"
157新增: out="$(PATH="$SB/fakebrew:$(nolima_path)" notty 'agent-vm setup --preinstall=none')"
158新增: [ ! -e "$SB/brew.log" ] && pass "no terminal: brew is not run without asking" \
159新增: || fail "brew ran without a prompt: $(cat "$SB/brew.log")"
160新增: case "${out##*rc=}:$out" in
161新增: 1:*"Install it with: brew install sylvinus/tap/lima-sylvinus"*"brew install lima"*) pass "no terminal: says how to install Lima, the one keeping .git read-only first" ;;
162新增: *) fail "no terminal: '$out'" ;;
163新增: esac
164新增: case "$out" in
165新增: */dev/tty*) fail "a /dev/tty error leaked: $out" ;;
166新增: *) pass "no /dev/tty error is printed" ;;
167新增: esac
168新增:
169新增: # The wizard is skipped too, rather than run and answered with its defaults
170新增: # because every read fails.
171新增: rm -f "$SB/brew.log" "$PROTECTS"
172新增: out="$(AGENT_VM_STATE_DIR="$SB/wizard-state" AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_PROTECTS="$PROTECTS" \
173新增: PATH="$SB/fakebrew:$PATH" notty '_agent_vm_check_linux_prereqs() { return 0; }; agent-vm setup')"
174新增: case "${out##*rc=}:$out" in
175新增: *"setup wizard"*) fail "the wizard ran with no terminal" ;;
176新增: 0:*) pass "no terminal: the wizard is skipped and setup completes" ;;
177新增: *) fail "setup with no terminal: '$out'" ;;
178新增: esac
179新增: check "the base records the agent-vm that built it" \
180新增: "$(cat "$SB/wizard-state/.agent-vm-base-built-by" 2>/dev/null)" "$AGENT_VM_VERSION"
181新增: # A base that did not stop is not marked ready: Lima cannot clone it.
182新增: out="$(AGENT_VM_STATE_DIR="$SB/wizard-state2" AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_PROTECTS="$PROTECTS" \
183新增: AGENT_VM_TEST_BASE_RUNNING=1 PATH="$SB/fakebrew:$PATH" notty '_agent_vm_check_linux_prereqs() { return 0; }; agent-vm setup')"
184新增: case "${out##*rc=}:$out" in
185新增: 1:*"the base VM is set up but did not stop"*) pass "a base that does not stop: setup fails, and says so" ;;
186新增: *) fail "a base that does not stop: '$out'" ;;
187新增: esac
188新增: [ ! -e "$SB/wizard-state2/.agent-vm-base-version" ] && pass "and it is not marked ready" \
189新增: || fail "a running base was marked ready"
190新增: # Lima's containerd is never installed: Docker brings its own when chosen.
191新增: grep -q "^create .*--containerd=none" "$REC" && pass "Lima's containerd is off" \
192新增: || fail "Lima's containerd stays on: $(grep '^create' "$REC")"
193新增: # The resources are read as for the other commands, both spellings.
194新增: : > "$REC"
195新增: AGENT_VM_STATE_DIR="$SB/wizard-state3" AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_PROTECTS="$PROTECTS" PATH="$SB/fakebrew:$PATH" \
196新增: notty '_agent_vm_check_linux_prereqs() { return 0; }; agent-vm setup --disk=20 --memory 2 --cpus=1' >/dev/null
197新增: grep -q "^create .*--disk=20 --memory=2 --cpus=1" "$REC" && pass "setup: --disk=20 --memory 2 --cpus=1 reach the base" \
198新增: || fail "setup resources: $(grep '^create' "$REC")"
199新增: # A Lima that cannot keep .git read-only: said, with the command, and setup
200新增: # goes on without installing anything.
201新增: case "$out" in
202新增: *"cannot keep .git read-only"*"brew install sylvinus/tap/lima-sylvinus"*"Continuing without .git protection"*)
203新增: pass "no terminal: setup says .git is not protected, and how to fix it" ;;
204新增: *) fail "no terminal: no .git protection warning: '$out'" ;;
205新增: esac
206新增: [ ! -e "$SB/brew.log" ] && pass "no terminal: nothing is installed" \
207新增: || fail "brew ran without a prompt: $(cat "$SB/brew.log")"
208新增:else
209新增: printf ' skip terminal detection (no setsid here)\n'
210新增:fi
211新增:
212新增:# =============================================================================
213新增:section "setup offers a Lima that keeps .git read-only"
214新增:# =============================================================================
215新增:# With a terminal and Homebrew. A stub brew records its calls; installing the
216新增:# formula makes the limactl stub answer like a Lima with readonlyNames.
217新增:# FAKE_BREW_HAS_LIMA: brew's own lima is installed. FAKE_BREW_FAIL: the
218新增:# install fails.
219新增:mkdir -p "$SB/fakebrew"
220新增:cat > "$SB/fakebrew/brew" <<STUB
221新增:#!/bin/sh
222新增:echo "brew \$*" >> "$SB/brew.log"
223新增:case "\$1 \$2" in
224新增: "list --formula") [ -n "\${FAKE_BREW_HAS_LIMA:-}" ] ;;
225新增: "install sylvinus/tap/lima-sylvinus") [ -z "\${FAKE_BREW_FAIL:-}" ] && touch "$PROTECTS" ;;
226新增:esac
227新增:STUB
228新增:chmod +x "$SB/fakebrew/brew"
229新增:# ANSWER is the reply to the prompt (1 yes, 0 no).
230新增:offer() {
231新增: rm -f "$SB/brew.log"
232新增: # The Homebrew path, on any host: on Windows the offer is the download,
233新增: # which 18-windows.sh covers with a stub.
234新增: ( export AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_PROTECTS="$PROTECTS" PATH="$SB/fakebrew:$PATH"
235新增: _agent_vm_on_windows() { return 1; }
236新增: _agent_vm_have_tty() { return 0; }
237新增: _agent_vm_ask_yn() { echo "${ANSWER:-1}"; }
238新增: _agent_vm_offer_git_protection ) 2>&1
239新增:}
240新增:brew_calls() { tr '\n' ';' < "$SB/brew.log" 2>/dev/null; }
241新增:
242新增:rm -f "$PROTECTS"
243新增:out="$(FAKE_BREW_HAS_LIMA=1 offer)"
244新增:check "yes, over brew's lima: unlink it, then install the formula" \
245新增: "$(brew_calls)" "brew list --formula lima;brew unlink lima;brew install sylvinus/tap/lima-sylvinus;"
246新增:case "$out" in *"Lima now keeps every .git read-only"*) pass "yes: says it worked, checked afresh" ;; *) fail "yes: $out" ;; esac
247新增:
248新增:rm -f "$PROTECTS"
249新增:offer >/dev/null
250新增:check "yes, no brew lima: nothing to unlink" \
251新增: "$(brew_calls)" "brew list --formula lima;brew install sylvinus/tap/lima-sylvinus;"
252新增:
253新增:rm -f "$PROTECTS"
254新增:out="$(FAKE_BREW_HAS_LIMA=1 FAKE_BREW_FAIL=1 offer)"
255新增:case "$(brew_calls)" in
256新增: *"brew install sylvinus/tap/lima-sylvinus;brew link lima;") pass "a failed install links brew's lima back" ;;
257新增: *) fail "failed install: $(brew_calls)" ;;
258新增:esac
259新增:case "$out" in *"the install failed. Continuing without .git protection"*) pass "and says so" ;; *) fail "failed install: $out" ;; esac
260新增:
261新增:rm -f "$PROTECTS"
262新增:out="$(ANSWER=0 offer)"
263新增:[ ! -e "$SB/brew.log" ] && pass "no: brew is not run" || fail "no: brew ran: $(brew_calls)"
264新增:case "$out" in *"cannot keep .git read-only"*"Continuing without .git protection"*) pass "no: the risk is said" ;; *) fail "no: $out" ;; esac
265新增:
266新增:touch "$PROTECTS"
267新增:out="$(offer)"
268新增:check "already protected: nothing said" "$out" ""
269新增:[ ! -e "$SB/brew.log" ] && pass "already protected: brew is not run" || fail "already protected: brew ran: $(brew_calls)"
270新增:
271新增:section "start: git on this machine ignores bare repositories"
272新增:# A folder holding HEAD, objects/ and refs/ is a repository to git, whatever
273新增:# its name, so .git protection does not cover it. A start with writable shares
274新增:# offers to set safe.bareRepository=explicit; left unset, it asks whether to go
275新增:# on, and stops by default. The stub git is the doctor section's.
276新增:# ANSWER is the reply to the offer (1 yes, 0 no), GO_ON the one to the
277新增:# security question; NOTTY=1 means no terminal to ask on. Prints the output,
278新增:# then rc=N.
279新增:bare_check() {
280新增: rm -f "$SB/git.log"
281新增: ( export PATH="$SB/fakegit:$PATH"
282新增: unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS
283新增: _agent_vm_can_ask() { [ -z "${NOTTY:-}" ]; }
284新增: _agent_vm_ask_yn() { case "$1" in "Continue anyway?") echo "${GO_ON:-0}" ;; *) echo "${ANSWER:-1}" ;; esac; }
285新增: _agent_vm_check_bare_repo_setting; echo "rc=$?" ) 2>&1
286新增:}
287新增:git_set_called() { grep -q 'config --global safe.bareRepository explicit' "$SB/git.log" 2>/dev/null; }
288新增:
289新增:rm -f "$SB/git-bare"
290新增:out="$(bare_check)"
291新增:[ "$(cat "$SB/git-bare" 2>/dev/null)" = "explicit" ] && pass "yes: the setting is made" || fail "yes: not set: $out"
292新增:case "$out" in
293新增: *"HEAD, objects/ and refs/"*"git config --global safe.bareRepository explicit"*"now ignores"*"rc=0") pass "yes: the risk, the command, the result, and on" ;;
294新增: *) fail "yes: $out" ;;
295新增:esac
296新增:rm -f "$SB/git-bare"
297新增:out="$(ANSWER=0 bare_check)"
298新增:git_set_called && fail "no: the setting was made anyway" || pass "no: git config is not run"
299新增:case "$out" in *"Warning: not set"*"Aborted."*"rc=1") pass "no: says what is left open, and stops by default" ;; *) fail "no: $out" ;; esac
300新增:out="$(ANSWER=0 GO_ON=1 bare_check)"
301新增:case "$out" in *"rc=0") pass "no, then go on: on" ;; *) fail "no, then go on: $out" ;; esac
302新增:out="$(NOTTY=1 bare_check)"
303新增:git_set_called && fail "no terminal: the setting was made without asking" || pass "no terminal: nothing is changed"
304新增:case "$out" in *"git config --global safe.bareRepository explicit"*"Aborted."*"rc=1") pass "no terminal: the command is printed, and it stops" ;; *) fail "no terminal: $out" ;; esac
305新增:out="$(FAKE_GIT_SET_FAILS=1 bare_check)"
306新增:case "$out" in *"did not take"*"Aborted."*"rc=1") pass "a failed git config is said, and it stops" ;; *) fail "failed git config: $out" ;; esac
307新增:# Disabled questions: no offer either, the global config is not changed unasked.
308新增:rm -f "$SB/git.log"
309新增:out="$( export AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1; PATH="$SB/fakegit:$PATH"; _agent_vm_check_bare_repo_setting 2>&1; echo "rc=$?" )"
310新增:git_set_called && fail "prompts disabled: the setting was made" || pass "prompts disabled: git config is not run"
311新增:case "$out" in *"Warning: not set"*"Continuing: AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1."*"rc=0") pass "prompts disabled: warned, then on" ;; *) fail "prompts disabled: $out" ;; esac
312新增:out="$(FAKE_GIT_VERSION=2.30.1 bare_check)"
313新增:git_set_called && fail "old git: set on a git that ignores it" || pass "old git: nothing is set"
314新增:case "$out" in *"older than 2.38"*"Aborted. Upgrade git"*"rc=1") pass "old git: stops, and says to upgrade" ;; *) fail "old git: $out" ;; esac
315新增:echo explicit > "$SB/git-bare"
316新增:check "already set: nothing said" "$(bare_check)" "rc=0"
317新增:git_set_called && fail "already set: git config was run" || pass "already set: git config is not run"
318新增:check "no git on this machine: nothing to protect" "$( hash -r; PATH="$SB/nolimactl" _agent_vm_bare_repo_state)" "nogit"
319新增:check "setup no longer asks" "$(declare -f _agent_vm_setup | grep -c 'bare_repo')" "0"
320新增:
321新增:# In a start: before anything changes, and not under --readonly, where the VM
322新增:# cannot write a repository anywhere.
323新增:rm -f "$SB/git-bare"
324新增:out="$( export PATH="$SB/fakegit:$PATH"; unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }
325新增: touch "$PROTECTS"; AGENT_VM_TEST_STOPPED=1 rec run true; echo "rc=$?" )"
326新增:case "$out" in *"Aborted. Run the command above"*"rc=1") pass "start: unset, no terminal: stopped" ;; *) fail "start: not stopped: $out" ;; esac
327新增:grep -Eq '^(edit|start|clone) ' "$REC" && fail "start: the VM was touched before the abort" || pass "start: nothing touched"
328新增:printf '[{"location": "%s", "writable": true, %s}]\n' "$PROJ" "$SSHFS_RO" > "$HOME/.agent-vm/.agent-vm-mounts-$PV"
329新增:out="$( export PATH="$SB/fakegit:$PATH"; unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }
330新增: rec run true; echo "rc=$?" )"
331新增:case "$out" in *"Aborted."*) fail "start of a running VM: stopped on the setting: $out" ;; *"Warning: git on this machine uses repositories a VM creates"*"rc=0") pass "start of a running VM: warned, not asked" ;; *) fail "start of a running VM: $out" ;; esac
332新增:case "$( PATH="$SB/fakegit:$PATH"; rec info | grep '^security_questions=')" in *bare-repo*) pass "info: security_questions names the setting" ;; *) fail "info: bare-repo not named" ;; esac
333新增:printf '[{"location": "%s", "writable": false, %s}]\n' "$PROJ" "$SSHFS_RO" > "$HOME/.agent-vm/.agent-vm-mounts-$PV"
334新增:out="$( export PATH="$SB/fakegit:$PATH"; unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }
335新增: AGENT_VM_TEST_STOPPED=1 AGENT_VM_TEST_RO=1 AGENT_VM_TEST_MOUNTTYPE=reverse-sshfs rec --readonly run true; echo "rc=$?" )"
336新增:case "$out" in *"repositories not named .git"*|*"Aborted."*) fail "start --readonly: asked anyway: $out" ;; *"rc=0") pass "start --readonly: no question" ;; *) fail "start --readonly: $out" ;; esac
337新增:rm -f "$PROTECTS" "$HOME/.agent-vm/.agent-vm-mounts-$PV"
338新增:# A first run opens on the familiar questions: the security ones come after the
339新增:# wizard, and before the VM exists.
340新增:check "security checks: after the wizard, before the VM" \
341新增: "$(declare -f _agent_vm_setup | grep -o -e 'Use these defaults' -e 'Running security checks' -e 'Creating base VM' | tr '\n' '|')" \
342新增: "Use these defaults|Running security checks|Creating base VM|"
343新增:
344新增:# Against the real git, when it is recent enough: only the system and global
345新增:# config count, as for git itself. A repository's own setting must not answer.
346新增:real_git_ver="$(git --version 2>/dev/null)"; real_git_ver="${real_git_ver#git version }"; real_git_ver="${real_git_ver%% *}"
347新增:if [ -n "$real_git_ver" ] && _agent_vm_ver_ge "$real_git_ver" 2.38.0; then
348新增: mkdir -p "$SB/realgit/home" "$SB/realgit/repo"
349新增: ( export HOME="$SB/realgit/home" GIT_CONFIG_NOSYSTEM=1 XDG_CONFIG_HOME="$SB/realgit/xdg"
350新增: cd "$SB/realgit/repo" && git init -q . && git config safe.bareRepository explicit
351新增: printf '%s ' "$(_agent_vm_bare_repo_state)"
352新增: git config --global safe.bareRepository explicit
353新增: printf '%s' "$(_agent_vm_bare_repo_state)" ) > "$SB/realgit/out"
354新增: check "real git: a repository's own setting does not count, the global one does" "$(cat "$SB/realgit/out")" "unset ok"
355新增:else
356新增: printf ' skip real git (absent or older than 2.38)\n'
357新增:fi
358新增:rm -f "$PROTECTS"
新增tests/17-curl-installer.sh+136 −0看文件
@@ -0,0 +1,136 @@
1新增:# =============================================================================
2新增:section "www/public/install.sh (curl | sh)"
3新增:# =============================================================================
4新增:# Stub curl and git serve releases from $WF, one directory per tag, and log
5新增:# what was asked for. A release is agent-vm.sh and lib/, plus a MARK file
6新增:# naming it.
7新增:INSTALLER="$SELF_DIR/www/public/install.sh"
8新增:WF="$SB/wfix"; WBIN="$SB/wbin"; WH="$SB/whome"
9新增:mkdir -p "$WBIN" "$WH"
10新增:cat > "$WBIN/curl" <<'STUB'
11新增:#!/bin/sh
12新增:out=""; url=""
13新增:while [ $# -gt 0 ]; do
14新增: case "$1" in -o) out="$2"; shift ;; https://*) url="$1" ;; esac
15新增: shift
16新增:done
17新增:echo "$url" >> "$WF/log"
18新增:case "$url" in
19新增: */releases/latest/download/*) f="$WF/$(cat "$WF/latest")/${url##*/}" ;;
20新增: */releases/download/*) t="${url%/*}"; f="$WF/${t##*/}/${url##*/}" ;;
21新增: *) exit 22 ;;
22新增:esac
23新增:[ -f "$f" ] || exit 22
24新增:cp "$f" "$out"
25新增:STUB
26新增:cat > "$WBIN/git" <<'STUB'
27新增:#!/bin/sh
28新增:echo "git $*" >> "$WF/log"
29新增:case "$1" in
30新增: clone) mkdir -p "$3/.git" && cp -R "$WF/src/." "$3/" ;;
31新增: -C) [ -d "$2/.git" ] ;;
32新增:esac
33新增:STUB
34新增:chmod +x "$WBIN/curl" "$WBIN/git"
35新增:make_release() { # <version> [corrupt]
36新增: local d="$WF/v$1" s="$WF/stage/agent-vm-$1"
37新增: mkdir -p "$d" "$s"
38新增: cp -R "$WF/src/." "$s/"; echo "$1" > "$s/MARK"
39新增: tar -czf "$d/agent-vm-$1.tar.gz" -C "$WF/stage" "agent-vm-$1"
40新增: local sum; sum="$(_agent_vm_sha256 < "$d/agent-vm-$1.tar.gz" | cut -d' ' -f1)"
41新增: [ -z "${2:-}" ] || sum="0000$sum"
42新增: printf '%s agent-vm-%s.tar.gz\n' "$sum" "$1" > "$d/SHA256SUMS"
43新增: echo "v$1" > "$WF/latest"
44新增:}
45新增:mkdir -p "$WF/src"; cp -R "$AGENT_VM_SH" "$(dirname "$AGENT_VM_SH")/lib" "$WF/src/"
46新增:# The base is built (the stub limactl lists it), so `install` has nothing to
47新增:# ask on a terminal.
48新增:mkdir -p "$WH/state"; echo 1 > "$WH/state/.agent-vm-base-version"
49新增:winst() {
50新增: ( export HOME="$WH" WF XDG_DATA_HOME= AGENT_VM_BIN_DIR="$WH/bin" SHELL=/bin/zsh PATH="$WBIN:$PATH" \
51新增: AGENT_VM_STATE_DIR="$WH/state"
52新增: sh "${WINSTALLER:-$INSTALLER}" "$@" ) 2>&1
53新增:}
54新增:# Without symlinks each install plants a copy, so a later install would trip
55新增:# over it instead of running: clear it where a check needs a fresh install.
56新增:fresh_link() { [[ -n "$AGENT_VM_HAS_SYMLINKS" ]] || rm -f "$WH/bin/agent-vm"; }
57新增:WDIR="$WH/.local/share/agent-vm"
58新增:
59新增:make_release 1.0.0
60新增:: > "$WF/log"
61新增:out="$(winst)"; rc=$?
62新增:check "release: installs" "$rc" "0"
63新增:case "$out" in *"agent-vm claude"*) pass "release: base built, nothing asked" ;; *) fail "release: $out" ;; esac
64新增:check "release: the latest tarball is in place" "$(cat "$WDIR/MARK" 2>/dev/null)" "1.0.0"
65新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
66新增:check "release: linked onto the PATH" "$(readlink "$WH/bin/agent-vm")" "$WDIR/agent-vm.sh"
67新增:else
68新增: printf ' skip release: readlink (ln -s plants copies on this machine)\n'
69新增:fi
70新增:check "release: sums from latest/, the tarball from its tag" "$(tr '\n' ' ' < "$WF/log")" \
71新增: "https://github.com/sylvinus/agent-vm/releases/latest/download/SHA256SUMS https://github.com/sylvinus/agent-vm/releases/download/v1.0.0/agent-vm-1.0.0.tar.gz "
72新增:
73新增:make_release 1.1.0
74新增:fresh_link
75新增:out="$(winst)"; rc=$?
76新增:check "rerun: replaced by the new release" "$rc:$(cat "$WDIR/MARK")" "0:1.1.0"
77新增:check "rerun: no staging or old copy left" "$(ls -A "$WH/.local/share")" "agent-vm"
78新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
79新增:case "$out" in *"already linked"*) pass "rerun: the link is kept" ;; *) fail "rerun: $out" ;; esac
80新增:else
81新增: printf ' skip rerun: the link is kept (ln -s plants copies on this machine)\n'
82新增:fi
83新增:
84新增:# The swap stopped between its two renames (a failed mv, a Ctrl-C): the
85新增:# previous version goes back where it was, nothing else left.
86新增:make_release 1.1.5
87新增:fresh_link
88新增:mkdir -p "$SB/wmvfail"
89新增:printf '#!/bin/sh\ncase "$1" in *.new.*) exit 1 ;; esac\nexec %s "$@"\n' "$(command -v mv)" > "$SB/wmvfail/mv"
90新增:chmod +x "$SB/wmvfail/mv"
91新增:out="$(PATH="$SB/wmvfail:$PATH" winst)"; rc=$?
92新增:check "swap cut short: the previous version is back" "$rc:$(cat "$WDIR/MARK" 2>/dev/null)" "1:1.1.0"
93新增:check "swap cut short: no staging or old copy left" "$(ls -A "$WH/.local/share")" "agent-vm"
94新增:
95新增:make_release 1.2.0 corrupt
96新增:fresh_link
97新增:out="$(winst)"; rc=$?
98新增:check "bad checksum: refused, the install is untouched" "$rc:$(cat "$WDIR/MARK")" "1:1.1.0"
99新增:case "$out" in *"checksum mismatch"*) pass "bad checksum: said" ;; *) fail "bad checksum: $out" ;; esac
100新增:
101新增:: > "$WF/log"
102新增:fresh_link
103新增:out="$(winst --version v1.0.0)"; rc=$?
104新增:check "--version: that release" "$rc:$(cat "$WDIR/MARK")" "0:1.0.0"
105新增:check "--version: its sums, from its tag" "$(head -n 1 "$WF/log")" \
106新增: "https://github.com/sylvinus/agent-vm/releases/download/v1.0.0/SHA256SUMS"
107新增:check "--version: not a version (exit 1)" "$(winst --version 1.0 >/dev/null; echo $?)" "1"
108新增:check "--version with --git (exit 1)" "$(winst --version 1.0.0 --git >/dev/null; echo $?)" "1"
109新增:check "unknown option (exit 2)" "$(winst --nope >/dev/null; echo $?)" "2"
110新增:
111新增:make_release 1.3.0
112新增:mkdir -p "$SB/wother"; echo mine > "$SB/wother/notes"
113新增:out="$(winst --dir "$SB/wother")"; rc=$?
114新增:check "a directory of the user's: refused, left as it was" "$rc:$(ls "$SB/wother")" "1:notes"
115新增:
116新增:rm -rf "$WDIR" "$WH/bin"
117新增:: > "$WF/log"
118新增:out="$(winst --git)"; rc=$?
119新增:check "--git: clones" "$rc:$(head -n 1 "$WF/log")" "0:git clone https://github.com/sylvinus/agent-vm.git $WDIR"
120新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
121新增:check "--git: linked onto the PATH" "$(readlink "$WH/bin/agent-vm")" "$WDIR/agent-vm.sh"
122新增:else
123新增: printf ' skip --git: readlink (ln -s plants copies on this machine)\n'
124新增:fi
125新增:fresh_link
126新增:out="$(winst --git)"; rc=$?
127新增:check "--git again: pulls" "$rc:$(tail -n 1 "$WF/log")" "0:git -C $WDIR pull --ff-only"
128新增:out="$(winst)"; rc=$?
129新增:check "release over a clone: refused" "$rc" "1"
130新增:case "$out" in *"is a git clone"*"git -C"*) pass "release over a clone: says how to update it" ;; *) fail "release over a clone: $out" ;; esac
131新增:
132新增:# A download cut short must run nothing: only the last line calls main.
133新增:rm -rf "$WDIR"
134新增:sed '$d' "$INSTALLER" > "$SB/install-cut.sh"
135新增:out="$(WINSTALLER="$SB/install-cut.sh" winst)"; rc=$?
136新增:check "cut short: runs nothing" "$rc:$([ -e "$WDIR" ] && echo there)" "0:"
新增tests/18-windows.sh+371 −0看文件
@@ -0,0 +1,371 @@
1新增:# =============================================================================
2新增:section "windows host support (Git Bash)"
3新增:# =============================================================================
4新增:# A fake uname reporting MINGW64, used through PATH in subshells only, so
5新增:# nothing leaks into the rest of the suite. Plain sh: the restricted-PATH
6新增:# cases below could not even resolve a bash shebang.
7新增:mkdir -p "$SB/fakewin" "$SB/fakeqemu" "$SB/emptybin"
8新增:cat > "$SB/fakewin/uname" <<'STUB'
9新增:#!/bin/sh
10新增:case "$1" in
11新增: -s) echo "MINGW64_NT-10.0-26100" ;;
12新增: *) echo "x86_64" ;;
13新增:esac
14新增:STUB
15新增:chmod +x "$SB/fakewin/uname"
16新增:# And one reporting Linux, for the "not on Windows" cases on a Windows runner.
17新增:mkdir -p "$SB/fakelinux"
18新增:printf '#!/bin/sh\necho Linux\n' > "$SB/fakelinux/uname"
19新增:chmod +x "$SB/fakelinux/uname"
20新增:printf '#!/bin/sh\nexit 0\n' > "$SB/fakeqemu/qemu-system-x86_64"
21新增:chmod +x "$SB/fakeqemu/qemu-system-x86_64"
22新增:
23新增:# 11-recorded-commands.sh stubs the host prereq checks (05 re-sources the
24新增:# engine, wiping helpers' stubs); restore the real ones: they are what is
25新增:# under test here. Same restore as in 19-wsl.sh.
26新增:. "$SELF_DIR/lib/host.sh"
27新增:if ( PATH="$SB/fakewin:$PATH"; _agent_vm_on_windows ); then
28新增: pass "MINGW64 uname is detected as Windows"
29新增:else
30新增: fail "MINGW64 uname is not detected as Windows"
31新增:fi
32新增:# Without the fake, detection must agree with the real kernel: true on an
33新增:# actual Windows runner, false everywhere else.
34新增:case "$(uname -s)" in
35新增: MINGW*|MSYS*|CYGWIN*) expect_win=1 ;;
36新增: *) expect_win="" ;;
37新增:esac
38新增:if _agent_vm_on_windows; then got_win=1; else got_win=""; fi
39新增:check "native detection agrees with uname" "$got_win" "$expect_win"
40新增:
41新增:if ( PATH="$SB/fakewin:$SB/fakeqemu:$PATH"; _agent_vm_check_windows_prereqs ); then
42新增: pass "QEMU present -> Windows prereqs pass"
43新增:else
44新增: fail "QEMU present but Windows prereqs fail"
45新增:fi
46新增:win_out="$(AGENT_VM_QEMU_DIR="$SB/no-qemu" PATH="$SB/fakewin:$SB/emptybin" _agent_vm_check_windows_prereqs 2>&1)"
47新增:check "QEMU absent -> Windows prereqs fail (exit 1)" "$?" "1"
48新增:case "$win_out" in
49新增: *winget*"Windows Hypervisor Platform"*) pass "the failure names the winget install and the hypervisor feature" ;;
50新增: *) fail "the failure does not say how to install QEMU: $win_out" ;;
51新增:esac
52新增:# winget's QEMU does not put itself on PATH: found in its directory, it goes
53新增:# on PATH for this shell, with the line to keep it.
54新增:mkdir -p "$SB/qemu-dir"
55新增:printf '#!/bin/sh\nexit 0\n' > "$SB/qemu-dir/qemu-system-x86_64.exe"
56新增:chmod +x "$SB/qemu-dir/qemu-system-x86_64.exe"
57新增:win_out="$( AGENT_VM_QEMU_DIR="$SB/qemu-dir"; PATH="$SB/fakewin:$SB/emptybin"
58新增: _agent_vm_check_windows_prereqs && printf 'PATH=%s' "$PATH" )"
59新增:case "$win_out" in
60新增: *"export PATH=\"$SB/qemu-dir:\$PATH\""*"PATH=$SB/qemu-dir:"*) pass "QEMU in its install directory: put on PATH, and the line to keep it printed" ;;
61新增: *) fail "QEMU in its install directory: $win_out" ;;
62新增:esac
63新增:
64新增:# A start that failed on WHPX says what it needs, and who can turn it on.
65新增:printf 'qemu-system-x86_64.exe: WHPX: No accelerator found, hr=00000000\n' > "$SB/whpx.log"
66新增:printf 'something else\n' > "$SB/other.log"
67新增:case "$(PATH="$SB/fakewin:$PATH" _agent_vm_windows_start_hint "$SB/other.log" "$SB/whpx.log" 2>&1)" in
68新增: *"Windows Hypervisor"*"FeatureName:HypervisorPlatform"*"IT department"*) pass "WHPX failure: the hint names the feature and the administrator" ;;
69新增: *) fail "WHPX failure: no hint" ;;
70新增:esac
71新增:check "another failure: no hint" "$(PATH="$SB/fakewin:$PATH" _agent_vm_windows_start_hint "$SB/other.log" 2>&1)" ""
72新增:check "not on Windows: no hint" "$(PATH="$SB/fakelinux:$PATH" _agent_vm_windows_start_hint "$SB/whpx.log" 2>&1)" ""
73新增:
74新增:# =============================================================================
75新增:section "Windows: paths, as Lima reads them and as the guest sees them"
76新增:# =============================================================================
77新增:# Git Bash spells C:\Users as /c/Users. Lima on Windows requires an absolute
78新增:# Windows path as a mount location, and Git Bash rewrites /c/... arguments to
79新增:# C:/... when it starts limactl.exe, guest paths included. A fake cygpath
80新增:# stands for Git Bash's.
81新增:cat > "$SB/fakewin/cygpath" <<'STUB'
82新增:#!/bin/sh
83新增:[ "$1" = -m ] && shift
84新增:[ "$1" = -- ] && shift
85新增:case "$1" in
86新增: /[a-z]/*) d="$(printf '%s' "$1" | cut -c2 | tr a-z A-Z)"; printf '%s:%s\n' "$d" "$(printf '%s' "$1" | cut -c3-)" ;;
87新增: *) printf 'C:/msys64%s\n' "$1" ;;
88新增:esac
89新增:STUB
90新增:chmod +x "$SB/fakewin/cygpath"
91新增:check "a host path in Lima's spelling" "$(PATH="$SB/fakewin:$PATH" _agent_vm_host_path /c/Users/me/proj)" "C:/Users/me/proj"
92新增:check "elsewhere, unchanged" "$(PATH="$SB/fakelinux:$PATH" _agent_vm_host_path /c/Users/me/proj)" "/c/Users/me/proj"
93新增:win_json="$( PATH="$SB/fakewin:$PATH"; AGENT_VM_STATE_DIR="$SB/winstate"
94新增: _agent_vm_build_mounts_json agent-vm-w /c/Users/me/proj true )"
95新增:check "the project share: a Windows location, mounted at the shell's path" \
96新增: "$win_json" '[{"location": "C:/Users/me/proj", "mountPoint": "/c/Users/me/proj", "writable": true}]'
97新增:
98新增:# limactl gets every argument as written: Git Bash's rewriting is off for it.
99新增:mkdir -p "$SB/convlima"
100新增:printf '#!/bin/sh\necho "${MSYS_NO_PATHCONV:-}|${MSYS2_ARG_CONV_EXCL:-}|$*"\n' > "$SB/convlima/limactl"
101新增:chmod +x "$SB/convlima/limactl"
102新增:conv="$( PATH="$SB/fakewin:$SB/convlima:$PATH"; . "$SELF_DIR/lib/host.sh"
103新增: limactl shell --workdir /c/proj vm true
104新增: printf '%s\n' "$(_agent_vm_limactl_path)" )"
105新增:check "on Windows, limactl runs without path rewriting" "$conv" "1|*|shell --workdir /c/proj vm true
106新增:$SB/convlima/limactl"
107新增:check "and a missing limactl is still missing" \
108新增: "$( PATH="$SB/fakewin:$SB/emptybin"; . "$SELF_DIR/lib/host.sh"; _agent_vm_limactl_path; echo "rc=$?" )" "rc=1"
109新增:# unset -f: on a Windows runner the suite's own sourcing defined the wrapper.
110新增:check "elsewhere, limactl is not wrapped" \
111新增: "$( PATH="$SB/fakelinux:$SB/convlima:$PATH"; unset -f limactl; . "$SELF_DIR/lib/host.sh"
112新增: limactl x )" "||x"
113新增:
114新增:# The .git probe hands limactl a file and a location Lima can read.
115新增:mkdir -p "$SB/validlima"
116新增:cat > "$SB/validlima/limactl" <<STUB
117新增:#!/bin/sh
118新增:echo "\$*" > "$SB/validate.args"
119新增:STUB
120新增:chmod +x "$SB/validlima/limactl"
121新增:( PATH="$SB/fakewin:$SB/validlima:$PATH"; export TMPDIR="$SB/probe-tmp"; _agent_vm_lima_protects_git ) >/dev/null 2>&1
122新增:case "$(cat "$SB/validate.args" 2>/dev/null)" in
123新增: "validate $(PATH="$SB/fakewin:$PATH" _agent_vm_host_path "$SB/probe-tmp")/"*"/probe.yaml") pass "the .git probe passes limactl a Windows path" ;;
124新增: *) fail "the .git probe: $(cat "$SB/validate.args" 2>/dev/null)" ;;
125新增:esac
126新增:
127新增:# =============================================================================
128新增:section "Windows: setup without Lima offers the download"
129新增:# =============================================================================
130新增:nolima_win() {
131新增: ( PATH="$SB/fakewin:$(nolima_path)"
132新增: _agent_vm_have_tty() { [ -n "${TTY:-}" ]; }
133新增: _agent_vm_ask_yn() { echo 1; }
134新增: _agent_vm_install_fork_windows() { echo "FORK DOWNLOAD"; return 1; }
135新增: _agent_vm_setup --preinstall=none ) 2>&1
136新增:}
137新增:case "$(TTY=1 nolima_win)" in
138新增: *"FORK DOWNLOAD"*) pass "with a terminal: the Lima build for Windows is offered" ;;
139新增: *) fail "with a terminal: no download offered" ;;
140新增:esac
141新增:case "$(nolima_win)" in
142新增: *"FORK DOWNLOAD"*) fail "no terminal: downloaded without asking" ;;
143新增: *"Run 'agent-vm setup' in a terminal"*) pass "no terminal: says where the offer is" ;;
144新增: *) fail "no terminal: $(nolima_win)" ;;
145新增:esac
146新增:
147新增:# =============================================================================
148新增:section "Windows: the Lima build is replaced when its tag changes"
149新增:# =============================================================================
150新增:# A stub curl serves the release from $FORKSRV/<tag>/, a stub unzip unpacks a
151新增:# "zip" that names its limactl.exe, so which build is installed can be read.
152新增:FORKSRV="$SB/forksrv"; mkdir -p "$SB/forkbin"
153新增:make_fork_release() { # <tag>
154新增: local d="$FORKSRV/$1" t="${1#v}" f
155新增: mkdir -p "$d"
156新增: for f in "lima-$t-Windows-AMD64.zip" "lima-additional-guestagents-$t-Windows-AMD64.zip"; do
157新增: echo "$1" > "$d/$f"
158新增: done
159新增: ( cd "$d" && if command -v sha256sum >/dev/null 2>&1; then sha256sum lima-*.zip; else shasum -a 256 lima-*.zip; fi > SHA256SUMS )
160新增:}
161新增:cat > "$SB/forkbin/curl" <<STUB
162新增:#!/bin/sh
163新增:out=""; url=""
164新增:while [ \$# -gt 0 ]; do case "\$1" in -o) out="\$2"; shift ;; https://*) url="\$1" ;; esac; shift; done
165新增:echo "\$url" >> "$SB/fork.log"
166新增:t="\${url%/*}"; cp "$FORKSRV/\${t##*/}/\${url##*/}" "\$out"
167新增:STUB
168新增:cat > "$SB/forkbin/unzip" <<'STUB'
169新增:#!/bin/sh
170新增:while [ $# -gt 0 ]; do case "$1" in -d) d="$2"; shift ;; -q|-o) ;; *) z="$1" ;; esac; shift; done
171新增:case "$z" in */lima-additional*) exit 0 ;; esac
172新增:mkdir -p "$d/bin" && cp "$z" "$d/bin/limactl.exe" && chmod +x "$d/bin/limactl.exe"
173新增:STUB
174新增:chmod +x "$SB/forkbin/curl" "$SB/forkbin/unzip"
175新增:# Under set -u, as a script sourcing agent-vm may run.
176新增:# The checksums are pinned in the engine: those of the stub release stand for
177新增:# them, unless PINNED gives others.
178新增:fork() { # <tag> [function]
179新增: ( set -u; PATH="$SB/fakewin:$SB/forkbin:$PATH"; AGENT_VM_LIMA_DIR="$SB/lima-fork"; AGENT_VM_LIMA_FORK_TAG="$1"
180新增: AGENT_VM_LIMA_FORK_SHA256="${PINNED:-$(cat "$FORKSRV/$1/SHA256SUMS")}"
181新增: _agent_vm_have_tty() { return 0; }; _agent_vm_ask_yn() { echo 1; }
182新增: "${2:-_agent_vm_install_fork_windows}" ) 2>&1
183新增:}
184新增:make_fork_release v9.0.0-sylvinus.1
185新增:make_fork_release v9.0.0-sylvinus.2
186新增:# A zip that does not match the pinned checksum is refused, even when the
187新增:# release's own SHA256SUMS agrees with it: whoever replaces one can replace both.
188新增:: > "$SB/fork.log"
189新增:out="$(PINNED="$(sed 's/^[0-9a-f]\{8\}/deadbeef/' "$FORKSRV/v9.0.0-sylvinus.1/SHA256SUMS")" fork v9.0.0-sylvinus.1)"
190新增:case "$?:$out" in
191新增: 1:*"checksum mismatch"*) pass "install: a zip that differs from the pinned checksum is refused" ;;
192新增: *) fail "install: pinned checksum not enforced: $out" ;;
193新增:esac
194新增:check "and nothing is installed" "$([ -e "$SB/lima-fork" ] && echo yes || echo no)" "no"
195新增:check "the release's SHA256SUMS is not downloaded" "$(grep -c 'SHA256SUMS' "$SB/fork.log")" "0"
196新增:: > "$SB/fork.log"
197新增:out="$(fork v9.0.0-sylvinus.1)"
198新增:check "install: the build of the tag, and a clean exit" \
199新增: "$? $(cat "$SB/lima-fork/bin/limactl.exe" 2>/dev/null)" "0 v9.0.0-sylvinus.1"
200新增:: > "$SB/fork.log"
201新增:case "$(fork v9.0.0-sylvinus.1)" in *"already installed"*) pass "same tag: reused" ;; *) fail "same tag: not reused" ;; esac
202新增:check "same tag: nothing downloaded" "$(cat "$SB/fork.log")" ""
203新增:fork v9.0.0-sylvinus.2 _agent_vm_offer_fork_windows_update >/dev/null
204新增:check "another tag: setup's update replaces it" "$(cat "$SB/lima-fork/bin/limactl.exe" 2>/dev/null)" "v9.0.0-sylvinus.2"
205新增:check "and leaves no staging or old copy" "$(ls -A "$SB" | grep -c '^lima-fork\.')" "0"
206新增:: > "$SB/fork.log"
207新增:check "up to date: no update offered" "$(fork v9.0.0-sylvinus.2 _agent_vm_offer_fork_windows_update)$(cat "$SB/fork.log")" ""
208新增:mkdir -p "$SB/not-lima"; echo mine > "$SB/not-lima/notes"
209新增:out="$( ( PATH="$SB/fakewin:$SB/forkbin:$PATH"; AGENT_VM_LIMA_DIR="$SB/not-lima"; _agent_vm_install_fork_windows ) 2>&1 )"
210新增:case "$?:$out" in
211新增: 1:*"is not a Lima install"*) pass "a directory of the user's: refused" ;;
212新增: *) fail "a directory of the user's: $out" ;;
213新增:esac
214新增:check "and left as it was" "$(ls "$SB/not-lima")" "notes"
215新增:
216新增:# =============================================================================
217新增:section "Windows: install makes a launcher where there are no symlinks"
218新增:# =============================================================================
219新增:# Git Bash's ln -s copies the file unless Windows grants symlinks, and a copy
220新增:# of agent-vm.sh cannot find lib/. `ln` stands for that here.
221新增:WIB="$SB/winbin"
222新增:winst_ln() {
223新增: ( export HOME="$SB/winhome" AGENT_VM_BIN_DIR="$WIB" PATH="$WIB:$PATH"
224新增: ln() { [ "$1" = -s ] && shift; cp "$1" "$2"; }
225新增: _agent_vm_have_tty() { return 1; }
226新增: _agent_vm_base_exists() { return 0; }
227新增: agent-vm "$@" ) 2>&1
228新增:}
229新增:mkdir -p "$SB/winhome"
230新增:out="$(winst_ln install)"
231新增:case "$out" in *"a launcher for"*) pass "install: says it wrote a launcher" ;; *) fail "install: $out" ;; esac
232新增:check "the launcher runs this agent-vm" "$(bash "$WIB/agent-vm" version 2>&1)" "$AGENT_VM_VERSION"
233新增:case "$(winst_ln install)" in *"already linked"*) pass "install again: the launcher is recognised" ;; *) fail "install again: $(winst_ln install)" ;; esac
234新增:winst_ln uninstall >/dev/null
235新增:[ ! -e "$WIB/agent-vm" ] && pass "uninstall removes the launcher" || fail "uninstall left the launcher"
236新增:echo "mine" > "$WIB/agent-vm"
237新增:winst_ln uninstall >/dev/null
238新增:check "uninstall leaves a file of the user's" "$(cat "$WIB/agent-vm")" "mine"
239新增:rm -f "$WIB/agent-vm"
240新增:
241新增:# =============================================================================
242新增:section "Windows: doctor and CRLF files"
243新增:# =============================================================================
244新增:mkdir -p "$SB/winstate2"
245新增:printf "K='v'\n" > "$SB/winstate2/env"; chmod 644 "$SB/winstate2/env"
246新增:out="$( cd "$PROJ" && PATH="$SB/fakewin:$SB/fakeqemu:$PATH" AGENT_VM_STATE_DIR="$SB/winstate2" _agent_vm_doctor 2>&1 )"
247新增:case "$out" in
248新增: *"readable by other users"*) fail "doctor on Windows: warns about emulated permission bits" ;;
249新增: *"- env: 1 key(s)"*) pass "doctor on Windows: the env file without a permission verdict" ;;
250新增: *) fail "doctor on Windows, env: $out" ;;
251新增:esac
252新增:case "$out" in
253新增: *"'Windows Hypervisor Platform' feature"*"FeatureName:HypervisorPlatform"*) pass "doctor on Windows: names the hypervisor feature" ;;
254新增: *) fail "doctor on Windows, hypervisor: $out" ;;
255新增:esac
256新增:
257新增:# Git for Windows checks files out with CRLF by default: the CRs must not
258新增:# reach the shells in the VM.
259新增:printf '#!/bin/bash -e\r\necho hi\r\n' > "$SB/crlf-runtime.sh"
260新增:check "a CRLF shebang with an option: bash" "$(_agent_vm_runtime_interpreter "$SB/crlf-runtime.sh")" "bash"
261新增:mkdir -p "$SB/catlima"
262新增:printf '#!/bin/sh\ncat > "%s"\n' "$SB/crlf-captured" > "$SB/catlima/limactl"
263新增:chmod +x "$SB/catlima/limactl"
264新增:( PATH="$SB/catlima:$PATH"; _agent_vm_run_runtime vm "$PROJ" "$SB/crlf-runtime.sh" )
265新增:check "a CRLF runtime reaches the VM without CRs" \
266新增: "$(grep -c 'echo hi' "$SB/crlf-captured") $(od -c < "$SB/crlf-captured" | grep -c '\\r')" "1 0"
267新增:( AGENT_VM_STATE_DIR="$SB/crlf-state"; mkdir -p "$AGENT_VM_STATE_DIR"
268新增: printf 'A=1\r\n' > "$AGENT_VM_STATE_DIR/env"
269新增: printf 'B=2\r\n' > "$SB/crlf-proj.env"
270新增: AGENT_VM_PROJECT_ENV="$SB/crlf-proj.env" _agent_vm_env_payload "$PROJ" ) > "$SB/crlf-payload"
271新增:check "CRLF env files reach the VM without CRs" \
272新增: "$(grep -c '^[AB]=' "$SB/crlf-payload") $(od -c < "$SB/crlf-payload" | grep -c '\\r')" "2 0"
273新增:
274新增:# QEMU on Windows has no 9p: a mount type left unset is reverse-sshfs there,
275新增:# which only the builtin SFTP server with readonlyNames enforces. On any other
276新增:# host the same VM gets 9p. A limactl of its own, reporting QEMU and no type.
277新增:mkdir -p "$SB/qemulima" "$SB/qemulima-home/agent-vm-w"
278新增:printf '#!/bin/sh\n[ "$1" = list ] && echo "qemu <nil>"\nexit 0\n' > "$SB/qemulima/limactl"
279新增:chmod +x "$SB/qemulima/limactl"
280新增:echo 2.1.0 > "$SB/qemulima-home/agent-vm-w/lima-version"
281新增:enforced_on() { # <fake uname dir>
282新增: ( PATH="$1:$SB/qemulima:$PATH"; LIMA_HOME="$SB/qemulima-home"; _agent_vm_mount_is_host_enforced agent-vm-w; printf '%s' "$?" )
283新增:}
284新增:check "unset on QEMU, Windows host: reverse-sshfs, not enforced" "$(enforced_on "$SB/fakewin")" "1"
285新增:check "unset on QEMU, Linux host: 9p, enforced" "$(enforced_on "$SB/fakelinux")" "0"
286新增:
287新增:# =============================================================================
288新增:section "the fork release: asset names and checksums"
289新增:# =============================================================================
290新增:# The download offer has no Windows machine to try it on here, so the parts
291新增:# that do not touch the network are pinned: which files, for which arch, and
292新增:# the checksum gate that refuses a bad download.
293新增:mkdir -p "$SB/fakewinarm" "$SB/fakewinodd"
294新增:cat > "$SB/fakewinarm/uname" <<'STUB'
295新增:#!/bin/sh
296新增:case "$1" in
297新增: -s) echo "MINGW64_NT-10.0-26100" ;;
298新增: -m) echo "aarch64" ;;
299新增: *) echo "aarch64" ;;
300新增:esac
301新增:STUB
302新增:cat > "$SB/fakewinodd/uname" <<'STUB'
303新增:#!/bin/sh
304新增:case "$1" in
305新增: -s) echo "MINGW64_NT-10.0-26100" ;;
306新增: *) echo "riscv64" ;;
307新增:esac
308新增:STUB
309新增:chmod +x "$SB/fakewinarm/uname" "$SB/fakewinodd/uname"
310新增:check "x86_64 is AMD64" \
311新增: "$(PATH="$SB/fakewin:$PATH" _agent_vm_lima_fork_arch)" "AMD64"
312新增:check "aarch64 is ARM64" \
313新增: "$(PATH="$SB/fakewinarm:$PATH" _agent_vm_lima_fork_arch)" "ARM64"
314新增:if PATH="$SB/fakewinodd:$PATH" _agent_vm_lima_fork_arch >/dev/null 2>&1; then
315新增: fail "an architecture with no build should be refused"
316新增:else
317新增: pass "an architecture with no build is refused"
318新增:fi
319新增:# Both zips, spelled exactly as the release publishes them: the installer
320新增:# downloads these names, so a rename breaks it loudly.
321新增:check "the asset names for AMD64" \
322新增: "$(PATH="$SB/fakewin:$PATH" _agent_vm_lima_fork_files | tr '\n' ' ')" \
323新增: "lima-2.3.0-sylvinus.2-Windows-AMD64.zip lima-additional-guestagents-2.3.0-sylvinus.2-Windows-AMD64.zip "
324新增:check "the asset names for ARM64" \
325新增: "$(PATH="$SB/fakewinarm:$PATH" _agent_vm_lima_fork_files | tr '\n' ' ')" \
326新增: "lima-2.3.0-sylvinus.2-Windows-ARM64.zip lima-additional-guestagents-2.3.0-sylvinus.2-Windows-ARM64.zip "
327新增:# Every file downloaded, for either architecture, has a pinned checksum, of
328新增:# the pinned tag.
329新增:pinned_ok=yes
330新增:for a in "$SB/fakewin" "$SB/fakewinarm"; do
331新增: for f in $(PATH="$a:$PATH" _agent_vm_lima_fork_files); do
332新增: # A here-string, not a pipe: grep -q exits on the match, printf can then
333新增: # die of SIGPIPE, and pipefail fails the line.
334新增: grep -Eq "^[0-9a-f]{64} $f\$" <<< "$AGENT_VM_LIMA_FORK_SHA256" || pinned_ok="no: $f"
335新增: done
336新增:done
337新增:check "each zip has a pinned checksum" "$pinned_ok" "yes"
338新增:case "$(PATH="$SB/fakewin:$PATH" _agent_vm_lima_fork_release)" in
339新增: *"/releases/download/v2.3.0-sylvinus.2") pass "the release URL carries the fork tag" ;;
340新增: *) fail "the release URL does not carry the fork tag: $(PATH="$SB/fakewin:$PATH" _agent_vm_lima_fork_release)" ;;
341新增:esac
342新增:
343新增:mkdir -p "$SB/sums"
344新增:printf 'hello\n' > "$SB/sums/a.zip"
345新增:printf 'world\n' > "$SB/sums/b.zip"
346新增:if command -v sha256sum >/dev/null 2>&1; then
347新增: ( cd "$SB/sums" && sha256sum a.zip b.zip > SHA256SUMS )
348新增:else
349新增: ( cd "$SB/sums" && shasum -a 256 a.zip b.zip > SHA256SUMS )
350新增:fi
351新增:sums() { cat "$SB/sums/SHA256SUMS"; }
352新增:_agent_vm_sha256_sums_check "$(sums)" "$SB/sums" a.zip b.zip \
353新增: && pass "matching checksums verify" \
354新增: || fail "matching checksums do not verify"
355新增:printf 'tampered\n' > "$SB/sums/b.zip"
356新增:if _agent_vm_sha256_sums_check "$(sums)" "$SB/sums" a.zip b.zip >/dev/null 2>&1; then
357新增: fail "a tampered download verified"
358新增:else
359新增: pass "a tampered download is refused"
360新增:fi
361新增:# Binary mode marks the name with a *: `sha256sum -b`, and Git Bash's default.
362新增:printf 'hello\n' > "$SB/sums/c.zip"
363新增:printf '%s *c.zip\n' "$(_agent_vm_sha256 < "$SB/sums/c.zip" | cut -d' ' -f1)" >> "$SB/sums/SHA256SUMS"
364新增:_agent_vm_sha256_sums_check "$(sums)" "$SB/sums" c.zip \
365新增: && pass "a binary-mode (*) checksum line verifies" \
366新增: || fail "a binary-mode (*) checksum line does not verify"
367新增:if _agent_vm_sha256_sums_check "$(sums)" "$SB/sums" missing.zip >/dev/null 2>&1; then
368新增: fail "an unlisted file verified"
369新增:else
370新增: pass "an unlisted file is refused"
371新增:fi
新增tests/19-wsl.sh+48 −0看文件
@@ -0,0 +1,48 @@
1新增:# =============================================================================
2新增:section "WSL detection (nested virtualization is the user's job)"
3新增:# =============================================================================
4新增:# Fake uname binaries reporting WSL2 and WSL1 kernel releases. Used through
5新增:# PATH in subshells only, like the MINGW64 fake in 18-windows.sh.
6新增:mkdir -p "$SB/fakewsl2" "$SB/fakewsl1"
7新增:cat > "$SB/fakewsl2/uname" <<'STUB'
8新增:#!/bin/sh
9新增:case "$1" in
10新增: -s) echo "Linux" ;;
11新增: -r) echo "6.6.87.1-microsoft-standard-WSL2" ;;
12新增: *) echo "x86_64" ;;
13新增:esac
14新增:STUB
15新增:cat > "$SB/fakewsl1/uname" <<'STUB'
16新增:#!/bin/sh
17新增:case "$1" in
18新增: -s) echo "Linux" ;;
19新增: -r) echo "4.4.0-19041-Microsoft" ;;
20新增: *) echo "x86_64" ;;
21新增:esac
22新增:STUB
23新增:chmod +x "$SB/fakewsl2/uname" "$SB/fakewsl1/uname"
24新增:
25新增:check "WSL2 kernel release detected" \
26新增: "$(PATH="$SB/fakewsl2:$PATH" _agent_vm_wsl_version)" "2"
27新增:check "WSL1 kernel release detected" \
28新增: "$(PATH="$SB/fakewsl1:$PATH" _agent_vm_wsl_version)" "1"
29新增:check "plain Linux is not WSL" "$(_agent_vm_wsl_version)" ""
30新增:
31新增:# helpers.sh stubs _agent_vm_check_linux_prereqs (the machine running the
32新增:# tests has no /dev/kvm); restore the real one to exercise the hint below.
33新增:. "$SELF_DIR/lib/host.sh"
34新增:if [[ ! -e /dev/kvm ]]; then
35新增: wsl_hint="$(PATH="$SB/fakewsl2:$PATH" _agent_vm_check_linux_prereqs 2>&1)"
36新增: check "WSL2 without KVM fails (exit 1)" "$?" "1"
37新增: case "$wsl_hint" in
38新增: *nested*virtualization*) pass "the failure points at nested virtualization" ;;
39新增: *) fail "the failure does not mention nested virtualization: $wsl_hint" ;;
40新增: esac
41新增: wsl_hint="$(PATH="$SB/fakewsl1:$PATH" _agent_vm_check_linux_prereqs 2>&1)"
42新增: case "$wsl_hint" in
43新增: *WSL1*) pass "the failure names WSL1 and the upgrade" ;;
44新增: *) fail "the failure does not name WSL1: $wsl_hint" ;;
45新增: esac
46新增:else
47新增: pass "/dev/kvm exists on this machine: missing-KVM hints not exercised"
48新增:fi
新增tests/20-project-files.sh+181 −0看文件
@@ -0,0 +1,181 @@
1新增:# =============================================================================
2新增:section "project files: never read on the host through a symlink"
3新增:# =============================================================================
4新增:# The VM can write the project, and make .agent-vm.env or
5新增:# .agent-vm.runtime.sh a symlink to any file of the user's. The host used to
6新增:# read both with a plain `<` on every start and hand the content to the VM:
7新增:# `ln -s ~/.ssh/id_ed25519 .agent-vm.env` got the key on the next command.
8新增:# Uses the recording limactl of 11-recorded-commands.sh.
9新增:SECRET="$SB/host-secret"
10新增:printf 'TOPSECRET=leaked\n' > "$SECRET"
11新增:PF="$SB/pf"; mkdir -p "$PF"
12新增:PFV="$(_agent_vm_name "$PF")"
13新增:pf_rec() {
14新增: : > "$REC"; : > "$SB/pf-stdin"
15新增: ( cd "$PF" || exit 1
16新增: export AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_VM="$PFV" AGENT_VM_TEST_STDIN="$SB/pf-stdin"
17新增: agent-vm "$@" </dev/null 2>&1 )
18新增:}
19新增:# Regular files only: the planted links themselves point at the secret, and
20新增:# some greps (busybox) follow links when recursing.
21新增:leaked() {
22新增: grep -q TOPSECRET <<< "$({ cat "$SB/pf-stdin"; find "$PF" -type f -exec cat {} +; } 2>/dev/null)" \
23新增: && echo leaked || echo no
24新增:}
25新增:
26新增:if [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
27新增: ln -s "$SECRET" "$PF/.agent-vm.env"
28新增: ln -s "$SECRET" "$PF/.agent-vm.runtime.sh"
29新增: AGENT_VM_TEST_RUNTIME_FOUND=1 pf_rec run true >/dev/null
30新增: check "a symlinked env or runtime: nothing of the target reaches the VM" "$(leaked)" "no"
31新增: grep -qF "$PF/.agent-vm.env" "$REC" && pass "the env file is handed to the VM by its path" \
32新增: || fail "the env file path is not passed to the VM: $(grep -A3 'agent-vm.env' "$REC")"
33新增: grep -q "^shell --workdir $PF $PFV zsh -lc" "$REC" && grep -qF "$PF/.agent-vm.runtime.sh" "$REC" \
34新增: && pass "the runtime script is run by its path in the VM" || fail "runtime: $(grep '^shell' "$REC")"
35新增: # The same through a relocated path whose directory is a link.
36新增: mkdir -p "$SB/pf-outside"; cp "$SECRET" "$SB/pf-outside/env"
37新增: ln -s "$SB/pf-outside" "$PF/.mytool"
38新增: AGENT_VM_PROJECT_ENV=.mytool/env AGENT_VM_PROJECT_RUNTIME=.mytool/env pf_rec run true >/dev/null
39新增: check "a symlinked directory on the way: nothing reaches the VM" "$(leaked)" "no"
40新增: rm -rf "$PF/.mytool"
41新增: # The project named another way: by its real path while it is used through
42新增: # a link (/tmp and /private/tmp on macOS). Still the project, by where the
43新增: # path leads, not how it is spelled.
44新增: ln -s "$PF" "$SB/pf-link"
45新增: pf_link() {
46新增: ( cd "$SB/pf-link" || exit 1
47新增: export AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_VM="$(_agent_vm_name "$SB/pf-link")" AGENT_VM_TEST_STDIN="$SB/pf-stdin"
48新增: : > "$REC"; : > "$SB/pf-stdin"
49新增: AGENT_VM_PROJECT_ENV="$PF/.agent-vm.env" AGENT_VM_PROJECT_RUNTIME="$PF/.agent-vm.runtime.sh" agent-vm "$@" </dev/null 2>&1 )
50新增: }
51新增: if [[ -n "$AGENT_VM_HAS_PERL" ]]; then
52新增: check "the real path of a linked project: project-env get refuses the link" \
53新增: "$(pf_link project-env get TOPSECRET; echo "rc=$?")" "$(printf '%s\n%s\n%s' "Error: $SB/pf-link/.agent-vm.env is a symlink, is reached through one, or is not a regular file." " agent-vm follows no link in the project, which the VM can write. Replace it with a plain file." "rc=2")"
54新增: pf_link project-env set X 1 >/dev/null
55新增: check "and project-env set leaves the link alone" "$([ -L "$PF/.agent-vm.env" ] && echo link || echo replaced)" "link"
56新增: else
57新增: printf ' skip project-env through a linked project (perl is not installed)\n'
58新增: fi
59新增: AGENT_VM_TEST_RUNTIME_FOUND=1 pf_link run true >/dev/null
60新增: check "and nothing of the target reaches the VM" "$(leaked)" "no"
61新增: grep -qF "$SB/pf-link/.agent-vm.env" "$REC" && pass "the env file is handed to the VM by its path there" \
62新增: || fail "linked project: env path not passed to the VM"
63新增: check "a relative path is found by where it leads" \
64新增: "$(_agent_vm_project_rel "$SB/pf-link" "$PF/sub/f"):$(_agent_vm_project_rel "$PF" "$SB/pf-link/f"):$(_agent_vm_project_rel "$PF" "$SB/other/f" || echo out)" \
65新增: "sub/f:f:out"
66新增: # A link of the user's to a folder IN the project, which the VM then makes
67新增: # a link out of it: still the project, not where the VM's link leads.
68新增: mkdir -p "$PF/sub" "$SB/pf-elsewhere"; ln -s "$PF/sub" "$SB/pf-sublink"
69新增: check "a user's link into the project: in it" "$(_agent_vm_project_rel "$PF" "$SB/pf-sublink/.env")" "sub/.env"
70新增: rmdir "$PF/sub"; ln -s "$SB/pf-elsewhere" "$PF/sub"
71新增: check "and once the VM swaps a link in below it: still in it" "$(_agent_vm_project_rel "$PF" "$SB/pf-sublink/.env")" "sub/.env"
72新增: check "a relative link outside, through .., is followed" \
73新增: "$(ln -s "../pf-link" "$SB/pf-elsewhere/up"; _agent_vm_project_rel "$PF" "$SB/pf-elsewhere/up/y")" "y"
74新增: rm -rf "$SB/pf-sublink" "$PF/sub" "$SB/pf-elsewhere"
75新增: rm -f "$SB/pf-link" "$PF/.agent-vm.env" "$PF/.agent-vm.runtime.sh"
76新增:else
77新增: printf ' skip symlinked project files (ln -s plants copies on this machine)\n'
78新增:fi
79新增:
80新增:# Kept outside the project by an absolute AGENT_VM_PROJECT_ENV, the file is
81新增:# the user's own, and the host still pushes it.
82新增:printf 'OUTSIDE=1\n' > "$SB/pf-own.env"
83新增:AGENT_VM_PROJECT_ENV="$SB/pf-own.env" pf_rec run true >/dev/null
84新增:check "an env file outside the project is pushed by the host" "$(grep -c '^OUTSIDE=1$' "$SB/pf-stdin")" "1"
85新增:# So is one a relative path takes out of the project: the VM cannot see it.
86新增:AGENT_VM_PROJECT_ENV=../pf-own.env pf_rec run true >/dev/null
87新增:check "a relative path out of the project (../) is pushed by the host" "$(grep -c '^OUTSIDE=1$' "$SB/pf-stdin")" "1"
88新增:check "and named without the detour" \
89新增: "$(cd "$PF" && AGENT_VM_PROJECT_ENV=sub/../../pf-own.env _agent_vm_project_env_file) $(AGENT_VM_PROJECT_RUNTIME=/a/./b/../rt.sh _agent_vm_project_runtime_path "$PF")" \
90新增: "$SB/pf-own.env /a/rt.sh"
91新增:check "project-env reads it there" \
92新增: "$( cd "$PF" && AGENT_VM_PROJECT_ENV=../pf-own.env AGENT_VM_STATE_DIR="$SB/pf-state" bash "$AGENT_VM_SH" project-env get OUTSIDE )" "1"
93新增:rm -f "$SB/pf-own.env"
94新增:# A runtime the VM does not find is not run.
95新增:pf_rec run true >/dev/null
96新增:grep -q "zsh -lc.*\.agent-vm\.runtime\.sh" "$REC" && fail "a runtime the VM did not find was run" \
97新增: || pass "no runtime in the project: nothing run"
98新增:
99新增:section "project files: what the VM does with them"
100新增:# A limactl that runs the guest's command here, with its own HOME: the
101新增:# scripts that read the project's files in the VM, run for real.
102新增:GH="$SB/guest-home"; mkdir -p "$GH" "$SB/localvm"
103新增:cat > "$SB/localvm/limactl" <<STUB
104新增:#!/usr/bin/env bash
105新增:[ "\$1" = shell ] || exit 0
106新增:shift
107新增:wd=""
108新增:[ "\$1" = --workdir ] && { wd="\$2"; shift 2; }
109新增:shift
110新增:[ -z "\$wd" ] || cd "\$wd"
111新增:HOME="$GH" exec "\$@"
112新增:STUB
113新增:chmod +x "$SB/localvm/limactl"
114新增:printf 'B=2\r\nA=project\r\n' > "$PF/.agent-vm.env"
115新增:: > "$PF/.agent-vm.runtime.sh"
116新增:out="$(PATH="$SB/localvm:$PATH" _agent_vm_push_env_and_probe vm "$PF" "A=shared" "$PF/.agent-vm.env" "$PF/.agent-vm.runtime.sh")"
117新增:check "the VM writes the shared payload, then the project's file, without CRs" \
118新增: "$(od -c < "$GH/.agent-vm.env" | grep -c '\\r') $(tr '\n' ' ' < "$GH/.agent-vm.env")" "0 A=shared B=2 A=project "
119新增:check "and says it did, and that the runtime is there" "$(printf '%s' "$out" | tr '\n' ' ')" "env-ok runtime-found"
120新增:if _agent_vm_on_windows; then
121新增: printf ' skip the guest env file is private (permission bits are emulated on Windows)\n'
122新增:else
123新增: check "the guest env file is private" "$(ls -l "$GH/.agent-vm.env" | cut -c2-10)" "rw-------"
124新增:fi
125新增:rm -f "$PF/.agent-vm.runtime.sh"
126新增:out="$(PATH="$SB/localvm:$PATH" _agent_vm_push_env_and_probe vm "$PF" "" "$PF/.agent-vm.env" "$PF/.agent-vm.runtime.sh")"
127新增:check "no runtime there: not found" "$out" "env-ok"
128新增:if command -v zsh >/dev/null 2>&1; then
129新增: printf '#!/usr/bin/env bash\r\necho "ran:${BASH_VERSION:+bash}" > "$HOME/rt-out"\r\n' > "$PF/.agent-vm.runtime.sh"
130新增: PATH="$SB/localvm:$PATH" _agent_vm_run_project_runtime vm "$PF" "$PF/.agent-vm.runtime.sh" >/dev/null 2>&1
131新增: check "the VM runs the runtime by its path, with its shebang, without CRs" "$(cat "$GH/rt-out" 2>/dev/null)" "ran:bash"
132新增:else
133新增: printf ' skip the runtime run in the VM (zsh is not installed)\n'
134新增:fi
135新增:rm -f "$PF/.agent-vm.env" "$PF/.agent-vm.runtime.sh"
136新增:
137新增:section "project-env: no symlink followed on the host"
138新增:# `project-env set` read the file through a link and wrote the target's
139新增:# content back into the project, where the VM reads it.
140新增:pfe() { ( cd "$PF" && AGENT_VM_STATE_DIR="$SB/pf-state" bash "$AGENT_VM_SH" project-env "$@" ); }
141新增:if ! command -v perl >/dev/null 2>&1; then
142新增: printf ' skip project-env through symlinks (perl is not installed)\n'
143新增:elif [[ -n "$AGENT_VM_HAS_SYMLINKS" ]]; then
144新增: ln -s "$SECRET" "$PF/.agent-vm.env"
145新增: for verb in "set K v" "unset TOPSECRET" "get TOPSECRET" "has TOPSECRET" "list"; do
146新增: # eval: zsh does not split an unquoted $verb into words.
147新增: out="$(eval "pfe $verb" 2>&1)"
148新增: case "$?:$out" in
149新增: 2:*"is a symlink, is reached through one"*) pass "project-env $verb on a symlink: refused" ;;
150新增: *) fail "project-env $verb on a symlink: $out" ;;
151新增: esac
152新增: done
153新增: check "the link is left, its target untouched, nothing copied" \
154新增: "$([ -L "$PF/.agent-vm.env" ] && echo link) $(cat "$SECRET") $(leaked)" "link TOPSECRET=leaked no"
155新增: rm -f "$PF/.agent-vm.env"
156新增: # A directory on the way that is a link: nothing read, nothing written there.
157新增: mkdir -p "$SB/pf-outside"; printf 'TOPSECRET=leaked\n' > "$SB/pf-outside/env"
158新增: ln -s "$SB/pf-outside" "$PF/.mytool"
159新增: out="$(AGENT_VM_PROJECT_ENV=.mytool/env pfe set K v 2>&1)"
160新增: check "set through a symlinked directory: refused" "$?" "2"
161新增: check "and nothing is written there" "$(ls -A "$SB/pf-outside" | tr '\n' ' ')" "env "
162新增: rm -rf "$PF/.mytool" "$SB/pf-outside"
163新增:fi
164新增:if command -v perl >/dev/null 2>&1; then
165新增: # A FIFO would hang a plain read.
166新增: if mkfifo "$PF/.agent-vm.env" 2>/dev/null; then
167新增: out="$(pfe get K 2>&1)"
168新增: check "a FIFO: refused, not waited on" "$?" "2"
169新增: rm -f "$PF/.agent-vm.env"
170新增: fi
171新增: # The ordinary way still works, in a directory created on the way.
172新增: AGENT_VM_PROJECT_ENV=.mytool/sub/env pfe set K "it's" >/dev/null 2>&1
173新增: check "a relocated file in new directories: written and read back" \
174新增: "$(AGENT_VM_PROJECT_ENV=.mytool/sub/env pfe get K)" "it's"
175新增: if ! _agent_vm_on_windows; then
176新增: check "and it is mode 600" "$(ls -l "$PF/.mytool/sub/env" | cut -c2-10)" "rw-------"
177新增: fi
178新增: check "no temporary file is left" "$(ls -A "$PF/.mytool/sub")" "env"
179新增: rm -rf "$PF/.mytool"
180新增:fi
181新增:rm -rf "$PF"
新增tests/21-scratch.sh+148 −0看文件
@@ -0,0 +1,148 @@
1新增:# =============================================================================
2新增:section "--scratch: a new VM sharing nothing, deleted on exit"
3新增:# =============================================================================
4新增:# The recording limactl of 11-recorded-commands.sh lists one VM, so the
5新增:# scratch name is fixed here, and the VM exists once `clone` made it.
6新增:SCR="agent-vm-proj-scratch-00000000"
7新增:SCR_CLONED="$SB/scr-cloned"
8新增:sc() {
9新增: : > "$REC"
10新增: rm -f "$REC.stopped" "$SCR_CLONED"
11新增: ( cd "${SC_DIR:-$PROJ}" || exit 1
12新增: export AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_VM="$SCR" AGENT_VM_TEST_PROTECTS="$PROTECTS" AGENT_VM_TEST_CLONED="$SCR_CLONED"
13新增: _agent_vm_scratch_name() { echo "$SCR"; }
14新增: agent-vm "$@" </dev/null 2>&1 )
15新增:}
16新增:check "a scratch name is the folder's, marked, with 8 random hex digits" \
17新增: "$(_agent_vm_scratch_name /work/My_App | sed 's/[0-9a-f]\{8\}$/RAND/')" "agent-vm-My-App-scratch-RAND"
18新增:check "a long folder name is cut, and a name of symbols still makes a valid one" \
19新增: "$(_agent_vm_scratch_name /work/a-very-long-folder-name-indeed | sed 's/[0-9a-f]\{8\}$/RAND/') $(_agent_vm_scratch_name /work/___ | sed 's/[0-9a-f]\{8\}$/RAND/')" \
20新增: "agent-vm-a-very-long-folder-n-scratch-RAND agent-vm-project-scratch-RAND"
21新增:[ "$(_agent_vm_scratch_name /w/x)" != "$(_agent_vm_scratch_name /w/x)" ] \
22新增: && pass "two scratch runs in one folder get two VMs" || fail "a scratch name repeats"
23新增:
24新增:# Made, given no share at all, used, deleted. The folder's own VM is never
25新增:# touched.
26新增:out="$(sc --scratch run true)"
27新增:rec_has "clone $AGENT_VM_TEMPLATE $SCR" && pass "a new VM, cloned from the base" || fail "not cloned: $(head -3 "$REC")"
28新增:rec_has "edit $SCR --set del(.mountType) | .mounts = []" && pass "no share at all" || fail "shares: $(grep '^edit' "$REC")"
29新增:rec_has "agent-vm-write-probe" && pass "the command runs" || fail "the command did not run: $out"
30新增:d="$(grep -n "^delete $SCR" "$REC" | head -1 | cut -d: -f1)"
31新增:p="$(grep -n "agent-vm-write-probe" "$REC" | tail -1 | cut -d: -f1)"
32新增:if [ -n "$d" ] && [ -n "$p" ] && [ "$d" -gt "$p" ]; then pass "then the VM is deleted"; else fail "deleted at '${d:-never}': $out"; fi
33新增:case "$out" in *"Deleting scratch VM '$SCR'"*) pass "and it says so" ;; *) fail "no notice: $out" ;; esac
34新增:grep -Eq "^(stop|delete|edit|start) $PV( |$)" "$REC" && fail "the folder's own VM was touched" || pass "the folder's own VM is left alone"
35新增:[ -e "$(_agent_vm_scratch_marker "$SCR")" ] && fail "the run's record outlived it" || pass "nothing left recorded"
36新增:
37新增:# Before the deletion, asked when it can be: a no opens a shell in the VM,
38新增:# and asks again on its exit. Yes, or an answer cut short, deletes. ANSWERS
39新增:# are the replies in order, in a file: each question is asked in a subshell.
40新增:answers() { printf '%s\n' "$@" > "$SB/scr-answers"; echo 0 > "$SB/scr-asked"; }
41新增:ask_stubs='_agent_vm_can_ask() { return 0; }
42新增: _agent_vm_ask_yn() { n=$(( $(cat "$SB/scr-asked") + 1 )); echo "$n" > "$SB/scr-asked"; sed -n "${n}p" "$SB/scr-answers"; }'
43新增:shells() { grep -c "^shell --workdir $PROJ $SCR zsh -l$" "$REC"; }
44新增:answers 0 1
45新增:out="$( eval "$ask_stubs"; sc --scratch run true )"
46新增:check "no, then yes: one shell in the VM, then the deletion" "$(shells) $(cat "$SB/scr-asked")" "1 2"
47新增:s="$(grep -n "zsh -l$" "$REC" | head -1 | cut -d: -f1)"; d="$(grep -n "^delete $SCR" "$REC" | head -1 | cut -d: -f1)"
48新增:[ -n "$s" ] && [ -n "$d" ] && [ "$s" -lt "$d" ] && pass "the shell comes before the deletion" || fail "shell at '${s:-none}', delete at '${d:-none}'"
49新增:case "$out" in *"Type 'exit' to be asked again"*) pass "the shell says how to come back" ;; *) fail "no shell notice: $out" ;; esac
50新增:answers 0 0 1
51新增:( eval "$ask_stubs"; sc --scratch run true ) >/dev/null
52新增:check "asked again after each shell" "$(shells)" "2"
53新增:answers 1
54新增:( eval "$ask_stubs"; sc --scratch run true ) >/dev/null
55新增:check "yes: deleted, no shell" "$(shells) $(grep -c "^delete $SCR" "$REC")" "0 1"
56新增:answers ""
57新增:( eval "$ask_stubs"; sc --scratch run true ) >/dev/null
58新增:check "an answer cut short deletes" "$(shells) $(grep -c "^delete $SCR" "$REC")" "0 1"
59新增:answers 0
60新增:( eval "$ask_stubs"; AGENT_VM_TEST_EDIT_FAIL=1 sc --scratch run true ) >/dev/null
61新增:check "a failed start asks nothing, and deletes" "$(cat "$SB/scr-asked") $(shells)" "0 0"
62新增:out="$( _agent_vm_can_ask() { return 1; }; sc --scratch run true )"
63新增:check "no terminal: deleted, no shell" "$(shells) $(grep -c "^delete $SCR" "$REC")" "0 1"
64新增:
65新增:# Nothing is shared, so none of the share questions: here a Lima without
66新增:# readonlyNames, no terminal, and the questions on.
67新增:rm -f "$PROTECTS"
68新增:out="$( unset AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS; _agent_vm_can_ask() { return 1; }; sc --scratch run true )"
69新增:case "$out" in *"Aborted"*|*"Lima cannot keep .git read-only"*) fail "a share question for a VM that shares nothing: $out" ;; *) pass "no share question" ;; esac
70新增:rec_has "agent-vm-write-probe" && pass "and the command runs" || fail "did not run: $out"
71新增:
72新增:# Nothing of the project goes in: not its env file, not its runtime script.
73新增:# The shared env does.
74新增:printf 'SHARED_KEY=shared\n' > "$HOME/.agent-vm/env"
75新增:printf 'PROJECT_KEY=project\n' > "$PROJ/.agent-vm.env"
76新增:printf '#!/bin/sh\necho project-runtime\n' > "$PROJ/.agent-vm.runtime.sh"
77新增:: > "$SB/scr-stdin"
78新增:out="$(AGENT_VM_TEST_STDIN="$SB/scr-stdin" sc --scratch run true)"
79新增:grep -q 'SHARED_KEY=shared' "$SB/scr-stdin" && pass "the shared env goes in" || fail "shared env missing: $(cat "$SB/scr-stdin")"
80新增:grep -q 'PROJECT_KEY' "$SB/scr-stdin" && fail "the project's env file went in" || pass "the project's env file stays out"
81新增:grep -q 'project-runtime\|\.agent-vm\.runtime\.sh' "$REC" "$SB/scr-stdin" && fail "the project's runtime script went in" || pass "the project's runtime script stays out"
82新增:case "$out" in *"project runtime"*) fail "a project runtime ran: $out" ;; *) pass "no project runtime run" ;; esac
83新增:# Nor one kept outside the project, which a start with a share reads on the
84新增:# host.
85新增:printf 'OUTSIDE_KEY=outside\n' > "$SB/outside.env"
86新增:: > "$SB/scr-stdin"
87新增:AGENT_VM_PROJECT_ENV="$SB/outside.env" AGENT_VM_TEST_STDIN="$SB/scr-stdin" sc --scratch run true >/dev/null
88新增:grep -q 'OUTSIDE_KEY' "$SB/scr-stdin" && fail "a project env file outside the project went in" || pass "nor one outside the project"
89新增:rm -f "$HOME/.agent-vm/env" "$PROJ/.agent-vm.env" "$PROJ/.agent-vm.runtime.sh" "$SB/outside.env"
90新增:
91新增:# The home directory is refused as a share; with nothing shared, it is fine.
92新增:out="$(SC_DIR="$HOME" sc --scratch run true)"
93新增:case "$out" in *"refusing to share"*) fail "--scratch refused the home directory: $out" ;; *) pass "--scratch runs from the home directory" ;; esac
94新增:
95新增:# Nothing to reset, nothing to make read-only.
96新增:for o in --reset --readonly; do
97新增: out="$(sc --scratch "$o" run true)"
98新增: case "$out" in *"--reset and --readonly do not go with it"*) pass "--scratch $o is refused" ;; *) fail "--scratch $o: $out" ;; esac
99新增:done
100新增:
101新增:# A failed start still deletes what it made.
102新增:out="$(AGENT_VM_TEST_EDIT_FAIL=1 sc --scratch run true)"
103新增:rec_has "delete $SCR" && pass "a failed start deletes the VM" || fail "a failed start left the VM: $out"
104新增:[ -e "$(_agent_vm_scratch_marker "$SCR")" ] && fail "a failed start left its record" || pass "and its record"
105新增:
106新增:# A scratch VM whose folder cannot be written is an error, never a repair:
107新增:# the repair of a VM with a share mounts the project.
108新增:out="$(AGENT_VM_TEST_RO=1 sc --scratch run true)"
109新增:case "$out" in *"is not writable in VM '$SCR'"*) pass "a scratch folder that cannot be written: an error" ;; *) fail "unwritable scratch folder: $out" ;; esac
110新增:grep -q "\"location\"" <<< "$(grep "^edit $SCR" "$REC")" && fail "the project was mounted into the scratch VM: $(grep "^edit $SCR" "$REC")" \
111新增: || pass "and the project is never mounted into it"
112新增:rec_has "delete $SCR" && pass "and the VM is deleted" || fail "not deleted: $out"
113新增:
114新增:# Only names a scratch run makes are deleted unasked.
115新增:mkdir -p "$AGENT_VM_STATE_DIR"
116新增:echo 999999 > "$AGENT_VM_STATE_DIR/.agent-vm-scratch-$AGENT_VM_TEMPLATE"
117新增:echo 999999 > "$AGENT_VM_STATE_DIR/.agent-vm-scratch-agent-vm-proj-1a2b3c4d"
118新增:check "a record that does not name a scratch VM is not a leftover" "$(_agent_vm_scratch_leftovers)" ""
119新增:rm -f "$AGENT_VM_STATE_DIR/.agent-vm-scratch-$AGENT_VM_TEMPLATE" "$AGENT_VM_STATE_DIR/.agent-vm-scratch-agent-vm-proj-1a2b3c4d"
120新增:
121新增:# A run killed outright leaves a record with a pid that is gone: the next
122新增:# scratch run deletes that VM. One whose run still goes on is left alone.
123新增:mkdir -p "$AGENT_VM_STATE_DIR"
124新增:dead_pid=999999; while kill -0 "$dead_pid" 2>/dev/null; do dead_pid=$((dead_pid - 1)); done
125新增:printf '%s\n' "$dead_pid" > "$(_agent_vm_scratch_marker agent-vm-old-scratch-11111111)"
126新增:printf '%s\n' "$$" > "$(_agent_vm_scratch_marker agent-vm-live-scratch-22222222)"
127新增:check "leftovers: the run that is gone, not the one that goes on" "$(_agent_vm_scratch_leftovers)" "agent-vm-old-scratch-11111111"
128新增:case "$(rec doctor)" in *"warn scratch VM agent-vm-old-scratch-11111111 was left by a run that did not finish"*) pass "doctor: a leftover is a warning" ;; *) fail "doctor: no leftover warning" ;; esac
129新增:out="$(sc --scratch run true)"
130新增:rec_has "delete agent-vm-old-scratch-11111111" && pass "the next scratch run deletes the leftover" || fail "leftover not deleted: $out"
131新增:rec_has "delete agent-vm-live-scratch-22222222" && fail "a scratch VM still in use was deleted" || pass "one still in use is left alone"
132新增:rm -f "$(_agent_vm_scratch_marker agent-vm-live-scratch-22222222)"
133新增:
134新增:# The run's Ctrl-C trap does not outlive it: agent-vm is a shell function
135新增:# too, and the user's own trap comes back.
136新增:trap_after="$( cd "$PROJ" && export AGENT_VM_TEST_REC="$REC" AGENT_VM_TEST_VM="$SCR" AGENT_VM_TEST_CLONED="$SCR_CLONED"
137新增: _agent_vm_scratch_name() { echo "$SCR"; }
138新增: trap 'echo mine' INT
139新增: agent-vm --scratch run true </dev/null >/dev/null 2>&1
140新增: trap )"
141新增:case "$trap_after" in *"echo mine"*) pass "the user's INT trap is back after a scratch run" ;; *) fail "INT trap after a scratch run: '$trap_after'" ;; esac
142新增:
143新增:# The flag comes right after the command's name too, and never reaches it.
144新增:out="$(sc run --scratch true)"
145新增:rec_has "edit $SCR --set del(.mountType) | .mounts = []" && pass "run --scratch: taken" || fail "run --scratch not taken: $out"
146新增:grep -q -- "--scratch" <<< "$(grep -v '^edit' "$REC")" && fail "--scratch reached the command" || pass "and it does not reach the command"
147新增:case "$(agent-vm --scratch stop 2>&1)" in *"is an option for the commands that start a VM"*) pass "--scratch before 'stop' is refused" ;; *) fail "--scratch stop accepted" ;; esac
148新增:_agent_vm_cleanup_state "$SCR"
新增tests/helpers.sh+119 −0看文件
@@ -0,0 +1,119 @@
1新增:AGENT_VM_SH="${AGENT_VM_SH:-$SELF_DIR/agent-vm.sh}"
2新增:SETUP_SH="${SETUP_SH:-$SELF_DIR/agent-vm.setup.sh}"
3新增:
4新增:FAIL=0
5新增:PASSED=0
6新增:pass() { PASSED=$((PASSED + 1)); printf ' ok %s\n' "$1"; }
7新增:fail() { FAIL=$((FAIL + 1)); printf ' FAIL %s\n' "$1"; }
8新增:check() {
9新增: if [ "$2" = "$3" ]; then pass "$1"
10新增: else fail "$1"; printf ' expected: %s\n actual: %s\n' "$3" "$2"; fi
11新增:}
12新增:section() { printf '\n%s\n' "$1"; }
13新增:
14新增:SB="$(mktemp -d)"
15新增:# Physical path: the temp dir itself is reached through a link on some
16新增:# machines (macOS /private, msys mounts), and tests compare $SB against paths
17新增:# the tools resolve themselves (git top-level, script dirs, readlink). Two
18新增:# spellings of one directory never match, so settle on one here.
19新增:SB="$(CDPATH= cd -P -- "$SB" >/dev/null && pwd)"
20新增:trap 'rm -rf "$SB"' EXIT
21新增:export HOME="$SB/home"
22新增:# git's config from this sandbox only: with XDG_CONFIG_HOME or
23新增:# GIT_CONFIG_GLOBAL set, `git config --global` would read and write the real
24新增:# one. safe.bareRepository is set, as on a machine agent-vm set up, so a start
25新增:# does not stop on it; the tests of that question use a stub git.
26新增:unset XDG_CONFIG_HOME GIT_CONFIG_GLOBAL
27新增:export GIT_CONFIG_NOSYSTEM=1
28新增:mkdir -p "$HOME"
29新增:printf '[safe]\n\tbareRepository = explicit\n' > "$HOME/.gitconfig"
30新增:# The stub Lima has no readonlyNames unless a test says so, and a VM started
31新增:# on it asks before going on (see _agent_vm_confirm_unsafe). Answered yes here;
32新增:# the tests of those questions unset it.
33新增:export AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1
34新增:# A real directory: `name` and `info` resolve their argument and reject a
35新增:# path that does not exist, so the tests cannot use a made-up one.
36新增:PROJ="$SB/proj"
37新增:mkdir -p "$HOME" "$SB/bin" "$PROJ"
38新增:
39新增:# --- stubs --------------------------------------------------------------------
40新增:# One base VM plus one project VM, running, 4 CPUs / 8 GiB / 32 GiB.
41新增:# `shell` dumps stdin so we can assert on what setup pipes into the VM.
42新增:# AGENT_VM_TEST_EXTRA_VM adds one more name to the inventory, so a test can
43新增:# make the VM of an arbitrary directory exist. AGENT_VM_TEST_CALLS records the
44新增:# destructive calls, to assert which VM they hit.
45新增:cat > "$SB/bin/limactl" <<'STUB'
46新增:#!/usr/bin/env bash
47新增:case "$1" in
48新增: list)
49新增: case "$*" in
50新增: *"{{.Name}}|{{.CPUs}}|{{.Memory}}|{{.Disk}}"*)
51新增: echo "agent-vm-base|4|8589934592|34359738368"
52新增: echo "agent-vm-proj-deadbeef|4|8589934592|34359738368" ;;
53新增: *"{{.Name}} {{.Status}}"*)
54新增: echo "agent-vm-base Stopped"
55新增: echo "agent-vm-proj-deadbeef Running" ;;
56新增: *-q*)
57新增: { echo "agent-vm-base"
58新增: echo "agent-vm-proj-deadbeef"
59新增: [ -n "${AGENT_VM_TEST_EXTRA_VM:-}" ] && echo "$AGENT_VM_TEST_EXTRA_VM"
60新增: } | if [ -s "${AGENT_VM_TEST_DELETED:-}" ]; then grep -vxF -f "$AGENT_VM_TEST_DELETED"; else cat; fi ;;
61新增: esac ;;
62新增: shell)
63新增: cat > "${AGENT_VM_TEST_CAPTURE:-/dev/null}"
64新增: if [ -n "${AGENT_VM_TEST_SHELL_FAIL:-}" ]; then echo "E: boom" >&2; exit 1; fi ;;
65新增: start)
66新增: echo 'time="2026-01-01T00:00:00Z" level=info msg="Attempting to download the image" arch=aarch64' >&2
67新增: if [ -n "${AGENT_VM_TEST_START_FAIL:-}" ]; then echo 'level=fatal msg="no start"' >&2; exit 1; fi ;;
68新增: stop) echo "$*" >> "${AGENT_VM_TEST_CALLS:-/dev/null}" ;;
69新增: # With AGENT_VM_TEST_DELETED (a file), a deleted VM leaves the listing.
70新增: delete)
71新增: echo "$*" >> "${AGENT_VM_TEST_CALLS:-/dev/null}"
72新增: [ -z "${AGENT_VM_TEST_DELETED:-}" ] || echo "$2" >> "$AGENT_VM_TEST_DELETED" ;;
73新增: *) : ;;
74新增:esac
75新增:exit 0
76新增:STUB
77新增:chmod +x "$SB/bin/limactl"
78新增:
79新增:# Minimal images (and some Linux hosts) have no shasum; _agent_vm_name needs one.
80新增:if ! command -v shasum >/dev/null 2>&1; then
81新增: cat > "$SB/bin/shasum" <<'STUB'
82新增:#!/usr/bin/env bash
83新增:if command -v sha256sum >/dev/null 2>&1; then sha256sum | cut -d' ' -f1
84新增:else echo "0000000000000000"; fi
85新增:STUB
86新增: chmod +x "$SB/bin/shasum"
87新增:fi
88新增:export PATH="$SB/bin:$PATH"
89新增:
90新增:# shellcheck source=./agent-vm.sh
91新增:source "$AGENT_VM_SH"
92新增:
93新增:# The start of a mounts JSON entry for host path <path> mounted at <mount point>
94新增:# (default: the same path), as _agent_vm_build_mounts_json writes it: the
95新增:# location in the host's own spelling, C:/... on Windows.
96新增:mnt() { printf '"location": "%s", "mountPoint": "%s"' "$(_agent_vm_host_path "$1")" "${2:-$1}"; }
97新增:
98新增:# The machine running the tests has no /dev/kvm and no QEMU; those checks are
99新增:# not under test (lib/host.sh covers them, tests/18-windows.sh the branches).
100新增:_agent_vm_check_linux_prereqs() { return 0; }
101新增:_agent_vm_check_windows_prereqs() { return 0; }
102新增:
103新增:# 0 when this machine makes real symlinks. Windows runners lack the privilege,
104新增:# so ln -s silently plants a copy instead, and every test asserting on links
105新增:# (readlink, resolve-through, link-not-file) would test the copy. Those tests
106新增:# skip on the verdict below, with the reason printed.
107新增:if ln -s "$SELF_DIR/test.sh" "$SB/ln-probe" 2>/dev/null && [ -L "$SB/ln-probe" ]; then
108新增: AGENT_VM_HAS_SYMLINKS=1
109新增:else
110新增: AGENT_VM_HAS_SYMLINKS=""
111新增:fi
112新增:rm -f "$SB/ln-probe"
113新增:
114新增:# project-env needs perl for a file inside the project (_agent_vm_nofollow).
115新增:# macOS and most Linux hosts have it; minimal images (bash:3.2) do not, and
116新增:# the tests that need it skip there, with the reason printed.
117新增:if command -v perl >/dev/null 2>&1; then AGENT_VM_HAS_PERL=1; else AGENT_VM_HAS_PERL=""; fi
118新增:
119新增:printf 'agent-vm test suite (sandbox: %s)\n' "$SB"
新增www/.gitignore+5 −0看文件
@@ -0,0 +1,5 @@
1新增:node_modules/
2新增:dist/
3新增:.astro/
4新增:.DS_Store
5新增:*.log
新增www/README.md+72 −0看文件
@@ -0,0 +1,72 @@
1新增:# www.agent-vm.org
2新增:
3新增:The agent-vm website. One page, two languages, no runtime: Astro builds it to
4新增:static HTML and GitHub Pages serves it.
5新增:
6新增:## Run it
7新增:
8新增:```bash
9新增:npm install
10新增:npm run dev # http://localhost:4321
11新增:npm run build # -> dist/
12新增:npm run preview # serve dist/ locally
13新增:```
14新增:
15新增:## Where the content lives
16新增:
17新增:All copy is in `src/i18n/`. `en.ts` is the source of truth for the shape;
18新增:`fr.ts` is typed against it, so a missing or renamed key fails the build rather
19新增:than falling back to English silently. Shell snippets are not translated.
20新增:
21新增:French strings are written with plain apostrophes and ordinary spaces.
22新增:`src/lib/french-typography.ts` converts them at load: apostrophes become
23新增:typographic, and the space before `;` `!` `?` `»` and `:` becomes a no-break
24新增:one. Keys named `code`, `href`, `lang` or ending in `Code` are left alone, so a
25新增:command stays pasteable.
26新增:
27新增:Adding a section means adding a key in both dictionaries, a component in
28新增:`src/components/`, an entry in `Landing.astro`, and a link in `Nav.astro`.
29新增:
30新增:## Adding a language
31新增:
32新增:1. Add the code to `locales` in `astro.config.mjs` and to `LOCALES` in
33新增: `src/i18n/index.ts`.
34新增:2. Copy `fr.ts`, translate, register it in the `dictionaries` map.
35新增:3. Add `src/pages/<code>/index.astro`, two lines like the French one.
36新增:
37新增:English is served from `/` (`prefixDefaultLocale: false`), every other language
38新增:from `/<code>/`.
39新增:
40新增:## The installer
41新增:
42新增:`public/install.sh` is served as-is at `/install.sh`, for
43新增:`curl -fsSL https://www.agent-vm.org/install.sh | sh`. It is plain `sh`, not
44新增:bash. Its tests are in `../tests/17-curl-installer.sh`, and CI runs `sh -n` on it. A change goes
45新增:live with the next deploy of the site, not with a release.
46新增:
47新增:## Social image
48新增:
49新增:`public/og.png` is committed. Regenerate it after changing the wording:
50新增:
51新增:```bash
52新增:npm run og
53新增:```
54新增:
55新增:That needs `sharp` (a devDependency) and a font on the machine. The deploy does
56新增:not: it only reads the committed PNG.
57新增:
58新增:## Deploying
59新增:
60新增:`.github/workflows/www.yml` builds on every push to `main` that touches `www/`
61新增:and publishes to GitHub Pages. A pull request builds but does not publish.
62新增:
63新增:Two things have to be set once in the repository settings:
64新增:
65新增:- **Settings → Pages → Source: GitHub Actions.**
66新增:- **Settings → Pages → Custom domain: `www.agent-vm.org`**, with a `CNAME`
67新增: record at the DNS provider pointing `www` to `sylvinus.github.io`. Tick
68新增: *Enforce HTTPS* once the certificate is issued.
69新增:
70新增:`public/CNAME` carries the domain into every build; the workflow fails if it
71新增:goes missing, because losing it silently reverts the site to the `github.io`
72新增:URL.
新增www/astro.config.mjs+29 −0看文件
@@ -0,0 +1,29 @@
1新增:// @ts-check
2新增:import { defineConfig } from 'astro/config';
3新增:import sitemap from '@astrojs/sitemap';
4新增:
5新增:// Custom domain (public/CNAME) means the site is served from the root, so no
6新增:// `base`. If this ever moves to a project page, set base: '/agent-vm'.
7新增:export default defineConfig({
8新增: site: 'https://www.agent-vm.org',
9新增: trailingSlash: 'always',
10新增: i18n: {
11新增: locales: ['en', 'fr'],
12新增: defaultLocale: 'en',
13新增: routing: {
14新增: // English stays at /, French at /fr/.
15新增: prefixDefaultLocale: false,
16新增: },
17新增: },
18新增: integrations: [
19新增: sitemap({
20新增: i18n: {
21新增: defaultLocale: 'en',
22新增: locales: { en: 'en', fr: 'fr' },
23新增: },
24新增: }),
25新增: ],
26新增: build: {
27新增: inlineStylesheets: 'auto',
28新增: },
29新增:});
新增www/package-lock.json+5310 −0看文件

改动太大,不在线显示。

新增www/package.json+31 −0看文件
@@ -0,0 +1,31 @@
1新增:{
2新增: "name": "agent-vm-www",
3新增: "type": "module",
4新增: "version": "0.1.0",
5新增: "private": true,
6新增: "description": "Website for www.agent-vm.org",
7新增: "license": "MIT",
8新增: "scripts": {
9新增: "dev": "astro dev",
10新增: "start": "astro dev",
11新增: "build": "astro build",
12新增: "preview": "astro preview",
13新增: "check": "astro check",
14新增: "og": "node scripts/build-og.mjs"
15新增: },
16新增: "dependencies": {
17新增: "@astrojs/sitemap": "^3.7.4",
18新增: "@fontsource-variable/inter": "^5.3.0",
19新增: "@fontsource-variable/jetbrains-mono": "^5.3.0",
20新增: "astro": "^7.3.3"
21新增: },
22新增: "devDependencies": {
23新增: "@astrojs/check": "^0.9.10",
24新增: "sharp": "^0.35.4",
25新增: "typescript": "^6.0.3"
26新增: },
27新增: "allowScripts": {
28新增: "[email protected]": true,
29新增: "[email protected]": true
30新增: }
31新增:}
新增www/public/CNAME+1 −0看文件
@@ -0,0 +1 @@
1新增:www.agent-vm.org
新增www/public/favicon.svg+5 −0看文件
@@ -0,0 +1,5 @@
1新增:<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="agent-vm">
2新增: <rect width="32" height="32" rx="7" fill="#191713"/>
3新增: <rect x="5.5" y="5.5" width="21" height="21" rx="4.5" fill="none" stroke="#7d766b" stroke-width="1.6"/>
4新增: <rect x="11" y="11" width="10" height="10" rx="2.2" fill="#d2772a"/>
5新增:</svg>
新增www/public/install.sh+189 −0看文件
@@ -0,0 +1,189 @@
1新增:#!/bin/sh
2新增:#
3新增:# agent-vm installer, served at https://www.agent-vm.org/install.sh
4新增:#
5新增:# curl -fsSL https://www.agent-vm.org/install.sh | sh
6新增:# curl -fsSL https://www.agent-vm.org/install.sh | sh -s -- --git
7新增:#
8新增:# Options:
9新增:# --version X.Y.Z install that release instead of the latest one
10新增:# --git install a git clone of main instead of a release
11新增:# --dir DIR where agent-vm goes (default: ~/.local/share/agent-vm,
12新增:# or $XDG_DATA_HOME/agent-vm)
13新增:#
14新增:# A release is the tarball published on GitHub, checked against its SHA256SUMS.
15新增:# Running this again replaces it with the latest release. A clone is updated
16新增:# with `git pull`, or by running this again with --git.
17新增:#
18新增:# Then `agent-vm.sh install` links agent-vm into ~/.local/bin (AGENT_VM_BIN_DIR
19新增:# overrides). Nothing needs root.
20新增:#
21新增:# Everything is in functions and only the last line runs them, so a download
22新增:# cut short runs nothing.
23新增:
24新增:set -eu
25新增:
26新增:REPO="sylvinus/agent-vm"
27新增:
28新增:say() { printf 'agent-vm: %s\n' "$*"; }
29新增:die() { printf 'agent-vm: error: %s\n' "$*" >&2; exit 1; }
30新增:
31新增:need() {
32新增: command -v "$1" >/dev/null 2>&1 || die "$1 is required"
33新增:}
34新增:
35新增:usage() {
36新增: echo "usage: install.sh [--version X.Y.Z] [--git] [--dir DIR]" >&2
37新增: exit 2
38新增:}
39新增:
40新增:# HTTPS only, redirects included: the release assets redirect to another host.
41新增:fetch() {
42新增: curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fsSL --retry 3 -o "$2" "$1"
43新增:}
44新增:
45新增:sha256_of() {
46新增: if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
47新增: elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1
48新增: else die "neither sha256sum nor shasum is installed"
49新增: fi
50新增:}
51新增:
52新增:cleanup() {
53新增: [ -z "$TMP" ] || rm -rf "$TMP"
54新增: [ -z "$LEFTOVER" ] || rm -rf "$LEFTOVER"
55新增: # Stopped between the two renames: the previous version goes back.
56新增: if [ -n "$ROLLBACK" ] && [ -e "$ROLLBACK" ] && [ ! -e "$DIR" ]; then
57新增: mv "$ROLLBACK" "$DIR" && say "interrupted: the previous version is back in $DIR"
58新增: fi
59新增:}
60新增:
61新增:install_release() {
62新增: need curl
63新增: need tar
64新增: if [ -e "$DIR/.git" ]; then
65新增: die "$DIR is a git clone: update it with 'git -C \"$DIR\" pull', or run this with --git"
66新增: fi
67新增: if [ -e "$DIR" ] && [ ! -f "$DIR/agent-vm.sh" ]; then
68新增: die "$DIR exists and is not an agent-vm install: move it, or pick another --dir"
69新增: fi
70新增:
71新增: if [ -n "$WANT_VERSION" ]; then
72新增: base="https://github.com/$REPO/releases/download/v$WANT_VERSION"
73新增: else
74新增: base="https://github.com/$REPO/releases/latest/download"
75新增: fi
76新增: fetch "$base/SHA256SUMS" "$TMP/SHA256SUMS" || die "could not download $base/SHA256SUMS"
77新增:
78新增: # One line per asset: "<sha256> agent-vm-X.Y.Z.tar.gz".
79新增: tarball="$(awk '$2 ~ /^agent-vm-[0-9]+\.[0-9]+\.[0-9]+\.tar\.gz$/ { print $2; exit }' "$TMP/SHA256SUMS")"
80新增: [ -n "$tarball" ] || die "SHA256SUMS lists no agent-vm tarball"
81新增: expected="$(awk -v f="$tarball" '$2 == f { print $1; exit }' "$TMP/SHA256SUMS")"
82新增: version="${tarball#agent-vm-}"
83新增: version="${version%.tar.gz}"
84新增: if [ -n "$WANT_VERSION" ] && [ "$version" != "$WANT_VERSION" ]; then
85新增: die "asked for $WANT_VERSION, the release has $tarball"
86新增: fi
87新增:
88新增: # From the tag, not from latest/: a release published in between would not
89新增: # match the checksum read above.
90新增: say "downloading agent-vm $version"
91新增: fetch "https://github.com/$REPO/releases/download/v$version/$tarball" "$TMP/$tarball" \
92新增: || die "could not download $tarball"
93新增: actual="$(sha256_of "$TMP/$tarball")"
94新增: [ "$actual" = "$expected" ] || die "checksum mismatch for $tarball (expected $expected, got $actual)"
95新增:
96新增: mkdir "$TMP/x"
97新增: tar -xzf "$TMP/$tarball" -C "$TMP/x"
98新增: src="$TMP/x/agent-vm-$version"
99新增: [ -f "$src/agent-vm.sh" ] || die "$tarball has no agent-vm-$version/agent-vm.sh"
100新增:
101新增: # Staged next to $DIR so the swap is two renames on one filesystem. The
102新增: # previous version is left in LEFTOVER, which cleanup removes, or put back
103新增: # from ROLLBACK when the swap did not finish.
104新增: mkdir -p "$(dirname "$DIR")"
105新增: LEFTOVER="$DIR.new.$$"
106新增: mv "$src" "$LEFTOVER"
107新增: if [ -e "$DIR" ]; then
108新增: ROLLBACK="$DIR.old.$$"
109新增: mv "$DIR" "$ROLLBACK"
110新增: mv "$LEFTOVER" "$DIR"
111新增: LEFTOVER="$ROLLBACK"
112新增: ROLLBACK=""
113新增: else
114新增: mv "$LEFTOVER" "$DIR"
115新增: LEFTOVER=""
116新增: fi
117新增: say "agent-vm $version is in $DIR"
118新增:}
119新增:
120新增:install_git() {
121新增: need git
122新增: if [ -e "$DIR/.git" ]; then
123新增: say "updating the clone in $DIR"
124新增: git -C "$DIR" pull --ff-only
125新增: elif [ -e "$DIR" ]; then
126新增: die "$DIR exists and is not a git clone: move it, or pick another --dir"
127新增: else
128新增: mkdir -p "$(dirname "$DIR")"
129新增: git clone "https://github.com/$REPO.git" "$DIR"
130新增: fi
131新增:}
132新增:
133新增:main() {
134新增: WANT_VERSION=""; USE_GIT=""; DIR=""
135新增: while [ $# -gt 0 ]; do
136新增: case "$1" in
137新增: --version)
138新增: [ $# -ge 2 ] || usage
139新增: WANT_VERSION="$2"; shift ;;
140新增: --version=*) WANT_VERSION="${1#*=}" ;;
141新增: --git) USE_GIT=1 ;;
142新增: --dir)
143新增: [ $# -ge 2 ] || usage
144新增: DIR="$2"; shift ;;
145新增: --dir=*) DIR="${1#*=}" ;;
146新增: -h|--help) usage ;;
147新增: *) usage ;;
148新增: esac
149新增: shift
150新增: done
151新增: WANT_VERSION="${WANT_VERSION#v}"
152新增: if [ -n "$WANT_VERSION" ]; then
153新增: printf '%s\n' "$WANT_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' \
154新增: || die "not a version: '$WANT_VERSION' (expected X.Y.Z)"
155新增: [ -z "$USE_GIT" ] || die "--version installs a release: it does not go with --git"
156新增: fi
157新增:
158新增: case "$(uname -s)" in
159新增: Darwin|Linux|MINGW*|MSYS*|CYGWIN*) ;;
160新增: *) die "agent-vm runs on macOS, Linux and Windows (Git Bash) only" ;;
161新增: esac
162新增: need bash
163新增:
164新增: [ -n "${HOME:-}" ] || die "HOME is not set"
165新增: [ -n "$DIR" ] || DIR="${XDG_DATA_HOME:-$HOME/.local/share}/agent-vm"
166新增: # C:/... and C:\... are absolute too, in Git Bash.
167新增: case "$DIR" in
168新增: /*|[A-Za-z]:/*|[A-Za-z]:\\*) ;;
169新增: *) DIR="$(pwd)/$DIR" ;;
170新增: esac
171新增: DIR="${DIR%/}"
172新增:
173新增: TMP=""; LEFTOVER=""; ROLLBACK=""
174新增: trap cleanup EXIT
175新增: trap 'exit 1' HUP INT TERM
176新增: TMP="$(mktemp -d 2>/dev/null || mktemp -d -t agent-vm)"
177新增:
178新增: if [ -n "$USE_GIT" ]; then install_git; else install_release; fi
179新增:
180新增: # `install` can go on to run `agent-vm setup`, whose brew and limactl calls
181新增: # may read stdin: give them the terminal, not the rest of this pipe.
182新增: if (exec </dev/tty) 2>/dev/null; then
183新增: bash "$DIR/agent-vm.sh" install </dev/tty
184新增: else
185新增: bash "$DIR/agent-vm.sh" install </dev/null
186新增: fi
187新增:}
188新增:
189新增:main "$@"
新增www/public/og.png看文件

二进制文件,不显示改动。

新增www/public/robots.txt+4 −0看文件
@@ -0,0 +1,4 @@
1新增:User-agent: *
2新增:Allow: /
3新增:
4新增:Sitemap: https://www.agent-vm.org/sitemap-index.xml
新增www/scripts/build-og.mjs+82 −0看文件
@@ -0,0 +1,82 @@
1新增:/**
2新增: * Renders public/og.png from an inline SVG.
3新增: *
4新增: * Run with `npm run og` after changing the wording. The PNG is committed, so a
5新增: * normal `npm run build` (and the CI deploy) never needs sharp or a font stack
6新增: * on the machine doing the build.
7新增: */
8新增:
9新增:import { mkdir } from 'node:fs/promises';
10新增:import { dirname, resolve } from 'node:path';
11新增:import { fileURLToPath } from 'node:url';
12新增:import sharp from 'sharp';
13新增:
14新增:const here = dirname(fileURLToPath(import.meta.url));
15新增:const out = resolve(here, '../public/og.png');
16新增:
17新增:const W = 1200;
18新增:const H = 630;
19新增:const GRID = 60;
20新增:
21新增:const gridLines = [];
22新增:for (let x = GRID; x < W; x += GRID) {
23新增: gridLines.push(`<line x1="${x}" y1="0" x2="${x}" y2="${H}" />`);
24新增:}
25新增:for (let y = GRID; y < H; y += GRID) {
26新增: gridLines.push(`<line x1="0" y1="${y}" x2="${W}" y2="${y}" />`);
27新增:}
28新增:
29新增:// The SVG renderer behind sharp does not map the generic `sans-serif` keyword
30新增:// to a real family, so both stacks name actual faces and end on the keyword.
31新增:// macOS hits Helvetica, a Linux CI box hits Liberation.
32新增:const SANS = 'Inter, Helvetica Neue, Helvetica, Liberation Sans, Arial, sans-serif';
33新增:const MONO = 'JetBrains Mono, SF Mono, Menlo, DejaVu Sans Mono, Liberation Mono, monospace';
34新增:
35新增:const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">
36新增: <defs>
37新增: <linearGradient id="fade" x1="0" y1="0" x2="0" y2="1">
38新增: <stop offset="0" stop-color="#ffffff" stop-opacity="0.05" />
39新增: <stop offset="1" stop-color="#ffffff" stop-opacity="0" />
40新增: </linearGradient>
41新增: </defs>
42新增:
43新增: <rect width="${W}" height="${H}" fill="#131210" />
44新增: <g stroke="#ffffff" stroke-opacity="0.035" stroke-width="1">
45新增: ${gridLines.join('\n ')}
46新增: </g>
47新增: <rect width="${W}" height="${H}" fill="url(#fade)" />
48新增:
49新增: <g transform="translate(96 96)">
50新增: <rect x="0" y="0" width="56" height="56" rx="13" fill="none" stroke="#8a8275" stroke-width="3" />
51新增: <rect x="17" y="17" width="22" height="22" rx="5" fill="#e08c3e" />
52新增: <text x="78" y="39" font-family="${MONO}" font-size="34" font-weight="700" fill="#f1ece2">
53新增: agent-vm
54新增: </text>
55新增: </g>
56新增:
57新增: <text x="96" y="310" font-family="${SANS}" font-size="66" font-weight="700" fill="#f1ece2">
58新增: Give agents a machine
59新增: </text>
60新增: <text x="96" y="388" font-family="${SANS}" font-size="66" font-weight="700" fill="#f1ece2">
61新增: they can wreck.
62新增: <tspan fill="#e08c3e"> Keep yours.</tspan>
63新增: </text>
64新增:
65新增: <text x="96" y="462" font-family="${SANS}" font-size="29" fill="#b8afa1">
66新增: Sandboxed Linux VMs for AI coding agents. One per project.
67新增: </text>
68新增:
69新增: <line x1="96" y1="524" x2="${W - 96}" y2="524" stroke="#2c2823" stroke-width="2" />
70新增:
71新增: <text x="96" y="568" font-family="${MONO}" font-size="24" fill="#8a8275">
72新增: www.agent-vm.org
73新增: </text>
74新增: <text x="${W - 96}" y="568" text-anchor="end" font-family="${MONO}" font-size="24" fill="#8a8275">
75新增: MIT · macOS + Linux · built on Lima
76新增: </text>
77新增:</svg>`;
78新增:
79新增:await mkdir(dirname(out), { recursive: true });
80新增:await sharp(Buffer.from(svg)).png({ compressionLevel: 9 }).toFile(out);
81新增:
82新增:console.log(`wrote ${out}`);
新增www/src/components/Architecture.astro+477 −0看文件
@@ -0,0 +1,477 @@
1新增:---
2新增:import { inline } from '../lib/inline';
3新增:import Heading from './Heading.astro';
4新增:import { slug } from '../lib/slug';
5新增:import { en } from '../i18n/en';
6新增:import { t, type Locale } from '../i18n';
7新增:
8新增:interface Props {
9新增: locale: Locale;
10新增:}
11新增:
12新增:const { locale } = Astro.props;
13新增:const d = t(locale);
14新增:const dg = d.architecture.diagram;
15新增:---
16新增:
17新增:<section class="section" id="architecture">
18新增: <div class="container">
19新增: <div class="section-head">
20新增: <p class="eyebrow">{d.architecture.eyebrow}</p>
21新增: <Heading as="h2" id="architecture" own={false} locale={locale}>{d.architecture.title}</Heading>
22新增: <p class="lede" set:html={inline(d.architecture.lede)} />
23新增: </div>
24新增:
25新增: <ol class="arch__steps">
26新增: {
27新增: d.architecture.steps.map((step, index) => (
28新增: <li class="arch__step">
29新增: <span class="arch__step-n" aria-hidden="true">
30新增: {step.n}
31新增: </span>
32新增: <Heading as="h3" id={slug(en.architecture.steps[index]!.title)} locale={locale} class="arch__step-title">{step.title}</Heading>
33新增: <p class="prose arch__step-body" set:html={inline(step.body)} />
34新增: </li>
35新增: ))
36新增: }
37新增: </ol>
38新增:
39新增: <div class="arch__diagram">
40新增: <div class="arch__panel arch__panel--host">
41新增: <div class="arch__panel-head">
42新增: <h3 class="arch__panel-title">{dg.hostTitle}</h3>
43新增: <span class="arch__panel-note">{dg.hostNote}</span>
44新增: </div>
45新增: <ul class="arch__items">
46新增: {dg.hostItems.map((item) => <li class="arch__item arch__item--locked">{item}</li>)}
47新增: </ul>
48新增: </div>
49新增:
50新增: <div class="arch__boundary">
51新增: <span class="arch__boundary-label">{dg.boundaryLabel}</span>
52新增: </div>
53新增:
54新增: <div class="arch__panel arch__panel--vm">
55新增: <div class="arch__panel-head">
56新增: <h3 class="arch__panel-title">{dg.vmTitle}</h3>
57新增: <span class="arch__panel-note arch__panel-note--safe">{dg.vmNote}</span>
58新增: </div>
59新增: <ul class="arch__items">
60新增: {dg.vmItems.map((item) => <li class="arch__item">{item}</li>)}
61新增: </ul>
62新增: </div>
63新增:
64新增: {/* Spans both columns on purpose: the project directory is the one
65新增: thing that exists on both sides of the boundary at once. */}
66新增: <div class="arch__shared">
67新增: <div class="arch__shared-stems" aria-hidden="true">
68新增: <span class="arch__stem"></span>
69新增: <span class="arch__stem"></span>
70新增: </div>
71新增: <div class="arch__shared-box">
72新增: <div class="arch__panel-head">
73新增: <h3 class="arch__shared-title">{dg.sharedTitle}</h3>
74新增: <span class="arch__shared-label">{dg.sharedLabel}</span>
75新增: </div>
76新增: <p class="prose arch__shared-body" set:html={inline(dg.sharedBody)} />
77新增: </div>
78新增: </div>
79新增: </div>
80新增:
81新增: <p class="prose arch__isolation" set:html={inline(d.architecture.isolationNote)} />
82新增:
83新增: <div class="arch__tables">
84新增: <div class="arch__table-block">
85新增: <Heading as="h3" id={slug(en.architecture.contentsTitle)} locale={locale} class="arch__sub">{d.architecture.contentsTitle}</Heading>
86新增: <p class="prose arch__sub-body" set:html={inline(d.architecture.contentsLede)} />
87新增: <div class="table-wrap">
88新增: <table>
89新增: <thead>
90新增: <tr>
91新增: {d.architecture.contentsHeaders.map((header) => <th scope="col">{header}</th>)}
92新增: </tr>
93新增: </thead>
94新增: <tbody>
95新增: {
96新增: d.architecture.contents.map(([category, packages, name, standard]) => (
97新增: <tr>
98新增: <td>{category}</td>
99新增: <td class="arch__packages">{packages}</td>
100新增: <td class="arch__name">{name}</td>
101新增: <td class="arch__flag">{standard}</td>
102新增: </tr>
103新增: ))
104新增: }
105新增: </tbody>
106新增: </table>
107新增: </div>
108新增: <p class="prose arch__sub-note" set:html={inline(d.architecture.contentsNote)} />
109新增: </div>
110新增:
111新增: <div class="arch__table-block">
112新增: <Heading as="h3" id={slug(en.architecture.dockerTitle)} locale={locale} class="arch__sub">{d.architecture.dockerTitle}</Heading>
113新增: <p class="prose arch__sub-body" set:html={inline(d.architecture.dockerLede)} />
114新增: <div class="table-wrap">
115新增: <table class="arch__compare">
116新增: <thead>
117新增: <tr>
118新增: {
119新增: d.architecture.dockerHeaders.map((header, index) => (
120新增: <th scope="col" class:list={[index === 3 && 'arch__col-win']}>
121新增: {header}
122新增: </th>
123新增: ))
124新增: }
125新增: </tr>
126新增: </thead>
127新增: <tbody>
128新增: {
129新增: d.architecture.docker.map((row) => (
130新增: <tr>
131新增: <th scope="row">{row[0]}</th>
132新增: <td set:html={inline(row[1] ?? '')} />
133新增: <td set:html={inline(row[2] ?? '')} />
134新增: <td class="arch__col-win" set:html={inline(row[3] ?? '')} />
135新增: </tr>
136新增: ))
137新增: }
138新增: </tbody>
139新增: </table>
140新增: </div>
141新增: <p class="prose arch__sub-note" set:html={inline(d.architecture.dockerNote)} />
142新增: </div>
143新增: </div>
144新增: </div>
145新增:</section>
146新增:
147新增:<style>
148新增: .arch__steps {
149新增: display: grid;
150新增: grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr));
151新增: gap: 0;
152新增: list-style: none;
153新增: border-top: 1px solid var(--line);
154新增: margin-bottom: clamp(2.75rem, 5.5vw, 4.5rem);
155新增: }
156新增:
157新增: .arch__step {
158新增: padding: 1.6rem clamp(1rem, 2vw, 1.75rem) 1.75rem;
159新增: border-left: 1px solid var(--line);
160新增: }
161新增:
162新增: .arch__step:first-child {
163新增: padding-left: 0;
164新增: border-left: 0;
165新增: }
166新增:
167新增: .arch__step-n {
168新增: display: block;
169新增: font-family: var(--font-mono);
170新增: font-size: 0.72rem;
171新增: letter-spacing: 0.12em;
172新增: color: var(--accent);
173新增: margin-bottom: 0.8rem;
174新增: }
175新增:
176新增: .arch__step-title {
177新增: font-size: 0.98rem;
178新增: margin-bottom: 0.45rem;
179新增: }
180新增:
181新增: .arch__step-body {
182新增: font-size: 0.89rem;
183新增: }
184新增:
185新增: /* Diagram ----------------------------------------------------------------- */
186新增:
187新增: .arch__diagram {
188新增: --diagram-gap: clamp(1rem, 2.5vw, 2rem);
189新增: display: grid;
190新增: grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
191新增: gap: var(--diagram-gap);
192新增: align-items: stretch;
193新增: padding: clamp(1.5rem, 3vw, 2.5rem);
194新增: border: 1px solid var(--line);
195新增: border-radius: var(--radius-lg);
196新增: background: var(--surface);
197新增: }
198新增:
199新增: .arch__panel {
200新增: display: grid;
201新增: align-content: start;
202新增: gap: 1.1rem;
203新增: padding: clamp(1.1rem, 2vw, 1.5rem);
204新增: border: 1px solid var(--line);
205新增: border-radius: var(--radius);
206新增: background: var(--surface-2);
207新增: }
208新增:
209新增: .arch__panel--vm {
210新增: border-color: var(--safe-line);
211新增: background: var(--safe-wash);
212新增: }
213新增:
214新增: .arch__panel-head {
215新增: display: flex;
216新增: flex-wrap: wrap;
217新增: align-items: baseline;
218新增: justify-content: space-between;
219新增: gap: 0.5rem;
220新增: }
221新增:
222新增: .arch__panel-title {
223新增: font-size: 1rem;
224新增: }
225新增:
226新增: .arch__panel-note {
227新增: font-family: var(--font-mono);
228新增: font-size: 0.68rem;
229新增: letter-spacing: 0.08em;
230新增: text-transform: uppercase;
231新增: color: var(--ink-3);
232新增: }
233新增:
234新增: .arch__panel-note--safe {
235新增: color: var(--safe);
236新增: }
237新增:
238新增: .arch__items {
239新增: display: grid;
240新增: gap: 0.4rem;
241新增: list-style: none;
242新增: }
243新增:
244新增: .arch__item {
245新增: position: relative;
246新增: padding-left: 1.15rem;
247新增: font-size: 0.89rem;
248新增: color: var(--ink-2);
249新增: }
250新增:
251新增: .arch__item::before {
252新增: content: '';
253新增: position: absolute;
254新增: left: 0;
255新增: top: 0.62em;
256新增: width: 0.4rem;
257新增: height: 0.4rem;
258新增: border-radius: 50%;
259新增: background: var(--safe);
260新增: }
261新增:
262新增: .arch__item--locked::before {
263新增: background: var(--ink-4);
264新增: }
265新增:
266新增: .arch__boundary {
267新增: position: relative;
268新增: display: grid;
269新增: place-items: center;
270新增: min-width: 2.5rem;
271新增: }
272新增:
273新增: .arch__boundary::before {
274新增: content: '';
275新增: position: absolute;
276新增: top: 0;
277新增: bottom: 0;
278新增: left: 50%;
279新增: width: 0;
280新增: border-left: 2px dashed var(--line-strong);
281新增: }
282新增:
283新增: .arch__boundary-label {
284新增: position: relative;
285新增: padding: 0.5rem 0.25rem;
286新增: background: var(--surface);
287新增: font-family: var(--font-mono);
288新增: font-size: 0.65rem;
289新增: letter-spacing: 0.14em;
290新增: text-transform: uppercase;
291新增: color: var(--ink-3);
292新增: writing-mode: vertical-rl;
293新增: text-orientation: mixed;
294新增: }
295新增:
296新增: /* The shared band sits under both panels and grows a stem up into each,
297新增: so the project directory reads as one thing touching both sides. */
298新增: .arch__shared {
299新增: grid-column: 1 / -1;
300新增: /* Cancel the row gap so the stems start at the panels' bottom edge
301新增: instead of floating below it. */
302新增: margin-top: calc(-1 * var(--diagram-gap));
303新增: }
304新增:
305新增: .arch__shared-stems {
306新增: display: grid;
307新增: grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
308新增: gap: var(--diagram-gap);
309新增: height: calc(var(--diagram-gap) + 1.4rem);
310新增: }
311新增:
312新增: .arch__stem {
313新增: justify-self: center;
314新增: width: 0;
315新增: height: 100%;
316新增: border-left: 2px solid var(--accent);
317新增: }
318新增:
319新增: /* The middle track is the hypervisor boundary column: nothing crosses it
320新增: here, the two stems flank it. */
321新增: .arch__stem:nth-child(2) {
322新增: grid-column: 3;
323新增: }
324新增:
325新增: .arch__shared-box {
326新增: display: grid;
327新增: gap: 0.65rem;
328新增: padding: clamp(1.1rem, 2vw, 1.5rem);
329新增: border: 1px solid var(--accent-line);
330新增: border-radius: var(--radius);
331新增: background: var(--accent-wash);
332新增: }
333新增:
334新增: .arch__shared-title {
335新增: font-family: var(--font-mono);
336新增: font-size: 0.92rem;
337新增: color: var(--accent);
338新增: }
339新增:
340新增: .arch__shared-label {
341新增: font-family: var(--font-mono);
342新增: font-size: 0.68rem;
343新增: letter-spacing: 0.08em;
344新增: text-transform: uppercase;
345新增: color: var(--accent);
346新增: }
347新增:
348新增: .arch__shared-body {
349新增: font-size: 0.88rem;
350新增: }
351新增:
352新增: .arch__isolation {
353新增: max-width: 48rem;
354新增: margin-top: 1.5rem;
355新增: font-size: 0.92rem;
356新增: }
357新增:
358新增: /* Tables ------------------------------------------------------------------ */
359新增:
360新增: .arch__tables {
361新增: display: grid;
362新增: gap: clamp(2.5rem, 5vw, 4rem);
363新增: margin-top: clamp(2.75rem, 5.5vw, 4.5rem);
364新增: }
365新增:
366新增: .arch__table-block {
367新增: display: grid;
368新增: gap: 1rem;
369新增: align-content: start;
370新增: min-width: 0;
371新增: }
372新增:
373新增: .arch__sub {
374新增: font-size: 1.05rem;
375新增: }
376新增:
377新增: .arch__sub-body {
378新增: font-size: 0.93rem;
379新增: margin-top: -0.35rem;
380新增: max-width: 48rem;
381新增: }
382新增:
383新增: .arch__sub-note {
384新增: font-size: 0.88rem;
385新增: max-width: 48rem;
386新增: }
387新增:
388新增: .arch__packages {
389新增: font-size: 0.84rem;
390新增: }
391新增:
392新增: .arch__name {
393新增: font-family: var(--font-mono);
394新增: font-size: 0.79rem;
395新增: color: var(--accent);
396新增: }
397新增:
398新增: .arch__flag {
399新增: font-variant-caps: all-small-caps;
400新增: letter-spacing: 0.06em;
401新增: color: var(--ink-3);
402新增: }
403新增:
404新增: .arch__compare th[scope='row'] {
405新增: padding: 0.72rem 1rem;
406新增: text-align: left;
407新增: font-weight: 500;
408新增: color: var(--ink);
409新增: border-bottom: 1px solid var(--line);
410新增: vertical-align: top;
411新增: }
412新增:
413新增: .arch__compare tbody tr:last-child th[scope='row'] {
414新增: border-bottom: 0;
415新增: }
416新增:
417新增: /* Marks our own column, nothing more. A green "we win" tint on a table of
418新增: plain facts reads as a scorecard and costs the table its credibility. */
419新增: .arch__col-win {
420新增: background: var(--surface-2);
421新增: color: var(--ink);
422新增: font-weight: 500;
423新增: }
424新增:
425新增: thead .arch__col-win {
426新增: color: var(--ink-2);
427新增: }
428新增:
429新增: @media (max-width: 62rem) {
430新增: .arch__steps {
431新增: grid-template-columns: minmax(0, 1fr);
432新增: }
433新增:
434新增: .arch__step {
435新增: padding: 1.35rem 0;
436新增: border-left: 0;
437新增: border-bottom: 1px solid var(--line);
438新增: }
439新增:
440新增: .arch__step:last-child {
441新增: border-bottom: 0;
442新增: }
443新增:
444新增: .arch__diagram {
445新增: grid-template-columns: minmax(0, 1fr);
446新增: }
447新增:
448新增: .arch__boundary {
449新增: min-height: 3.5rem;
450新增: }
451新增:
452新增: .arch__boundary::before {
453新增: top: 50%;
454新增: bottom: auto;
455新增: left: 0;
456新增: right: 0;
457新增: width: auto;
458新增: border-left: 0;
459新增: border-top: 2px dashed var(--line-strong);
460新增: }
461新增:
462新增: .arch__boundary-label {
463新增: writing-mode: horizontal-tb;
464新增: padding: 0.25rem 0.75rem;
465新增: }
466新增:
467新增: /* One column: the two stems would point at nothing. */
468新增: .arch__shared-stems {
469新增: grid-template-columns: minmax(0, 1fr);
470新增: height: 1rem;
471新增: }
472新增:
473新增: .arch__stem:nth-child(2) {
474新增: display: none;
475新增: }
476新增: }
477新增:</style>
新增www/src/components/CodeBlock.astro+215 −0看文件
@@ -0,0 +1,215 @@
1新增:---
2新增:import { highlightShell } from '../lib/shell-highlight';
3新增:import { escapeHtml } from '../lib/inline';
4新增:import { t, type Locale } from '../i18n';
5新增:
6新增:interface Props {
7新增: code: string;
8新增: locale: Locale;
9新增: title?: string;
10新增: /** Render a `$` gutter before each non-comment, non-blank line. */
11新增: prompt?: boolean;
12新增: class?: string;
13新增:}
14新增:
15新增:const { code, locale, title, prompt = false, class: className } = Astro.props;
16新增:const d = t(locale);
17新增:
18新增:// Built as a string rather than as markup: inside a <pre>, the indentation of
19新增:// the template would land in the output as real whitespace.
20新增:const html = highlightShell(code)
21新增: .map((tokens) => {
22新增: const bare = tokens.length === 0 || tokens[0]!.kind === 'comment';
23新增: const gutter = prompt
24新增: ? `<span class="code__prompt" aria-hidden="true">${bare ? ' ' : '$'}</span>`
25新增: : '';
26新增: const body = tokens
27新增: .map((token) => `<span class="tk tk--${token.kind}">${escapeHtml(token.text)}</span>`)
28新增: .join('');
29新增: return `<span class="code__line">${gutter}${body}</span>`;
30新增: })
31新增: .join('\n');
32新增:---
33新增:
34新增:<figure class:list={['code', className]}>
35新增: {
36新增: title && (
37新增: <figcaption class="code__bar">
38新增: <span class="code__title">{title}</span>
39新增: </figcaption>
40新增: )
41新增: }
42新增: <div class="code__body">
43新增: <pre class="code__pre"><code set:html={html} /></pre>
44新增: <button
45新增: type="button"
46新增: class="code__copy"
47新增: data-copy
48新增: data-copied-label={d.ui.copied}
49新增: data-failed-label={d.ui.copyFailed}
50新增: data-idle-label={d.ui.copy}
51新增: aria-label={d.ui.copyLabel}
52新增: >
53新增: <span data-copy-text>{d.ui.copy}</span>
54新增: </button>
55新增: </div>
56新增:</figure>
57新增:
58新增:<style>
59新增: .code {
60新增: margin: 0;
61新增: border: 1px solid var(--code-line);
62新增: border-radius: var(--radius-lg);
63新增: background: var(--code-bg);
64新增: overflow: hidden;
65新增: }
66新增:
67新增: .code__bar {
68新增: display: flex;
69新增: align-items: center;
70新增: gap: 0.5rem;
71新增: padding: 0.5rem 0.9rem;
72新增: border-bottom: 1px solid var(--code-line);
73新增: background: color-mix(in srgb, var(--code-bg) 82%, #fff 18%);
74新增: }
75新增:
76新增: .code__title {
77新增: font-family: var(--font-mono);
78新增: font-size: 0.7rem;
79新增: letter-spacing: 0.1em;
80新增: text-transform: uppercase;
81新增: color: var(--code-ink-2);
82新增: }
83新增:
84新增: .code__body {
85新增: position: relative;
86新增: }
87新增:
88新增: .code__pre {
89新增: margin: 0;
90新增: padding: 1rem 1.1rem;
91新增: overflow-x: auto;
92新增: font-size: 0.815rem;
93新增: line-height: 1.75;
94新增: color: var(--code-ink);
95新增: tab-size: 2;
96新增: }
97新增:
98新增: .code__pre :global(.code__prompt) {
99新增: display: inline-block;
100新增: width: 1.15rem;
101新增: color: var(--code-ink-2);
102新增: user-select: none;
103新增: }
104新增:
105新增: .code__pre :global(.tk--command) {
106新增: color: #eaa963;
107新增: }
108新增: .code__pre :global(.tk--flag) {
109新增: color: #86b8d8;
110新增: }
111新增: .code__pre :global(.tk--string) {
112新增: color: #9dc08b;
113新增: }
114新增: .code__pre :global(.tk--variable) {
115新增: color: #cba6d8;
116新增: }
117新增: .code__pre :global(.tk--comment) {
118新增: color: var(--code-ink-2);
119新增: font-style: italic;
120新增: }
121新增:
122新增: .code__copy {
123新增: position: absolute;
124新增: top: 0.55rem;
125新增: right: 0.55rem;
126新增: padding: 0.28rem 0.6rem;
127新增: border: 1px solid var(--code-line);
128新增: border-radius: 5px;
129新增: background: var(--surface);
130新增: color: var(--code-ink-2);
131新增: font-family: var(--font-mono);
132新增: font-size: 0.68rem;
133新增: letter-spacing: 0.06em;
134新增: text-transform: uppercase;
135新增: cursor: pointer;
136新增: opacity: 0;
137新增: transition: opacity 0.14s ease, color 0.14s ease, border-color 0.14s ease;
138新增: }
139新增:
140新增: .code:hover .code__copy,
141新增: .code__copy:focus-visible {
142新增: opacity: 1;
143新增: }
144新增:
145新增: .code__copy:hover {
146新增: color: var(--code-ink);
147新增: border-color: var(--code-ink-2);
148新增: }
149新增:
150新增: .code__copy[data-state='done'] {
151新增: opacity: 1;
152新增: color: #9dc08b;
153新增: border-color: #9dc08b;
154新增: }
155新增:
156新增: .code__copy[data-state='failed'] {
157新增: opacity: 1;
158新增: color: #e08c6b;
159新增: border-color: #e08c6b;
160新增: }
161新增:
162新增: /* Coarse pointers never hover, so the button has to stay visible, and the
163新增: code starts below it instead of under it. */
164新增: @media (hover: none) {
165新增: .code__copy {
166新增: opacity: 1;
167新增: }
168新增:
169新增: .code__pre {
170新增: padding-top: 2.6rem;
171新增: }
172新增: }
173新增:</style>
174新增:
175新增:<script>
176新增: // One delegated listener rather than one per block: the page has a lot of
177新增: // them, and they are all identical.
178新增: document.addEventListener('click', async (event) => {
179新增: const target = event.target;
180新增: if (!(target instanceof Element)) return;
181新增: const button = target.closest<HTMLButtonElement>('[data-copy]');
182新增: if (!button) return;
183新增:
184新增: const pre = button.parentElement?.querySelector('pre');
185新增: if (!pre) return;
186新增:
187新增: const label = button.querySelector<HTMLElement>('[data-copy-text]');
188新增: // Reading the token spans rather than the line's textContent keeps the `$`
189新增: // gutter out: it is an aria-hidden decoration, and pasting it would break
190新增: // every command.
191新增: const text = Array.from(pre.querySelectorAll('.code__line'))
192新增: .map((line) =>
193新增: Array.from(line.querySelectorAll('.tk'))
194新增: .map((tk) => tk.textContent ?? '')
195新增: .join(''),
196新增: )
197新增: .join('\n');
198新增:
199新增: const settle = (state: 'done' | 'failed', message: string) => {
200新增: button.setAttribute('data-state', state);
201新增: if (label) label.textContent = message;
202新增: window.setTimeout(() => {
203新增: button.removeAttribute('data-state');
204新增: if (label) label.textContent = button.dataset.idleLabel ?? 'Copy';
205新增: }, 1800);
206新增: };
207新增:
208新增: try {
209新增: await navigator.clipboard.writeText(text);
210新增: settle('done', button.dataset.copiedLabel ?? 'Copied');
211新增: } catch {
212新增: settle('failed', button.dataset.failedLabel ?? 'Copy failed');
213新增: }
214新增: });
215新增:</script>
新增www/src/components/Contribute.astro+195 −0看文件
@@ -0,0 +1,195 @@
1新增:---
2新增:import CodeBlock from './CodeBlock.astro';
3新增:import Roadmap from './Roadmap.astro';
4新增:import { inline } from '../lib/inline';
5新增:import Heading from './Heading.astro';
6新增:import { slug } from '../lib/slug';
7新增:import { en } from '../i18n/en';
8新增:import { t, type Locale } from '../i18n';
9新增:
10新增:interface Props {
11新增: locale: Locale;
12新增:}
13新增:
14新增:const { locale } = Astro.props;
15新增:const d = t(locale);
16新增:---
17新增:
18新增:<section class="section contribute" id="contribute">
19新增: <div class="container">
20新增: <div class="section-head">
21新增: <p class="eyebrow">{d.contribute.eyebrow}</p>
22新增: <Heading as="h2" id="contribute" own={false} locale={locale}>{d.contribute.title}</Heading>
23新增: <p class="lede" set:html={inline(d.contribute.lede)} />
24新增: </div>
25新增:
26新增: <Roadmap locale={locale} />
27新增:
28新增: <div class="contribute__grid">
29新增: <div class="contribute__col">
30新增: <Heading as="h3" id={slug(en.contribute.testsTitle)} locale={locale} class="contribute__sub">{d.contribute.testsTitle}</Heading>
31新增: <p class="prose contribute__body" set:html={inline(d.contribute.testsBody)} />
32新增: <CodeBlock locale={locale} code={d.contribute.testsCode} prompt />
33新增:
34新增: <Heading as="h3" id={slug(en.contribute.shellsTitle)} locale={locale} class="contribute__sub contribute__sub--spaced">{d.contribute.shellsTitle}</Heading>
35新增: <p class="prose contribute__body" set:html={inline(d.contribute.shellsBody)} />
36新增: <CodeBlock locale={locale} code={d.contribute.shellsCode} prompt />
37新增: </div>
38新增:
39新增: <div class="contribute__col">
40新增: <Heading as="h3" id={slug(en.contribute.structureTitle)} locale={locale} class="contribute__sub">{d.contribute.structureTitle}</Heading>
41新增: <div class="table-wrap">
42新增: <table class="table--code">
43新增: <thead>
44新增: <tr>
45新增: {d.contribute.structureHeaders.map((header) => <th scope="col">{header}</th>)}
46新增: </tr>
47新增: </thead>
48新增: <tbody>
49新增: {
50新增: d.contribute.structure.map(([file, description]) => (
51新增: <tr>
52新增: <td>{file}</td>
53新增: <td>{description}</td>
54新增: </tr>
55新增: ))
56新增: }
57新增: </tbody>
58新增: </table>
59新增: </div>
60新增:
61新增: <Heading as="h3" id={slug(en.contribute.guidelinesTitle)} locale={locale} class="contribute__sub contribute__sub--spaced">{d.contribute.guidelinesTitle}</Heading>
62新增: <ul class="contribute__rules">
63新增: {
64新增: d.contribute.guidelines.map((rule) => (
65新增: <li class="contribute__rule">
66新增: <span class="prose" set:html={inline(rule)} />
67新增: </li>
68新增: ))
69新增: }
70新增: </ul>
71新增: </div>
72新增: </div>
73新增:
74新增: <div class="contribute__links">
75新增: <a class="contribute__link" href={d.contribute.issuesHref} rel="noopener" target="_blank">
76新增: <span class="contribute__link-label">{d.contribute.issuesLabel}</span>
77新增: <span class="contribute__link-arrow" aria-hidden="true">→</span>
78新增: </a>
79新增: <a class="contribute__link" href={d.contribute.prHref} rel="noopener" target="_blank">
80新增: <span class="contribute__link-label">{d.contribute.prLabel}</span>
81新增: <span class="contribute__link-arrow" aria-hidden="true">→</span>
82新增: </a>
83新增: <a class="contribute__link" href={d.contribute.repoHref} rel="noopener" target="_blank">
84新增: <span class="contribute__link-label">{d.contribute.repoLabel}</span>
85新增: <span class="contribute__link-arrow" aria-hidden="true">→</span>
86新增: </a>
87新增: </div>
88新增: </div>
89新增:</section>
90新增:
91新增:<style>
92新增: .contribute {
93新增: background: var(--paper-sunk);
94新增: }
95新增:
96新增: .contribute__grid {
97新增: display: grid;
98新增: grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
99新增: gap: clamp(1.75rem, 4vw, 3.25rem);
100新增: align-items: start;
101新增: }
102新增:
103新增: .contribute__col {
104新增: display: grid;
105新增: align-content: start;
106新增: min-width: 0;
107新增: }
108新增:
109新增: .contribute__sub {
110新增: font-size: 1.05rem;
111新增: margin-bottom: 0.65rem;
112新增: }
113新增:
114新增: .contribute__sub--spaced {
115新增: margin-top: 2.25rem;
116新增: }
117新增:
118新增: .contribute__body {
119新增: font-size: 0.92rem;
120新增: margin-bottom: 1rem;
121新增: max-width: 44rem;
122新增: }
123新增:
124新增: .contribute__rules {
125新增: display: grid;
126新增: gap: 0.75rem;
127新增: list-style: none;
128新增: }
129新增:
130新增: .contribute__rule {
131新增: position: relative;
132新增: padding-left: 1.4rem;
133新增: font-size: 0.92rem;
134新增: }
135新增:
136新增: .contribute__rule::before {
137新增: content: '';
138新增: position: absolute;
139新增: left: 0;
140新增: top: 0.62em;
141新增: width: 0.45rem;
142新增: height: 0.45rem;
143新增: border: 1px solid var(--accent);
144新增: border-radius: 1px;
145新增: transform: rotate(45deg);
146新增: }
147新增:
148新增: .contribute__links {
149新增: display: grid;
150新增: grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
151新增: gap: 1px;
152新增: margin-top: clamp(2.5rem, 5vw, 4rem);
153新增: background: var(--line);
154新增: border: 1px solid var(--line);
155新增: border-radius: var(--radius-lg);
156新增: overflow: hidden;
157新增: }
158新增:
159新增: .contribute__link {
160新增: display: flex;
161新增: align-items: center;
162新增: justify-content: space-between;
163新增: gap: 1rem;
164新增: padding: 1.15rem 1.35rem;
165新增: background: var(--surface);
166新增: color: var(--ink);
167新增: text-decoration: none;
168新增: font-weight: 540;
169新增: font-size: 0.95rem;
170新增: transition: background-color 0.14s ease, color 0.14s ease;
171新增: }
172新增:
173新增: .contribute__link:hover {
174新增: background: var(--accent-wash);
175新增: color: var(--accent);
176新增: }
177新增:
178新增: .contribute__link-arrow {
179新增: font-family: var(--font-mono);
180新增: color: var(--ink-4);
181新增: transition: transform 0.14s ease, color 0.14s ease;
182新增: }
183新增:
184新增: .contribute__link:hover .contribute__link-arrow {
185新增: color: var(--accent);
186新增: transform: translateX(3px);
187新增: }
188新增:
189新增: @media (max-width: 62rem) {
190新增: .contribute__grid {
191新增: grid-template-columns: minmax(0, 1fr);
192新增: gap: 2.5rem;
193新增: }
194新增: }
195新增:</style>
新增www/src/components/Credits.astro+156 −0看文件
@@ -0,0 +1,156 @@
1新增:---
2新增:import { inline } from '../lib/inline';
3新增:import Heading from './Heading.astro';
4新增:import { t, type Locale } from '../i18n';
5新增:
6新增:interface Props {
7新增: locale: Locale;
8新增:}
9新增:
10新增:const { locale } = Astro.props;
11新增:const d = t(locale);
12新增:---
13新增:
14新增:<section class="section" id="credits">
15新增: <div class="container">
16新增: <div class="section-head">
17新增: <p class="eyebrow">{d.credits.eyebrow}</p>
18新增: <Heading as="h2" id="credits" own={false} locale={locale}>{d.credits.title}</Heading>
19新增: <p class="lede" set:html={inline(d.credits.lede)} />
20新增: </div>
21新增:
22新增: <div class="credits__groups">
23新增: {
24新增: d.credits.groups.map((group) => (
25新增: <section class="credits__group">
26新增: <h3 class="credits__group-title">{group.title}</h3>
27新增: <ul class="credits__list">
28新增: {group.items.map((item) => (
29新增: <li class="credits__item">
30新增: <a class="credits__name" href={item.href} rel="noopener" target="_blank">
31新增: {item.name}
32新增: </a>
33新增: <span class="credits__note">{item.note}</span>
34新增: </li>
35新增: ))}
36新增: </ul>
37新增: </section>
38新增: ))
39新增: }
40新增: </div>
41新增:
42新增: <div class="credits__meta">
43新增: <div class="credits__meta-block">
44新增: <h3 class="credits__meta-title">{d.credits.authorTitle}</h3>
45新增: <p class="prose">
46新增: {d.credits.authorBody}
47新增: </p>
48新增: <a class="credits__handle" href={d.credits.authorHref} rel="noopener" target="_blank">
49新增: @{d.credits.authorName}
50新增: </a>
51新增: </div>
52新增:
53新增: <div class="credits__meta-block">
54新增: <h3 class="credits__meta-title">{d.credits.licenseTitle}</h3>
55新增: <p class="prose">{d.credits.licenseBody}</p>
56新增: <a class="credits__handle" href={d.credits.licenseHref} rel="noopener" target="_blank">
57新增: LICENSE
58新增: </a>
59新增: </div>
60新增: </div>
61新增: </div>
62新增:</section>
63新增:
64新增:<style>
65新增: .credits__groups {
66新增: display: grid;
67新增: grid-template-columns: repeat(auto-fit, minmax(min(100%, 17rem), 1fr));
68新增: gap: clamp(1.75rem, 4vw, 3rem);
69新增: }
70新增:
71新增: .credits__group-title {
72新增: font-family: var(--font-mono);
73新增: font-size: 0.72rem;
74新增: font-weight: 500;
75新增: letter-spacing: 0.12em;
76新增: text-transform: uppercase;
77新增: color: var(--ink-3);
78新增: padding-bottom: 0.75rem;
79新增: margin-bottom: 1.1rem;
80新增: border-bottom: 1px solid var(--line);
81新增: }
82新增:
83新增: .credits__list {
84新增: display: grid;
85新增: gap: 1rem;
86新增: list-style: none;
87新增: }
88新增:
89新增: .credits__item {
90新增: display: grid;
91新增: gap: 0.15rem;
92新增: }
93新增:
94新增: .credits__name {
95新增: font-size: 0.97rem;
96新增: font-weight: 560;
97新增: color: var(--ink);
98新增: text-decoration: none;
99新增: justify-self: start;
100新增: border-bottom: 1px solid var(--line-strong);
101新增: }
102新增:
103新增: .credits__name:hover {
104新增: color: var(--accent);
105新增: border-bottom-color: var(--accent);
106新增: }
107新增:
108新增: .credits__note {
109新增: font-size: 0.87rem;
110新增: color: var(--ink-3);
111新增: }
112新增:
113新增: .credits__meta {
114新增: display: grid;
115新增: grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
116新增: gap: clamp(1.25rem, 3vw, 2.5rem);
117新增: margin-top: clamp(2.5rem, 5vw, 4rem);
118新增: padding-top: clamp(2rem, 4vw, 3rem);
119新增: border-top: 1px solid var(--line);
120新增: }
121新增:
122新增: .credits__meta-block {
123新增: display: grid;
124新增: gap: 0.5rem;
125新增: align-content: start;
126新增: }
127新增:
128新增: .credits__meta-title {
129新增: font-family: var(--font-mono);
130新增: font-size: 0.72rem;
131新增: font-weight: 500;
132新增: letter-spacing: 0.12em;
133新增: text-transform: uppercase;
134新增: color: var(--ink-3);
135新增: }
136新增:
137新增: .credits__meta-block .prose {
138新增: font-size: 0.93rem;
139新增: }
140新增:
141新增: .credits__handle {
142新增: justify-self: start;
143新增: font-family: var(--font-mono);
144新增: font-size: 0.83rem;
145新增: text-decoration: none;
146新增: padding: 0.28rem 0.6rem;
147新增: border: 1px solid var(--line-strong);
148新增: border-radius: var(--radius);
149新增: color: var(--ink-2);
150新增: }
151新增:
152新增: .credits__handle:hover {
153新增: border-color: var(--accent);
154新增: color: var(--accent);
155新增: }
156新增:</style>
新增www/src/components/Docs.astro+103 −0看文件
@@ -0,0 +1,103 @@
1新增:---
2新增:// A section of reference prose: groups of topics, each with paragraphs, an
3新增:// optional list and an optional code sample. Used for `reference` and
4新增:// `security`, which share this shape in the dictionaries.
5新增:import CodeBlock from './CodeBlock.astro';
6新增:import { inline } from '../lib/inline';
7新增:import Heading from './Heading.astro';
8新增:import { slug } from '../lib/slug';
9新增:import { en } from '../i18n/en';
10新增:import { t, type Locale } from '../i18n';
11新增:
12新增:interface Props {
13新增: locale: Locale;
14新增: part: 'reference' | 'security';
15新增:}
16新增:
17新增:const { locale, part } = Astro.props;
18新增:const d = t(locale)[part];
19新增:// Anchors come from the English titles, so links work in every language.
20新增:const source = en[part];
21新增:---
22新增:
23新增:<section class="section docs" id={part}>
24新增: <div class="container">
25新增: <div class="section-head">
26新增: <p class="eyebrow">{d.eyebrow}</p>
27新增: <Heading as="h2" id={part} own={false} locale={locale}>{d.title}</Heading>
28新增: <p class="lede" set:html={inline(d.lede)} />
29新增: </div>
30新增:
31新增: {
32新增: d.groups.map((group, g) => (
33新增: <div class="docs__group">
34新增: <Heading as="h3" id={slug(source.groups[g]!.title)} locale={locale} class="docs__group-title">{group.title}</Heading>
35新增: <div class="docs__topics">
36新增: {group.topics.map((topic, i) => (
37新增: <article class="docs__topic">
38新增: <Heading as="h4" id={slug(source.groups[g]!.topics[i]!.title)} locale={locale} class="docs__topic-title">{topic.title}</Heading>
39新增: {topic.paras.map((para) => <p class="prose docs__p" set:html={inline(para)} />)}
40新增: {topic.list.length > 0 && (
41新增: <ul class="docs__list">
42新增: {topic.list.map((item) => <li class="prose docs__p" set:html={inline(item)} />)}
43新增: </ul>
44新增: )}
45新增: {topic.code && <CodeBlock locale={locale} code={topic.code} />}
46新增: </article>
47新增: ))}
48新增: </div>
49新增: </div>
50新增: ))
51新增: }
52新增: </div>
53新增:</section>
54新增:
55新增:<style>
56新增: .docs__group {
57新增: display: grid;
58新增: gap: 1rem;
59新增: margin-top: clamp(2rem, 4vw, 3rem);
60新增: }
61新增:
62新增: .docs__group-title {
63新增: font-size: 1.15rem;
64新增: }
65新增:
66新增: .docs__topics {
67新增: display: grid;
68新增: grid-template-columns: repeat(auto-fit, minmax(min(100%, 28rem), 1fr));
69新增: gap: 1px;
70新增: background: var(--line);
71新增: border: 1px solid var(--line);
72新增: border-radius: var(--radius-lg);
73新增: overflow: hidden;
74新增: }
75新增:
76新增: .docs__topic {
77新增: display: grid;
78新增: align-content: start;
79新增: min-width: 0;
80新增: gap: 0.75rem;
81新增: padding: clamp(1.25rem, 2.4vw, 1.75rem);
82新增: background: var(--surface);
83新增: }
84新增:
85新增: /* An odd count would otherwise leave a hole in the last row. */
86新增: .docs__topic:last-child:nth-child(odd) {
87新增: grid-column: 1 / -1;
88新增: }
89新增:
90新增: .docs__topic-title {
91新增: font-size: 1.02rem;
92新增: }
93新增:
94新增: .docs__p {
95新增: font-size: 0.91rem;
96新增: }
97新增:
98新增: .docs__list {
99新增: display: grid;
100新增: gap: 0.5rem;
101新增: padding-left: 1.1rem;
102新增: }
103新增:</style>
新增www/src/components/Footer.astro+98 −0看文件
@@ -0,0 +1,98 @@
1新增:---
2新增:import { t, localeHref, otherLocales, type Locale } from '../i18n';
3新增:
4新增:interface Props {
5新增: locale: Locale;
6新增:}
7新增:
8新增:const { locale } = Astro.props;
9新增:const d = t(locale);
10新增:---
11新增:
12新增:<footer class="footer">
13新增: <div class="container footer__inner">
14新增: <div class="footer__brand">
15新增: <span class="footer__name">agent-vm</span>
16新增: <p class="footer__tagline">{d.footer.tagline}</p>
17新增: </div>
18新增:
19新增: <div class="footer__meta">
20新增: <a class="footer__link" href="https://github.com/sylvinus/agent-vm" rel="noopener" target="_blank">
21新增: {d.nav.github}
22新增: </a>
23新增: <a
24新增: class="footer__link"
25新增: href="https://github.com/sylvinus/agent-vm/blob/main/LICENSE"
26新增: rel="noopener"
27新增: target="_blank"
28新增: >
29新增: {d.footer.license}
30新增: </a>
31新增: {
32新增: otherLocales(locale).map((other) => (
33新增: <a class="footer__link" href={localeHref(other)} hreflang={other} lang={other}>
34新增: {t(other).meta.label}
35新增: </a>
36新增: ))
37新增: }
38新增: <a class="footer__link" href="#main">{d.footer.backToTop}</a>
39新增: </div>
40新增: </div>
41新增:</footer>
42新增:
43新增:<style>
44新增: .footer {
45新增: border-top: 1px solid var(--line);
46新增: background: var(--paper-sunk);
47新增: padding-block: clamp(2.5rem, 5vw, 3.5rem);
48新增: }
49新增:
50新增: .footer__inner {
51新增: display: grid;
52新增: grid-template-columns: minmax(0, 1fr) auto;
53新增: gap: 1.5rem clamp(1.5rem, 4vw, 3rem);
54新增: align-items: start;
55新增: }
56新增:
57新增: .footer__name {
58新增: font-family: var(--font-mono);
59新增: font-size: 0.95rem;
60新增: font-weight: 600;
61新增: color: var(--ink);
62新增: }
63新增:
64新增: .footer__tagline {
65新增: margin-top: 0.4rem;
66新增: max-width: 30rem;
67新增: font-size: 0.89rem;
68新增: color: var(--ink-3);
69新增: text-wrap: pretty;
70新增: }
71新增:
72新增: .footer__meta {
73新增: display: flex;
74新增: flex-wrap: wrap;
75新增: gap: 0.4rem 1.25rem;
76新增: justify-content: flex-end;
77新增: }
78新增:
79新增: .footer__link {
80新增: font-size: 0.87rem;
81新增: color: var(--ink-2);
82新增: text-decoration: none;
83新增: }
84新增:
85新增: .footer__link:hover {
86新增: color: var(--accent);
87新增: }
88新增:
89新增: @media (max-width: 48rem) {
90新增: .footer__inner {
91新增: grid-template-columns: minmax(0, 1fr);
92新增: }
93新增:
94新增: .footer__meta {
95新增: justify-content: flex-start;
96新增: }
97新增: }
98新增:</style>
新增www/src/components/Heading.astro+109 −0看文件
@@ -0,0 +1,109 @@
1新增:---
2新增:// A heading with a link to itself, shown on hover. Clicking it follows the
3新增:// link, as any anchor, and copies the full URL.
4新增://
5新增:// `id` is the anchor. With `own` false the heading does not carry it: a
6新增:// section title, whose <section> already has the id.
7新增:import { t, type Locale } from '../i18n';
8新增:
9新增:interface Props {
10新增: as: 'h2' | 'h3' | 'h4';
11新增: id: string;
12新增: locale: Locale;
13新增: own?: boolean;
14新增: class?: string;
15新增: [key: string]: unknown;
16新增:}
17新增:
18新增:// `...rest` carries the caller's scoped-style attribute, so the class it
19新增:// passes keeps its styles.
20新增:const { as: Tag, id, locale, own = true, class: className, ...rest } = Astro.props;
21新增:const d = t(locale);
22新增:---
23新增:
24新增:<Tag id={own ? id : undefined} class:list={['anchored', className]} {...rest}>
25新增: <slot /><a
26新增: class="anchored__link"
27新增: href={`#${id}`}
28新增: data-anchor
29新增: aria-label={d.ui.anchorLabel}
30新增: data-copied-label={d.ui.linkCopied}
31新增: ><svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"
32新增: ><path
33新增: d="M6.9 9.1a3 3 0 0 0 4.2 0l2.2-2.2a3 3 0 0 0-4.2-4.2l-.9.9M9.1 6.9a3 3 0 0 0-4.2 0L2.7 9.1a3 3 0 0 0 4.2 4.2l.9-.9"
34新增: ></path></svg
35新增: ></a
36新增: >
37新增:</Tag>
38新增:
39新增:<style>
40新增: .anchored__link {
41新增: position: relative;
42新增: display: inline-flex;
43新增: align-items: center;
44新增: margin-left: 0.4em;
45新增: vertical-align: middle;
46新增: color: var(--ink-4);
47新增: text-decoration: none;
48新增: opacity: 0;
49新增: transition: opacity 0.14s ease, color 0.14s ease;
50新增: }
51新增:
52新增: .anchored__link svg {
53新增: width: 0.8em;
54新增: height: 0.8em;
55新增: fill: none;
56新增: stroke: currentColor;
57新增: stroke-width: 1.6;
58新增: stroke-linecap: round;
59新增: }
60新增:
61新增: .anchored:hover .anchored__link,
62新增: .anchored__link:focus-visible {
63新增: opacity: 1;
64新增: }
65新增:
66新增: .anchored__link:hover {
67新增: color: var(--accent);
68新增: }
69新增:
70新增: .anchored__link[data-state='done'] {
71新增: opacity: 1;
72新增: color: var(--safe);
73新增: }
74新增:
75新增: .anchored__link[data-state='done']::after {
76新增: content: attr(data-copied-label);
77新增: position: absolute;
78新增: left: calc(100% + 0.4rem);
79新增: white-space: nowrap;
80新增: font-family: var(--font-mono);
81新增: font-size: 0.68rem;
82新增: font-weight: 400;
83新增: letter-spacing: 0.06em;
84新增: text-transform: uppercase;
85新增: }
86新增:
87新增: /* Coarse pointers never hover: keep the link findable. */
88新增: @media (hover: none) {
89新增: .anchored__link {
90新增: opacity: 0.45;
91新增: }
92新增: }
93新增:</style>
94新增:
95新增:<script>
96新增: // One listener for every heading on the page. The link is followed as
97新增: // usual; this only adds the copy.
98新增: document.addEventListener('click', (event) => {
99新增: const link = (event.target as Element | null)?.closest<HTMLAnchorElement>('[data-anchor]');
100新增: if (!link || !navigator.clipboard) return;
101新增: navigator.clipboard.writeText(link.href).then(
102新增: () => {
103新增: link.dataset.state = 'done';
104新增: window.setTimeout(() => delete link.dataset.state, 1600);
105新增: },
106新增: () => {},
107新增: );
108新增: });
109新增:</script>
新增www/src/components/Hero.astro+330 −0看文件
@@ -0,0 +1,330 @@
1新增:---
2新增:import InstallTabs from './InstallTabs.astro';
3新增:import { t, type Locale } from '../i18n';
4新增:
5新增:interface Props {
6新增: locale: Locale;
7新增:}
8新增:
9新增:const { locale } = Astro.props;
10新增:const d = t(locale);
11新增:
12新增:// Illustrative session, with no real path or host. The output lines follow
13新增:// what agent-vm prints for a VM that exists but is stopped, trimmed to what
14新增:// makes the point: not every line has to be there.
15新增:const session: Array<{ kind: 'cmd' | 'out' | 'ok' | 'dim' | 'gap'; text: string }> = [
16新增: { kind: 'cmd', text: 'cd ~/work/acme-api' },
17新增: { kind: 'cmd', text: 'agent-vm run cat ~/.ssh/id_ed25519' },
18新增: { kind: 'out', text: "Starting VM 'agent-vm-acme-api-8f3c1d20'..." },
19新增: { kind: 'out', text: ' Resources: CPUs: 1, Memory: 3 GiB, Disk: 10 GiB' },
20新增: { kind: 'ok', text: 'cat: /Users/you/.ssh/id_ed25519: No such file or directory' },
21新增: { kind: 'gap', text: '' },
22新增: { kind: 'cmd', text: 'agent-vm opencode' },
23新增: { kind: 'out', text: ' Resources: CPUs: 1, Memory: 3 GiB, Disk: 10 GiB' },
24新增: { kind: 'dim', text: '# OpenCode starts here, with --auto' },
25新增:];
26新增:---
27新增:
28新增:<section class="hero">
29新增: <div class="hero__grid" aria-hidden="true"></div>
30新增:
31新增: <div class="container hero__inner">
32新增: <div class="hero__copy">
33新增: <h1 class="hero__title">
34新增: {d.hero.title}
35新增: <span class="hero__accent">{d.hero.titleAccent}</span>
36新增: </h1>
37新增:
38新增: <p class="lede hero__lede">{d.hero.lede}</p>
39新增:
40新增: <div class="hero__install">
41新增: <p class="hero__install-label">{d.hero.installLabel}</p>
42新增: {/* The curl installer offers to run setup itself. */}
43新增: <InstallTabs
44新增: locale={locale}
45新增: id="hero-install"
46新增: then={{ brew: 'agent-vm setup', git: 'agent-vm setup' }}
47新增: />
48新增: </div>
49新增:
50新增: <div class="hero__ctas">
51新增: <a class="btn btn--primary" href="#install">{d.hero.ctaPrimary}</a>
52新增: <a class="btn btn--ghost" href="#architecture">{d.hero.ctaSecondary}</a>
53新增: </div>
54新增:
55新增: <p class="hero__meta">{d.hero.meta}</p>
56新增: </div>
57新增:
58新增: <div class="hero__demo">
59新增: <div class="term">
60新增: <div class="term__bar">
61新增: <span class="term__dots" aria-hidden="true">
62新增: <i></i><i></i><i></i>
63新增: </span>
64新增: </div>
65新增: <div class="term__body">
66新增: {
67新增: session.map((line) => (
68新增: <div class:list={['term__line', `term__line--${line.kind}`]}>
69新增: {line.kind === 'cmd' && (
70新增: <span class="term__prompt" aria-hidden="true">
71新增: $
72新增: </span>
73新增: )}
74新增: <span class="term__text">{line.text}</span>
75新增: </div>
76新增: ))
77新增: }
78新增: </div>
79新增: </div>
80新增: <p class="hero__caption">{d.hero.terminalCaption}</p>
81新增: </div>
82新增: </div>
83新增:
84新增: <div class="container">
85新增: <ul class="hero__points">
86新增: {
87新增: d.hero.points.map((point) => (
88新增: <li class="hero__point">
89新增: <h2 class="hero__point-title">{point.title}</h2>
90新增: <p class="hero__point-body">{point.body}</p>
91新增: </li>
92新增: ))
93新增: }
94新增: </ul>
95新增: </div>
96新增:</section>
97新增:
98新增:<style>
99新增: .hero {
100新增: position: relative;
101新增: padding-top: clamp(3rem, 7vw, 5.5rem);
102新增: padding-bottom: clamp(2.5rem, 5vw, 4rem);
103新增: overflow: hidden;
104新增: }
105新增:
106新增: /* A faint engineering grid, fading out downward. Decoration only. */
107新增: .hero__grid {
108新增: position: absolute;
109新增: inset: 0;
110新增: background-image: linear-gradient(to right, var(--line) 1px, transparent 1px),
111新增: linear-gradient(to bottom, var(--line) 1px, transparent 1px);
112新增: background-size: 3.5rem 3.5rem;
113新增: mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), transparent 72%);
114新增: -webkit-mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), transparent 72%);
115新增: pointer-events: none;
116新增: }
117新增:
118新增: .hero__inner {
119新增: position: relative;
120新增: display: grid;
121新增: grid-template-columns: minmax(0, 1.05fr) minmax(0, 0.95fr);
122新增: gap: clamp(2rem, 5vw, 4.5rem);
123新增: align-items: start;
124新增: }
125新增:
126新增: .hero__title {
127新增: margin-bottom: 1.5rem;
128新增: }
129新增:
130新增: .hero__meta {
131新增: margin-top: 1.5rem;
132新增: font-family: var(--font-mono);
133新增: font-size: 0.72rem;
134新增: letter-spacing: 0.1em;
135新增: text-transform: uppercase;
136新增: color: var(--ink-4);
137新增: }
138新增:
139新增: .hero__accent {
140新增: display: block;
141新增: color: var(--accent);
142新增: }
143新增:
144新增: .hero__lede {
145新增: max-width: 38rem;
146新增: margin-bottom: 2.25rem;
147新增: }
148新增:
149新增: .hero__install {
150新增: margin-bottom: 1.5rem;
151新增: }
152新增:
153新增: .hero__install-label {
154新增: margin-bottom: 0.6rem;
155新增: font-family: var(--font-mono);
156新增: font-size: 0.7rem;
157新增: letter-spacing: 0.12em;
158新增: text-transform: uppercase;
159新增: color: var(--ink-3);
160新增: }
161新增:
162新增: .hero__ctas {
163新增: display: flex;
164新增: flex-wrap: wrap;
165新增: gap: 0.7rem;
166新增: }
167新增:
168新增: /* Terminal ---------------------------------------------------------------- */
169新增:
170新增: .hero__copy,
171新增: .hero__demo {
172新增: min-width: 0;
173新增: }
174新增:
175新增: .hero__demo {
176新增: position: relative;
177新增: padding-top: 2.5rem;
178新增: }
179新增:
180新增: .term {
181新增: border: 1px solid var(--code-line);
182新增: border-radius: var(--radius-lg);
183新增: background: var(--code-bg);
184新增: overflow: hidden;
185新增: }
186新增:
187新增: .term__bar {
188新增: display: flex;
189新增: align-items: center;
190新增: padding: 0.6rem 0.9rem;
191新增: border-bottom: 1px solid var(--code-line);
192新增: background: color-mix(in srgb, var(--code-bg) 82%, #fff 18%);
193新增: }
194新增:
195新增: .term__dots {
196新增: display: inline-flex;
197新增: gap: 0.35rem;
198新增: }
199新增:
200新增: .term__dots i {
201新增: width: 0.55rem;
202新增: height: 0.55rem;
203新增: border-radius: 50%;
204新增: background: var(--code-line);
205新增: }
206新增:
207新增: .term__body {
208新增: padding: 1.1rem 1.15rem 1.4rem;
209新增: font-family: var(--font-mono);
210新增: font-size: 0.79rem;
211新增: line-height: 1.85;
212新增: color: var(--code-ink);
213新增: overflow-x: auto;
214新增: }
215新增:
216新增: .term__line {
217新增: display: flex;
218新增: gap: 0.55rem;
219新增: white-space: pre;
220新增: }
221新增:
222新增: .term__line--gap {
223新增: height: 0.7rem;
224新增: }
225新增:
226新增: .term__prompt {
227新增: color: #eaa963;
228新增: user-select: none;
229新增: }
230新增:
231新增: .term__line--out .term__text {
232新增: color: var(--code-ink-2);
233新增: }
234新增:
235新增: .term__line--dim .term__text {
236新增: color: #6f6a60;
237新增: font-style: italic;
238新增: }
239新增:
240新增: .term__line--ok .term__text {
241新增: color: #9dc08b;
242新增: }
243新增:
244新增: .hero__caption {
245新增: margin-top: 0.9rem;
246新增: font-size: 0.82rem;
247新增: color: var(--ink-3);
248新增: }
249新增:
250新增: /* Points ------------------------------------------------------------------ */
251新增:
252新增: .hero__points {
253新增: position: relative;
254新增: display: grid;
255新增: grid-template-columns: repeat(4, minmax(0, 1fr));
256新增: gap: 0;
257新增: margin-top: clamp(3rem, 6vw, 5rem);
258新增: list-style: none;
259新增: border-top: 1px solid var(--line);
260新增: }
261新增:
262新增: .hero__point {
263新增: padding: 1.6rem clamp(1rem, 2vw, 1.75rem) 0;
264新增: border-left: 1px solid var(--line);
265新增: }
266新增:
267新增: .hero__point:first-child {
268新增: padding-left: 0;
269新增: border-left: 0;
270新增: }
271新增:
272新增: .hero__point-title {
273新增: font-size: 0.95rem;
274新增: font-weight: 600;
275新增: letter-spacing: -0.01em;
276新增: margin-bottom: 0.4rem;
277新增: }
278新增:
279新增: .hero__point-body {
280新增: font-size: 0.9rem;
281新增: color: var(--ink-2);
282新增: text-wrap: pretty;
283新增: }
284新增:
285新增: /* Four columns only while they stay readable; two, then one. */
286新增: @media (max-width: 72rem) {
287新增: .hero__points {
288新增: grid-template-columns: repeat(2, minmax(0, 1fr));
289新增: }
290新增:
291新增: .hero__point:nth-child(odd) {
292新增: padding-left: 0;
293新增: border-left: 0;
294新增: }
295新增:
296新增: .hero__point:nth-child(n + 3) {
297新增: padding-top: 1.6rem;
298新增: border-top: 1px solid var(--line);
299新增: }
300新增: }
301新增:
302新增: @media (max-width: 62rem) {
303新增: .hero__inner {
304新增: grid-template-columns: minmax(0, 1fr);
305新增: }
306新增:
307新增: .hero__demo {
308新增: padding-top: 0;
309新增: }
310新增:
311新增: .hero__points {
312新增: grid-template-columns: minmax(0, 1fr);
313新增: }
314新增:
315新增: .hero__point {
316新增: padding: 1.25rem 0;
317新增: border-left: 0;
318新增: border-top: 0;
319新增: border-bottom: 1px solid var(--line);
320新增: }
321新增:
322新增: .hero__point:first-child {
323新增: padding-top: 1.25rem;
324新增: }
325新增:
326新增: .hero__point:last-child {
327新增: border-bottom: 0;
328新增: }
329新增: }
330新增:</style>
新增www/src/components/Install.astro+263 −0看文件
@@ -0,0 +1,263 @@
1新增:---
2新增:import CodeBlock from './CodeBlock.astro';
3新增:import InstallTabs from './InstallTabs.astro';
4新增:import { inline } from '../lib/inline';
5新增:import Heading from './Heading.astro';
6新增:import { slug } from '../lib/slug';
7新增:import { en } from '../i18n/en';
8新增:import { t, type Locale } from '../i18n';
9新增:
10新增:interface Props {
11新增: locale: Locale;
12新增:}
13新增:
14新增:const { locale } = Astro.props;
15新增:const d = t(locale);
16新增:---
17新增:
18新增:<section class="section" id="install">
19新增: <div class="container">
20新增: <div class="section-head">
21新增: <p class="eyebrow">{d.install.eyebrow}</p>
22新增: <Heading as="h2" id="install" own={false} locale={locale}>{d.install.title}</Heading>
23新增: <p class="lede" set:html={inline(d.install.lede)} />
24新增: </div>
25新增:
26新增: <div class="install__layout">
27新增: <aside class="install__prereq card card--sunk">
28新增: <h3 class="install__prereq-title">{d.install.prerequisitesTitle}</h3>
29新增: <ul class="install__prereq-list">
30新增: {
31新增: d.install.prerequisites.map((item) => (
32新增: <li class="install__prereq-item">
33新增: <span class="install__prereq-name">
34新增: {item.href ? (
35新增: <a href={item.href} rel="noopener noreferrer" target="_blank">
36新增: {item.name}
37新增: </a>
38新增: ) : (
39新增: item.name
40新增: )}
41新增: </span>
42新增: <span class="install__prereq-note" set:html={inline(item.note)} />
43新增: </li>
44新增: ))
45新增: }
46新增: </ul>
47新增: </aside>
48新增:
49新增: <ol class="install__steps">
50新增: <li class="install__step">
51新增: <div class="install__step-head">
52新增: <span class="install__step-n" aria-hidden="true">01</span>
53新增: <div>
54新增: <Heading as="h3" id={slug(en.install.methodsTitle)} locale={locale} class="install__step-title">{d.install.methodsTitle}</Heading>
55新增: <p class="prose install__step-body" set:html={inline(d.install.methodsBody)} />
56新增: </div>
57新增: </div>
58新增: <InstallTabs locale={locale} id="install-methods" notes />
59新增: </li>
60新增: {
61新增: d.install.steps.map((step, index) => (
62新增: <li class="install__step">
63新增: <div class="install__step-head">
64新增: <span class="install__step-n" aria-hidden="true">
65新增: {String(index + 2).padStart(2, '0')}
66新增: </span>
67新增: <div>
68新增: <Heading as="h3" id={slug(en.install.steps[index]!.title)} locale={locale} class="install__step-title">{step.title}</Heading>
69新增: <p class="prose install__step-body" set:html={inline(step.body)} />
70新增: </div>
71新增: </div>
72新增: <CodeBlock locale={locale} code={step.code} prompt />
73新增: </li>
74新增: ))
75新增: }
76新增: </ol>
77新增: </div>
78新增:
79新增: {/* Sits with step 2 rather than in its own reference section: it is only
80新增: ever about `agent-vm setup`, which is on this page. */}
81新增: <div class="install__preinstall">
82新增: <Heading as="h3" id={slug(en.install.preinstallTitle)} locale={locale} class="install__sub">{d.install.preinstallTitle}</Heading>
83新增: <p class="prose install__sub-body" set:html={inline(d.install.preinstallBody)} />
84新增: <p class="install__names">{d.install.preinstallNames}</p>
85新增: <div class="table-wrap">
86新增: <table class="table--code table--grid">
87新增: <thead>
88新增: <tr>{d.install.setupHeaders.map((header) => <th scope="col">{header}</th>)}</tr>
89新增: </thead>
90新增: <tbody>
91新增: {
92新增: d.install.setup.map(([flag, description, fallback]) => (
93新增: <tr>
94新增: <td>{flag}</td>
95新增: <td set:html={inline(description ?? '')} />
96新增: <td class="install__default">{fallback}</td>
97新增: </tr>
98新增: ))
99新增: }
100新增: </tbody>
101新增: </table>
102新增: </div>
103新增: <CodeBlock locale={locale} code={d.install.preinstallCode} />
104新增: </div>
105新增:
106新增: <div class="install__extras">
107新增: <div class="note">
108新增: <strong class="note__title">{d.install.updateTitle}</strong>
109新增: <p class="prose" set:html={inline(d.install.updateBody)} />
110新增: </div>
111新增: </div>
112新增: </div>
113新增:</section>
114新增:
115新增:<style>
116新增: .install__layout {
117新增: display: grid;
118新增: grid-template-columns: minmax(0, 0.62fr) minmax(0, 1.38fr);
119新增: gap: clamp(1.5rem, 3.5vw, 3rem);
120新增: align-items: start;
121新增: }
122新增:
123新增: .install__prereq {
124新增: position: sticky;
125新增: top: calc(var(--nav-h) + 2rem);
126新增: }
127新增:
128新增: .install__prereq-title {
129新增: font-size: 0.72rem;
130新增: font-family: var(--font-mono);
131新增: letter-spacing: 0.12em;
132新增: text-transform: uppercase;
133新增: color: var(--ink-3);
134新增: font-weight: 500;
135新增: margin-bottom: 1.1rem;
136新增: }
137新增:
138新增: .install__prereq-list {
139新增: list-style: none;
140新增: display: grid;
141新增: gap: 1.05rem;
142新增: }
143新增:
144新增: .install__prereq-item {
145新增: display: grid;
146新增: gap: 0.2rem;
147新增: padding-left: 0.9rem;
148新增: border-left: 2px solid var(--accent-line);
149新增: }
150新增:
151新增: .install__prereq-name {
152新增: font-size: 0.95rem;
153新增: font-weight: 560;
154新增: color: var(--ink);
155新增: }
156新增:
157新增: .install__prereq-note {
158新增: font-size: 0.86rem;
159新增: color: var(--ink-3);
160新增: }
161新增:
162新增: .install__steps {
163新增: list-style: none;
164新增: display: grid;
165新增: gap: clamp(1.75rem, 3vw, 2.5rem);
166新增: min-width: 0;
167新增: }
168新增:
169新增: .install__step {
170新增: display: grid;
171新增: gap: 1rem;
172新增: min-width: 0;
173新增: }
174新增:
175新增: .install__step-head {
176新增: display: flex;
177新增: gap: 1rem;
178新增: align-items: start;
179新增: }
180新增:
181新增: .install__step-n {
182新增: flex: none;
183新增: width: 2.1rem;
184新增: height: 2.1rem;
185新增: display: grid;
186新增: place-items: center;
187新增: border: 1px solid var(--line-strong);
188新增: border-radius: 50%;
189新增: font-family: var(--font-mono);
190新增: font-size: 0.74rem;
191新增: color: var(--accent);
192新增: background: var(--surface);
193新增: }
194新增:
195新增: .install__step-title {
196新增: margin-bottom: 0.3rem;
197新增: }
198新增:
199新增: .install__step-body {
200新增: font-size: 0.94rem;
201新增: max-width: 44rem;
202新增: }
203新增:
204新增: .install__preinstall {
205新增: display: grid;
206新增: gap: 1rem;
207新增: min-width: 0;
208新增: margin-top: clamp(2.5rem, 5vw, 4rem);
209新增: }
210新增:
211新增: .install__sub {
212新增: font-size: 1.05rem;
213新增: }
214新增:
215新增: .install__sub-body {
216新增: font-size: 0.93rem;
217新增: margin-top: -0.35rem;
218新增: max-width: 48rem;
219新增: }
220新增:
221新增: .install__names {
222新增: font-family: var(--font-mono);
223新增: font-size: 0.8rem;
224新增: line-height: 2;
225新增: color: var(--accent);
226新增: padding: 0.9rem 1.1rem;
227新增: border: 1px solid var(--accent-line);
228新增: border-radius: var(--radius);
229新增: background: var(--accent-wash);
230新增: overflow-wrap: anywhere;
231新增: }
232新增:
233新增: .install__default {
234新增: font-family: var(--font-mono);
235新增: font-size: 0.78rem;
236新增: color: var(--ink-3);
237新增: white-space: nowrap;
238新增: }
239新增:
240新增: .install__extras {
241新增: display: grid;
242新增: grid-template-columns: minmax(0, 1fr);
243新增: gap: clamp(1.25rem, 3vw, 2.5rem);
244新增: margin-top: clamp(2.5rem, 5vw, 4rem);
245新增: align-items: start;
246新增: max-width: 52rem;
247新增: }
248新增:
249新增: .install__extras .prose {
250新增: font-size: 0.93rem;
251新增: }
252新增:
253新增: @media (max-width: 62rem) {
254新增: .install__layout,
255新增: .install__extras {
256新增: grid-template-columns: minmax(0, 1fr);
257新增: }
258新增:
259新增: .install__prereq {
260新增: position: static;
261新增: }
262新增: }
263新增:</style>
新增www/src/components/InstallTabs.astro+171 −0看文件
@@ -0,0 +1,171 @@
1新增:---
2新增:import CodeBlock from './CodeBlock.astro';
3新增:import { inline } from '../lib/inline';
4新增:import { t, type Locale } from '../i18n';
5新增:
6新增:interface Props {
7新增: locale: Locale;
8新增: /** Keeps ids unique: the hero and the install section both have one. */
9新增: id: string;
10新增: /** Command appended to a method's code, by method id. */
11新增: then?: Record<string, string>;
12新增: /** Show each method's note under its code. */
13新增: notes?: boolean;
14新增:}
15新增:
16新增:const { locale, id, then = {}, notes = false } = Astro.props;
17新增:const d = t(locale);
18新增:const methods = d.install.methods;
19新增:---
20新增:
21新增:<div class="tabs" data-tabs>
22新增: <div class="tabs__list" role="tablist" aria-label={d.install.methodsLabel}>
23新增: {
24新增: methods.map((method, index) => (
25新增: <button
26新增: type="button"
27新增: class="tabs__tab"
28新增: role="tab"
29新增: id={`${id}-tab-${method.id}`}
30新增: aria-controls={`${id}-panel-${method.id}`}
31新增: aria-selected={index === 0 ? 'true' : 'false'}
32新增: tabindex={index === 0 ? 0 : -1}
33新增: data-tab={method.id}
34新增: >
35新增: {method.label}
36新增: </button>
37新增: ))
38新增: }
39新增: </div>
40新增: {
41新增: methods.map((method, index) => (
42新增: <div
43新增: class="tabs__panel"
44新增: role="tabpanel"
45新增: id={`${id}-panel-${method.id}`}
46新增: aria-labelledby={`${id}-tab-${method.id}`}
47新增: data-panel={method.id}
48新增: hidden={index !== 0}
49新增: >
50新增: <CodeBlock locale={locale} prompt code={then[method.id] ? `${method.code}\n${then[method.id]}` : method.code} />
51新增: {notes && <p class="prose tabs__note" set:html={inline(method.note)} />}
52新增: </div>
53新增: ))
54新增: }
55新增:</div>
56新增:
57新增:<style>
58新增: .tabs {
59新增: display: grid;
60新增: gap: 0.6rem;
61新增: min-width: 0;
62新增: }
63新增:
64新增: .tabs__list {
65新增: display: flex;
66新增: flex-wrap: wrap;
67新增: gap: 0.35rem;
68新增: }
69新增:
70新增: .tabs__tab {
71新增: padding: 0.3rem 0.75rem;
72新增: border: 1px solid var(--line);
73新增: border-radius: 999px;
74新增: background: transparent;
75新增: color: var(--ink-3);
76新增: font-family: var(--font-mono);
77新增: font-size: 0.74rem;
78新增: letter-spacing: 0.02em;
79新增: cursor: pointer;
80新增: transition: color 0.14s ease, border-color 0.14s ease, background 0.14s ease;
81新增: }
82新增:
83新增: .tabs__tab:hover {
84新增: color: var(--ink);
85新增: border-color: var(--line-strong);
86新增: }
87新增:
88新增: .tabs__tab[aria-selected='true'] {
89新增: color: var(--accent);
90新增: border-color: var(--accent-line);
91新增: background: var(--accent-wash);
92新增: }
93新增:
94新增: .tabs__tab:focus-visible {
95新增: outline: 2px solid var(--accent);
96新增: outline-offset: 2px;
97新增: }
98新增:
99新增: .tabs__panel {
100新增: display: grid;
101新增: gap: 0.75rem;
102新增: min-width: 0;
103新增: }
104新增:
105新增: .tabs__panel[hidden] {
106新增: display: none;
107新增: }
108新增:
109新增: .tabs__note {
110新增: font-size: 0.9rem;
111新增: max-width: 44rem;
112新增: }
113新增:</style>
114新增:
115新增:<script>
116新增: // Every tab set on the page shows the same method, and the choice is kept
117新增: // for the next visit.
118新增: const KEY = 'agent-vm:install-method';
119新增:
120新增: function select(method: string, focus?: HTMLElement) {
121新增: const tabs = document.querySelectorAll<HTMLElement>('[data-tabs] [data-tab]');
122新增: if (![...tabs].some((tab) => tab.dataset.tab === method)) return;
123新增: for (const tab of tabs) {
124新增: const on = tab.dataset.tab === method;
125新增: tab.setAttribute('aria-selected', on ? 'true' : 'false');
126新增: tab.tabIndex = on ? 0 : -1;
127新增: }
128新增: for (const panel of document.querySelectorAll<HTMLElement>('[data-tabs] [data-panel]')) {
129新增: panel.hidden = panel.dataset.panel !== method;
130新增: }
131新增: focus?.focus();
132新增: }
133新增:
134新增: function remember(method: string) {
135新增: try {
136新增: localStorage.setItem(KEY, method);
137新增: } catch {}
138新增: }
139新增:
140新增: try {
141新增: const saved = localStorage.getItem(KEY);
142新增: if (saved) select(saved);
143新增: } catch {}
144新增:
145新增: document.addEventListener('click', (event) => {
146新增: const tab = (event.target as Element | null)?.closest<HTMLElement>('[data-tabs] [data-tab]');
147新增: if (!tab?.dataset.tab) return;
148新增: select(tab.dataset.tab);
149新增: remember(tab.dataset.tab);
150新增: });
151新增:
152新增: // Arrow keys, Home and End move between tabs and select as they go.
153新增: document.addEventListener('keydown', (event) => {
154新增: const tab = (event.target as Element | null)?.closest<HTMLElement>('[data-tabs] [data-tab]');
155新增: const list = tab?.parentElement;
156新增: if (!tab || !list) return;
157新增: const tabs = [...list.querySelectorAll<HTMLElement>('[data-tab]')];
158新增: const at = tabs.indexOf(tab);
159新增: const moves: Record<string, HTMLElement | undefined> = {
160新增: ArrowRight: tabs[(at + 1) % tabs.length],
161新增: ArrowLeft: tabs[(at - 1 + tabs.length) % tabs.length],
162新增: Home: tabs[0],
163新增: End: tabs[tabs.length - 1],
164新增: };
165新增: const next = moves[event.key];
166新增: if (!next?.dataset.tab) return;
167新增: event.preventDefault();
168新增: select(next.dataset.tab, next);
169新增: remember(next.dataset.tab);
170新增: });
171新增:</script>
新增www/src/components/Landing.astro+27 −0看文件
@@ -0,0 +1,27 @@
1新增:---
2新增:import Hero from './Hero.astro';
3新增:import Threat from './Threat.astro';
4新增:import Install from './Install.astro';
5新增:import Usage from './Usage.astro';
6新增:import Docs from './Docs.astro';
7新增:import Architecture from './Architecture.astro';
8新增:import Contribute from './Contribute.astro';
9新增:import Credits from './Credits.astro';
10新增:import type { Locale } from '../i18n';
11新增:
12新增:interface Props {
13新增: locale: Locale;
14新增:}
15新增:
16新增:const { locale } = Astro.props;
17新增:---
18新增:
19新增:<Hero locale={locale} />
20新增:<Threat locale={locale} />
21新增:<Install locale={locale} />
22新增:<Usage locale={locale} />
23新增:<Docs locale={locale} part="reference" />
24新增:<Architecture locale={locale} />
25新增:<Docs locale={locale} part="security" />
26新增:<Contribute locale={locale} />
27新增:<Credits locale={locale} />
新增www/src/components/Nav.astro+325 −0看文件
@@ -0,0 +1,325 @@
1新增:---
2新增:import { t, localeHref, otherLocales, type Locale } from '../i18n';
3新增:
4新增:interface Props {
5新增: locale: Locale;
6新增:}
7新增:
8新增:const { locale } = Astro.props;
9新增:const d = t(locale);
10新增:
11新增:// Prefixed with the locale root rather than left as bare fragments: on the 404
12新增:// page, where none of these sections exist, a bare `#install` goes nowhere.
13新增:// On the landing page itself the browser still treats these as same-document
14新增:// fragment navigations, so the smooth scroll is unaffected.
15新增:const home = localeHref(locale);
16新增:const links = [
17新增: { href: `${home}#install`, label: d.nav.sections.install },
18新增: { href: `${home}#usage`, label: d.nav.sections.usage },
19新增: { href: `${home}#reference`, label: d.nav.sections.reference },
20新增: { href: `${home}#architecture`, label: d.nav.sections.architecture },
21新增: { href: `${home}#security`, label: d.nav.sections.security },
22新增: { href: `${home}#contribute`, label: d.nav.sections.contribute },
23新增: { href: `${home}#credits`, label: d.nav.sections.credits },
24新增:];
25新增:---
26新增:
27新增:<header class="nav">
28新增: <div class="nav__inner container">
29新增: <a class="nav__brand" href={localeHref(locale)}>
30新增: <svg class="nav__mark" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
31新增: <rect x="1.25" y="1.25" width="21.5" height="21.5" rx="4.5" />
32新增: <rect class="nav__mark-inner" x="6.75" y="6.75" width="10.5" height="10.5" rx="2" />
33新增: </svg>
34新增: <span class="nav__name">agent-vm</span>
35新增: </a>
36新增:
37新增: <button
38新增: type="button"
39新增: class="nav__burger"
40新增: data-nav-toggle
41新增: aria-expanded="false"
42新增: aria-controls="nav-panel"
43新增: >
44新增: <span class="visually-hidden">{d.nav.menu}</span>
45新增: <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
46新增: <path class="nav__burger-lines" d="M4 7h16M4 12h16M4 17h16" />
47新增: <path class="nav__burger-close" d="M6 6l12 12M18 6L6 18" />
48新增: </svg>
49新增: </button>
50新增:
51新增: <div class="nav__panel" id="nav-panel" data-nav-panel>
52新增: <nav class="nav__links" aria-label={d.nav.menu}>
53新增: {
54新增: links.map((link) => (
55新增: <a class="nav__link" href={link.href} data-nav-link>
56新增: {link.label}
57新增: </a>
58新增: ))
59新增: }
60新增: </nav>
61新增:
62新增: <div class="nav__tools">
63新增: <div class="nav__langs" role="group" aria-label={d.nav.language}>
64新增: <span class="nav__lang nav__lang--current" aria-current="true">
65新增: {locale.toUpperCase()}
66新增: </span>
67新增: {
68新增: otherLocales(locale).map((other) => (
69新增: <a class="nav__lang" href={localeHref(other)} hreflang={other} lang={other}>
70新增: {other.toUpperCase()}
71新增: </a>
72新增: ))
73新增: }
74新增: </div>
75新增:
76新增: <a
77新增: class="nav__icon"
78新增: href="https://github.com/sylvinus/agent-vm"
79新增: rel="noopener"
80新增: target="_blank"
81新增: >
82新增: <span class="visually-hidden">{d.nav.github}</span>
83新增: <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" class="nav__gh">
84新增: <path
85新增: d="M12 1.8a10.2 10.2 0 0 0-3.23 19.88c.51.1.7-.22.7-.49v-1.9c-2.84.62-3.44-1.2-3.44-1.2-.47-1.18-1.14-1.5-1.14-1.5-.93-.63.07-.62.07-.62 1.03.07 1.57 1.06 1.57 1.06.91 1.57 2.4 1.12 2.99.86.09-.66.36-1.12.65-1.37-2.27-.26-4.65-1.13-4.65-5.04 0-1.12.4-2.03 1.05-2.74-.1-.26-.45-1.3.1-2.7 0 0 .86-.28 2.8 1.05a9.7 9.7 0 0 1 5.1 0c1.94-1.33 2.8-1.05 2.8-1.05.55 1.4.2 2.44.1 2.7.65.71 1.05 1.62 1.05 2.74 0 3.92-2.39 4.78-4.66 5.03.37.32.7.94.7 1.9v2.81c0 .27.18.59.7.49A10.2 10.2 0 0 0 12 1.8z"
86新增: />
87新增: </svg>
88新增: </a>
89新增: </div>
90新增: </div>
91新增: </div>
92新增:</header>
93新增:
94新增:<style>
95新增: .nav {
96新增: position: sticky;
97新增: top: 0;
98新增: z-index: 50;
99新增: background: color-mix(in srgb, var(--paper) 88%, transparent);
100新增: backdrop-filter: saturate(160%) blur(12px);
101新增: border-bottom: 1px solid var(--line);
102新增: }
103新增:
104新增: .nav__inner {
105新增: display: flex;
106新增: align-items: center;
107新增: gap: 1rem;
108新增: min-height: var(--nav-h);
109新增: }
110新增:
111新增: .nav__brand {
112新增: display: inline-flex;
113新增: align-items: center;
114新增: gap: 0.55rem;
115新增: margin-right: auto;
116新增: color: var(--ink);
117新增: text-decoration: none;
118新增: font-weight: 600;
119新增: letter-spacing: -0.015em;
120新增: }
121新增:
122新增: .nav__mark {
123新增: width: 1.35rem;
124新增: height: 1.35rem;
125新增: fill: none;
126新增: stroke: var(--ink);
127新增: stroke-width: 1.5;
128新增: }
129新增:
130新增: .nav__mark-inner {
131新增: fill: var(--accent);
132新增: stroke: none;
133新增: }
134新增:
135新增: .nav__name {
136新增: font-family: var(--font-mono);
137新增: font-size: 0.95rem;
138新增: }
139新增:
140新增: .nav__burger {
141新增: display: none;
142新增: align-items: center;
143新增: justify-content: center;
144新增: width: 2.25rem;
145新增: height: 2.25rem;
146新增: padding: 0;
147新增: border: 1px solid var(--line);
148新增: border-radius: var(--radius);
149新增: background: transparent;
150新增: color: var(--ink);
151新增: cursor: pointer;
152新增: }
153新增:
154新增: .nav__burger svg {
155新增: width: 1.1rem;
156新增: height: 1.1rem;
157新增: fill: none;
158新增: stroke: currentColor;
159新增: stroke-width: 1.6;
160新增: stroke-linecap: round;
161新增: }
162新增:
163新增: .nav__burger-close,
164新增: .nav__burger[aria-expanded='true'] .nav__burger-lines {
165新增: display: none;
166新增: }
167新增:
168新增: .nav__burger[aria-expanded='true'] .nav__burger-close {
169新增: display: inline;
170新增: }
171新增:
172新增: .nav__panel {
173新增: display: flex;
174新增: align-items: center;
175新增: gap: clamp(1rem, 2.5vw, 2rem);
176新增: }
177新增:
178新增: .nav__links {
179新增: display: flex;
180新增: align-items: center;
181新增: gap: clamp(0.85rem, 1.8vw, 1.6rem);
182新增: }
183新增:
184新增: .nav__link {
185新增: position: relative;
186新增: padding-block: 0.3rem;
187新增: color: var(--ink-2);
188新增: font-size: 0.875rem;
189新增: font-weight: 500;
190新增: text-decoration: none;
191新增: white-space: nowrap;
192新增: }
193新增:
194新增: .nav__link:hover {
195新增: color: var(--ink);
196新增: }
197新增:
198新增: .nav__link[data-current] {
199新增: color: var(--ink);
200新增: }
201新增:
202新增: .nav__link[data-current]::after {
203新增: content: '';
204新增: position: absolute;
205新增: left: 0;
206新增: right: 0;
207新增: bottom: -0.15rem;
208新增: height: 1.5px;
209新增: background: var(--accent);
210新增: border-radius: 2px;
211新增: }
212新增:
213新增: .nav__tools {
214新增: display: flex;
215新增: align-items: center;
216新增: gap: 0.5rem;
217新增: }
218新增:
219新增: .nav__langs {
220新增: display: inline-flex;
221新增: align-items: center;
222新增: border: 1px solid var(--line);
223新增: border-radius: var(--radius);
224新增: overflow: hidden;
225新增: }
226新增:
227新增: .nav__lang {
228新增: padding: 0.3rem 0.5rem;
229新增: font-family: var(--font-mono);
230新增: font-size: 0.7rem;
231新增: font-weight: 500;
232新增: letter-spacing: 0.06em;
233新增: color: var(--ink-3);
234新增: text-decoration: none;
235新增: background: transparent;
236新增: }
237新增:
238新增: .nav__lang:hover {
239新增: color: var(--ink);
240新增: background: var(--surface-2);
241新增: }
242新增:
243新增: .nav__lang--current {
244新增: background: var(--ink);
245新增: color: var(--paper);
246新增: }
247新增:
248新增: .nav__lang--current:hover {
249新增: background: var(--ink);
250新增: color: var(--paper);
251新增: }
252新增:
253新增: .nav__icon {
254新增: display: inline-flex;
255新增: align-items: center;
256新增: justify-content: center;
257新增: width: 2rem;
258新增: height: 2rem;
259新增: padding: 0;
260新增: border: 1px solid var(--line);
261新增: border-radius: var(--radius);
262新增: background: transparent;
263新增: color: var(--ink-2);
264新增: cursor: pointer;
265新增: }
266新增:
267新增: .nav__icon:hover {
268新增: color: var(--ink);
269新增: background: var(--surface-2);
270新增: }
271新增:
272新增: .nav__icon svg {
273新增: width: 1.05rem;
274新增: height: 1.05rem;
275新增: }
276新增:
277新增: .nav__gh {
278新增: fill: currentColor;
279新增: stroke: none;
280新增: }
281新增:
282新增: @media (max-width: 62rem) {
283新增: .nav__burger {
284新增: display: inline-flex;
285新增: }
286新增:
287新增: .nav__panel {
288新增: display: none;
289新增: position: absolute;
290新增: left: 0;
291新增: right: 0;
292新增: top: 100%;
293新增: flex-direction: column;
294新增: align-items: stretch;
295新增: gap: 0.25rem;
296新增: padding: 1rem var(--gutter) 1.25rem;
297新增: background: var(--paper);
298新增: border-bottom: 1px solid var(--line);
299新增: }
300新增:
301新增: .nav__panel[data-open] {
302新增: display: flex;
303新增: }
304新增:
305新增: .nav__links {
306新增: flex-direction: column;
307新增: align-items: stretch;
308新增: gap: 0;
309新增: }
310新增:
311新增: .nav__link {
312新增: padding-block: 0.7rem;
313新增: border-bottom: 1px solid var(--line);
314新增: font-size: 1rem;
315新增: }
316新增:
317新增: .nav__link[data-current]::after {
318新增: display: none;
319新增: }
320新增:
321新增: .nav__tools {
322新增: padding-top: 0.9rem;
323新增: }
324新增: }
325新增:</style>
新增www/src/components/Roadmap.astro+95 −0看文件
@@ -0,0 +1,95 @@
1新增:---
2新增:import { inline } from '../lib/inline';
3新增:import Heading from './Heading.astro';
4新增:import { slug } from '../lib/slug';
5新增:import { en } from '../i18n/en';
6新增:import { t, type Locale } from '../i18n';
7新增:
8新增:interface Props {
9新增: locale: Locale;
10新增:}
11新增:
12新增:const { locale } = Astro.props;
13新增:const d = t(locale);
14新增:---
15新增:
16新增:{/* A subsection of Contribute, not a section of its own: the list is only
17新增: useful next to how to pick something off it. Keeps its own id so the
18新增: README can link straight here. */}
19新增:<div class="roadmap" id="roadmap">
20新增: <Heading as="h3" id="roadmap" own={false} locale={locale} class="roadmap__title">{d.roadmap.title}</Heading>
21新增:
22新增: <ul class="roadmap__list">
23新增: {
24新增: d.roadmap.items.map((item, index) => (
25新增: <li class="roadmap__row">
26新增: <span class="roadmap__status">{item.status}</span>
27新增: <div class="roadmap__text">
28新增: <Heading as="h4" id={slug(en.roadmap.items[index]!.title)} locale={locale} class="roadmap__row-title"><Fragment set:html={inline(item.title)} /></Heading>
29新增: <p class="prose roadmap__row-body" set:html={inline(item.body)} />
30新增: </div>
31新增: </li>
32新增: ))
33新增: }
34新增: </ul>
35新增:</div>
36新增:
37新增:<style>
38新增: .roadmap {
39新增: margin-bottom: clamp(2.5rem, 5vw, 4rem);
40新增: }
41新增:
42新增: .roadmap__title {
43新增: font-size: 1.05rem;
44新增: margin-bottom: 1rem;
45新增: }
46新增:
47新增: .roadmap__list {
48新增: list-style: none;
49新增: border-top: 1px solid var(--line);
50新增: }
51新增:
52新增: .roadmap__row {
53新增: display: grid;
54新增: grid-template-columns: 11rem minmax(0, 1fr);
55新增: gap: 0 clamp(1rem, 3vw, 2.5rem);
56新增: padding-block: 1.25rem;
57新增: border-bottom: 1px solid var(--line);
58新增: }
59新增:
60新增: /* What the item waits on, in the gutter, so the list scans down the titles
61新增: without the state interrupting each line. */
62新增: .roadmap__status {
63新增: font-family: var(--font-mono);
64新增: font-size: 0.68rem;
65新增: letter-spacing: 0.08em;
66新增: text-transform: uppercase;
67新增: color: var(--ink-3);
68新增: padding-top: 0.2rem;
69新增: }
70新增:
71新增: .roadmap__text {
72新增: min-width: 0;
73新增: }
74新增:
75新增: .roadmap__row-title {
76新增: font-size: 0.97rem;
77新增: margin-bottom: 0.3rem;
78新增: }
79新增:
80新增: .roadmap__row-body {
81新增: font-size: 0.91rem;
82新增: max-width: 52rem;
83新增: }
84新增:
85新增: @media (max-width: 48rem) {
86新增: .roadmap__row {
87新增: grid-template-columns: minmax(0, 1fr);
88新增: gap: 0.4rem;
89新增: }
90新增:
91新增: .roadmap__status {
92新增: padding-top: 0;
93新增: }
94新增: }
95新增:</style>
新增www/src/components/Threat.astro+133 −0看文件
@@ -0,0 +1,133 @@
1新增:---
2新增:import { inline } from '../lib/inline';
3新增:import Heading from './Heading.astro';
4新增:import { t, type Locale } from '../i18n';
5新增:
6新增:interface Props {
7新增: locale: Locale;
8新增:}
9新增:
10新增:const { locale } = Astro.props;
11新增:const d = t(locale);
12新增:---
13新增:
14新增:<section class="section threat" id="why">
15新增: <div class="container threat__inner">
16新增: <div class="threat__head">
17新增: <p class="eyebrow">{d.threat.eyebrow}</p>
18新增: <Heading as="h2" id="why" own={false} locale={locale} class="threat__title">{d.threat.title}</Heading>
19新增: <p class="lede threat__lede" set:html={inline(d.threat.lede)} />
20新增: </div>
21新增:
22新增: <div class="threat__body">
23新增: <ol class="threat__reasons">
24新增: {
25新增: d.threat.reasons.map((reason, index) => (
26新增: <li class="threat__reason">
27新增: <span class="threat__reason-n" aria-hidden="true">
28新增: {String(index + 1).padStart(2, '0')}
29新增: </span>
30新增: <div class="threat__reason-text">
31新增: <h3 class="threat__reason-title">{reason.title}</h3>
32新增: <p class="prose threat__p" set:html={inline(reason.body)} />
33新增: </div>
34新增: </li>
35新增: ))
36新增: }
37新增: </ol>
38新增:
39新增: <div class="note note--accent threat__note">
40新增: <p class="prose" set:html={inline(d.threat.closing)} />
41新增: </div>
42新增: </div>
43新增: </div>
44新增:</section>
45新增:
46新增:<style>
47新增: .threat {
48新增: background: var(--paper-sunk);
49新增: }
50新增:
51新增: .threat__inner {
52新增: display: grid;
53新增: grid-template-columns: minmax(0, 0.8fr) minmax(0, 1.2fr);
54新增: gap: clamp(2rem, 5vw, 4.5rem);
55新增: align-items: start;
56新增: }
57新增:
58新增: .threat__head {
59新增: position: sticky;
60新增: top: calc(var(--nav-h) + 2.5rem);
61新增: display: grid;
62新增: gap: 1.15rem;
63新增: }
64新增:
65新增: .threat__title {
66新增: font-size: clamp(1.8rem, 3.2vw, 2.6rem);
67新增: }
68新增:
69新增: .threat__lede {
70新增: font-size: 1rem;
71新增: }
72新增:
73新增: .threat__body {
74新增: display: grid;
75新增: gap: 1.75rem;
76新增: max-width: 44rem;
77新增: }
78新增:
79新增: .threat__reasons {
80新增: display: grid;
81新增: gap: 1.75rem;
82新增: list-style: none;
83新增: }
84新增:
85新增: .threat__reason {
86新增: display: flex;
87新增: gap: 1rem;
88新增: align-items: start;
89新增: }
90新增:
91新增: .threat__reason-n {
92新增: flex: none;
93新增: width: 2.1rem;
94新增: height: 2.1rem;
95新增: display: grid;
96新增: place-items: center;
97新增: border: 1px solid var(--line-strong);
98新增: border-radius: 50%;
99新增: font-family: var(--font-mono);
100新增: font-size: 0.74rem;
101新增: color: var(--danger);
102新增: background: var(--surface);
103新增: }
104新增:
105新增: .threat__reason-text {
106新增: min-width: 0;
107新增: }
108新增:
109新增: .threat__reason-title {
110新增: font-size: 1.02rem;
111新增: margin-bottom: 0.4rem;
112新增: }
113新增:
114新增: .threat__p {
115新增: font-size: 0.97rem;
116新增: line-height: 1.7;
117新增: }
118新增:
119新增: .threat__note .prose {
120新增: font-size: 0.97rem;
121新增: line-height: 1.7;
122新增: }
123新增:
124新增: @media (max-width: 62rem) {
125新增: .threat__inner {
126新增: grid-template-columns: minmax(0, 1fr);
127新增: }
128新增:
129新增: .threat__head {
130新增: position: static;
131新增: }
132新增: }
133新增:</style>
新增www/src/components/Usage.astro+309 −0看文件
@@ -0,0 +1,309 @@
1新增:---
2新增:import CodeBlock from './CodeBlock.astro';
3新增:import { inline } from '../lib/inline';
4新增:import Heading from './Heading.astro';
5新增:import { slug } from '../lib/slug';
6新增:import { en } from '../i18n/en';
7新增:import { t, type Locale } from '../i18n';
8新增:
9新增:interface Props {
10新增: locale: Locale;
11新增:}
12新增:
13新增:const { locale } = Astro.props;
14新增:const d = t(locale);
15新增:---
16新增:
17新增:<section class="section" id="usage">
18新增: <div class="container">
19新增: <div class="section-head">
20新增: <p class="eyebrow">{d.usage.eyebrow}</p>
21新增: <Heading as="h2" id="usage" own={false} locale={locale}>{d.usage.title}</Heading>
22新增: <p class="lede" set:html={inline(d.usage.lede)} />
23新增: </div>
24新增:
25新增: <div class="usage__cards">
26新增: {
27新增: d.usage.cards.map((card, index) => (
28新增: <article class="usage__card">
29新增: <Heading as="h3" id={slug(en.usage.cards[index]!.title)} locale={locale} class="usage__card-title">{card.title}</Heading>
30新增: <p class="prose usage__card-body" set:html={inline(card.body)} />
31新增: <CodeBlock locale={locale} code={card.code} class="usage__card-code" />
32新增: </article>
33新增: ))
34新增: }
35新增: </div>
36新增:
37新增: <div class="usage__split">
38新增: <div class="usage__custom">
39新增: <Heading as="h3" id={slug(en.usage.customTitle)} locale={locale} class="usage__sub">{d.usage.customTitle}</Heading>
40新增: <p class="prose usage__sub-body" set:html={inline(d.usage.customLede)} />
41新增: <div class="table-wrap">
42新增: <table class="table--code">
43新增: <thead>
44新增: <tr>{d.usage.customTable.headers.map((header) => <th scope="col">{header}</th>)}</tr>
45新增: </thead>
46新增: <tbody>
47新增: {
48新增: d.usage.customTable.rows.map((row) => (
49新增: <tr>
50新增: {row.map((cell, index) =>
51新增: index === 0 ? (
52新增: <th scope="row">
53新增: <code>{cell}</code>
54新增: </th>
55新增: ) : (
56新增: <td>{cell}</td>
57新增: ),
58新增: )}
59新增: </tr>
60新增: ))
61新增: }
62新增: </tbody>
63新增: </table>
64新增: </div>
65新增:
66新增: <Heading as="h4" id={slug(en.usage.volumesTitle)} locale={locale} class="usage__sub">{d.usage.volumesTitle}</Heading>
67新增: <p class="prose usage__sub-body" set:html={inline(d.usage.volumesBody)} />
68新增: <CodeBlock locale={locale} code={d.usage.volumesCode} />
69新增: <p class="prose usage__note" set:html={inline(d.usage.volumesNote)} />
70新增: </div>
71新增:
72新增: <div class="usage__git">
73新增: <Heading as="h3" id={slug(en.usage.gitTitle)} locale={locale} class="usage__sub">{d.usage.gitTitle}</Heading>
74新增: <p class="prose usage__sub-body" set:html={inline(d.usage.gitBody)} />
75新增: <CodeBlock locale={locale} code={d.usage.gitCode} />
76新增: <p class="prose usage__note" set:html={inline(d.usage.gitNote)} />
77新增:
78新增: <div class="note note--accent">
79新增: <strong class="note__title">{d.usage.gitHumanTitle}</strong>
80新增: <p class="prose usage__note" set:html={inline(d.usage.gitHumanBody)} />
81新增: </div>
82新增: </div>
83新增: </div>
84新增:
85新增: {/* The reference tail. The cards above show the commands in use; this is
86新增: the exhaustive list, with the details prose would bury. */}
87新增: <div class="usage__ref">
88新增: <Heading as="h3" id={slug(en.usage.refTitle)} locale={locale} class="usage__sub">{d.usage.refTitle}</Heading>
89新增: <p class="prose usage__sub-body" set:html={inline(d.usage.refNote)} />
90新增:
91新增: <div class="usage__groups">
92新增: {
93新增: d.usage.commandGroups.map((group) => (
94新增: <div class="usage__group">
95新增: <h4 class="usage__group-title">{group.title}</h4>
96新增: <div class="table-wrap">
97新增: <table class="usage__commands">
98新增: <tbody>
99新增: {group.rows.map(([command, description]) => (
100新增: <tr>
101新增: <th scope="row">{command}</th>
102新增: <td set:html={inline(description ?? '')} />
103新增: </tr>
104新增: ))}
105新增: </tbody>
106新增: </table>
107新增: </div>
108新增: </div>
109新增: ))
110新增: }
111新增: </div>
112新增:
113新增: <h4 class="usage__group-title usage__group-title--spaced">{d.usage.optionsTitle}</h4>
114新增: <p class="prose usage__note" set:html={inline(d.usage.optionsNote)} />
115新增: <div class="table-wrap">
116新增: <table class="table--code table--grid">
117新增: <thead>
118新增: <tr>{d.usage.optionsHeaders.map((header) => <th scope="col">{header}</th>)}</tr>
119新增: </thead>
120新增: <tbody>
121新增: {
122新增: d.usage.options.map(([flag, description, fallback]) => (
123新增: <tr>
124新增: <td>{flag}</td>
125新增: <td set:html={inline(description ?? '')} />
126新增: <td class="usage__default">{fallback}</td>
127新增: </tr>
128新增: ))
129新增: }
130新增: </tbody>
131新增: </table>
132新增: </div>
133新增: </div>
134新增:
135新增: <div class="usage__split">
136新增: <div class="usage__git">
137新增: <Heading as="h3" id="git" locale={locale} class="usage__sub">{d.usage.gitGuardTitle}</Heading>
138新增: <p class="prose usage__sub-body" set:html={inline(d.usage.gitGuardBody)} />
139新增: <CodeBlock locale={locale} code={d.usage.gitGuardCode} />
140新增: <p class="prose usage__note" set:html={inline(d.usage.gitGuardNote)} />
141新增: <p class="prose usage__note" set:html={inline(d.usage.gitGuardEditor)} />
142新增: </div>
143新增:
144新增: <div class="usage__git">
145新增: <Heading as="h3" id="node" locale={locale} class="usage__sub">{d.usage.nodeTitle}</Heading>
146新增: <p class="prose usage__sub-body" set:html={inline(d.usage.nodeBody)} />
147新增: <CodeBlock locale={locale} code={d.usage.nodeCode} />
148新增: <p class="prose usage__note" set:html={inline(d.usage.nodeNote)} />
149新增: </div>
150新增: </div>
151新增: </div>
152新增:</section>
153新增:
154新增:<style>
155新增: .usage__cards {
156新增: display: grid;
157新增: /* 28rem so two columns fit the container: at three, the trailing `#`
158新增: comments in the samples get clipped and need sideways scrolling. */
159新增: grid-template-columns: repeat(auto-fit, minmax(min(100%, 28rem), 1fr));
160新增: gap: 1px;
161新增: background: var(--line);
162新增: border: 1px solid var(--line);
163新增: border-radius: var(--radius-lg);
164新增: overflow: hidden;
165新增: }
166新增:
167新增: .usage__card {
168新增: display: grid;
169新增: align-content: start;
170新增: /* Without this a grid item keeps min-width:auto and a wide code block
171新增: pushes the card past its track, over the neighbouring column. */
172新增: min-width: 0;
173新增: gap: 0.85rem;
174新增: padding: clamp(1.25rem, 2.4vw, 1.75rem);
175新增: background: var(--surface);
176新增: }
177新增:
178新增: .usage__card-title {
179新增: font-size: 1.02rem;
180新增: }
181新增:
182新增: .usage__card-body {
183新增: font-size: 0.91rem;
184新增: }
185新增:
186新增: .usage__card-code {
187新增: margin-top: 0.15rem;
188新增: }
189新增:
190新增: /* An odd card count would otherwise leave a hole in the last row. */
191新增: .usage__card:last-child:nth-child(odd) {
192新增: grid-column: 1 / -1;
193新增: }
194新增:
195新增: .usage__split {
196新增: display: grid;
197新增: grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
198新增: gap: clamp(1.75rem, 4vw, 3.25rem);
199新增: margin-top: clamp(2.5rem, 5vw, 4rem);
200新增: align-items: start;
201新增: }
202新增:
203新增: .usage__custom,
204新增: .usage__git {
205新增: display: grid;
206新增: gap: 1rem;
207新增: align-content: start;
208新增: min-width: 0;
209新增: }
210新增:
211新增: .usage__sub {
212新增: font-size: 1.05rem;
213新增: }
214新增:
215新增: .usage__sub-body {
216新增: font-size: 0.93rem;
217新增: margin-top: -0.35rem;
218新增: }
219新增:
220新增: .usage__note {
221新增: font-size: 0.88rem;
222新增: }
223新增:
224新增: .usage__split th[scope='row'] {
225新增: padding: 0.72rem 1rem;
226新增: border-bottom: 1px solid var(--line);
227新增: text-align: left;
228新增: font-weight: 500;
229新增: vertical-align: top;
230新增: }
231新增:
232新增: .usage__split tbody tr:last-child th[scope='row'] {
233新增: border-bottom: 0;
234新增: }
235新增:
236新增: .usage__split th[scope='row'] code {
237新增: font-size: 0.8rem;
238新增: color: var(--accent);
239新增: white-space: nowrap;
240新增: }
241新增:
242新增: /* Reference tail ---------------------------------------------------------- */
243新增:
244新增: .usage__ref {
245新增: display: grid;
246新增: gap: 1rem;
247新增: align-content: start;
248新增: min-width: 0;
249新增: margin-top: clamp(2.5rem, 5vw, 4rem);
250新增: }
251新增:
252新增: .usage__groups {
253新增: display: grid;
254新增: grid-template-columns: repeat(auto-fit, minmax(min(100%, 24rem), 1fr));
255新增: gap: clamp(1.5rem, 3vw, 2.5rem);
256新增: align-items: start;
257新增: }
258新增:
259新增: .usage__group {
260新增: display: grid;
261新增: align-content: start;
262新增: min-width: 0;
263新增: }
264新增:
265新增: .usage__group-title {
266新增: margin-bottom: 0.75rem;
267新增: font-family: var(--font-mono);
268新增: font-size: 0.72rem;
269新增: font-weight: 500;
270新增: letter-spacing: 0.12em;
271新增: text-transform: uppercase;
272新增: color: var(--ink-3);
273新增: }
274新增:
275新增: .usage__group-title--spaced {
276新增: margin-top: clamp(1.5rem, 3vw, 2.25rem);
277新增: }
278新增:
279新增: /* No thead on the command tables: the group title names the block, and a
280新增: repeated "Command / What it does" row on five tables is noise. */
281新增: .usage__commands th[scope='row'] {
282新增: padding: 0.72rem 1rem;
283新增: border-bottom: 1px solid var(--line);
284新增: text-align: left;
285新增: vertical-align: top;
286新增: font-family: var(--font-mono);
287新增: font-size: 0.83rem;
288新增: font-weight: 450;
289新增: white-space: nowrap;
290新增: color: var(--accent);
291新增: }
292新增:
293新增: .usage__commands tbody tr:last-child th[scope='row'] {
294新增: border-bottom: 0;
295新增: }
296新增:
297新增: .usage__default {
298新增: font-family: var(--font-mono);
299新增: font-size: 0.78rem;
300新增: color: var(--ink-3);
301新增: white-space: nowrap;
302新增: }
303新增:
304新增: @media (max-width: 62rem) {
305新增: .usage__split {
306新增: grid-template-columns: minmax(0, 1fr);
307新增: }
308新增: }
309新增:</style>
新增www/src/i18n/en.ts+817 −0看文件
@@ -0,0 +1,817 @@
1新增:// English copy. `fr.ts` mirrors this shape exactly, typed against it, so a
2新增:// missing or renamed key is a build error rather than a silent fallback.
3新增://
4新增:// Shell commands are not translated: they are the same on every machine.
5新增:// Only prose, labels and descriptions live here.
6新增://
7新增:// House style: say what the thing does. No slogans, no absolutes the code
8新增:// cannot back up ("cannot escape", "nothing leaves"), no sentence whose job
9新增:// is to sound good.
10新增:
11新增:export const en = {
12新增: meta: {
13新增: lang: 'en',
14新增: label: 'English',
15新增: title: 'agent-vm | a disposable Linux VM per project for AI coding agents',
16新增: description:
17新增: 'agent-vm gives every project its own Linux VM and runs the coding agent there with permissions bypassed. Your SSH keys, your browser sessions and the rest of your disk are invisible to it. Built on Lima. MIT.',
18新增: skipToContent: 'Skip to content',
19新增: },
20新增:
21新增: nav: {
22新增: sections: {
23新增: install: 'Install',
24新增: usage: 'Usage',
25新增: reference: 'Reference',
26新增: architecture: 'Architecture',
27新增: security: 'Security',
28新增: contribute: 'Contribute',
29新增: credits: 'Credits',
30新增: },
31新增: github: 'GitHub',
32新增: menu: 'Menu',
33新增: language: 'Language',
34新增: },
35新增:
36新增: hero: {
37新增: title: 'Give agents a machine they can wreck.',
38新增: titleAccent: 'Keep yours.',
39新增: lede:
40新增: 'AI coding agents need broad permissions to be useful: they install dependencies, run builds, start servers. agent-vm gives each project its own Linux VM and runs the agent in there instead. Your SSH keys, your browser sessions and the rest of your disk are invisible to it.',
41新增: installLabel: 'Get started',
42新增: ctaPrimary: 'Install it',
43新增: ctaSecondary: 'How it works',
44新增: meta: 'MIT licensed · macOS, Linux, Windows (experimental) · built on Lima',
45新增: terminalCaption:
46新增: 'Only the project directory is mounted. One VM per directory, created on first use and reused afterwards.',
47新增: points: [
48新增: {
49新增: title: 'Lima is the only host dependency',
50新增: body: 'No Node, no npm, no Docker Desktop on your machine: the toolchain lives in the VM. On Linux, Lima also needs QEMU and access to KVM.',
51新增: },
52新增: {
53新增: title: 'A separate kernel, not a namespace',
54新增: body: 'On Linux, escaping a container puts you on the host. Escaping a VM means getting through the hypervisor first.',
55新增: },
56新增: {
57新增: title: 'Ports are forwarded for you',
58新增: body: 'A dev server started in the VM answers on localhost at the same port. Lima does it; there is no flag and no config.',
59新增: },
60新增: {
61新增: title: 'Five agents, one command',
62新增: body: 'OpenCode, Claude Code, Codex CLI and Mistral Vibe, each launched with its own auto-approve flag. Pi, opt-in, never asks in the first place.',
63新增: },
64新增: ],
65新增: },
66新增:
67新增: threat: {
68新增: eyebrow: 'Why this exists',
69新增: title: 'Why not just run the agent on your machine?',
70新增: lede:
71新增: 'Every agent has a flag that turns approvals off, and many people run them that way. When that happens in your home directory, three things can go wrong.',
72新增: reasons: [
73新增: {
74新增: title: 'Dependency installs run arbitrary code',
75新增: body: 'Every `npm install` executes third-party install scripts before anyone has read them. In 2025 the Shai-Hulud worm used that to spread through thousands of npm packages: it collected npm tokens, GitHub PATs, SSH keys and cloud credentials, then republished itself using them. Nothing about the installs looked unusual.',
76新增: },
77新增: {
78新增: title: 'Approval prompts stop working',
79新增: body: 'The alternative is approving each command by hand. After the first few dozen prompts the answer is reflexive, and the one that mattered gets the same yes as the rest. That is why the bypass flag exists, and why it gets used.',
80新增: },
81新增: {
82新增: title: 'The agent is not reliable either',
83新增: body: 'No compromised package needed. Agents read issues, web pages and READMEs, and anything they read can try to give them instructions. They also make plain mistakes: the wrong path, a `git checkout .` over uncommitted work.',
84新增: },
85新增: ],
86新增: closing:
87新增: 'A VM limits what a mistake or a compromised agent can reach: your source tree and whatever you put in [its env file](#share-secrets-across-vms), but not your SSH keys, your git credentials or your browser sessions. [`--readonly`](#tighten-the-session) narrows it further, and the host enforces it, so root in the guest cannot lift it. The shared project is guarded too: with a Lima that has `sshfs.readonlyNames`, every `.git` in it is read-only for the VM, so the agent cannot plant a hook or a config in `.git` that git on your host would then run (see [Protecting .git](#git) below). What stays open is the network: the agent can send data anywhere, and Lima puts your host loopback at `192.168.5.2`, so a dev database listening on localhost is reachable from the VM.',
88新增: },
89新增:
90新增: install: {
91新增: eyebrow: 'Install',
92新增: title: 'Install, build a template, run an agent.',
93新增: lede:
94新增: 'agent-vm is a few shell scripts, with no daemon.',
95新增: prerequisitesTitle: 'Prerequisites',
96新增: prerequisites: [
97新增: { name: 'macOS, Linux or Windows', note: 'Windows is experimental: Git Bash, QEMU and Lima for Windows required.', href: '' },
98新增: {
99新增: name: 'Lima',
100新增: note: 'agent-vm setup offers to install it with Homebrew, as a build that keeps `.git` read-only until that is merged upstream. On Linux, QEMU and KVM too. On Windows, QEMU (winget) and the Windows Hypervisor Platform feature; setup offers the Lima download.',
101新增: href: 'https://lima-vm.io/docs/installation/',
102新增: },
103新增: {
104新增: name: 'An agent subscription or API key',
105新增: note: 'Authentication happens inside the VM, per VM.',
106新增: href: '',
107新增: },
108新增: ],
109新增: methodsTitle: 'Install the command',
110新增: methodsBody: 'Pick one. Each puts `agent-vm` on your `PATH` without root.',
111新增: methodsLabel: 'Install method',
112新增: methods: [
113新增: {
114新增: id: 'curl',
115新增: label: 'curl',
116新增: code: 'curl -fsSL https://www.agent-vm.org/install.sh | sh',
117新增: note: 'Downloads the latest release from GitHub, checks it against the release’s `SHA256SUMS`, unpacks it in `~/.local/share/agent-vm` and links `agent-vm` into `~/.local/bin`. It then offers to run step 2 right away. Run it again to update. `sh -s -- --version X.Y.Z` installs a given release, `sh -s -- --git` a clone of `main`.',
118新增: },
119新增: {
120新增: id: 'brew',
121新增: label: 'Homebrew',
122新增: code: 'brew install sylvinus/tap/agent-vm',
123新增: note: 'macOS, or Linux with Homebrew. `brew upgrade agent-vm` updates it.',
124新增: },
125新增: {
126新增: id: 'git',
127新增: label: 'git',
128新增: code: 'git clone https://github.com/sylvinus/agent-vm.git\ncd agent-vm && ./agent-vm.sh install',
129新增: note: '`install` symlinks `agent-vm` onto your `PATH`, so `git pull` in the clone is the update. It then offers to run step 2 right away.',
130新增: },
131新增: {
132新增: id: 'windows',
133新增: label: 'Windows',
134新增: code: '# in Git Bash (experimental)\nwinget install SoftwareFreedom.QEMU\ncurl -fsSL https://www.agent-vm.org/install.sh | sh',
135新增: note: 'Experimental. Run it in Git Bash: it is the curl installer, and `agent-vm setup` then offers a Lima build for Windows. Take it: with Lima’s own, the shares use `reverse-sshfs`, which does not keep the VM to them, and root in the VM may reach your SSH keys and the rest of your disk (a start says so, and asks). VMs also need Windows’ own hypervisor, the Windows Hypervisor Platform feature. It is off by default and only an administrator can turn it on, once (Windows Features, or `DISM /Online /Enable-Feature /FeatureName:HypervisorPlatform /All`, then a reboot). On a managed laptop, that is a request to IT. Without it, VMs do not start.',
136新增: },
137新增: ],
138新增: steps: [
139新增: {
140新增: title: 'Build the base template',
141新增: body: 'Run once. Without Lima, it first offers to install it, the build that keeps `.git` read-only for the VMs. Its wizard then offers a default set; press Enter to accept it. After it, a Lima that cannot keep `.git` read-only gets the same offer. Then it creates a Debian 13 VM, installs the toolchain and the agents, and keeps it, stopped, as a reusable template.',
142新增: code: 'agent-vm setup',
143新增: },
144新增: {
145新增: title: 'Run an agent in your project',
146新增: body: 'Clones the template into a VM for this directory, mounts the working directory, launches the agent with permissions already granted. Before the VM boots, agent-vm may stop on a security question, such as a git setting it offers to make: see [Protecting .git](#git).',
147新增: code: 'cd your-project\nagent-vm opencode # or: agent-vm claude',
148新增: },
149新增: ],
150新增: preinstallTitle: 'Choosing what goes in the template',
151新增: preinstallBody:
152新增: 'Lowercase, comma-separated. `default` is everything except Ruby, Rust, Go, Pi and the Playwright MCP. `all` is everything, `none` is nothing. `codex` and `pi` pull in `node`, and so does `mcp-chrome` when `chromium` and an agent are selected, because those installs use `npm` and `npx`. Both MCP servers are skipped without `node` and `chromium`. With no terminal attached, the wizard is skipped and the default set is installed. `setup` also takes `--disk`, `--memory` and `--cpus` for the template itself.',
153新增: preinstallNames:
154新增: 'python · node · ruby · rust · golang · docker · chromium · gh · claude · opencode · codex · vibe · pi · mcp-chrome · mcp-playwright',
155新增: preinstallCode:
156新增: 'agent-vm setup # interactive wizard\nagent-vm setup --preinstall=default # no prompts\nagent-vm setup --preinstall=default,rust # plus Rust\nagent-vm setup --preinstall=python,docker,claude # minimal Claude setup\nagent-vm setup --preinstall=node,chromium,opencode # no MCP wired in\nagent-vm setup --disk 50 --memory 16 --cpus 8 # heavier workloads',
157新增: setupHeaders: ['Flag', 'What it does', 'Default'],
158新增: setup: [
159新增: ['--disk GB', 'Base template disk size.', '10'],
160新增: ['--memory GB', 'Base template memory.', '3'],
161新增: ['--cpus N', 'Base template CPU count.', '1'],
162新增: ['--preinstall=LIST', 'Install only this comma-separated subset. Skips the wizard.', 'wizard'],
163新增: ],
164新增: updateTitle: 'Updating',
165新增: updateBody:
166新增: 'Installed with curl: run the installer again. With Homebrew: `brew upgrade agent-vm`. From a clone: `git pull`, nothing to reinstall. `agent-vm uninstall` removes the link that curl and git installs make. From 0.1.0, run `agent-vm setup` once: a VM from a base 0.1.0 built boots once more on its next start to install `sshfs`, which keeping `.git` read-only needs, and `--reset` gives it the new base. That migration will be removed in a future release.',
167新增: },
168新增:
169新增:
170新增: usage: {
171新增: eyebrow: 'Usage',
172新增: title: 'Everyday commands.',
173新增: lede:
174新增: 'Every VM is keyed to a directory, `--scratch` ones excepted. Run an agent command twice in the same folder and you get the same machine back, with its packages, its containers and its logins intact.',
175新增: cards: [
176新增: {
177新增: title: 'Run an agent',
178新增: body: 'Extra arguments are forwarded to the agent as-is, so anything its own CLI accepts works here.',
179新增: code: 'agent-vm opencode # OpenCode\nagent-vm claude # Claude Code\nagent-vm codex # Codex CLI\nagent-vm vibe # Mistral Vibe\n\nagent-vm claude -p "fix all lint errors"\nagent-vm opencode run "update the changelog"',
180新增: },
181新增: {
182新增: title: 'Reach the dev server',
183新增: body: 'Lima forwards ports opened inside the VM to the host. Start a server from the agent or from a shell and it answers on localhost at the same port, in your browser. It also means that anything the agent listens on inside the VM shows up on your own localhost: treat those ports as the agent’s.',
184新增: code: 'agent-vm run npm run dev # then open localhost:5173\nagent-vm shell # same for docker compose up',
185新增: },
186新增: {
187新增: title: 'Get inside',
188新增: body: 'A shell to poke around, or a single command when you already know what you want.',
189新增: code: 'agent-vm shell # zsh in the VM\nagent-vm run npm install # one-off command\nagent-vm run --tty opencode # allocate a PTY for TUIs\nagent-vm sh -c "ls -la | grep config"',
190新增: },
191新增: {
192新增: title: 'Connect an IDE over SSH',
193新增: body: 'VS Code Remote-SSH, JetBrains Gateway or a GUI agent can keep their window on the host and run the rest in the VM. Lima writes an SSH config per VM with the current port, under the alias `agent-vm info` prints as `ssh_host`. Put the lines below at the top of `~/.ssh/config`, above any `Host *`: ssh takes the first value it finds, and a `ForwardAgent yes` there would hand the VM every key in your SSH agent, as would VS Code’s `remote.SSH.enableAgentForwarding` without these lines. For a tool that saves the port instead of the alias, `--ssh-port` fixes it (`0` goes back to a new one on each start).',
194新增: code: '# top of ~/.ssh/config\nInclude ~/.lima/*/ssh.config\nHost lima-agent-vm-*\n ForwardAgent no\n ForwardX11 no\n\nagent-vm info | grep ^ssh_host # the alias to use\nagent-vm --ssh-port 2222 shell # a fixed port',
195新增: },
196新增: {
197新增: title: 'Manage the fleet',
198新增: body: 'The current directory’s VM is marked with `>` in `list`. If a directory is renamed, `list` is the only way to find its VM again.',
199新增: code: 'agent-vm list # all VMs, current one marked, base of each\nagent-vm stop # stop, keep the disk\nagent-vm rm # stop and delete\nagent-vm destroy-all # every VM, base template included\nagent-vm doctor # what is wrong, and what to run',
200新增: },
201新增: {
202新增: title: 'Tighten the session',
203新增: body: 'Useful for review and audit work, where the agent has no business writing anything. `--readonly` makes every host share read-only: the project and the [`~/.agent-vm/volumes`](#customisation-files) entries, `rw` ones included, since a writable volume containing the project would be a second way in. It is set on the Lima shares, so the host refuses the writes (the hypervisor, or Lima’s SFTP server on the shares that protect `.git`) and root in the VM cannot lift it. Where Lima would only apply it inside the guest, agent-vm refuses the flag: `reverse-sshfs` without `readonlyNames`, and virtiofs under QEMU. A running VM in the other mode is restarted, asked first (no by default): declined, or with no terminal, the command fails, in either direction, so another session’s read-only VM is not made writable under it. The VM’s own disk, `$HOME` and `/tmp` stay writable, so the agent can still install packages and write caches. Anything it writes inside the project fails, including `node_modules`, its own state directory, and whatever a runtime script writes: the mode is applied before those run. `--scratch` goes further: a new VM with nothing of yours mounted, which the agent fills from the network (a `git clone` with a token from `agent-vm env`), deleted when the command ends; on a terminal it asks first, and a no opens a shell in the VM. Its work leaves the same way, as a push or a pull request. Logins do not survive it, so agents need their token in `agent-vm env`: `ANTHROPIC_API_KEY`, or `CLAUDE_CODE_OAUTH_TOKEN` from `claude setup-token`.',
204新增: code: 'agent-vm --readonly shell # nothing on the host is writable\nagent-vm --scratch claude # nothing of yours mounted, deleted on exit\nagent-vm --rm run npm test # destroy the VM on exit',
205新增: },
206新增: {
207新增: title: 'Resize on the fly',
208新增: body: 'A new VM gets the base template’s: 10 GB of disk, 3 GB of memory and 1 CPU, unless `setup` was given others. Pass a flag with another value and the VM is stopped, reconfigured and restarted; a running one is asked about first (no by default), and declined, or with no terminal, it keeps its settings. Disk can grow, never shrink. CPU and memory are clamped to half the host per VM, which is not a budget across all of them: VMs persist, so several running at once add up. `agent-vm list` shows what you have, `rm` and `destroy-all` reclaim it.',
209新增: code: 'agent-vm --disk 50 opencode\nagent-vm --memory 16 --cpus 8 shell\nagent-vm --reset claude # re-clone from the base template',
210新增: },
211新增: {
212新增: title: 'Share secrets across VMs',
213新增: body: 'Plain `KEY=value` lines in `~/.agent-vm/env`, pushed into every VM on every invocation and loaded in its shells. Use the subcommands rather than editing the file by hand: a shell sources it, so one unescaped quote breaks every secret in the file, not just that line.',
214新增: code: 'agent-vm env set GH_TOKEN # paste it: not shown, not in history\nagent-vm env list # names only, never values\nagent-vm env has ANTHROPIC_API_KEY\n\n# scoped to this project only\nagent-vm project-env set SOME_PATH ./config',
215新增: },
216新增: {
217新增: title: 'Ask from a script',
218新增: body: 'If you wrap agent-vm from another tool, use these rather than parsing human-facing output or reading `~/.agent-vm` directly: VM naming, the template name and the state files are implementation details and will change. `version --min` exits `0` when the engine is recent enough, `1` with a message when it is older, and `2` when the call itself is malformed, so a typo in the required version cannot read as "engine too old". One catch: an engine predating `--min` ignores the flag and exits `0`. In `info`, booleans are `1` or `0` and anything undeterminable reads `unknown`; all four commands work without Lima installed. A start with no terminal stops where it would ask a security question: `security_questions` in `info` lists them beforehand, and `--unsafe-disable-security-prompts` accepts them, or `--readonly` avoids them. A restart it would ask about fails too: `--readonly` on a running writable VM, or the other way round, and a resize of a running VM is left unapplied.',
219新增: code: 'agent-vm version --min 0.2.0 || exit 1 # silent when OK\nagent-vm name [dir] # VM name for a directory\nagent-vm info [dir] # one key=value per line\nagent-vm help # the built-in help\n\n# info keys: version, template, state_dir,\n# project_env, dir, vm_name, base_exists,\n# vm_exists, vm_running, vm_stale,\n# ssh_host, ssh_config, git_protected,\n# security_questions',
220新增: },
221新增: ],
222新增: customTitle: 'Customisation files',
223新增: customLede:
224新增: 'Six optional files, none of them needed to get started. The per-user ones sit in `~/.agent-vm/`, the per-project ones in the project itself.',
225新增: customTable: {
226新增: headers: ['File', 'Scope', 'Runs when'],
227新增: rows: [
228新增: ['~/.agent-vm/env', 'All VMs', 'Pushed in on every invocation'],
229新增: ['~/.agent-vm/volumes', 'All VMs, or the projects an entry names', 'Mounted at VM creation'],
230新增: ['~/.agent-vm/setup.sh', 'Base template', 'Once, during agent-vm setup'],
231新增: ['~/.agent-vm/runtime.sh', 'All VMs', 'Every command that enters a VM, first'],
232新增: ['.agent-vm.runtime.sh', 'Single project', 'Every command that enters its VM, after the global one'],
233新增: ['.agent-vm.env', 'Single project', 'Pushed in after the shared env, so it wins'],
234新增: ],
235新增: },
236新增: volumesTitle: 'Extra mounts: ~/.agent-vm/volumes',
237新增: volumesBody:
238新增: 'One `source[:destination][:mode][:project]` per line, `~` expanded on the left, `#` for comments. The mode is `ro` (default) or `rw`, and `rw` only works for directories. Without a destination, the path is mounted at the same place in the VM. A relative destination is inside the project, over whatever the project has there. The fourth field, after an explicit mode, limits the entry to the projects it matches, `*` matching anything. An entry that does not read that way is skipped with a warning, never mounted everywhere.',
239新增: volumesCode:
240新增: '# ~/.agent-vm/volumes\n~/.gitconfig # same path, read-only\n~/.cache/shared:/home/you.guest/.cache/shared:rw\n\n# only in ~/work/webapp, as its .claude, read-only\n~/.claude-vm/webapp:.claude:ro:~/work/webapp\n\n# every project under ~/work\n~/.cache/pip:/home/you.guest/.cache/pip:rw:~/work/*\n\n# same path, one project only\n~/datasets::ro:~/work/ml',
241新增: volumesNote:
242新增: 'Kept on your side and not in the project on purpose: the agent can write the project, and a mount list there would let it mount any host directory into its own VM. For the same reason, a relative destination that leaves the project with `..` or goes through a symlink in it is skipped. agent-vm creates a missing mount point in the project on your machine, so an empty `.claude` shows up there too. Changes apply to new VMs: `--reset` re-applies them.',
243新增: gitTitle: 'Letting the agent commit',
244新增: gitBody:
245新增: 'git reads its identity from the environment, so the shared env file covers it with no `git config` inside the VM. All four variables are needed: git refuses to commit without a committer, not just an author.',
246新增: gitCode:
247新增: '# ~/.agent-vm/env\nGIT_AUTHOR_NAME=Your Name\[email protected]\nGIT_COMMITTER_NAME=Your Name\[email protected]',
248新增: gitNote:
249新增: 'These variables win over `git config`, in every repository of the VM: for per-repository identities, set `user.name` and `user.email` from a runtime script instead. `gh` picks up `GH_TOKEN` on its own, so `gh pr create` works with nothing else. Plain `git push` over HTTPS needs a credential helper: one `gh auth setup-git` line in your [runtime script](#customisation-files).',
250新增: gitHumanTitle: 'That said, keep the commits human',
251新增: gitHumanBody:
252新增: 'Being able to commit is not a reason to let it. A commit says you read the diff, so let the agent write the code, read it, and commit it yourself. With a Lima that [keeps `.git` read-only](#git), that is the only way: the agent cannot commit in the shared project, unless you turn the protection off, which gives it a way to run commands on your host.',
253新增: gitGuardTitle: 'Protecting .git',
254新增: gitGuardBody:
255新增: 'Git on your machine runs what a repository’s `.git/config` and hooks name: `core.fsmonitor` on every `git status`, hooks on commit. Your editor and shell prompt run `git status` on their own, so a VM able to write `.git` could run commands on your host within seconds, and nothing of it would show in `git diff`. With a Lima that has `sshfs.readonlyNames`, every `.git` in the shares is read-only for the VM, at any depth, and Lima’s SFTP server enforces it on the host: the agent reads the history but cannot commit. It is not merged upstream yet ([lima-vm/lima#5529](https://github.com/lima-vm/lima/issues/5529)), so `agent-vm setup` offers a build that has it. The shares then use `reverse-sshfs`, slower on many files (see [Node.js](#node)).',
256新增: gitGuardCode:
257新增: 'brew unlink lima; brew install sylvinus/tap/lima-sylvinus\nagent-vm doctor # where you stand\nagent-vm --unsafe-writable-git claude # let it commit anyway\n# no Homebrew: build github.com/sylvinus/lima\n# Windows (Git Bash): setup offers this download; by hand (AMD64 shown):\nbase=https://github.com/sylvinus/lima/releases/download/v2.3.0-sylvinus.2\ncurl -fsSLO "$base/lima-2.3.0-sylvinus.2-Windows-AMD64.zip" \\\n -fsSLO "$base/lima-additional-guestagents-2.3.0-sylvinus.2-Windows-AMD64.zip"\nsha256sum -c <<\'EOF\' # the checksums agent-vm pins\n053f3479b397628b79fe46b0268a50a7f1fc51073691d7d8bce78c9be2ae2787 lima-2.3.0-sylvinus.2-Windows-AMD64.zip\na0828aa4518e21c9519d341be9f32adf07cbeb74a3f8beadaa2f350c45b5933b lima-additional-guestagents-2.3.0-sylvinus.2-Windows-AMD64.zip\nEOF\nfor z in lima-*-Windows-AMD64.zip; do unzip -q -o "$z" -d ~/.local/share/lima-sylvinus; done\nexport PATH="$HOME/.local/share/lima-sylvinus/bin:$PATH" # and in ~/.bash_profile',
258新增: gitGuardNote:
259新增: 'Every `.hg` is read-only too, and so is the folder each `core.hooksPath` points to in the project (`.husky` for husky). A running VM gets new protections at its next start, which agent-vm offers. The `.git` name is not the only way in, though. A folder the VM fills with git’s internal files (`HEAD`, `objects/`, `refs/`, a `config`) is a repository to git under any name, and git runs the commands its `config` names, such as its pager as soon as you type `git log` there: `git config --global safe.bareRepository explicit` makes git ignore such folders. A config file included from the project, or a setting whose command is a file in it, is the same kind of door. Before a VM boots with writable shares, agent-vm stops on each of these it finds, and on a Lima without `readonlyNames`, and asks whether to go on: Enter, or no terminal, aborts. It offers to set `safe.bareRepository` for you. `doctor` lists them, and `info` names them for scripts. `--unsafe-writable-git`, or `AGENT_VM_UNSAFE_WRITABLE_GIT=1` in your shell, turns the protection off so the agent can commit, and reopens that path to your host: a warning says so on every run.',
260新增: gitGuardEditor:
261新增: 'Your editor is the same kind of door. The agent can write a `.vscode/tasks.json`, workspace settings, an `eslint.config.js` or a `build.rs`, which VS Code and its extensions can run. When VS Code asks, leave the project untrusted (Restricted Mode), and do not trust a parent folder: that trusts everything below it. JetBrains IDEs have the same choice (Safe Mode). The rest is in [Security](#what-else-on-your-machine-reads-the-project).',
262新增: nodeTitle: 'Node.js: node_modules in the VM',
263新增: nodeBody:
264新增: 'Hundreds of thousands of files are slow across the share, and native packages differ between macOS and Linux anyway. Mount a folder of the VM’s own disk over `node_modules` from the project’s [runtime script](#customisation-files), which runs on every command:',
265新增: nodeCode:
266新增: '#!/bin/bash\n# .agent-vm.runtime.sh\nset -e\nmkdir -p "$HOME/node_modules" node_modules\nmountpoint -q node_modules ||\n sudo mount --bind "$HOME/node_modules" node_modules',
267新增: nodeNote: 'The host sees an empty `node_modules`, or keeps its own: install there too if your editor needs the packages. `--reset` and `rm` delete the VM’s copy. In a workspace, the root `node_modules` holds nearly everything (npm hoists, pnpm keeps its store in `node_modules/.pnpm`); repeat the mount for a package with a large one of its own. A dev server in the VM may need polling to see edits made on the host (Vite: `server.watch.usePolling`).',
268新增: refTitle: 'Every command',
269新增: refNote: 'Call the command, do not source the file: a shell function is not inherited by child processes, so a tool that spawns a shell cannot see one.',
270新增: commandGroups: [
271新增: {
272新增: title: 'Run an agent',
273新增: rows: [
274新增: ['opencode [args]', 'Run OpenCode with `--auto`.'],
275新增: ['claude [args]', 'Run Claude Code with `--dangerously-skip-permissions`.'],
276新增: ['codex [args]', 'Run Codex CLI with `--dangerously-bypass-approvals-and-sandbox`.'],
277新增: ['vibe [args]', 'Run Mistral Vibe with `--agent auto-approve`.'],
278新增: ['pi [args]', 'Run Pi, which has no permission prompts. Opt-in at setup.'],
279新增: ],
280新增: },
281新增: {
282新增: title: 'Get inside',
283新增: rows: [
284新增: ['shell, sh', 'Open a zsh shell in the VM. `-c "…"` runs a one-shot command through a login shell.'],
285新增: ['run <cmd> [args]', 'Run a command with no shell. `--tty` allocates a PTY for TUIs.'],
286新增: ],
287新增: },
288新增: {
289新增: title: 'Manage the fleet',
290新增: rows: [
291新增: ['list, status', 'List all agent-vm VMs, the current directory’s marked with `>`, with the agent-vm version that built the base each was cloned from, and when.'],
292新增: ['stop [vm-name]', 'Stop this directory’s VM, or the named one. The disk survives.'],
293新增: ['rm [vm-name]', 'Stop and delete. A name from `list` reaches a VM whose directory is gone.'],
294新增: ['destroy-all', 'Stop and delete every agent-vm VM, the base template included. `setup` rebuilds it.'],
295新增: ['doctor', 'Check the host, Lima, the base template and this directory, and say what to run. Changes nothing.'],
296新增: ],
297新增: },
298新增: {
299新增: title: 'Set up and configure',
300新增: rows: [
301新增: ['install', 'Put `agent-vm` on your `PATH`, from the clone: `./agent-vm.sh install`. The curl installer runs it for you.'],
302新增: ['uninstall', 'Remove that link. VMs and `~/.agent-vm` stay.'],
303新增: ['setup', 'Create the base VM template. Run once.'],
304新增: ['env <sub>', '`set`, `get`, `has`, `unset`, `list` on the secrets shared by every VM.'],
305新增: ['project-env <sub>', 'Same subcommands, scoped to this project. Wins over the shared file.'],
306新增: ['help', 'Show the built-in help.'],
307新增: ],
308新增: },
309新增: {
310新增: title: 'Ask, from a script',
311新增: rows: [
312新增: ['version', 'Print the version. `--min X.Y.Z` checks it instead of printing it.'],
313新增: ['info [dir]', 'Machine-readable state, one `key=value` per line.'],
314新增: ['name [dir]', 'Print the VM name for a directory. Defaults to the working directory.'],
315新增: ],
316新增: },
317新增: ],
318新增: optionsTitle: 'VM options',
319新增: optionsNote: 'For `claude`, `opencode`, `codex`, `vibe`, `pi`, `shell` and `run`, placed before the command or right after its name. Anything later belongs to the command: in `agent-vm run docker run --rm x`, `--rm` is docker’s.',
320新增: optionsHeaders: ['Flag', 'What it does', 'Default'],
321新增: options: [
322新增: ['--disk GB', 'VM disk size. Can grow, never shrink.', 'the template’s (10)'],
323新增: ['--memory GB', 'VM memory. Clamped to half the host, per VM.', 'the template’s (3)'],
324新增: ['--cpus N', 'CPU count. Clamped to half the host, per VM.', 'the template’s (1)'],
325新增: ['--ssh-port N', 'Fixed host port for the VM’s SSH, for tools that save it. `0` goes back to a new one on each start. Restarts a running VM, asked first.', 'a new one per start'],
326新增: ['--reset', 'Destroy and re-clone the VM from the base template.', 'off'],
327新增: ['--readonly', 'Every host share read-only (project and volumes), host-side. Restarts a running VM, asked first.', 'off'],
328新增: ['--unsafe-writable-git', 'Leave every `.git` writable so the agent can commit, with a warning. See [Protecting .git](#git).', 'off'],
329新增: ['--unsafe-disable-security-prompts', 'Go on where a start would stop to ask a security question (see [Protecting .git](#git)), without offering to change your git config. The warnings are still printed. For scripts with no terminal; `AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1` in your shell does the same.', 'off'],
330新增: ['--rm', 'Destroy the VM once the command exits.', 'off'],
331新增: ['--scratch', 'A new VM with nothing of yours mounted, neither the project nor the volumes, deleted when the command ends, Ctrl-C included. On a terminal, the deletion is asked first (yes by default): no opens a shell in the VM, and leaving it asks again. The project’s env file and runtime script stay out; `~/.agent-vm/env` and `runtime.sh` go in. The folder’s own VM is left alone, and several can run at once. A run killed outright leaves its VM behind: the next `--scratch` run deletes it, and `doctor` lists it until then. See [Tighten the session](#tighten-the-session).', 'off'],
332新增: ],
333新增: },
334新增:
335新增:
336新增:
337新增: reference: {
338新增: eyebrow: 'Reference',
339新增: title: 'The details.',
340新增: lede: 'What the cards above leave out: installer options, what setup does, the configuration files, and the variables for scripts.',
341新增: groups: [
342新增: {
343新增: title: 'Install and setup',
344新增: topics: [
345新增: {
346新增: title: 'Installer options',
347新增: paras: [
348新增: 'Options go after `sh -s --`: `--version X.Y.Z`, `--git` for a clone of `main`, `--dir DIR` for another place than `~/.local/share/agent-vm` (or `$XDG_DATA_HOME/agent-vm`). To read the installer first, download it, then run it with `sh`.',
349新增: 'It ends with `agent-vm install`, which links `agent-vm` into `~/.local/bin` (`AGENT_VM_BIN_DIR` changes it), or writes a small launcher where Git Bash makes no symlinks. The command works from any shell, fish included: the `source .../agent-vm.sh` line earlier versions added to your shell rc is no longer needed, and `install` says so when it finds one. `./install.sh` remains as a wrapper, for now.',
350新增: ],
351新增: list: [],
352新增: code: 'curl -fsSL https://www.agent-vm.org/install.sh | sh -s -- --dir ~/tools/agent-vm\ncurl -fsSLO https://www.agent-vm.org/install.sh && sh install.sh',
353新增: },
354新增: {
355新增: title: 'What setup does',
356新增: paras: [
357新增: 'The wizard first offers the default set; answer `n` to be asked about each component. Creating the VM (the first run downloads a Debian image) and installing packages show their last 10 lines, in place; the full output goes to `~/.agent-vm/setup.log`.',
358新增: 'The `mcp-*` names wire an MCP server into every installed agent but Pi, which has no MCP support. Leave them out to keep the agents’ MCP config untouched, when MCP servers are managed per project. `mcp-playwright` does not pull in `node`: list it too.',
359新增: 'Running `setup` again rebuilds the template, not the existing VMs: agent-vm warns when a VM comes from an older template, and `--reset` re-clones it. An interrupted `setup` leaves an unusable template, which `info` reports as `base_exists=0`; run `setup` again.',
360新增: ],
361新增: list: [],
362新增: code: '',
363新增: },
364新增: {
365新增: title: 'Windows, WSL and paths',
366新增: paras: [
367新增: 'On Windows, `setup` puts the Lima build in `~/.local/share/lima-sylvinus` (`AGENT_VM_LIMA_DIR` moves it) and looks for QEMU in `/c/Program Files/qemu` when it is not on `PATH` (`AGENT_VM_QEMU_DIR` points elsewhere).',
368新增: 'In WSL2, KVM needs nested virtualization, which the Windows host has to pass through; WSL1 cannot run VMs. `setup` and `doctor` say which case you are in.',
369新增: 'Lima cannot mount a path containing whitespace, and agent-vm refuses one, as it does a path with a quote, a backslash or a control character. iCloud Drive paths contain spaces: go through a symlink.',
370新增: ],
371新增: list: [],
372新增: code: 'ln -s ~/Library/Mobile\\ Documents/com~apple~CloudDocs/Dev ~/Dev\ncd ~/Dev/your-project && agent-vm claude',
373新增: },
374新增: ],
375新增: },
376新增: {
377新增: title: 'Agents',
378新增: topics: [
379新增: {
380新增: title: 'How each agent runs',
381新增: paras: [
382新增: 'Claude Code also gets bypass mode from managed settings (`/etc/claude-code/managed-settings.json`): it drops the command-line flag when it relaunches itself ([#72479](https://github.com/anthropics/claude-code/issues/72479)). OpenCode’s `--auto` approves every prompt not explicitly denied. For Pi, setup sets `defaultProjectTrust: "always"`, so a project’s `.pi/` extensions and skills load.',
383新增: 'Log in inside the VM (`claude login`, `gh auth login`): the login stays with that VM. Mounting your host credentials instead would hand your main login to everything in the VM.',
384新增: 'Lima passes `COLORTERM` into the VM. A terminal with 24-bit colour that does not set it (Terminal.app on macOS 26 may not) needs `export COLORTERM=truecolor`.',
385新增: ],
386新增: list: [],
387新增: code: '',
388新增: },
389新增: {
390新增: title: 'MCP servers',
391新增: paras: [
392新增: 'Playwright MCP runs with `--executable-path /usr/bin/chromium` and `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1`, so it downloads no browsers of its own. For another engine, edit its entry (drop `--executable-path`, add `--browser firefox`) and run `npx playwright install firefox` in the VM.',
393新增: 'To add a server for Claude Code, add it to `mcpServers` in `~/.claude.json`, from `~/.agent-vm/setup.sh` or inside a VM.',
394新增: ],
395新增: list: [],
396新增: code: '{\n "mcpServers": {\n "postgres": {\n "command": "npx",\n "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost:5432/mydb"]\n }\n }\n}',
397新增: },
398新增: ],
399新增: },
400新增: {
401新增: title: 'Configuration',
402新增: topics: [
403新增: {
404新增: title: 'The env files',
405新增: paras: [
406新增: 'Plain `KEY=value` lines, `#` for comments, pushed into the VM on every command, so edits need no `--reset`. agent-vm knows none of the names: `gh` reads `GH_TOKEN`, Claude Code `ANTHROPIC_API_KEY` when not logged in, Codex `OPENAI_API_KEY`, Vibe `MISTRAL_API_KEY`.',
407新增: 'Everything in the VM can read them, the agent and its dependencies included, and send them out. Use dedicated, narrowly scoped tokens you can revoke.',
408新增: 'The project’s file, `.agent-vm.env` (`AGENT_VM_PROJECT_ENV` moves it, relative to the project or absolute), is pushed after the shared one and wins. It sits in a repository, so keep secrets out: `project-env set` prints the line that gitignores it, or the `git rm --cached` when it is already tracked. The VM can make it a symlink, so the VM reads it at each start, and `project-env` refuses a link, checked with `perl` so the VM cannot race it.',
409新增: '`get` and `has` read the file, never the environment, and never run it. They accept what `set` writes and plain dotenv lines (`KEY=value`, `export`, quotes, a trailing comment). A value that needs a shell (`$`, backquotes, backslashes, `~`, `;`, `|`...) exits `2`, as does a key that appears after such a line: the shell may read the lines that follow differently. `set` rewrites a value in a form they read. Without a value, `set` reads it from standard input, or has you type it unseen, so a secret stays out of your shell history.',
410新增: ],
411新增: list: [],
412新增: code: '',
413新增: },
414新增: {
415新增: title: 'Extra mounts, in detail',
416新增: paras: [
417新增: 'A destination is used as written, with no `~`: the VM home is `/home/<you>.guest` (Lima 2.1 and later, `.linux` before). A source that does not exist is skipped with a warning. `rw` works for directories only. A destination named `ro` or `rw` needs an explicit mode after it, and a destination cannot contain `:`.',
418新增: 'A single file is hardlinked into `~/.agent-vm/file-mounts/<vm>/` and bind-mounted in the VM, without its directory. Across filesystems it is copied instead, and host edits wait for the next start.',
419新增: 'A missing mount point in the project is created without following symlinks, which needs `perl`.',
420新增: ],
421新增: list: [],
422新增: code: '# ~/.agent-vm/volumes: your Claude instructions and skills,\n# not the whole ~/.claude, which holds your login on Linux\n~/.claude/CLAUDE.md:/home/you.guest/.claude/CLAUDE.md\n~/.claude/skills:/home/you.guest/.claude/skills',
423新增: },
424新增: {
425新增: title: 'Setup and runtime scripts',
426新增: paras: [
427新增: '`~/.agent-vm/setup.sh` runs once, in the template, at the end of `setup`, as the VM user with sudo. `~/.agent-vm/runtime.sh` runs in the VM on every command that enters one, then the project’s `.agent-vm.runtime.sh`: both must be safe to run again. [`runtime.example.sh`](https://github.com/sylvinus/agent-vm/blob/main/runtime.example.sh) covers git identity, `gh auth setup-git`, skills, MCP servers and a status line. Keep private keys out: the agent can read whatever they set up.',
428新增: '`setup.sh` runs under zsh. A runtime script runs under the shell its shebang names (bash or sh, zsh otherwise). Both are fed on standard input: `$0` is the shell, and a command in it that reads standard input reads the rest of the script, so give it `</dev/null`.',
429新增: '`AGENT_VM_PROJECT_RUNTIME` moves the project’s script, relative to the project or absolute, `..` resolved as `cd` does. Inside the project, the VM reads it; outside, the host. mise picks up `.ruby-version`, `.python-version`, `.node-version` and `.tool-versions`.',
430新增: ],
431新增: list: [],
432新增: code: '# .agent-vm.runtime.sh\nmise install\nnpm install\ndocker compose up -d',
433新增: },
434新增: ],
435新增: },
436新增: {
437新增: title: 'Operations and scripts',
438新增: topics: [
439新增: {
440新增: title: 'Resources, ports, doctor',
441新增: paras: [
442新增: 'CPU and memory are clamped to half the host per VM, with a notice. `AGENT_VM_HOST_SHARE` changes the divisor (`1` for the whole host); when the host capacity cannot be read, nothing is clamped.',
443新增: 'A port set with `--ssh-port` stays until `--reset` or `rm`. One another Lima VM is set to is refused; one used by anything else makes the start fail. The VM must run for SSH to connect.',
444新增: '`doctor` prints no secret, so its output can go into an issue as is. It exits `1` when a check fails.',
445新增: ],
446新增: list: [],
447新增: code: '',
448新增: },
449新增: {
450新增: title: 'For integrators',
451新增: paras: [
452新增: '`AGENT_VM_STATE_DIR` moves `~/.agent-vm`, for a test, a CI job or a second install, without moving `HOME` (which would move Lima’s VMs too). Read it back from `info` (`state_dir=`) rather than from `$HOME`.',
453新增: '`base_exists=1` means the template is usable, not only listed by Lima. `agent-vm.sh` can be sourced under `set -u` and `pipefail`, not `set -e`.',
454新增: 'A start asks its questions on the terminal, and only when stderr is one too: a tool that captures stderr gets the answer "no", so the start stops. `security_questions=` in `info` says beforehand what the start of a VM that is not running would stop on (`lima`, `lima-unknown`, `hooks`, `git-config`, `bare-repo`, or `none`), and `git_protected=` whether `.git` would be read-only. Pass `--unsafe-disable-security-prompts` to go on anyway, once the user has agreed.',
455新增: ],
456新增: list: [],
457新增: code: '',
458新增: },
459新增: ],
460新增: },
461新增: ],
462新增: },
463新增:
464新增: security: {
465新增: eyebrow: 'Security',
466新增: title: 'What crosses the boundary.',
467新增: lede: 'The VM cannot leave its shares. What remains is what crosses them: the project folder, which the agent writes and your machine reads, the terminal, and the network.',
468新增: groups: [
469新增: {
470新增: title: 'What agent-vm does',
471新增: topics: [
472新增: {
473新增: title: 'Refused directories and files',
474新增: paras: [
475新增: 'agent-vm will not share your home directory, `/`, its own directory, `~/.agent-vm`, Lima’s directory, or a directory containing one of them: `cd ~ && agent-vm shell` would hand the VM your dotfiles and SSH keys.',
476新增: 'It never reads a file in the project by its path, since the VM can make it a symlink to any file of yours. Its own git calls in a project refuse a bare repository and run no `core.fsmonitor` or pager.',
477新增: ],
478新增: list: [],
479新增: code: '',
480新增: },
481新增: {
482新增: title: '--readonly and .git, in detail',
483新增: paras: [
484新增: '`--readonly` covers every share, `rw` volumes included, with a notice naming them: a writable volume containing the project would be a second way in. Whether the host enforces it is decided from what Lima reports for the VM, never by asking the guest. agent-vm records the mounts it gave each VM, so one left with a writable share is changed; a stopped VM gets the mode before it boots.',
485新增: 'Every `.git` is read-only at any depth, whatever the case of the name. `git status`, `diff` and `log` work in the VM; `commit` does not. Every `.hg` is too, for Mercurial’s hooks.',
486新增: 'When git’s `core.hooksPath` puts the hooks in the project (husky sets `.husky/_`), the first folder of that path, from the top of its repository, is read-only as well, by its name and at any depth like `.git`, so the agent cannot change the hooks git runs on your commits. A name that does not start with a dot (`tools` for `tools/hooks`) would lock every folder of that name in the project, so the start asks first; yes is the default. Hooks at the top of a repository cannot be protected that way, so the start stops on them, as on the other risks above. The repository holding the project and those up to two levels below it are checked on every start: `doctor` says whether the VM has the names.',
487新增: 'A Lima whose answer agent-vm cannot read (a failing `limactl validate`, an unknown wording) stops the start with an error rather than being taken for one without `readonlyNames`, which would drop the protection of your VMs; `--readonly`, `--unsafe-writable-git` and `--scratch` still start. The `AGENT_VM_UNSAFE_*` variables must be exactly `1`, and are read from your shell, never from a file of the project. A tool that loads environment variables from the project on `cd` (mise’s `[env]`, for one) can set them, though: see [mise](#shell-commands-hooks) below. With a Lima that lacks `readonlyNames`, a VM goes back to Lima’s default mount type at its next start, since `reverse-sshfs` without it is the weaker one. Back to Homebrew’s Lima: `brew uninstall lima-sylvinus && brew link lima`.',
488新增: ],
489新增: list: [],
490新增: code: '# the Lima build, without Homebrew (needs Go and make)\ngit clone --depth 1 -b v2.3.0-sylvinus.2 https://github.com/sylvinus/lima\ncd lima && make native && sudo make install',
491新增: },
492新增: ],
493新增: },
494新增: {
495新增: title: 'What else on your machine reads the project',
496新增: topics: [
497新增: {
498新增: title: 'The rule',
499新增: paras: [
500新增: 'The agent writes the project folder, so anything on your machine that reads it and acts on what it finds can run what the agent wrote. agent-vm closes what nearly every machine has and what runs without you doing anything: git, through `.git`, `.hg`, hooks folders and git config (see [Protecting .git](#git)). It cannot know your other tools, and cannot lock the files they read without stopping the agent from working: it has to be able to write `.vscode/`, `docker-compose.yml` or `mise.toml`.',
501新增: 'So on your machine, open the project in your editor and use git in it; run everything else in the VM, with `agent-vm run`. The lists below are examples, sorted by what sets them off, not a complete inventory: check your own setup against them.',
502新增: ],
503新增: list: [
504新增: 'Nothing at all: what runs when you `cd` into the folder, when your prompt redraws, when your editor opens it or a file manager shows it. The most dangerous kind, since you never decide.',
505新增: 'Something you do anyway: `git commit` runs hooks whose commands sit in the working tree, `docker compose up` mounts whatever the compose file names, your home directory included.',
506新增: 'Running project code: `npm test`, `make`, a build. That is the agent’s code by definition, so it belongs in the VM.',
507新增: ],
508新增: code: '',
509新增: },
510新增: {
511新增: title: 'Keeping your checkout out of reach',
512新增: paras: [
513新增: 'To take the question off the table, do not give agent-vm the checkout you work in. Clone the project a second time, run agent-vm there, and bring its work into your own checkout with `git fetch` once you have read the diff. Your editor, prompt and habits stay in a folder the VM cannot write, and nothing of yours opens the agent’s folder by reflex. Fetching reads objects and does not check them out, so the agent’s files reach your working tree only when you merge. It does run git in the clone’s `.git`, so this holds with a Lima that keeps `.git` read-only: without one, the VM can write that `.git` too, and git’s own documentation advises against fetching, as yourself, from a `.git` someone else could write.',
514新增: ],
515新增: list: [],
516新增: code: '# once; --no-local copies the objects instead of hardlinking them\ngit clone --no-local ~/work/app ~/agent/app\n# the agent works there\ncd ~/agent/app && agent-vm claude\n# back in your checkout, when it is done\ncd ~/work/app\ngit fetch ~/agent/app HEAD:agent/review\ngit diff ...agent/review # read it all, .vscode/ and package.json included\ngit merge agent/review',
517新增: },
518新增: {
519新增: title: 'Editors and agents',
520新增: paras: [
521新增: 'Anything that runs in the project on your machine can run code the agent wrote. A changed tracked file shows in `git diff`, a new one as untracked; one in an ignored path (`node_modules`, `.venv`, `target/`) shows nowhere.',
522新增: ],
523新增: list: [
524新增: 'VS Code: open agent-vm projects in Restricted Mode (“No, I don’t trust the authors”), and do not trust a parent folder, which trusts everything below it. A trusted workspace runs tasks and extensions that execute project code: `eslint.config.js`, `vite.config.ts`, `build.rs` through rust-analyzer, the Python interpreter the settings name.',
525新增: 'JetBrains IDEs: “Preview in Safe Mode”. A trusted project runs its Gradle or Maven scripts on import.',
526新增: 'Neovim asks before running a project’s `.nvim.lua` or `.exrc` (`exrc`, off by default), and again when it changes; Vim does not ask, so leave `exrc` off. Emacs asks before applying risky `.dir-locals.el` values.',
527新增: 'Agents on your machine read project config that runs commands: `.claude/settings.json` hooks, `.mcp.json`, `.cursor/`. Review those before running one there, and treat `CLAUDE.md` and `AGENTS.md` as the VM’s writing.',
528新增: ],
529新增: code: '',
530新增: },
531新增: {
532新增: title: 'Shell, commands, hooks',
533新增: paras: [],
534新增: list: [
535新增: 'direnv only loads an `.envrc` you allowed, and a change revokes it.',
536新增: 'mise trusts a config by its path: the agent can change a trusted `mise.toml`, and your shell runs its hooks and sets its env on the next `cd`, agent-vm’s own variables included. `mise settings set paranoid true` ties trust to the content.',
537新增: 'Mercurial runs hooks from `.hg/hgrc` in a repository you own, which files written through the share are. With a Lima that keeps `.git` read-only, every `.hg` is read-only too.',
538新增: '`npm run`, `make`, `./gradlew`, `pytest` (`conftest.py`), `node_modules/.bin`, an activated `.venv`: each runs files the agent can write. Run them in the VM, with `agent-vm run`.',
539新增: '`docker compose up` on your machine does what the compose file says, and a service can mount any folder of yours, `/` included, into a container running as root. Docker runs in the VM: use it there.',
540新增: 'Commit hooks: lefthook (`lefthook.yml`) and pre-commit (`.pre-commit-config.yaml`) keep their commands in the working tree, so `git commit` on your machine runs what the agent wrote there. Read them in the diff, or commit with `--no-verify`. With a Lima that keeps `.git` read-only, the `.husky/` folder of husky is read-only too, since `core.hooksPath` points into it (see [Protecting .git](#git)), but the commands its hooks call (`npx lint-staged`, `npm test`) run project files.',
541新增: ],
542新增: code: '',
543新增: },
544新增: {
545新增: title: 'File managers',
546新增: paras: [],
547新增: list: [
548新增: 'macOS: files written through the share carry no quarantine flag, so Gatekeeper does not check an `.app`, `.command` or `.pkg` the agent left there. Do not open them from Finder.',
549新增: 'Windows: Explorer contacts the server named in a `.library-ms`, `.searchConnector-ms`, `.url`, `.lnk` or `desktop.ini` when it shows the folder, sending your NTLM hash ([CVE-2025-24054](https://research.checkpoint.com/2025/cve-2025-24054-ntlm-exploit-in-the-wild/), exploited in 2025). Keep Windows updated and outbound SMB blocked.',
550新增: 'Linux: KDE’s Dolphin ran commands from a `.desktop` or `.directory` file in a folder it only displayed (CVE-2019-14744, fixed in KDE Frameworks 5.61).',
551新增: ],
552新增: code: '',
553新增: },
554新增: ],
555新增: },
556新增: {
557新增: title: 'Terminal and network',
558新增: topics: [
559新增: {
560新增: title: 'Terminal escape sequences',
561新增: paras: [
562新增: 'What the VM prints reaches your terminal unfiltered, and terminals act on escape sequences. agent-vm cannot filter them without breaking the agents’ full-screen interfaces.',
563新增: ],
564新增: list: [
565新增: 'Clipboard: OSC 52 lets a program set your clipboard, and in some terminals read it. Allow writes only if you need them, never reads, and check what you paste into a host shell.',
566新增: 'Replies typed for you: some sequences make the terminal type an answer. During a session it goes to the VM, but one sent just before exit lands in your host shell. Answers that carried a command were real bugs: iTerm2 [CVE-2024-38396](https://www.sentinelone.com/vulnerability-database/cve-2024-38396/) (fixed in 3.5.2), xterm before it. Keep your terminal updated.',
567新增: 'Features that act on your machine: iTerm2 file transfer and triggers, kitty remote control (off by default: keep it off), links whose text differs from their target.',
568新增: 'Spoofing: the VM can print a fake host prompt after a fake exit. Check where you are before typing a secret.',
569新增: ],
570新增: code: '',
571新增: },
572新增: {
573新增: title: 'Network and ports',
574新增: paras: [
575新增: 'The VM reaches the internet and every service on your machine’s loopback, at `192.168.5.2`: a dev database, another project’s VM through its forwarded ports. Lima forwards every port a VM listens on to your `127.0.0.1`, unless it is taken: a VM that listens first on 5432 receives the connections, and passwords, meant for your local Postgres. Blocking this is [on the roadmap](#roadmap).',
576新增: ],
577新增: list: [],
578新增: code: '',
579新增: },
580新增: ],
581新增: },
582新增: ],
583新增: },
584新增:
585新增: architecture: {
586新增: eyebrow: 'Architecture',
587新增: title: 'A template, then a clone per directory.',
588新增: lede:
589新增: 'Setup pays the provisioning cost once. Every project after that is a clone of a VM that already has the toolchain in it.',
590新增: steps: [
591新增: {
592新增: n: '01',
593新增: title: 'setup builds the template',
594新增: body: 'Lima creates a Debian 13 VM. `agent-vm.setup.sh` installs the dev tools, Docker, Chromium and the agents inside it, then the VM is stopped and kept as a base template.',
595新增: },
596新增: {
597新增: n: '02',
598新增: title: 'The first run clones it',
599新增: body: 'Running an agent in a directory clones the template into a persistent VM keyed to that path, mounts the working directory, and runs the [runtime scripts](#customisation-files): the per-user one first, the per-project one second.',
600新增: },
601新增: {
602新增: n: '03',
603新增: title: 'The agent works unattended',
604新增: body: 'It is launched with its own auto-approve flag. Lima forwards the ports it opens inside the VM, so a dev server is reachable in your browser as usual.',
605新增: },
606新增: {
607新增: n: '04',
608新增: title: 'The VM outlives the session',
609新增: body: 'It persists after the agent exits. Any later command in the same directory reuses it, with its containers and its logins intact, until `rm` or `--rm`.',
610新增: },
611新增: ],
612新增: diagram: {
613新增: hostTitle: 'Your machine',
614新增: hostItems: ['SSH keys', 'API tokens', 'Browser sessions', 'git config', 'Everything else'],
615新增: hostNote: 'Only Lima installed',
616新增: boundaryLabel: 'Hypervisor boundary',
617新增: vmTitle: 'The VM',
618新增: vmItems: ['The agent', 'node, python, docker, ...', 'Headless Chromium, ...', 'Ports, forwarded out'],
619新增: vmNote: 'Separate kernel',
620新增: sharedLabel: 'Shared',
621新增: sharedTitle: '~/work/your-project',
622新增: sharedBody:
623新增: 'Your project directory, mounted into the VM at the same path. Your editor and the agent work on the same files, so there is nothing to copy back. Read-write by default, read-only with `--readonly`. Anything else that crosses is something you chose: the env file, and extra mounts listed in `~/.agent-vm/volumes`.',
624新增: },
625新增: isolationNote:
626新增: 'Each VM authenticates on its own: `claude login` happens inside it. Credentials persist across restarts of that VM and are shared with neither the host nor any other VM. The network is shared, though: see [Network and ports](#network-and-ports).',
627新增: contentsTitle: 'What is in the VM',
628新增: contentsLede:
629新增: 'The wizard’s default install and `--preinstall=default` produce the same set: everything below except the rows marked no.',
630新增: contentsHeaders: ['Category', 'Packages', 'Name', 'Default'],
631新增: contents: [
632新增: ['Core', 'git, curl, wget, jq, zsh, ca-certificates, sshfs, build-essential, pkgconf, patch, unzip, zip, ripgrep, fd-find, htop', 'always', 'yes'],
633新增: ['Build libs', 'libssl-dev, libreadline-dev, zlib1g-dev, libyaml-dev, libffi-dev', 'always', 'yes'],
634新增: ['Version manager', 'mise', 'always', 'yes'],
635新增: ['Python', 'python3, pip, venv', 'python', 'yes'],
636新增: ['Node.js', 'Node.js 24 LTS via NodeSource', 'node', 'yes'],
637新增: ['Ruby', 'ruby-full', 'ruby', 'no'],
638新增: ['Rust', 'rustup, stable toolchain', 'rust', 'no'],
639新增: ['Go', 'golang-go', 'golang', 'no'],
640新增: ['GitHub CLI', 'gh', 'gh', 'yes'],
641新增: ['Browser', 'Chromium headless, xvfb', 'chromium', 'yes'],
642新增: ['Containers', 'Docker Engine, Docker Compose', 'docker', 'yes'],
643新增: ['AI agents', 'Claude Code, OpenCode, Codex CLI, Mistral Vibe', 'claude, opencode, codex, vibe', 'yes'],
644新增: ['AI agents', 'Pi', 'pi', 'no'],
645新增: ['MCP', 'Chrome DevTools MCP, wired into every installed agent but Pi (no MCP support)', 'mcp-chrome', 'yes'],
646新增: ['MCP', 'Playwright MCP, reusing the same Chromium', 'mcp-playwright', 'no'],
647新增: ],
648新增: contentsNote:
649新增: 'This is only what the template ships, so a first run is not spent downloading a toolchain. The agent is root in the VM and has the network, so it installs whatever else it needs: `apt install`, `pip`, `cargo`, a language runtime that is not on the list.',
650新增: dockerTitle: 'Why not Docker',
651新增: dockerLede:
652新增: 'On Linux, containers share the host kernel, so a compromised dependency that finds a kernel bug is on your host. On macOS, Docker Desktop already runs a VM, which narrows the gap, but it is one VM shared by every container rather than one per project. A VM brings its own kernel, and root inside it still has the hypervisor between it and your machine. The practical differences matter as much as the security one.',
653新增: dockerHeaders: ['', 'No sandbox', 'Docker / devcontainer', 'agent-vm'],
654新增: docker: [
655新增: ['Agent can run any command', 'Yes', 'Yes', 'Yes'],
656新增: ['Host files it can reach', 'All of them', 'What you mount', 'The project directory'],
657新增: [
658新增: 'git credentials, SSH agent',
659新增: 'Yours',
660新增: 'None with plain Docker, forwarded by VS Code devcontainers',
661新增: 'Nothing, beyond what you put in ~/.agent-vm/env',
662新增: ],
663新增: ['Outbound network', 'Open', 'Open by default', 'Open (see [the roadmap](#roadmap))'],
664新增: ['Shares the host kernel', 'Yes', 'On Linux; on macOS, the Docker Desktop VM’s', 'No'],
665新增: [
666新增: 'Reaching the host needs',
667新增: 'Nothing',
668新增: 'A kernel bug, plus a hypervisor bug on macOS',
669新增: 'A hypervisor bug',
670新增: ],
671新增: ['Docker inside', 'Yes', 'Needs DinD or a socket mount', 'Yes, natively'],
672新增: ['Headless browser', 'On the host', 'Up to your image', 'Chromium, included'],
673新增: [
674新增: 'Environment definition',
675新增: 'None, your machine',
676新增: 'A devcontainer.json versioned with the project',
677新增: 'One base template, the same for every project',
678新增: ],
679新增: ],
680新增: dockerNote:
681新增: 'Docker runs natively inside the VM with no Docker-in-Docker, headless Chromium works out of the box, and Lima forwards ports on its own. On a Mac, this replaces Docker Desktop.',
682新增: },
683新增:
684新增: roadmap: {
685新增: title: 'Known gaps.',
686新增: items: [
687新增: {
688新增: status: 'Needs Lima',
689新增: title: 'Block outbound network',
690新增: body: '`--offline` existed and was removed: it set iptables rules inside the VM, where the agent has root and could drop them. Blocking on the host needs a Lima setting that does not exist. QEMU has the flag already (`-netdev user,restrict=on`); on `vz` the user-mode network is Lima’s own gvisor stack, so it would go there. The same block would also close the host loopback, which the guest reaches at `192.168.5.2` today.',
691新增: },
692新增: {
693新增: status: 'Needs an M3',
694新增: title: 'Run a VM inside the VM',
695新增: body: 'A `--allow-nested-vm` flag, for testing VM tooling from in there. Lima supports nested virtualization, but it is off by default and cannot be turned on unconditionally: below an Apple M3, `limactl start` fails outright instead of degrading, so every VM would stop starting. The flag would have to detect host support first. Nothing here has an M3 to test it on. It would also hand the agent a hypervisor interface.',
696新增: },
697新增: {
698新增: status: 'Designed, not built',
699新增: title: 'Run the VMs on another machine',
700新增: body: 'One install on your laptop driving VMs on a box you rent. Close the laptop, the agent keeps working. Open questions: addressing a VM by name rather than by working directory, and who owns deleting a workspace.',
701新增: },
702新增: ],
703新增: },
704新增:
705新增: contribute: {
706新增: eyebrow: 'Contribute',
707新增: title: 'Patches welcome.',
708新增: lede:
709新增: 'agent-vm is a small, readable Bash codebase with a test suite that creates no VMs and needs no network. Bug reports, engine fixes and support for new agents are all welcome.',
710新增: testsTitle: 'Run the tests',
711新增: testsBody:
712新增: 'The suite runs against a stub `limactl` in a throwaway `HOME`, with git reading its config from there only. No VM is created, started or deleted, your real `~/.agent-vm` and git config are untouched, and nothing is downloaded. It covers VM naming, resource comparison, staleness, the `info`, `version` and `name` surface, the `--preinstall` parser, the MCP config writer, and the project mount mode that `--readonly` rides on. `./test-e2e.sh` is the other half: it builds a real VM with `--preinstall=none` and checks what a stub cannot, starting with whether root in the guest can lift `--readonly`, and, with a Lima that has `readonlyNames`, whether it can write `.git`, and that a `--scratch` VM sees nothing of the host and is gone afterwards. It runs in its own `LIMA_HOME`, so your own VMs are never touched. The unit tests are `tests/NN-*.sh`, run in order in one shell after `tests/helpers.sh`, so a file can use what an earlier one set up; a new area gets its own file.',
713新增: testsCode: './test.sh # fast, no VM\n./test-e2e.sh # real VM, needs Lima',
714新增: shellsTitle: 'Test the shells that matter',
715新增: shellsBody:
716新增: 'macOS still ships bash 3.2, which is stricter about empty array expansion under `set -u` than modern bash. A change that passes on bash 5 can still break on a stock Mac. The `bash:3.2` image has no git, so the tests that need it skip there: add it with `apk`.',
717新增: shellsCode: 'docker run --rm -v "$PWD:/w" -w /w bash:3.2 ./test.sh\ndocker run --rm -v "$PWD:/w" -w /w bash:3.2 sh -c \'apk add -q git && git config --global safe.directory "*" && ./test.sh\'',
718新增: structureTitle: 'Where things live',
719新增: structureHeaders: ['File', 'What it is'],
720新增: structure: [
721新增: ['agent-vm.sh', 'The command: settings, the lib/ loader, starting a VM, the commands. What goes on your PATH.'],
722新增: ['lib/', 'The rest of the command, one file per concern: mounts, .git protection, env, doctor, setup…'],
723新增: ['agent-vm.setup.sh', 'Package installation, runs inside the base VM during setup.'],
724新增: ['install.sh', 'Former installer, now a wrapper for ./agent-vm.sh install.'],
725新增: ['test.sh', 'Test suite. Stub limactl, no VMs, no network. Runs tests/, in order.'],
726新增: ['test-e2e.sh', 'End-to-end suite. Builds a real VM in a throwaway LIMA_HOME.'],
727新增: ['runtime.example.sh', 'Commented template for ~/.agent-vm/runtime.sh.'],
728新增: ['CHANGELOG.md', 'What changed in each release.'],
729新增: ['release.sh', 'Checks, tags and publishes a release. --dry-run first.'],
730新增: ['www/', 'This website. Astro, static, deployed to GitHub Pages.'],
731新增: ['www/public/install.sh', 'The curl installer, served at /install.sh.'],
732新增: ],
733新增: guidelinesTitle: 'Before you open a PR',
734新增: guidelines: [
735新增: 'Keep it bash 3.2 compatible, and run `./test.sh` under `bash:3.2` as well as your own shell.',
736新增: 'Every code path should be safe to re-run: check state before acting rather than assuming a clean machine.',
737新增: 'New behaviour gets a test in `tests/` (a new area gets its own `NN-*.sh`). The stub `limactl` makes that cheap.',
738新增: 'Integrator-facing surfaces (`info`, `env`, `version`) are contracts. Adding keys is fine, changing meanings is not.',
739新增: 'No secret, token or personal path in a commit, a test fixture or an issue.',
740新增: ],
741新增: issuesLabel: 'Open an issue',
742新增: issuesHref: 'https://github.com/sylvinus/agent-vm/issues',
743新增: prLabel: 'Browse pull requests',
744新增: prHref: 'https://github.com/sylvinus/agent-vm/pulls',
745新增: repoLabel: 'Read the source',
746新增: repoHref: 'https://github.com/sylvinus/agent-vm',
747新增: },
748新增:
749新增: credits: {
750新增: eyebrow: 'Credits',
751新增: title: 'Built on other people’s work.',
752新增: lede:
753新增: 'agent-vm is a thin layer over software other people wrote. Most of what makes it work is on this list.',
754新增: groups: [
755新增: {
756新增: title: 'The machine',
757新增: items: [
758新增: { name: 'Lima', note: 'Linux VMs on macOS, Linux and Windows. The only host dependency, with QEMU on Windows.', href: 'https://lima-vm.io/' },
759新增: { name: 'Debian', note: 'The guest distribution. Debian 13.', href: 'https://www.debian.org/' },
760新增: { name: 'mise', note: 'Runtime version manager inside the VM.', href: 'https://mise.jdx.dev/' },
761新增: ],
762新增: },
763新增: {
764新增: title: 'The agents',
765新增: items: [
766新增: { name: 'Claude Code', note: 'Anthropic.', href: 'https://claude.ai/code' },
767新增: { name: 'OpenCode', note: 'Open-source terminal agent.', href: 'https://github.com/anomalyco/opencode' },
768新增: { name: 'Codex CLI', note: 'OpenAI.', href: 'https://github.com/openai/codex' },
769新增: { name: 'Mistral Vibe', note: 'Mistral AI.', href: 'https://docs.mistral.ai/vibe/code/cli/install-setup' },
770新增: { name: 'Pi', note: 'Minimal open-source harness. Opt-in.', href: 'https://pi.dev' },
771新增: ],
772新增: },
773新增: {
774新增: title: 'Browser access',
775新增: items: [
776新增: {
777新增: name: 'Chrome DevTools MCP',
778新增: note: 'Wired into every installed agent by default.',
779新增: href: 'https://github.com/ChromeDevTools/chrome-devtools-mcp',
780新增: },
781新增: {
782新增: name: 'Playwright MCP',
783新增: note: 'Opt-in, pointed at the same Chromium.',
784新增: href: 'https://github.com/microsoft/playwright-mcp',
785新增: },
786新增: ],
787新增: },
788新增: ],
789新增: authorTitle: 'Maintainer',
790新增: authorBody: 'Built and maintained by Sylvain Zimmer.',
791新增: authorHref: 'https://github.com/sylvinus',
792新增: authorName: 'sylvinus',
793新增: licenseTitle: 'License',
794新增: licenseBody: 'MIT: use, copy, modify and redistribute it, as long as the copyright and license notice stay with it. No warranty.',
795新增: licenseHref: 'https://github.com/sylvinus/agent-vm/blob/main/LICENSE',
796新增: },
797新增:
798新增: footer: {
799新增: tagline: 'A disposable Linux VM per project for AI coding agents.',
800新增: license: 'MIT',
801新增: backToTop: 'Back to top',
802新增: },
803新增:
804新增: ui: {
805新增: copy: 'Copy',
806新增: copied: 'Copied',
807新增: copyFailed: 'Copy failed',
808新增: copyLabel: 'Copy code to clipboard',
809新增: anchorLabel: 'Link to this section (copies it)',
810新增: linkCopied: 'Link copied',
811新增: },
812新增:};
813新增:
814新增:// Not `as const`: the literal types it would produce are exactly what every
815新增:// other locale fails to match. Widened to string, the shape still has to line
816新增:// up, which is the part worth enforcing.
817新增:export type Dictionary = typeof en;
新增www/src/i18n/fr.ts+814 −0看文件

改动太大,不在线显示。

新增www/src/i18n/index.ts+38 −0看文件

改动太大,不在线显示。

新增www/src/layouts/Base.astro+114 −0看文件

改动太大,不在线显示。

新增www/src/lib/french-typography.ts+44 −0看文件

改动太大,不在线显示。

新增www/src/lib/inline.ts+30 −0看文件

改动太大,不在线显示。

新增www/src/lib/shell-highlight.ts+138 −0看文件

改动太大,不在线显示。

新增www/src/lib/slug.ts+12 −0看文件

改动太大,不在线显示。

新增www/src/pages/404.astro+49 −0看文件

改动太大,不在线显示。

新增www/src/pages/fr/index.astro+8 −0看文件

改动太大,不在线显示。

新增www/src/pages/index.astro+8 −0看文件

改动太大,不在线显示。

新增www/src/styles/global.css+408 −0看文件

改动太大,不在线显示。

新增www/tsconfig.json+5 −0看文件

改动太大,不在线显示。