Files
magpie/internal/update/launcher.go
T
yetone f9e6061b85 claude: claude-magpie runs Claude Code through magpie, a plain claude left on the user's account
baranwang on X (11-06): `claude` stays on the user's own Claude account,
`claude-magpie` goes through magpie, and nothing is switched back and
forth.

`claude-magpie` runs `magpie claude run [args…]`. That writes a settings
file of magpie's own, <config>/claude-launch/settings.json, connected as
Connect connects Claude Code (the gateway, its key, the shared LAN key when
sharing is on, the model, the tiers) and starts
`claude --settings <file> args…`. Claude Code puts a --settings file's env
and model over the user's settings.json, a claude.ai sign-in and the
shell's variables (tried on 2.1.318), so ~/.claude/settings.json is never
rewritten. ANTHROPIC_API_KEY and the cloud switches (Bedrock, Vertex…) are
blanked in the file, so neither the user's file nor the shell can take a
request past magpie. The file is the agent `claude#launch`, listed nowhere:
the Agents page, Check and Notice see only the user's file. It is set again
when the gateway moved or its key changed.

- /model in a claude-magpie session saves to the user's settings.json
  (Claude Code never writes a --settings file). After the session a magpie
  model picked there moves into the launch file, for the next claude-magpie,
  and the user's file gets its model back. A Claude alias (sonnet) stays.
- Claude Code's own one-time `opus` -> `opus[1m]` rewrite of the user's
  file (migration_opus_to_opus1m), which the launch file's 1M opus tier sets
  off, is undone the same way. Found in the end-to-end run below.
- claude runs as a child so that can happen: on Unix a stopped child stops
  magpie too (^Z, fg; proc.WaitFollowingStops reaps it with WUNTRACED, as
  cmd.Wait can't see a stop), and claude's exit code is magpie's. On Windows magpie
  ignores Ctrl+C while claude has it.
- The command: a launcher beside the `magpie` command. Settings › Command
  line (AddCLI) writes it; `magpie claude launcher [add|remove]` adds it for
  a command put there before. It is a `#!/bin/sh` exec of magpie's stable
  path, or on Windows a .cmd running "%~dp0magpie". A file by that name
  without "written by magpie" is never written over.
- Docs: agent-wiring.md, and the start page in en/zh/ja.

Run at this commit (rebased on origin/main 218b38c59):
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build for darwin, linux (nogui), windows;
  go test ./... -timeout 45m: 85 packages ok; red only
  TestMainWindowCorners (#3949) and TestRenewLoginsKeepsClaudeReading
  (#5481), both red alone on origin/main b020ae102. The run before at
  f22a9ae61 also had proc's TestEveryStartedCommandIsWaited red on this
  change's own Wait4 loop, fixed here by moving it into proc.
- Windows (xiaomi-gpu): go test ./internal/update ./internal/cli: cli ok;
  update red only in TestPackagedByDpkg, red the same on origin/main
  f47390bf3, filed as #4603.
- Real Claude Code 2.1.318 in WSL (magpie-desktop), sandbox HOME, a built
  magpie (`serve` on its own port), a fake Anthropic upstream:
  - `magpie claude run -p "say hi"`: PONG, exit 0; upstream got
    claude-opus-4-6 with the provider's key. A user settings.json with its
    own ANTHROPIC_API_KEY and "model": "opus" kept both values.
  - Interactive in tmux under bash -i: `/model fakeco/glm-4.6` then /exit:
    the user's file is back on opus, the launch file on fakeco/glm-4.6.
    ^Z stops both magpie and claude (T), fg resumes both.
  - `magpie claude launcher add` wrote ~/bin/claude-magpie, and running it
    answered PONG.
- Real Claude Code 2.1.281 on Windows: claude-magpie.cmd beside a built
  magpie.exe, `claude-magpie --version` printed the version through
  `claude --settings <launch file>`, exit 0.

Broken by hand, each red: the blanks dropped; the launch dir override; the
stale-address check; ClaudeLaunchAfter returning early; the opus[1m]
rewrite check; WaitFollowingStops answering 0 for a signal; "$@" turned into $* in the launcher; the model mark check;
AddCLI's launcher loop; --settings dropped from the args; the restore call
dropped.

Not tried: macOS with a real Claude Code (the Unix path ran in WSL only);
Windows interactive (Ctrl+C, /model restore); a real Claude subscription or
API key upstream (a fake upstream only). Known limits: a session that ends
by a crash or kill skips the restore; managed settings (policy) outrank
--settings; magpie has to be running (claude-magpie warns when it isn't);
Claude Code itself reformats the user's settings.json when it runs its
opus migration, values kept.
2026-11-06 17:31:04 +08:00

138 lines
4.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package update
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
)
// A launcher is a command of its own a terminal runs, which runs magpie
// with arguments: claude-magpie runs `magpie claude run` (baranwang on X:
// `claude` on the user's own Claude account, `claude-magpie` through
// magpie). It goes where the terminal finds the magpie command, put there
// first as Settings › Command line puts it (AddCLI): beside its link in
// ~/.local/bin and the like, a shell script naming this program by the
// path that stays put (Program); on Windows a .cmd in the app's folder,
// which runs the magpie there as a terminal's `magpie` would (magpie.com
// before magpie.exe, PATHEXT's order), so the terminal waits for it.
// launcherMark is in every launcher magpie writes, so one of the user's
// own by the same name is never taken for magpie's.
const launcherMark = "written by magpie"
// Launchers are the launchers magpie puts beside its command, each name
// with the arguments it runs magpie with.
var Launchers = map[string][]string{"claude-magpie": {"claude", "run"}}
// LauncherFile is the file name of the launcher name on goos.
func LauncherFile(goos, name string) string {
if goos == "windows" {
return name + ".cmd"
}
return name
}
// launcherText is the launcher on goos that runs prog (on Windows, the
// magpie command beside it) with args and every argument it is given.
func launcherText(goos, prog string, args ...string) string {
if goos == "windows" {
var b strings.Builder
b.WriteString("@echo off\r\nrem " + launcherMark + ": runs magpie " + strings.Join(args, " ") + "\r\n\"%~dp0magpie\"")
for _, a := range args {
b.WriteString(" " + strings.ReplaceAll(a, "%", "%%"))
}
b.WriteString(" %*\r\n")
return b.String()
}
q := func(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
var b strings.Builder
b.WriteString("#!/bin/sh\n# " + launcherMark + ": runs magpie " + strings.Join(args, " ") + "\nexec " + q(prog))
for _, a := range args {
b.WriteString(" " + q(a))
}
b.WriteString(" \"$@\"\n")
return b.String()
}
// Launcher is where the launcher name is, "" when magpie hasn't put one
// on the PATH: in the folder the magpie command is found in.
func Launcher(name string) string {
v := ReadCLI()
if !v.Ours || v.Command == "" {
return ""
}
p := filepath.Join(filepath.Dir(v.Command), LauncherFile(runtime.GOOS, name))
if !ownLauncher(p) {
return ""
}
return p
}
// ownLauncher says the file at p is a launcher magpie wrote.
func ownLauncher(p string) bool {
b, err := os.ReadFile(p)
return err == nil && strings.Contains(string(b), launcherMark)
}
// AddLauncher writes the launcher name, which runs magpie with args,
// beside the magpie command a terminal runs, putting that there first
// when it isn't (AddCLI). A file of the user's own by that name is left
// as it is. It answers the launcher's path.
func AddLauncher(name string, args ...string) (string, error) {
v := ReadCLI()
if !v.Ours {
var err error
if v, err = addCLI(""); err != nil {
return "", fmt.Errorf("the magpie command isn't on your PATH, and putting it there failed: %w", err)
}
}
if !v.Ours || v.Command == "" {
return "", errors.New("the magpie command isn't on your PATH: add it in Settings › Command line, then run this again")
}
p := filepath.Join(filepath.Dir(v.Command), LauncherFile(runtime.GOOS, name))
return p, addLauncherBeside(v, name, args...)
}
// addLauncherBeside writes the launcher name beside v's magpie command.
func addLauncherBeside(v *CLI, name string, args ...string) error {
prog, err := cliExe()
if err != nil {
return err
}
p := filepath.Join(filepath.Dir(v.Command), LauncherFile(runtime.GOOS, name))
return writeLauncher(p, launcherText(runtime.GOOS, prog, args...))
}
// writeLauncher writes text to p, unless a file there is the user's own.
func writeLauncher(p, text string) error {
if b, err := os.ReadFile(p); err == nil {
if string(b) == text {
return nil
}
if !strings.Contains(string(b), launcherMark) {
return fmt.Errorf("%s is there already, and isn't magpie's: nothing was written", p)
}
}
tmp := p + ".magpie-new"
if err := os.WriteFile(tmp, []byte(text), 0o755); err != nil {
return err
}
if err := os.Rename(tmp, p); err != nil {
os.Remove(tmp)
return err
}
return nil
}
// RemoveLauncher takes the launcher name out, where magpie wrote it.
func RemoveLauncher(name string) (string, error) {
p := Launcher(name)
if p == "" {
return "", nil
}
return p, os.Remove(p)
}