跳到主要内容

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

提交记录
新增cmd/cage/host_download.go+22 −0看文件
@@ -0,0 +1,22 @@
1新增:package main
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "io"
7新增:
8新增: "github.com/sylvinus/agent-vm/internal/hostproxy"
9新增:)
10新增:
11新增:// Private subprocess entry for host installers. Proxy settings are resolved in
12新增:// Go for every HTTPS request, including redirects and PAC host rules.
13新增:func hostDownload(ctx context.Context, args []string, out io.Writer) error {
14新增: if len(args) != 3 && len(args) != 4 {
15新增: return errors.New("host-download requires URL, staging path, component name and optional Accept value")
16新增: }
17新增: accept := ""
18新增: if len(args) == 4 {
19新增: accept = args[3]
20新增: }
21新增: return hostproxy.Download(ctx, args[0], args[1], args[2], accept, out)
22新增:}
修改cmd/cage/mac_guest_install_darwin_arm64.go+2 −0看文件
@@ -17,6 +17,7 @@ import (
1717
1818 "al.essio.dev/pkg/shellescape"
1919 "github.com/sylvinus/agent-vm/internal/guestos"
20新增: "github.com/sylvinus/agent-vm/internal/hostproxy"
2021 "github.com/sylvinus/agent-vm/internal/vm"
2122)
2223
@@ -64,6 +65,7 @@ func installMacWorkbench(ctx context.Context, profile, state string, l *vm.Lima)
6465 }
6566 local := func(name string, args ...string) error {
6667 cmd := exec.CommandContext(ctx, name, args...)
68新增: cmd.Env = append(append(os.Environ(), hostproxy.DownloadEnvironment()...), "CAGE_HOST_DOWNLOADER="+exe)
6769 cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
6870 return cmd.Run()
6971 }
修改cmd/cage/main.go+8 −0看文件
@@ -88,6 +88,14 @@ func run() int {
8888 os.Unsetenv(name)
8989 }
9090 args := os.Args[1:]
91新增: if len(args) > 0 && args[0] == "host-download" {
92新增: ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
93新增: defer cancel()
94新增: if err := hostDownload(ctx, args[1:], os.Stdout); err != nil {
95新增: return fail(err)
96新增: }
97新增: return 0
98新增: }
9199 if len(args) == 0 || args[0] == "help" || args[0] == "--help" {
92100 fmt.Print(help)
93101 return 0
修改docs/guide/installation.md+1 −1看文件
@@ -60,7 +60,7 @@ Git 保护会修改当前主机用户的全局 `safe.bareRepository=explicit`,
6060
6161首次安装内容取决于客机系统。克隆入口优先复用已校验的匹配材料,缺少时下载官方镜像。macOS 使用 Apple IPSW;Windows 克隆使用匹配的 Microsoft ESD,手动安装可选择官方 ISO;Linux 克隆使用对应发行版的云镜像。Debian 13 基础镜像约 320–325 MiB,开发工具另行安装。镜像来源、系统许可和存储要求见[客机系统指南](guest-systems.md#下载量与磁盘空间)。
6262
63删除:系统镜像与镜像版本目录通过主机网络下载,遵循主机代理设置,不使用 Cage 为客机选择的节点。使用 Clash 等软件时,先开启其系统代理或 TUN;实际出口仍由该软件对镜像网站的规则决定。已选择的主机代理连接失败、明确配置的 PAC 解析失败时,下载会报错,保留已有文件,不自动回退直连。客机内的进程和开发工具继续使用 Cage 的独立代理,具体平台设置见[系统镜像的下载网络](network.md#系统镜像的下载网络)。
63新增:系统镜像、镜像版本目录和在主机上预备的 macOS 应用与开发工具包通过主机网络下载,遵循主机代理设置;未配置代理时直连官方源。使用 Clash 等软件时,可开启其系统代理或 TUN,实际出口由该软件对下载网站的规则决定。已选择的主机代理连接失败、明确配置的 PAC 解析失败时,下载会报错,不自动回退直连。客机内的进程和下载任务使用 Cage 的独立代理,官方源与备用镜像的选择及平台设置见[系统镜像的下载网络](network.md#系统镜像的下载网络)。
6464
6565Debian 初始虚拟磁盘容量上限为 24 GiB,macOS 和 Windows 需为系统及开发工具留出更多空间。实际占用随安装和使用增加,创建前查看所选版本的要求。Claude Desktop 按需单独下载。随后启动会复用工具、文件与登录资料。
6666
修改docs/guide/network.md+4 −2看文件
@@ -69,7 +69,7 @@ Hysteria2 节点可使用 `mport` 指定端口跳跃范围、`pinSHA256` 指定
6969
7070## 系统镜像的下载网络
7171
72删除:系统镜像和镜像版本目录使用主机网络,与 Cage 客机的代理节点分开。Clash 等软件只开启“系统代理”也可以接管镜像下载,无需为了 Cage 下载镜像而开启 TUN;下载连接不绑定物理网卡,也不会修改代理软件的节点或规则。镜像网站若被主机代理规则设为直连,Cage 遵循该规则。
72新增:系统镜像、镜像版本目录以及在主机上预备的 macOS 应用和开发工具包使用主机网络,与 Cage 客机的代理节点分开。Clash 等软件只开启“系统代理”也可以接管这些下载,无需开启 TUN;下载连接不绑定物理网卡,也不会修改代理软件的节点或规则。下载网站若被主机代理规则设为直连,Cage 遵循该规则;主机未配置代理时使用直连。
7373
7474- macOS:读取系统 HTTP、HTTPS、SOCKS 代理及 PAC,每次请求和重定向按目标地址解析。
7575- Windows:读取当前用户的系统代理;PAC 与自动检测通过 WinHTTP 按目标地址解析。
@@ -77,7 +77,9 @@ Hysteria2 节点可使用 `mport` 指定端口跳跃范围、`pinSHA256` 指定
7777
7878从终端启动时,目标协议对应的 `HTTP_PROXY`、`HTTPS_PROXY` 优先于系统设置,`ALL_PROXY` 作为缺省代理,并遵循对应的 `NO_PROXY` 例外。这些主机设置不会传入客机。代理连不上或已配置的 PAC 解析失败时,下载停止,不因失败切换直连;修复主机代理后,在初始化界面继续安装,已有下载会尝试续传。
7979
80删除:客机进程和开发工具安装继续走 Cage 的独立代理。系统镜像下载成功不代表客机网络检查通过,进入工作台仍需完成客机的网络与隔离检查。
80新增:系统镜像和开发工具优先使用官方源。Debian 镜像下载失败后尝试提供同一固定版本的国内镜像;Debian 软件源和 Linux 工具在官方源不可用时尝试备用镜像。各下载路径保留原有的摘要、软件包签名或应用签名检查,自定义 Debian 软件源保持原样。
81新增:
82新增:客机进程和在客机内下载的开发工具继续走 Cage 的独立代理。系统镜像下载成功不代表客机网络检查通过,进入工作台仍需完成客机的网络与隔离检查。
8183
8284## 时区、语言与出口规则
8385
修改internal/cage/debian-mirrors.sh+5 −1看文件
@@ -28,7 +28,11 @@ for repository in debian debian-security; do
2828 suite=$(. /etc/os-release; printf '%s' "${VERSION_CODENAME:-trixie}")
2929 [ "$repository" != debian-security ] || suite="$suite-security"
3030 priority=0
31删除: if [ "$preference" = auto ]; then
31新增: # Prefer the official CDN when it works through the guest's configured
32新增: # network. Probe domestic mirrors only after the official source fails.
33新增: if [ "$preference" = auto ] && ! timeout 8 /usr/lib/apt/apt-helper -o Acquire::Retries=0 \
34新增: -o Acquire::http::Timeout=5 -o Acquire::https::Timeout=5 \
35新增: download-file "$official/dists/$suite/InRelease" "$probe" >/dev/null 2>&1; then
3236 for mirror in "https://mirrors.nju.edu.cn/$repository" "https://mirrors.ustc.edu.cn/$repository"; do
3337 rm -f "$probe"
3438 if timeout 8 /usr/lib/apt/apt-helper -o Acquire::Retries=0 \
修改internal/cage/debian_mirrors_test.go+9 −3看文件
@@ -10,7 +10,7 @@ import (
1010
1111func TestDebianMirrorFailureFallbackAndPreference(t *testing.T) {
1212 old := "https://mirrors.nju.edu.cn/debian\tpriority:1\nhttps://mirrors.ustc.edu.cn/debian\tpriority:2\nhttps://deb.debian.org/debian\tpriority:3\n"
13删除: for _, mode := range []string{"reachable", "bookworm", "tls-failure", "nju-failure", "official", "custom", "old", "reboot", "invalid"} {
13新增: for _, mode := range []string{"reachable", "bookworm", "tls-failure", "official-failure", "nju-failure", "official", "custom", "old", "reboot", "invalid"} {
1414 t.Run(mode, func(t *testing.T) {
1515 dir := t.TempDir()
1616 mirrors := filepath.Join(dir, "mirrors")
@@ -37,7 +37,10 @@ func TestDebianMirrorFailureFallbackAndPreference(t *testing.T) {
3737 "apt-helper": `#!/bin/sh
3838printf '%s\n' "$*" >> "$FIXTURE/probes"
3939[ "$MODE" != tls-failure ] || exit 1
40删除:case "$*" in *mirrors.nju*) [ "$MODE" != nju-failure ] || exit 1;; esac
40新增:case "$*" in
41新增: *deb.debian.org*) [ "$MODE" != nju-failure ] && [ "$MODE" != official-failure ] || exit 1;;
42新增: *mirrors.nju*) [ "$MODE" != nju-failure ] || exit 1;;
43新增:esac
4144exit 0
4245`,
4346 "timeout": "#!/bin/sh\nshift\nexec \"$@\"\n",
@@ -78,7 +81,7 @@ exit 0
7881 if got != content {
7982 t.Fatal("custom source overwritten")
8083 }
81删除: case "official", "tls-failure":
84新增: case "official", "tls-failure", "reachable", "bookworm", "old", "reboot":
8285 if strings.Contains(got, "mirrors.") || !strings.Contains(got, "deb.debian.org") {
8386 t.Fatal(got)
8487 }
@@ -101,6 +104,9 @@ exit 0
101104 if err != nil || !strings.Contains(string(probes), "/dists/"+suite+"/InRelease") || !strings.Contains(string(probes), "/dists/"+suite+"-security/InRelease") {
102105 t.Fatalf("wrong distribution probes: %s, %v", probes, err)
103106 }
107新增: if strings.Contains(string(probes), "mirrors.") {
108新增: t.Fatal("reachable official source still contacted domestic mirrors")
109新增: }
104110 }
105111 if out, err := run(); err != nil {
106112 t.Fatalf("repeat: %v %s", err, out)
修改internal/cage/guest-tools.sh+10 −4看文件
@@ -82,7 +82,7 @@ cage_download_tool() (
8282 for ((attempt=1; attempt<=attempts; attempt++)); do
8383 url="$upstream"
8484 part="$artifact.part"
85删除: if [ "$attempt" = 1 ] && [ -n "$mirror" ] && [ ! -s "$part" ]; then
85新增: if [ "$attempt" = 2 ] && [ -n "$mirror" ] && [ ! -s "$part" ]; then
8686 url="$mirror"
8787 part="$artifact.mirror.part"
8888 fi
@@ -118,6 +118,10 @@ cage_download_tool() (
118118 fi
119119 continue
120120 fi
121新增: if [ "$attempt" = 1 ] && [ -n "$mirror" ] && [ ! -s "$part" ]; then
122新增: echo 'Official download unavailable; trying the fallback mirror.' >&2
123新增: continue
124新增: fi
121125 case "$status" in
122126 33|36) rm -f "$artifact.part" ;; # Server cannot resume: next attempt starts at zero.
123127 5|6|7|18|28|35|52|55|56|92) ;; # Connection, partial body, TLS EOF or timeout.
@@ -163,7 +167,9 @@ cage_install_mise() (
163167 npm_arch=arm64
164168 npm_sum="$CAGE_MISE_NPM_ARM64_SHA256"
165169 fi
166删除: if [ ! -f "$archive" ] && [ ! -s "$archive.part" ]; then
170新增: # The GitHub release is preferred. The independently pinned npm archive is
171新增: # a fallback, including when the official connection cannot make progress.
172新增: if ! cage_download_tool "$release_url" "$release_sum" "$archive" sha256sum '' 1; then
167173 npm_url="https://cdn.npmmirror.com/packages/%40jdxcode/mise-linux-$npm_arch/$wanted/mise-linux-$npm_arch-$wanted.tgz"
168174 npm_archive="$cache/$npm_sum/mise.tar.gz"
169175 mkdir -p "${npm_archive%/*}"
@@ -171,10 +177,10 @@ cage_install_mise() (
171177 archive="$npm_archive"
172178 member=package/bin/mise
173179 else
174删除: echo 'mise mirror unavailable or failed verification; trying the official release.' >&2
180新增: echo 'mise mirror unavailable or failed verification; retrying the official release.' >&2
175181 fi
176182 fi
177删除: if [ "$member" = mise/bin/mise ]; then
183新增: if [ "$member" = mise/bin/mise ] && [ ! -f "$archive" ]; then
178184 cage_download_tool "$release_url" "$release_sum" "$archive" || return $?
179185 fi
180186 if [ "${CAGE_SETUP_PROGRESS:-}" = 1 ]; then echo 'Installing mise...'; fi
修改internal/cage/guest_mise_test.go+9 −4看文件
@@ -36,10 +36,11 @@ func miseArchive(t *testing.T, member, content string) ([]byte, string) {
3636
3737func TestMiseArchivesHaveIndependentPinsResumeAndFallback(t *testing.T) {
3838 for _, tc := range []struct{ arch, mode, sources string }{
39删除: {"amd64", "fresh", "npm:0"}, {"arm64", "fresh", "npm:0"},
40删除: {"amd64", "bad-mirror", "npm:0 release:0"},
41删除: {"arm64", "cached-release", ""}, {"amd64", "partial-release", "release:7"}, {"arm64", "partial-npm", "npm:7"},
42删除: {"amd64", "both-corrupt", "npm:0 release:0"},
39新增: {"amd64", "fresh", "release:0"}, {"arm64", "fresh", "release:0"},
40新增: {"amd64", "official-failure", "release:0 npm:0"},
41新增: {"amd64", "bad-mirror", "release:0 npm:0 release:0"},
42新增: {"arm64", "cached-release", ""}, {"amd64", "partial-release", "release:7"}, {"arm64", "partial-npm", "release:0 npm:7"},
43新增: {"amd64", "both-corrupt", "release:0 npm:0 release:0"},
4344 } {
4445 t.Run(tc.arch+"/"+tc.mode, func(t *testing.T) {
4546 dir := t.TempDir()
@@ -86,6 +87,10 @@ done
8687n=0
8788if [ -f "$out" ]; then n=$(wc -c <"$out" | tr -d ' '); fi
8889printf '%s:%s\n' "$src" "$n" >> "$HOME/sources"
90新增:if [ "$src" = release ]; then
91新增: case "$TEST_MODE" in official-failure|partial-npm) printf 503; exit 22;; esac
92新增: if [ "$TEST_MODE" = bad-mirror ] && [ "$(wc -l < "$HOME/sources" | tr -d ' ')" = 1 ]; then printf 503; exit 22; fi
93新增:fi
8994if [ "$TEST_MODE" = both-corrupt ] || { [ "$src" = npm ] && [ "$TEST_MODE" = bad-mirror ]; }; then
9095 printf wrong-archive >"$out"
9196else
修改internal/cage/guest_versions_test.go+1 −4看文件
@@ -279,10 +279,7 @@ esac
279279 if _, err := os.Stat(filepath.Join(dir, "installed")); err != nil {
280280 t.Fatal(err)
281281 }
282删除: want := "mirror\n"
283删除: if arch == "amd64" {
284删除: want += "upstream\n"
285删除: }
282新增: want := "upstream\n"
286283 if got, err := os.ReadFile(filepath.Join(dir, "sources")); err != nil || string(got) != want {
287284 t.Fatalf("sources: %q, want %q (%v)", got, want, err)
288285 }
新增internal/guestos/host_download_test.go+69 −0看文件
@@ -0,0 +1,69 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "crypto/sha256"
5新增: "fmt"
6新增: "os"
7新增: "os/exec"
8新增: "path/filepath"
9新增: "regexp"
10新增: "strings"
11新增: "testing"
12新增:)
13新增:
14新增:// Run both real shell entry points, including concurrent CLI downloads and the
15新增:// GitHub asset fallback. A host helper path with spaces must remain one command.
16新增:func TestMacMediaUsesHostDownloaderForEveryPackage(t *testing.T) {
17新增: if _, err := exec.LookPath("bash"); err != nil {
18新增: t.Skip("bash unavailable")
19新增: }
20新增: dir := t.TempDir()
21新增: digest := fmt.Sprintf("%x", sha256.Sum256([]byte("fixture")))
22新增: for _, name := range []string{"prepare-macos-media.sh", "prepare-macos-cli-kit.sh"} {
23新增: data, err := os.ReadFile(filepath.Join("..", "..", "scripts", "guest-os", name))
24新增: if err != nil {
25新增: t.Fatal(err)
26新增: }
27新增: data = regexp.MustCompile(`[a-f0-9]{64}`).ReplaceAll(data, []byte(digest))
28新增: if err := os.WriteFile(filepath.Join(dir, name), data, 0700); err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: }
32新增: for _, name := range []string{"macos-cli.py", "install-macos-cli.sh", "claude-account.py", "cli_channel.py", "cli_channel.resume.md", "claude_account_resume.md"} {
33新增: if err := os.WriteFile(filepath.Join(dir, name), []byte("fixture"), 0600); err != nil {
34新增: t.Fatal(err)
35新增: }
36新增: }
37新增: helper := filepath.Join(dir, "Cage helper")
38新增: body := `#!/bin/sh
39新增:set -eu
40新增:test "$1" = host-download
41新增:printf '%s %s %s\n' "$2" "$4" "${5:-}" >> "$FIXTURE_DOWNLOADS"
42新增:case "$2" in https://github.com/*) exit 1;; esac
43新增:case "$2" in https://api.github.com/*) test "$5" = application/octet-stream;; esac
44新增:printf fixture > "$3"
45新增:printf 'CAGE_HOST_BYTES %s 7 7\n' "$4"
46新增:`
47新增: if err := os.WriteFile(helper, []byte(body), 0700); err != nil {
48新增: t.Fatal(err)
49新增: }
50新增: media := filepath.Join(dir, "media")
51新增: cmd := exec.CommandContext(t.Context(), "bash", filepath.Join(dir, "prepare-macos-media.sh"), media)
52新增: cmd.Env = append(os.Environ(), "CAGE_HOST_DOWNLOADER="+helper, "CAGE_REFRESH_TOOLS=1", "FIXTURE_DOWNLOADS="+filepath.Join(dir, "requests"))
53新增: output, err := cmd.CombinedOutput()
54新增: if err != nil {
55新增: t.Fatalf("%v\n%s", err, output)
56新增: }
57新增: requests, _ := os.ReadFile(filepath.Join(dir, "requests"))
58新增: for _, name := range []string{"editor.tgz", "playwright.tgz", "node.tgz", "chrome.dmg", "macos-cli-claude", "macos-cli-uv.tar.gz", "macos-cli-python.tar.gz", "macos-cli-git.tar.gz"} {
59新增: if !strings.Contains(string(requests), " "+name+" ") || !strings.Contains(string(output), "CAGE_HOST_BYTES "+name+" 7 7") {
60新增: t.Fatalf("component bypassed host download helper: %s\n%s", name, requests)
61新增: }
62新增: }
63新增: for _, name := range []string{"claude", "uv.tar.gz", "python.tar.gz", "git.tar.gz"} {
64新增: data, err := os.ReadFile(filepath.Join(media, "cli", name))
65新增: if err != nil || string(data) != "fixture" {
66新增: t.Fatalf("CLI kit not published: %s %v", name, err)
67新增: }
68新增: }
69新增:}
修改internal/guestos/maintenance_macos.go+5 −1看文件
@@ -62,8 +62,12 @@ func MaintainMacOSComponents(ctx context.Context, profile, kit, manifestPath str
6262 cache := filepath.Join(profile, "state", "guest-media", MacOS)
6363 if tools {
6464 mode = "tools"
65新增: exe, err := os.Executable()
66新增: if err != nil {
67新增: return err
68新增: }
6569 command := exec.CommandContext(ctx, "/bin/bash", filepath.Join(kit, "prepare-macos-media.sh"), cache)
66删除: command.Env = append(os.Environ(), "CAGE_REFRESH_TOOLS=1")
70新增: command.Env = append(os.Environ(), "CAGE_REFRESH_TOOLS=1", "CAGE_HOST_DOWNLOADER="+exe)
6771 command.Stdout, command.Stderr = stdout, stderr
6872 if err = command.Run(); err != nil {
6973 return fmt.Errorf("准备原生工具包失败:%w", err)
新增internal/hostproxy/download.go+119 −0看文件
@@ -0,0 +1,119 @@
1新增:package hostproxy
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "fmt"
7新增: "io"
8新增: "net/http"
9新增: "os"
10新增: "sync"
11新增: "time"
12新增:)
13新增:
14新增:// Download prepares host-side application media. The caller owns staging and
15新增:// checksum verification; this transport never enters a guest environment.
16新增:func Download(ctx context.Context, address, target, name, accept string, out io.Writer) error {
17新增: transport := NewTransport()
18新增: defer transport.CloseIdleConnections()
19新增: client := &http.Client{Transport: transport, CheckRedirect: func(req *http.Request, previous []*http.Request) error {
20新增: if req.URL.Scheme != "https" || len(previous) >= 5 {
21新增: return errors.New("下载重定向无效:只允许 HTTPS,最多跳转五次")
22新增: }
23新增: return nil
24新增: }}
25新增: var err error
26新增: for attempt := 0; attempt < 3; attempt++ {
27新增: err = downloadOnce(ctx, client, address, target, name, accept, out, 60*time.Second)
28新增: if ctx.Err() != nil {
29新增: return ctx.Err()
30新增: }
31新增: if err == nil {
32新增: return err
33新增: }
34新增: if attempt < 2 {
35新增: select {
36新增: case <-ctx.Done():
37新增: return ctx.Err()
38新增: case <-time.After(time.Duration(attempt+1) * time.Second):
39新增: }
40新增: }
41新增: }
42新增: // Do not include signed redirect URLs or proxy credentials in job output.
43新增: return errors.New("主机下载失败,请检查主机代理或网络后继续安装;已有安装文件已保留")
44新增:}
45新增:
46新增:func downloadOnce(parent context.Context, client *http.Client, address, target, name, accept string, out io.Writer, idle time.Duration) error {
47新增: ctx, cancel := context.WithCancel(parent)
48新增: defer cancel()
49新增: req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
50新增: if err != nil || req.URL.Scheme != "https" || req.URL.User != nil {
51新增: return errors.New("主机安装材料必须通过 HTTPS 下载")
52新增: }
53新增: if accept != "" {
54新增: req.Header.Set("Accept", accept)
55新增: }
56新增: req.Header.Set("Accept-Encoding", "identity")
57新增: response, err := client.Do(req)
58新增: if err != nil {
59新增: return err
60新增: }
61新增: defer response.Body.Close()
62新增: if response.StatusCode != http.StatusOK {
63新增: return fmt.Errorf("下载返回 HTTP %d", response.StatusCode)
64新增: }
65新增: file, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
66新增: if err != nil {
67新增: return err
68新增: }
69新增: defer file.Close()
70新增: // Check the latest activity while holding the same lock used by the body
71新增: // reader, so a timer already queued cannot cancel a resumed stream.
72新增: var mu sync.Mutex
73新增: stopped := false
74新增: last := time.Now()
75新增: var timer *time.Timer
76新增: var check func()
77新增: check = func() {
78新增: mu.Lock()
79新增: defer mu.Unlock()
80新增: if stopped {
81新增: return
82新增: }
83新增: if remaining := idle - time.Since(last); remaining > 0 {
84新增: timer.Reset(remaining)
85新增: } else {
86新增: cancel()
87新增: }
88新增: }
89新增: timer = time.AfterFunc(idle, check)
90新增: defer func() { mu.Lock(); defer mu.Unlock(); stopped = true; timer.Stop() }()
91新增: var received int64
92新增: total := max(response.ContentLength, 0)
93新增: report := func() { fmt.Fprintf(out, "CAGE_HOST_BYTES %s %d %d\n", name, received, total) }
94新增: report()
95新增: reported := time.Now()
96新增: buffer := make([]byte, 128<<10)
97新增: for {
98新增: n, readErr := response.Body.Read(buffer)
99新增: if n > 0 {
100新增: mu.Lock()
101新增: last = time.Now()
102新增: mu.Unlock()
103新增: if _, err = file.Write(buffer[:n]); err != nil {
104新增: return err
105新增: }
106新增: received += int64(n)
107新增: }
108新增: if time.Since(reported) >= time.Second || readErr != nil {
109新增: report()
110新增: reported = time.Now()
111新增: }
112新增: if readErr == io.EOF {
113新增: return file.Close()
114新增: }
115新增: if readErr != nil {
116新增: return readErr
117新增: }
118新增: }
119新增:}
新增internal/hostproxy/download_test.go+63 −0看文件
@@ -0,0 +1,63 @@
1新增:package hostproxy
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "io"
7新增: "net/http"
8新增: "net/http/httptest"
9新增: "os"
10新增: "path/filepath"
11新增: "strings"
12新增: "testing"
13新增: "time"
14新增:)
15新增:
16新增:func TestHostDownloadRedirectProgressAndAccept(t *testing.T) {
17新增: server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
18新增: if r.Header.Get("Accept") != "application/octet-stream" {
19新增: t.Error("GitHub asset Accept header lost")
20新增: }
21新增: if r.URL.Path == "/release" {
22新增: http.Redirect(w, r, "/asset", http.StatusFound)
23新增: return
24新增: }
25新增: io.WriteString(w, "verified by caller")
26新增: }))
27新增: defer server.Close()
28新增: file := filepath.Join(t.TempDir(), "archive")
29新增: var output bytes.Buffer
30新增: if err := downloadOnce(t.Context(), server.Client(), server.URL+"/release", file, "macos-cli-uv.tar.gz", "application/octet-stream", &output, time.Second); err != nil {
31新增: t.Fatal(err)
32新增: }
33新增: got, _ := os.ReadFile(file)
34新增: if string(got) != "verified by caller" || !strings.Contains(output.String(), "CAGE_HOST_BYTES macos-cli-uv.tar.gz 18 18") {
35新增: t.Fatalf("body=%q progress=%s", got, &output)
36新增: }
37新增:}
38新增:
39新增:func TestHostDownloadStallAndCancellation(t *testing.T) {
40新增: server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
41新增: w.WriteHeader(200)
42新增: w.(http.Flusher).Flush()
43新增: <-r.Context().Done()
44新增: }))
45新增: defer server.Close()
46新增: ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
47新增: defer cancel()
48新增: start := time.Now()
49新增: err := downloadOnce(ctx, server.Client(), server.URL, filepath.Join(t.TempDir(), "archive"), "chrome.dmg", "", io.Discard, 30*time.Millisecond)
50新增: if err == nil || time.Since(start) >= time.Second {
51新增: t.Fatalf("stalled body did not stop promptly: %v", err)
52新增: }
53新增: cancel()
54新增: if err := Download(ctx, server.URL, filepath.Join(t.TempDir(), "archive"), "chrome.dmg", "", io.Discard); err != context.Canceled {
55新增: t.Fatalf("cancellation was not preserved: %v", err)
56新增: }
57新增:}
58新增:
59新增:func TestHostDownloadRejectsPlainHTTP(t *testing.T) {
60新增: if err := downloadOnce(t.Context(), http.DefaultClient, "http://example.invalid/archive", filepath.Join(t.TempDir(), "archive"), "chrome.dmg", "", io.Discard, time.Second); err == nil {
61新增: t.Fatal("unencrypted host download accepted")
62新增: }
63新增:}
修改internal/hostproxy/transport.go+18 −1看文件
@@ -1,4 +1,4 @@
1删除:// Package hostproxy routes host-side system image requests through the host's
1新增:// Package hostproxy routes host-side image and application requests through the host's
22// proxy settings. Guest traffic must continue to use cage.Egress instead.
33package hostproxy
44
@@ -56,6 +56,23 @@ func NewTransport() *http.Transport {
5656 return transport(&copy, systemProxy)
5757}
5858
59新增:// DownloadEnvironment restores only the captured proxy variables for a host
60新增:// downloader subprocess. Callers must not pass these into guest operations.
61新增:func DownloadEnvironment() []string {
62新增: environment.Lock()
63新增: defer environment.Unlock()
64新增: cfg := environment.config
65新增: if cfg == nil {
66新增: cfg = readEnvironment()
67新增: }
68新增: return []string{
69新增: "HTTP_PROXY=" + cfg.HTTPProxy, "http_proxy=" + cfg.HTTPProxy,
70新增: "HTTPS_PROXY=" + cfg.HTTPSProxy, "https_proxy=" + cfg.HTTPSProxy,
71新增: "NO_PROXY=" + cfg.NoProxy, "no_proxy=" + cfg.NoProxy,
72新增: "ALL_PROXY=", "all_proxy=",
73新增: }
74新增:}
75新增:
5976func transport(env *httpproxy.Config, system func(*http.Request) (*url.URL, error)) *http.Transport {
6077 envProxy := env.ProxyFunc()
6178 return &http.Transport{
修改internal/hostproxy/transport_test.go+26 −0看文件
@@ -126,6 +126,32 @@ func TestHTTPOnlyEnvironmentKeepsHTTPSSystemProxy(t *testing.T) {
126126 }
127127}
128128
129新增:func TestHostDownloadSubprocessKeepsCapturedProxyAfterGuestSanitization(t *testing.T) {
130新增: environment.Lock()
131新增: previous := environment.config
132新增: environment.config = nil
133新增: environment.Unlock()
134新增: t.Cleanup(func() { environment.Lock(); environment.config = previous; environment.Unlock() })
135新增: t.Setenv("HTTPS_PROXY", "http://127.0.0.1:7896")
136新增: t.Setenv("HTTP_PROXY", "http://127.0.0.1:7896")
137新增: t.Setenv("NO_PROXY", "skip.invalid")
138新增: t.Setenv("no_proxy", "skip.invalid")
139新增: t.Setenv("https_proxy", "")
140新增: t.Setenv("http_proxy", "")
141新增: CaptureEnvironment()
142新增: t.Setenv("HTTPS_PROXY", "")
143新增: t.Setenv("HTTP_PROXY", "")
144新增: t.Setenv("NO_PROXY", "")
145新增: t.Setenv("no_proxy", "")
146新增: got := strings.Join(DownloadEnvironment(), "\n")
147新增: if !strings.Contains(got, "HTTPS_PROXY=http://127.0.0.1:7896") || !strings.Contains(got, "NO_PROXY=skip.invalid") {
148新增: t.Fatalf("host subprocess lost captured proxy settings: %s", got)
149新增: }
150新增: if os.Getenv("HTTPS_PROXY") != "" {
151新增: t.Fatal("host settings were restored into the guest process environment")
152新增: }
153新增:}
154新增:
129155// Run manually to verify the real system proxy without changing host settings.
130156func TestLiveSystemProxyDownload(t *testing.T) {
131157 if testing.Short() {
修改internal/vm/lima.go+1 −1看文件
@@ -357,7 +357,7 @@ func cageDebianImages(images []limatype.Image) ([]byte, error) {
357357 if !ok || img.Variant != "genericcloud" || img.Digest.Validate() != nil || img.Digest.Algorithm() != "sha512" {
358358 continue
359359 }
360删除: for _, base := range []string{"https://mirrors.nju.edu.cn/debian-cdimage/cloud/", "https://mirrors.ustc.edu.cn/debian-cdimage/cloud/", upstream} {
360新增: for _, base := range []string{upstream, "https://mirrors.nju.edu.cn/debian-cdimage/cloud/", "https://mirrors.ustc.edu.cn/debian-cdimage/cloud/"} {
361361 candidate := img
362362 candidate.Location = base + suffix
363363 candidates = append(candidates, candidate)
修改internal/vm/lima_test.go+1 −1看文件
@@ -86,7 +86,7 @@ func TestCageDebianMirrors(t *testing.T) {
8686 if len(images) != 3 {
8787 t.Fatalf("%s: expected two mirrors and one upstream, got %+v", arch, images)
8888 }
89删除: for i, base := range []string{"https://mirrors.nju.edu.cn/debian-cdimage/cloud/", "https://mirrors.ustc.edu.cn/debian-cdimage/cloud/", "https://cloud.debian.org/images/cloud/"} {
89新增: for i, base := range []string{"https://cloud.debian.org/images/cloud/", "https://mirrors.nju.edu.cn/debian-cdimage/cloud/", "https://mirrors.ustc.edu.cn/debian-cdimage/cloud/"} {
9090 if !strings.HasPrefix(images[i].Location, base) || images[i].Digest != images[2].Digest || images[i].Digest.Validate() != nil {
9191 t.Fatalf("unexpected image or missing pin: %+v", images[i])
9292 }
修改internal/workbench/setup_progress.go+31 −12看文件
@@ -20,6 +20,24 @@ type SetupProgress struct {
2020// continues through the existing redacted operation log.
2121func parseSetupProgress(line string) *SetupProgress {
2222 line = strings.TrimSpace(line)
23新增: if strings.HasPrefix(line, "CAGE_HOST_BYTES ") {
24新增: fields := strings.Fields(line)
25新增: if len(fields) != 4 {
26新增: return nil
27新增: }
28新增: label := macOSDownloadLabel(fields[1])
29新增: received, err := strconv.ParseInt(fields[2], 10, 64)
30新增: total, te := strconv.ParseInt(fields[3], 10, 64)
31新增: if label == "" || err != nil || te != nil || received < 0 || total < 0 || total > 0 && received > total {
32新增: return nil
33新增: }
34新增: return &SetupProgress{Phase: "image", Label: label, System: "macos", Operation: "download", Received: &received, Total: total}
35新增: }
36新增: if strings.HasPrefix(line, "下载 ") {
37新增: if label := macOSDownloadLabel(strings.TrimPrefix(line, "下载 ")); label != "" {
38新增: return &SetupProgress{Phase: "image", Label: label, System: "macos"}
39新增: }
40新增: }
2341 if strings.HasPrefix(line, "CAGE_GUEST_BYTES ") {
2442 fields := strings.Fields(line)
2543 if len(fields) != 5 {
@@ -107,18 +125,6 @@ func parseSetupProgress(line string) *SetupProgress {
107125 return p
108126 }
109127 switch line {
110删除: case "下载 editor.tgz":
111删除: return &SetupProgress{Phase: "image", Label: "正在下载 macOS 网页编辑器", System: "macos"}
112删除: case "下载 playwright.tgz":
113删除: return &SetupProgress{Phase: "image", Label: "正在下载浏览器控制组件", System: "macos"}
114删除: case "下载 node.tgz":
115删除: return &SetupProgress{Phase: "image", Label: "正在下载 Node.js", System: "macos"}
116删除: case "下载 macfuse.dmg":
117删除: return &SetupProgress{Phase: "image", Label: "正在下载 macFUSE 文件共享组件", System: "macos"}
118删除: case "下载 claude.dmg":
119删除: return &SetupProgress{Phase: "image", Label: "正在下载 Claude Desktop", System: "macos"}
120删除: case "下载 chrome.dmg":
121删除: return &SetupProgress{Phase: "image", Label: "正在下载 Chrome 浏览器", System: "macos"}
122128 case "CAGE_IMAGE_READY":
123129 return &SetupProgress{Phase: "image", Label: "正在启动 Linux 基础环境"}
124130 case "CAGE_IMAGE_VERIFY":
@@ -144,6 +150,19 @@ func parseSetupProgress(line string) *SetupProgress {
144150 return nil
145151}
146152
153新增:func macOSDownloadLabel(name string) string {
154新增: component := map[string]string{
155新增: "editor.tgz": "macOS 网页编辑器", "playwright.tgz": "浏览器控制组件", "node.tgz": "Node.js",
156新增: "macfuse.dmg": "macFUSE 文件共享组件", "claude.dmg": "Claude Desktop", "chrome.dmg": "Chrome 浏览器",
157新增: "macos-cli-claude": "Claude Code", "macos-cli-uv.tar.gz": "uv 开发工具",
158新增: "macos-cli-python.tar.gz": "Python", "macos-cli-git.tar.gz": "Git",
159新增: }[name]
160新增: if component == "" {
161新增: return ""
162新增: }
163新增: return "正在下载 " + component
164新增:}
165新增:
147166func guestProgressName(system string) string {
148167 return map[string]string{"macos": "macOS", "windows-11": "Windows 11", "debian-12": "Debian 12", "debian-13": "Debian 13", "ubuntu-22.04": "Ubuntu 22.04", "ubuntu-24.04": "Ubuntu 24.04"}[system]
149168}
修改internal/workbench/setup_progress_test.go+17 −0看文件
@@ -93,3 +93,20 @@ func TestToolProgressUsesOnlyKnownPackageNames(t *testing.T) {
9393 t.Fatalf("excess bytes entered UI: %+v", p)
9494 }
9595}
96新增:
97新增:func TestMacHostDownloadsReplacePreviousComponentProgress(t *testing.T) {
98新增: for _, name := range []string{"chrome.dmg", "macos-cli-claude", "macos-cli-uv.tar.gz", "macos-cli-python.tar.gz", "macos-cli-git.tar.gz"} {
99新增: p := parseSetupProgress("CAGE_HOST_BYTES " + name + " 25 100")
100新增: if p == nil || p.System != "macos" || p.Total != 100 || *p.Received != 25 {
101新增: t.Fatalf("missing host component progress: %s %+v", name, p)
102新增: }
103新增: if p := parseSetupProgress("下载 " + name); p == nil || p.Received != nil {
104新增: t.Fatalf("missing component start: %s %+v", name, p)
105新增: }
106新增: }
107新增: for _, line := range []string{"CAGE_HOST_BYTES unknown 1 2", "CAGE_HOST_BYTES chrome.dmg 3 2", "CAGE_HOST_BYTES chrome.dmg -1 2"} {
108新增: if p := parseSetupProgress(line); p != nil {
109新增: t.Fatalf("invalid host progress: %s", line)
110新增: }
111新增: }
112新增:}
修改scripts/guest-os/prepare-macos-cli-kit.sh+10 −2看文件
@@ -7,6 +7,13 @@ umask 077
77src=$(cd "$(dirname "$0")" && pwd)
88stage=$(mktemp -d "$(dirname "$1")/.cage-cli-kit.XXXXXXXX")
99trap 'rm -rf "$stage"' EXIT
10新增:fetch() {
11新增: if [[ -n ${CAGE_HOST_DOWNLOADER:-} ]]; then
12新增: "$CAGE_HOST_DOWNLOADER" host-download "$1" "$2" "macos-cli-$3" "${4:-}"
13新增: else
14新增: curl --disable --proto '=https' --proto-redir '=https' --location --fail --silent --show-error --connect-timeout 15 --speed-time 60 --speed-limit 1 --retry 2 -H "Accept: ${4:-*/*}" "$1" -o "$2"
15新增: fi
16新增:}
1017download() {
1118 local name=$1 url=$2 digest=$3 api=$4
1219 # An existing guest may already have the exact signed release archives.
@@ -15,9 +22,10 @@ download() {
1522 cp "$cache/$name" "$stage/$name"
1623 if [[ $(shasum -a 256 "$stage/$name" | cut -d' ' -f1) == "$digest" ]]; then return; fi
1724 fi
18删除: if ! curl --proto '=https' --proto-redir '=https' --location --fail --silent --show-error --connect-timeout 15 --max-time 600 --retry 2 "$url" -o "$stage/$name"; then
25新增: printf '下载 macos-cli-%s\n' "$name"
26新增: if ! fetch "$url" "$stage/$name" "$name"; then
1927 [[ -n $api ]] || return 1
20删除: curl --proto '=https' --proto-redir '=https' --location --fail --silent --show-error --connect-timeout 15 --max-time 600 --retry 2 -H 'Accept: application/octet-stream' "$api" -o "$stage/$name"
28新增: fetch "$api" "$stage/$name" "$name" application/octet-stream
2129 fi
2230 [[ $(shasum -a 256 "$stage/$name" | cut -d' ' -f1) == "$digest" ]]
2331}
修改scripts/guest-os/prepare-macos-media.sh+10 −2看文件
@@ -6,6 +6,14 @@ export PATH=/usr/bin:/bin:/usr/sbin:/sbin
66media=$1
77src=$(cd "$(dirname "$0")" && pwd)
88mkdir -p "$media"
9新增:fetch() {
10新增: if [[ -n ${CAGE_HOST_DOWNLOADER:-} ]]; then
11新增: "$CAGE_HOST_DOWNLOADER" host-download "$1" "$2" "$3" "${4:-}"
12新增: else
13新增: # Standalone source builds can supply curl proxy environment variables.
14新增: curl --disable -fsSL --proto '=https' --proto-redir '=https' --retry 2 --connect-timeout 15 --speed-time 60 --speed-limit 1 -H "Accept: ${4:-*/*}" "$1" -o "$2"
15新增: fi
16新增:}
917download() {
1018 local name=$1 url=$2 expected=$3 api=${4:-}
1119 local target="$media/$name" temporary
@@ -15,8 +23,8 @@ download() {
1523 fi
1624 printf '下载 %s\n' "$name"
1725 temporary=$(mktemp "$media/.$name.XXXXXXXX")
18删除: if ! curl --disable -fsSL --proto '=https' --proto-redir '=https' --retry 2 --connect-timeout 15 --speed-time 90 --speed-limit 1024 "$url" -o "$temporary"; then
19删除: if [[ -z $api ]] || ! curl --disable -fsSL --proto '=https' --proto-redir '=https' --retry 2 --connect-timeout 15 --speed-time 90 --speed-limit 1024 -H 'Accept: application/octet-stream' "$api" -o "$temporary"; then
26新增: if ! fetch "$url" "$temporary" "$name"; then
27新增: if [[ -z $api ]] || ! fetch "$api" "$temporary" "$name" application/octet-stream; then
2028 rm "$temporary"
2129 return 1
2230 fi