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/main218b38c59): - 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/mainb020ae102. 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/mainf47390bf3, 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.
178 lines
6.6 KiB
Go
178 lines
6.6 KiB
Go
package agent
|
|
|
|
import (
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/yetone/magpie/internal/agentenv"
|
|
"github.com/yetone/magpie/internal/appdir"
|
|
"github.com/yetone/magpie/internal/edit"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// claude-magpie (baranwang on X): Claude Code started through magpie while
|
|
// a plain `claude` stays on the user's own account, with nothing switched
|
|
// back and forth. magpie keeps a settings file of its own,
|
|
// <config>/claude-launch/settings.json, wired as it would wire Claude
|
|
// Code's (its gateway, key, models and tiers), and `magpie claude run`
|
|
// starts claude with --settings and that file. Claude Code puts a
|
|
// --settings file over the user's settings.json, its env key by key over
|
|
// the user's env and the shell's (tried with Claude Code 2.1.318: a
|
|
// claude.ai sign-in, the user's own base URL and token, a shell
|
|
// ANTHROPIC_BASE_URL all lost to it), so ~/.claude/settings.json is never
|
|
// written. What could still take a request past magpie, an
|
|
// ANTHROPIC_API_KEY or a cloud switch from the user's file or the shell,
|
|
// is blanked in the file (claudeLaunchBlanks).
|
|
|
|
// ClaudeLaunchID is the launch file's agent id: claude's lists (ListsFor
|
|
// cuts at #), its stash keys under its own name.
|
|
const ClaudeLaunchID = "claude#launch"
|
|
|
|
// claudeLaunchDir is the folder of the launch file; a var so tests can
|
|
// put it in their own folder.
|
|
var claudeLaunchDir = func() string { return filepath.Join(appdir.Config(), "claude-launch") }
|
|
|
|
// ClaudeLaunchPath is the settings file `magpie claude run` hands claude.
|
|
func ClaudeLaunchPath() string { return filepath.Join(claudeLaunchDir(), "settings.json") }
|
|
|
|
// claudeLaunch is the launch file as an agent: Claude Code at this home,
|
|
// its settings.json the launch file. It is listed nowhere, so the Agents
|
|
// page, Check and Notice see only the user's own settings.json.
|
|
func claudeLaunch(home string) *Agent {
|
|
a := claudeIn(place{home: home, id: ClaudeLaunchID, dir: claudeLaunchDir()})
|
|
a.ID = ClaudeLaunchID
|
|
a.Name = "claude-magpie"
|
|
a.Aliases = nil
|
|
return a
|
|
}
|
|
|
|
// claudeLaunchBlanks are the variables the launch file sets to "", each
|
|
// over the user's settings.json and the shell: an API key would go to
|
|
// magpie beside its own key (x-api-key), and a cloud switch takes Claude
|
|
// Code to Bedrock, Vertex and the like, past magpie.
|
|
func claudeLaunchBlanks() []string {
|
|
return append([]string{"ANTHROPIC_API_KEY"}, agentenv.ClaudeProviders...)
|
|
}
|
|
|
|
// ClaudeLaunch writes the launch file for a start: connected the first
|
|
// time as Connect connects Claude Code (the model it would pick, the
|
|
// tiers following it), brought up to the catalog after that (Sync), the
|
|
// gateway's address and key as they are now, and the blanks. It answers
|
|
// the file's path.
|
|
func ClaudeLaunch(home string) (string, error) {
|
|
a := claudeLaunch(home)
|
|
path := ClaudeLaunchPath()
|
|
switch {
|
|
case !a.Wired():
|
|
if _, err := a.ConnectHow(); err != nil {
|
|
return "", err
|
|
}
|
|
case claudeLaunchStale(a, path):
|
|
// the gateway moved (another port, MAGPIE_ADDR) or wants another
|
|
// key (LAN sharing) since: set again at the address and key of
|
|
// now, as Rewire does. The Agents page reads a Claude Code on an
|
|
// older address as wired still; the launch file is set at once
|
|
if _, errs := setAgain([]*Agent{a}); len(errs) > 0 {
|
|
return "", errs[0]
|
|
}
|
|
default:
|
|
if err := a.Sync(); err != nil {
|
|
return "", err
|
|
}
|
|
}
|
|
var kvs []edit.KV
|
|
for _, k := range claudeLaunchBlanks() {
|
|
if v, has := edit.GetJSON(path, "env."+k); !has || v != "" {
|
|
kvs = append(kvs, edit.KV{Path: "env." + k, Value: ""})
|
|
}
|
|
}
|
|
if len(kvs) > 0 {
|
|
if err := edit.SetJSON(path, kvs...); err != nil {
|
|
return "", err
|
|
}
|
|
}
|
|
return path, nil
|
|
}
|
|
|
|
// claudeLaunchStale says the launch file names another address or key
|
|
// than the gateway's of now, or the Agents page's check finds it unwired.
|
|
func claudeLaunchStale(a *Agent, path string) bool {
|
|
at := here("")
|
|
u, _ := edit.GetJSON(path, "env.ANTHROPIC_BASE_URL")
|
|
k, _ := edit.GetJSON(path, "env.ANTHROPIC_AUTH_TOKEN")
|
|
if u != at.gw() || k != at.gwKey() {
|
|
return true
|
|
}
|
|
d := a.Drift()
|
|
return d != nil && d.Kind == "unwired"
|
|
}
|
|
|
|
// ClaudeModelMark is what the user's settings.json says of its model
|
|
// before a claude-magpie session, for ClaudeLaunchAfter.
|
|
type ClaudeModelMark struct {
|
|
model string
|
|
has bool
|
|
}
|
|
|
|
// ClaudeLaunchBefore marks the user's model before a session.
|
|
func ClaudeLaunchBefore(home string) ClaudeModelMark {
|
|
m, has := edit.GetJSON(claudeUserSettings(home), "model")
|
|
return ClaudeModelMark{m, has}
|
|
}
|
|
|
|
func claudeUserSettings(home string) string {
|
|
return filepath.Join(here(home).claudeDir(), "settings.json")
|
|
}
|
|
|
|
// ClaudeLaunchAfter is what a claude-magpie session's /model leaves:
|
|
// Claude Code saves a pick there to the user's settings.json, never to a
|
|
// --settings file (tried with 2.1.318). A model of magpie's picked goes
|
|
// to the launch file, for claude-magpie's next session, and the user's
|
|
// file gets its model back while magpie isn't wired into it: a plain
|
|
// `claude` would ask Anthropic for a model only magpie serves. A Claude
|
|
// model of its own (sonnet) is a pick plain claude can run, and stays.
|
|
func ClaudeLaunchAfter(home string, was ClaudeModelMark) error {
|
|
user := claudeUserSettings(home)
|
|
now, has := edit.GetJSON(user, "model")
|
|
if now == was.model && has == was.has {
|
|
return nil
|
|
}
|
|
if claudeRouted(here(home), user) {
|
|
read := provider.ClaudeRead(now)
|
|
if m, _ := tierAt(read); isMagpie(strings.TrimSuffix(m, "[1m]")) {
|
|
return claudeLaunch(home).Apply("model", read)
|
|
}
|
|
return nil
|
|
}
|
|
if !claudeLaunchRewrote(was, now) {
|
|
read := provider.ClaudeRead(now)
|
|
m, _ := tierAt(read)
|
|
if !isMagpie(strings.TrimSuffix(m, "[1m]")) {
|
|
return nil
|
|
}
|
|
if err := claudeLaunch(home).Apply("model", read); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if was.has {
|
|
return edit.SetJSON(user, edit.KV{Path: "model", Value: was.model})
|
|
}
|
|
return edit.DelJSON(user, "model")
|
|
}
|
|
|
|
// claudeLaunchRewrote says now is Claude Code's own rewrite of the user's
|
|
// model at a claude-magpie start, not a pick: with the launch file's opus
|
|
// tier on 1M, Claude Code 2.1.318 turns a user's "opus" into "opus[1m]"
|
|
// in their settings.json once (migration_opus_to_opus1m, which asks
|
|
// whether the opus it would run is opted in to 1M). Plain claude, on the
|
|
// user's own account, would then ask for 1M context it may not have.
|
|
func claudeLaunchRewrote(was ClaudeModelMark, now string) bool {
|
|
return was.has && !strings.HasSuffix(was.model, "[1m]") && now == was.model+"[1m]"
|
|
}
|
|
|
|
// claudeLaunchStandIn is StandIn for a claude-magpie session: the launch
|
|
// file's main model and tiers, while it is on this gateway.
|
|
func claudeLaunchStandIn(model string) string {
|
|
return claudeStandIn(ClaudeLaunchPath(), model)
|
|
}
|