diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 58e234990..ad5ec95ba 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -20,9 +20,17 @@ platform's SHA-256 and size, and a build that doesn't match both is not kept. It is only made when the user asks (`magpie claude-code install`, or yes to `magpie accounts add claude`'s offer on a machine without one), for a server or a container (Jorben on Discord). It is not on PATH and stands -in for no agent. It doesn't update itself (the bridge sets -`DISABLE_AUTOUPDATER`); installing again takes the newest and removes the -older one. +in for no agent. It doesn't update itself (every run magpie starts sets +`DISABLE_AUTOUPDATER`), so the serving magpie keeps it current +(`claudecode.KeepCurrent`, a `WhileServing` loop): a minute after it +starts and every six hours it asks for the latest release and downloads a +newer one, checked the same way. The version it replaced is removed on the +next look, not at once, as a run being started may hold its path; +`magpie claude-code install` removes it at once. It does nothing when +magpie downloaded none, when the machine has its own `claude`, or when +`DISABLE_AUTOUPDATER` is set for magpie (alextjy on Discord: a container's +download stayed at its first version across image updates). A failed look +keeps the download as it is and is logged. A run is started with `--dangerously-skip-permissions` (`claudeCLIArgs`): its only tools are magpie's MCP ones, answered by the client, and @@ -1161,6 +1169,7 @@ go test -tags nogui ./internal/gateway/ -run '^TestClaudeLeanPrompt' -count=1 go test -tags nogui ./internal/gateway/ -run '^TestClaudeTUIChosen$' -count=1 go test ./internal/claudetui/ -count=1 go test -tags nogui ./internal/claudecode/ -count=1 +go test -tags nogui ./internal/claudecode/ -run TestKeepCurrent -count=1 go test -tags nogui ./internal/gateway/ -run '^TestClaudeCodeGivenTheBridgeForASOCKSProxy$' -count=1 go test -tags nogui ./internal/provider/ -run '^TestClaudeSignInBridgesASOCKSProxy$' -count=1 go test -tags nogui ./internal/netproxy/ -run '^TestEnvForBunWith' -count=1 diff --git a/internal/claudecode/claudecode.go b/internal/claudecode/claudecode.go index e41a0c507..262f9008d 100644 --- a/internal/claudecode/claudecode.go +++ b/internal/claudecode/claudecode.go @@ -6,7 +6,9 @@ // takes it: the release's manifest.json names each platform's SHA-256 and // size, and the binary is checked against both before it is kept. It is // kept in magpie's cache folder, not on PATH, so it stands in for no agent: -// it is only what the bridge and the sign-in run. +// it is only what the bridge and the sign-in run. While magpie serves, it +// keeps that download at the newest release (KeepCurrent), as Claude +// Code's own updater would, which magpie's runs turn off. package claudecode import ( @@ -215,6 +217,15 @@ func get(ctx context.Context, url string, limit int64) ([]byte, error) { // has none of its own; the versions downloaded before are removed. progress, // when set, is told the bytes so far. It returns the binary's path. func Install(ctx context.Context, r Release, progress func(done int64)) (string, error) { + exe, err := install(ctx, r, progress) + if err == nil { + prune(r.Version) + } + return exe, err +} + +// install is Install without removing the versions before it. +func install(ctx context.Context, r Release, progress func(done int64)) (string, error) { dir := filepath.Join(Root(), r.Version) if !versionRe.MatchString(r.Version) { return "", fmt.Errorf("not a version: %q", r.Version) @@ -232,14 +243,26 @@ func Install(ctx context.Context, r Release, progress func(done int64)) (string, os.Remove(tmp) return "", err } - // one version kept: what a run takes is the newest, and each is ~240 MB + return exe, nil +} + +// prune removes every version but kept: what a run takes is the newest, and +// each is ~240 MB. A folder with a download under way (a .part) stays. +// Removing the binary of a Claude Code still running is fine on Linux and +// macOS (the run keeps its file); on Windows that one stays, for the next +// prune. +func prune(kept string) { ents, _ := os.ReadDir(Root()) for _, e := range ents { - if e.IsDir() && e.Name() != r.Version && versionRe.MatchString(e.Name()) { - _ = os.RemoveAll(filepath.Join(Root(), e.Name())) + if !e.IsDir() || e.Name() == kept || !versionRe.MatchString(e.Name()) { + continue } + dir := filepath.Join(Root(), e.Name()) + if _, err := os.Stat(filepath.Join(dir, exeName(runtime.GOOS)+".part")); err == nil { + continue + } + _ = os.RemoveAll(dir) } - return exe, nil } func download(ctx context.Context, r Release, to string, progress func(int64)) error { diff --git a/internal/claudecode/keep.go b/internal/claudecode/keep.go new file mode 100644 index 000000000..2be75f9cf --- /dev/null +++ b/internal/claudecode/keep.go @@ -0,0 +1,81 @@ +package claudecode + +import ( + "context" + "fmt" + "log" + "os" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// When KeepCurrent first looks, and how often after that; vars for tests. +var ( + keepFirst = time.Minute + keepEvery = 6 * time.Hour +) + +// keep is what KeepCurrent reads of the machine; tests stand in for it. +var keep = struct { + own func() string + latest func(context.Context) (Release, error) +}{ + own: func() string { return proc.FindTool("claude") }, + latest: Latest, +} + +// KeepCurrent keeps the Claude Code magpie downloaded at Claude Code's +// newest release while magpie serves: a minute after it starts and every six +// hours after. Every run magpie starts sets DISABLE_AUTOUPDATER, so nothing +// else updates it, and a container's download (in /config/cache, on the +// volume) would otherwise stay at the version first installed, image +// update after image update (alextjy on Discord). It does nothing when +// magpie downloaded none, when the machine has a Claude Code of its own +// (that one is run, and updates itself), or when DISABLE_AUTOUPDATER is set +// for magpie: Claude Code's own way of holding a version. +func KeepCurrent(ctx context.Context) { + t := time.NewTimer(keepFirst) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + } + if said, err := keepOnce(ctx); err != nil { + log.Printf("Claude Code: keeping magpie's download current: %v", err) + } else if said != "" { + log.Print(said) + } + t.Reset(keepEvery) + } +} + +// keepOnce updates magpie's download when a newer release is out, and says +// what it did ("" for nothing). The version an earlier look replaced goes +// first: no run has been started on it since then. +func keepOnce(ctx context.Context) (string, error) { + path, v := Downloaded() + if path == "" || keep.own() != "" || os.Getenv("DISABLE_AUTOUPDATER") != "" { + return "", nil + } + prune(v) + lctx, cancel := context.WithTimeout(ctx, 30*time.Second) + r, err := keep.latest(lctx) + cancel() + if err != nil { + return "", err + } + if !newer(r.Version, v) { + return "", nil + } + dctx, cancel := context.WithTimeout(ctx, 30*time.Minute) + defer cancel() + // the old version stays until the next look: a run being started now + // may have been handed its path + if _, err := install(dctx, r, nil); err != nil { + return "", fmt.Errorf("Claude Code %s: %w", r.Version, err) + } + return fmt.Sprintf("Claude Code: magpie's download updated from %s to %s", v, r.Version), nil +} diff --git a/internal/claudecode/keep_test.go b/internal/claudecode/keep_test.go new file mode 100644 index 000000000..4748f3095 --- /dev/null +++ b/internal/claudecode/keep_test.go @@ -0,0 +1,169 @@ +package claudecode + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" +) + +// keepRelease serves 2.1.287 as downloads.claude.ai does and counts what is +// asked: the latest version, and the build's download. +func keepRelease(t *testing.T, latestV string) (asked, downloads *atomic.Int32) { + t.Helper() + const body = "#!/bin/sh\necho 2.1.287 '(Claude Code)'\n" + platform := thisPlatform(t) + asked, downloads = new(atomic.Int32), new(atomic.Int32) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/latest": + asked.Add(1) + fmt.Fprint(w, latestV) + case "/2.1.287/manifest.json": + fmt.Fprint(w, manifest(platform, body)) + case "/2.1.287/" + platform + "/" + exeName(runtime.GOOS): + downloads.Add(1) + fmt.Fprint(w, body) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + oldBase, oldKeep := Base, keep + Base = srv.URL + keep.own = func() string { return "" } + keep.latest = func(ctx context.Context) (Release, error) { + return latest(ctx, runtime.GOOS, runtime.GOARCH, false) + } + t.Cleanup(func() { Base, keep = oldBase, oldKeep }) + t.Cleanup(func() { _ = Remove() }) + t.Setenv("DISABLE_AUTOUPDATER", "") + return asked, downloads +} + +// downloaded puts a Claude Code of version v where magpie keeps its own. +func downloaded(t *testing.T, v string) string { + t.Helper() + dir := filepath.Join(Root(), v) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + p := filepath.Join(dir, exeName(runtime.GOOS)) + if err := os.WriteFile(p, []byte("old"), 0o755); err != nil { + t.Fatal(err) + } + return p +} + +func TestKeepCurrentUpdatesMagpiesDownload(t *testing.T) { + asked, downloads := keepRelease(t, "2.1.287\n") + old := downloaded(t, "2.1.200") + + said, err := keepOnce(context.Background()) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(said, "2.1.200 to 2.1.287") { + t.Errorf("said %q", said) + } + if p, v := Downloaded(); v != "2.1.287" || p == old { + t.Fatalf("Downloaded() = %q, %q; want 2.1.287", p, v) + } + // a run started a moment ago may hold the old path: it stays for now + if _, err := os.Stat(old); err != nil { + t.Errorf("the replaced version went at once: %v", err) + } + + // the next look removes it, and downloads nothing again + if said, err := keepOnce(context.Background()); err != nil || said != "" { + t.Fatalf("second look: %q, %v", said, err) + } + if _, err := os.Stat(filepath.Dir(old)); !os.IsNotExist(err) { + t.Errorf("the replaced version is still there on the next look: %v", err) + } + if asked.Load() != 2 || downloads.Load() != 1 { + t.Errorf("asked %d times, downloaded %d; want 2 and 1", asked.Load(), downloads.Load()) + } +} + +func TestKeepCurrentLeavesWhatIsntMagpiesToUpdate(t *testing.T) { + for name, set := range map[string]func(t *testing.T){ + "nothing downloaded": func(t *testing.T) {}, + "the machine's own": func(t *testing.T) { + downloaded(t, "2.1.200") + keep.own = func() string { return "/usr/local/bin/claude" } + }, + "held by the user": func(t *testing.T) { downloaded(t, "2.1.200"); t.Setenv("DISABLE_AUTOUPDATER", "1") }, + "already the newest": func(t *testing.T) { downloaded(t, "2.1.287") }, + "newer than the latest": func(t *testing.T) { downloaded(t, "2.1.300") }, + } { + t.Run(name, func(t *testing.T) { + _, downloads := keepRelease(t, "2.1.287") + set(t) + _, before := Downloaded() + if said, err := keepOnce(context.Background()); err != nil || said != "" { + t.Fatalf("keepOnce = %q, %v", said, err) + } + if downloads.Load() != 0 { + t.Errorf("downloaded %d times", downloads.Load()) + } + if _, v := Downloaded(); v != before { + t.Errorf("Downloaded() is %q, was %q", v, before) + } + }) + } +} + +func TestKeepCurrentKeepsTheDownloadWhenTheReleaseCantBeRead(t *testing.T) { + keepRelease(t, "
docker exec -it magpie magpie accounts add codex
Open the link it prints, sign in, then paste the address the browser ended on. The browser UI can also import sign-ins from a file.
-A Claude subscription is signed in to and answered through Claude Code, which the image doesn’t have. Have magpie download Anthropic’s own build first: it says the version, where it comes from and where it goes, asks, and checks the download’s SHA-256 against Anthropic’s manifest. It is kept in /config/cache; run it again for a newer one. magpie accounts add claude offers it too when Claude Code is missing.
A Claude subscription is signed in to and answered through Claude Code, which the image doesn’t have. Have magpie download Anthropic’s own build first: it says the version, where it comes from and where it goes, asks, and checks the download’s SHA-256 against Anthropic’s manifest. It is kept in /config/cache, on the volume, so a new image keeps it, and magpie keeps it at Claude Code’s newest release by itself: it looks a minute after it starts and every six hours, and downloads a newer one the same way. Nothing needs installing again after an update. To hold a version, set -e DISABLE_AUTOUPDATER=1. magpie accounts add claude offers it too when Claude Code is missing.
docker exec -it magpie magpie accounts add codex
表示されたリンクを開いてサインインし、ブラウザが最後に表示したアドレスを貼り付けます。ブラウザ UI からはファイルからサインインを取り込むこともできます。
-Claude サブスクリプションのサインインとリクエストは Claude Code を通りますが、イメージには入っていません。先に magpie に Anthropic 公式のビルドをダウンロードさせます。バージョン、ダウンロード元、保存先を示して確認してからダウンロードし、Anthropic のマニフェストにある SHA-256 で検証します。/config/cache に保存され、もう一度実行すると新しいバージョンになります。Claude Code がないときは magpie accounts add claude もダウンロードを提案します。
Claude サブスクリプションのサインインとリクエストは Claude Code を通りますが、イメージには入っていません。先に magpie に Anthropic 公式のビルドをダウンロードさせます。バージョン、ダウンロード元、保存先を示して確認してからダウンロードし、Anthropic のマニフェストにある SHA-256 で検証します。ボリューム上の /config/cache に保存されるので新しいイメージでも残り、magpie が Claude Code の最新リリースに自動で保ちます。起動の 1 分後と、その後 6 時間ごとに確認し、新しいバージョンがあれば同じように検証してダウンロードします。更新のたびに入れ直す必要はありません。バージョンを固定するには -e DISABLE_AUTOUPDATER=1 を設定します。Claude Code がないときは magpie accounts add claude もダウンロードを提案します。
docker exec -it magpie magpie accounts add codex
打开它打印的链接并登录,再把浏览器最后停在的地址粘贴回去。Web 界面也能从文件导入登录。
-Claude 订阅的登录和请求都经过 Claude Code,而镜像里没有它。先让 magpie 下载 Anthropic 官方的构建:它会说明版本、下载来源和保存位置,问过你再下载,并用 Anthropic 清单里的 SHA-256 校验。它保存在 /config/cache 里;再运行一次可以更新到新版本。缺少 Claude Code 时,magpie accounts add claude 也会提出下载。
Claude 订阅的登录和请求都经过 Claude Code,而镜像里没有它。先让 magpie 下载 Anthropic 官方的构建:它会说明版本、下载来源和保存位置,问过你再下载,并用 Anthropic 清单里的 SHA-256 校验。它保存在卷里的 /config/cache,换新镜像也还在;magpie 会自己让它保持在 Claude Code 的最新版本:启动一分钟后检查一次,之后每六小时一次,有新版本就同样校验后下载。更新 magpie 后不用重新安装。想固定某个版本,设置 -e DISABLE_AUTOUPDATER=1。缺少 Claude Code 时,magpie accounts add claude 也会提出下载。