diff --git a/internal/agent/cliupdate.go b/internal/agent/cliupdate.go index 65a53c62b..80caaaad5 100644 --- a/internal/agent/cliupdate.go +++ b/internal/agent/cliupdate.go @@ -14,6 +14,7 @@ import ( "errors" "fmt" "io" + "log" "net/http" "os" "os/exec" @@ -30,8 +31,10 @@ import ( "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/desktopdir" "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/source" "github.com/yetone/magpie/internal/update" ) @@ -1081,6 +1084,32 @@ func updateEnv(u *updater) []string { return append(env, "NONINTERACTIVE=1", "HOMEBREW_NO_ENV_HINTS=1", "NO_COLOR=1", "CLINE_NO_AUTO_UPDATE=1") } +// letGoBeforeUpdate ends what magpie itself keeps running of the agent +// id's CLI, before a package manager on Windows replaces its package: a +// program running from it can't be removed there (EPERM), and npm, which +// takes the old shims away first, stopped partway and left none (CLJY on +// Discord: %APPDATA%\npm with only the sh shim of claude, no claude.cmd, +// and no codex at all). The Claude subscription bridge's runs kept for +// their conversations' next turns, and Codex's app-server daemon with no +// session on it; a var so tests can see it asked. +var letGoBeforeUpdate = func(ctx context.Context, id string) { + switch id { + case "claude": + if n := gateway.LetGoIdleClaudeCode(); n > 0 { + log.Printf("claude: ended %d Claude Code runs waiting for their next turn, to update it", n) + } + case "codex": + if stopped, err := provider.StopIdleCodexDaemon(ctx); err != nil { + log.Println("codex: before its update:", err) + } else if stopped { + log.Println("codex: stopped its app-server daemon, to update it") + } + } +} + +// updateGOOS is runtime.GOOS; a var so tests can be Windows. +var updateGOOS = runtime.GOOS + // updateTimeout bounds an update: a download, or Homebrew updating itself first. var updateTimeout = 10 * time.Minute @@ -1110,6 +1139,9 @@ func (a *Agent) UpdateCLI() (CLI, error) { } ctx, cancel := context.WithTimeout(context.Background(), updateTimeout) defer cancel() + if updateGOOS == "windows" && (u.via == "npm" || u.via == "bun" || u.via == "pnpm") { + letGoBeforeUpdate(ctx, a.ID) + } run := runUpdate if u.admin { run = runAdmin @@ -1135,6 +1167,13 @@ func (a *Agent) UpdateCLI() (CLI, error) { } return c, fmt.Errorf("%s: %s", u.shown(), msg) } + if updateGOOS == "windows" && !isFile(bin) { + // npm took the old shims away and stopped before it wrote the new + // ones: a file of the old package's was still running (EPERM), and + // what is left of claude is npm's sh shim, which Windows can't run + // (CLJY on Discord) + return c, fmt.Errorf("%s was updated, but %s is gone (a copy of it still running keeps %s from finishing): quit it, and %s", a.Name, bin, u.via, mendHint(u, c.Version)) + } if c.Update && c.Version == before { return c, fmt.Errorf("%s is still %s after %s; %s is out", a.Name, c.Version, u.shown(), c.Latest) } diff --git a/internal/agent/cliupdate_letgo_test.go b/internal/agent/cliupdate_letgo_test.go new file mode 100644 index 000000000..9d572b845 --- /dev/null +++ b/internal/agent/cliupdate_letgo_test.go @@ -0,0 +1,77 @@ +package agent + +import ( + "context" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// CLJY (Discord): on Windows npm can't replace Claude Code while a copy of +// its claude.exe runs, and an update stopped partway and left only the sh +// shim, which Windows can't run. Before an npm update there, magpie lets go +// of what it keeps running of that CLI; and an update that leaves the CLI +// gone is a failure that says to quit it and reinstall, not "updated". +func TestUpdateCLIOnWindowsLetsGoFirst(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell scripts as the CLI") + } + tmp, _ := filepath.EvalSymlinks(t.TempDir()) + prefix := filepath.Join(tmp, "npm") + pkgDir := filepath.Join(prefix, "lib/node_modules/@anthropic-ai/claude-code") + pkgJSON := filepath.Join(pkgDir, "package.json") + file(t, pkgJSON, `{"name":"@anthropic-ai/claude-code","version":"2.1.298"}`) + file(t, filepath.Join(pkgDir, "bin/claude.exe"), "#!/bin/sh\necho '2.1.298 (Claude Code)'\n") + file(t, filepath.Join(prefix, "bin/npm"), "#!/bin/sh\nexit 1\n") + shim := filepath.Join(prefix, "bin/claude") + link(t, "../lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe", shim) + t.Setenv("PATH", filepath.Join(prefix, "bin")) + t.Setenv("HOME", filepath.Join(tmp, "home")) + + oldRun, oldLetGo, oldGOOS := runUpdate, letGoBeforeUpdate, updateGOOS + t.Cleanup(func() { + runUpdate, letGoBeforeUpdate, updateGOOS = oldRun, oldLetGo, oldGOOS + versions, latests = memo{}, memo{} + }) + versions, latests = memo{}, memo{} + latests.get("npm:@anthropic-ai/claude-code", "", 1<<40, 1<<40, func() (string, error) { return "2.1.299", nil }) + updateGOOS = "windows" + var order []string + letGoBeforeUpdate = func(_ context.Context, id string) { order = append(order, "let go of "+id) } + runUpdate = func(_ context.Context, u *updater) ([]byte, error) { + order = append(order, u.via) + // npm's reify: the old shims removed, the new ones never written + os.Remove(shim) + os.WriteFile(pkgJSON, []byte(`{"name":"@anthropic-ai/claude-code","version":"2.1.299"}`), 0o644) + return []byte("npm warn cleanup Failed to remove some directories\nchanged 1 package in 3s"), nil + } + a := &Agent{ID: "claude", Name: "Claude Code", Bin: "claude"} + if c, ok := a.CLI(); !ok || c.Via != "npm" { + t.Fatalf("before: %+v", c) + } + _, err := a.UpdateCLI() + if got := strings.Join(order, ", "); got != "let go of claude, npm" { + t.Errorf("ran %q; want magpie's own runs let go of before npm", got) + } + if err == nil || !strings.Contains(err.Error(), "is gone") { + t.Fatalf("an update that left no claude to run: %v", err) + } + + // elsewhere a running program doesn't hold its file: nothing let go of + updateGOOS = "darwin" + order = nil + file(t, pkgJSON, `{"name":"@anthropic-ai/claude-code","version":"2.1.298"}`) + link(t, "../lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe", shim) + versions = memo{} + runUpdate = func(_ context.Context, u *updater) ([]byte, error) { + order = append(order, u.via) + os.WriteFile(pkgJSON, []byte(`{"name":"@anthropic-ai/claude-code","version":"2.1.299"}`), 0o644) + return nil, nil + } + a.UpdateCLI() + if got := strings.Join(order, ", "); !strings.HasPrefix(got, "npm") || strings.Contains(got, "let go") { + t.Errorf("ran %q off Windows", got) + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 0974098d3..71ff2d8bd 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -7388,3 +7388,67 @@ func allowedTools(req *Request) map[string]bool { } return nil } + +// LetGoIdleClaudeCode ends the Claude Code runs every subscription bridge +// keeps waiting for their conversations' next turns, each one's session +// shelved for that turn as a run let go past idleMost is, and waits for +// them to have exited. It says how many it ended. An update of Claude +// Code by npm on Windows asks it first (agent.UpdateCLI): a run holds the +// package's claude.exe for up to idleLongest, which npm can't remove +// while it runs (EPERM), so the update stopped partway and left +// %APPDATA%\npm without claude.cmd (CLJY on Discord). A run in a turn is +// left to finish it. +func LetGoIdleClaudeCode() int { + var runs []*subscriptionRun + bridges.Range(func(b, _ any) bool { + runs = append(runs, b.(*subscriptionBridge).letGoIdle("Claude Code is being updated")...) + return true + }) + // Windows' Stop kills the tree and returns; the process has exited, + // and let go of its files, once exited closes + gone := time.After(stopGrace + time.Second) + for _, r := range runs { + r.mu.Lock() + exited := r.exited + r.mu.Unlock() + if exited == nil { + continue + } + select { + case <-exited: + case <-gone: + return len(runs) + } + } + return len(runs) +} + +// letGoIdle ends b's runs waiting for their next turn, for why, waits +// until each tree is ended, and says which they were. +func (b *subscriptionBridge) letGoIdle(why string) []*subscriptionRun { + var drop []*subscriptionRun + b.mu.Lock() + for key, run := range b.idle { + if run.idleKey == key { + b.shelve(run) + } + delete(b.idle, key) + run.idleKey = "" + if !slices.Contains(drop, run) { + drop = append(drop, run) + } + } + b.mu.Unlock() + stops := make([]<-chan struct{}, 0, len(drop)) + for _, run := range drop { + run.abortFor(why) + } + for _, run := range drop { + stops = append(stops, run.abort()) + } + for _, s := range stops { + <-s + } + claudeRoom.nudge() + return drop +} diff --git a/internal/gateway/claude_update_letgo_test.go b/internal/gateway/claude_update_letgo_test.go new file mode 100644 index 000000000..3de37b750 --- /dev/null +++ b/internal/gateway/claude_update_letgo_test.go @@ -0,0 +1,101 @@ +package gateway + +import ( + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// CLJY (Discord): npm couldn't remove claude.exe while a Claude Code run +// magpie kept for a conversation's next turn still ran it (EPERM), so an +// update stopped partway and left %APPDATA%\npm with the sh shim alone. +// LetGoIdleClaudeCode, which an npm update on Windows asks first, ends +// every waiting run and returns once its process has exited: the exe it +// ran can then be removed. Its conversation is shelved for its next turn; +// a run in a turn is left to finish it. +func TestLetGoIdleClaudeCodeFreesTheExe(t *testing.T) { + const child = "MAGPIE_TEST_LETGO_CHILD" + if os.Getenv(child) != "" { + time.Sleep(2 * time.Minute) // a Claude Code waiting for its next turn + return + } + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + exe := filepath.Join(dir, "claude"+filepath.Ext(self)) + body, err := os.ReadFile(self) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(exe, body, 0o755); err != nil { + t.Fatal(err) + } + + b := idleTestBridge() + start := func() *subscriptionRun { + cmd := proc.Command(exe, "-test.run=^TestLetGoIdleClaudeCodeFreesTheExe$", "-test.timeout=3m") + cmd.Env = append(os.Environ(), child+"=1") + tree, err := proc.StartTree(cmd) + if err != nil { + t.Fatal(err) + } + exited := make(chan struct{}) + r := &subscriptionRun{bridge: b, cmd: cmd, tree: tree, exited: exited, pending: map[string]chan mcpToolResult{}} + go func() { + tree.Wait() + r.mu.Lock() + close(exited) + r.mu.Unlock() + }() + t.Cleanup(func() { <-tree.Stop(0) }) + return r + } + waiting := start() + waiting.sessionID, waiting.sessions = "s1", []string{filepath.Join(dir, "project")} + b.keepIdle(waiting, "conversation", "conversation") + b.runs["waiting"] = waiting + busy := &subscriptionRun{bridge: b, pending: map[string]chan mcpToolResult{}} + b.runs["busy"] = busy + t.Cleanup(func() { + b.mu.Lock() + defer b.mu.Unlock() + for _, s := range b.shelf { + if s.timer != nil { + s.timer.Stop() + } + } + }) + + bridges.Store(b, true) + t.Cleanup(func() { bridges.Delete(b) }) + if n := LetGoIdleClaudeCode(); n < 1 { + t.Fatalf("let go of %d runs; one was waiting", n) + } + select { + case <-waiting.exited: + default: + t.Fatal("LetGoIdleClaudeCode returned before the waiting run's Claude Code exited") + } + if len(b.idle) != 0 { + t.Fatalf("%d runs still kept for a next turn", len(b.idle)) + } + if s := b.shelf["conversation"]; s == nil || s.session != "s1" { + t.Fatal("the waiting run's conversation was not shelved for its next turn") + } + busy.mu.Lock() + closed := busy.closed + busy.mu.Unlock() + if closed { + t.Fatal("a run in a turn was ended") + } + // the exe npm replaces: on Windows a running copy refuses this (EPERM) + if err := os.Remove(exe); err != nil { + t.Fatalf("the exe can't be removed after the let-go (%s): %v", runtime.GOOS, err) + } +} diff --git a/internal/proc/find.go b/internal/proc/find.go index 8a8b20d33..ecbbe0eeb 100644 --- a/internal/proc/find.go +++ b/internal/proc/find.go @@ -3,6 +3,7 @@ package proc import ( "os" "path/filepath" + "regexp" "runtime" "strings" ) @@ -61,12 +62,22 @@ func SystemDirs(paths ...string) []string { return out } +// ToolIn is name's program in the first of dirs that has one, as toolIn +// finds it on this system. +func ToolIn(name string, dirs []string) string { return toolIn(name, runtime.GOOS, dirs) } + // toolIn is name's program in the first of dirs that has one: on Windows -// name.exe, name.cmd or name, as npm's shim or an installer's binary. +// name.exe or name.cmd, as an installer's binary or npm's shim, else the +// program npm's sh shim name runs, when that is a Windows program +// (npmShimExe). A file with no extension is never run on Windows itself: +// CreateProcess refuses it ("%1 is not a valid Win32 application"), and +// what npm left of its shims when an install failed partway is that sh +// one alone (CLJY on Discord: %APPDATA%\npm\claude, 308 bytes, with no +// claude.cmd beside it, was what magpie ran). func toolIn(name, goos string, dirs []string) string { names := []string{name} if goos == "windows" { - names = []string{name + ".exe", name + ".cmd", name} + names = []string{name + ".exe", name + ".cmd"} } for _, d := range dirs { if d == "" { @@ -78,6 +89,43 @@ func toolIn(name, goos string, dirs []string) string { return p } } + if goos == "windows" { + if p := npmShimExe(filepath.Join(d, name)); p != "" { + return p + } + } } return "" } + +// npmShimLine is the line of npm's sh shim (cmd-shim) that runs a program +// of its package's directly: exec "$basedir/node_modules//" "$@". +// A shim of a node script names node first, and isn't matched. +var npmShimLine = regexp.MustCompile(`(?m)^\s*exec "\$basedir/([^"$]+\.exe)"\s+"\$@"`) + +// npmShimExe is the Windows program the npm sh shim at path runs, where it +// is: Claude Code's is node_modules\@anthropic-ai\claude-code\bin\claude.exe. +// "" when path is no such shim or its program is gone. +func npmShimExe(path string) string { + st, err := os.Stat(path) + if err != nil || st.IsDir() || st.Size() > wrapperMax { + return "" + } + b, err := os.ReadFile(path) + if err != nil { + return "" + } + m := npmShimLine.FindSubmatch(b) + if m == nil { + return "" + } + rel := filepath.FromSlash(string(m[1])) + if !filepath.IsLocal(rel) { + return "" + } + exe := filepath.Join(filepath.Dir(path), rel) + if st, err := os.Stat(exe); err != nil || st.IsDir() { + return "" + } + return exe +} diff --git a/internal/proc/find_test.go b/internal/proc/find_test.go index 7b630b9ae..273cb8036 100644 --- a/internal/proc/find_test.go +++ b/internal/proc/find_test.go @@ -74,3 +74,57 @@ func TestSystemDirsLieInTheTestsHome(t *testing.T) { t.Errorf("SystemDirs outside a test = %q", got) } } + +// What npm leaves of a package's shims when an install stops partway on +// Windows is its sh shim alone, which Windows can't run: a folder holding +// only that is given as the program it names, when that is a Windows one +// still there, and passed over otherwise (CLJY on Discord: %APPDATA%\npm +// had the 308-byte claude and no claude.cmd, and magpie ran the sh file). +// The shims are cmd-shim 7's own bytes, made on the Windows box. +func TestToolInNPMShShimAlone(t *testing.T) { + read := func(name string) []byte { + b, err := os.ReadFile(filepath.Join("testdata", name)) + if err != nil { + t.Fatal(err) + } + return b + } + d := t.TempDir() + npm, later := filepath.Join(d, "npm"), filepath.Join(d, "later") + os.MkdirAll(later, 0o755) + exe := filepath.Join(npm, "node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe") + os.MkdirAll(filepath.Dir(exe), 0o755) + os.WriteFile(filepath.Join(npm, "claude"), read("npm-sh-shim-claude"), 0o644) + os.WriteFile(filepath.Join(npm, "codex"), read("npm-sh-shim-codex"), 0o644) + os.WriteFile(filepath.Join(npm, "gemini"), []byte("#!/bin/sh\nexec gemini \"$@\"\n"), 0o644) + + // the package's program is gone too: the shim is no tool + if got := toolIn("claude", "windows", []string{npm}); got != "" { + t.Errorf("shim of a missing program: %q", got) + } + os.WriteFile(exe, []byte("MZ"), 0o755) + if got := toolIn("claude", "windows", []string{npm, later}); got != exe { + t.Errorf("claude: %q, want %q", got, exe) + } + // a shim that runs node, or anything but npm's, is passed over, for a + // runnable one in a later folder + if got := toolIn("codex", "windows", []string{npm}); got != "" { + t.Errorf("codex's node shim: %q", got) + } + if got := toolIn("gemini", "windows", []string{npm}); got != "" { + t.Errorf("a script that isn't npm's: %q", got) + } + os.WriteFile(filepath.Join(later, "codex.exe"), []byte("MZ"), 0o755) + if got := toolIn("codex", "windows", []string{npm, later}); got != filepath.Join(later, "codex.exe") { + t.Errorf("codex in a later folder: %q", got) + } + // a shim naming a program outside its folder is not followed + os.WriteFile(filepath.Join(npm, "evil"), []byte("exec \"$basedir/../../x.exe\" \"$@\"\n"), 0o644) + if got := toolIn("evil", "windows", []string{npm}); got != "" { + t.Errorf("a shim leaving its folder: %q", got) + } + // elsewhere the sh shim is the tool, as before + if got := toolIn("claude", "linux", []string{npm}); got != filepath.Join(npm, "claude") { + t.Errorf("linux: %q", got) + } +} diff --git a/internal/proc/testdata/npm-sh-shim-claude b/internal/proc/testdata/npm-sh-shim-claude new file mode 100644 index 000000000..46b6f7a91 --- /dev/null +++ b/internal/proc/testdata/npm-sh-shim-claude @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +exec "$basedir/node_modules/@anthropic-ai/claude-code/bin/claude.exe" "$@" diff --git a/internal/proc/testdata/npm-sh-shim-codex b/internal/proc/testdata/npm-sh-shim-codex new file mode 100644 index 000000000..332709431 --- /dev/null +++ b/internal/proc/testdata/npm-sh-shim-codex @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/node_modules/@openai/codex/bin/codex.js" "$@" +else + exec node "$basedir/node_modules/@openai/codex/bin/codex.js" "$@" +fi diff --git a/internal/provider/codex_daemon.go b/internal/provider/codex_daemon.go index d8c568270..280a38923 100644 --- a/internal/provider/codex_daemon.go +++ b/internal/provider/codex_daemon.go @@ -621,3 +621,35 @@ func CodexPIDs(ctx context.Context) []int { } return pids } + +// StopIdleCodexDaemon stops Codex's app-server daemon for the Codex home +// magpie signs Codex in through, when it runs with no codex session on it, +// and says whether it did. An update of Codex by npm on Windows asks it +// first (agent.UpdateCLI): the daemon, which has no idle exit and which +// magpie restarts (KeepCodexDaemonCurrent), holds the package's codex.exe, +// which npm can't remove while it runs (EPERM), and the update stopped +// partway. The next codex started starts it again. One with sessions on it +// is left: they hold codex.exe too. +func StopIdleCodexDaemon(ctx context.Context) (bool, error) { + home := codexHome() + ps, err := listProcesses(ctx) + if err != nil { + return false, err + } + if findCodexDaemon(ps, home) == 0 || codexClients(ps, home) > 0 { + return false, nil + } + codexRestarting.Lock() + defer codexRestarting.Unlock() + cmd, err := codexDaemonCommand(ctx, home, "stop") + if err != nil { + return false, err + } + if out, err := cmd.CombinedOutput(); err != nil { + if msg := lastLine(out); msg != "" { + return false, errors.New("codex app-server daemon stop: " + msg) + } + return false, errors.New("codex app-server daemon stop: " + err.Error()) + } + return true, nil +} diff --git a/internal/provider/codex_daemon_test.go b/internal/provider/codex_daemon_test.go index 470222496..fd760a1a4 100644 --- a/internal/provider/codex_daemon_test.go +++ b/internal/provider/codex_daemon_test.go @@ -680,3 +680,47 @@ func TestCodexPIDsFindsOpenCodex(t *testing.T) { t.Fatalf("a failed list gave %v", got) } } + +// CLJY (Discord): before npm updates Codex on Windows, magpie stops the +// app-server daemon when no codex session is on it, since it holds the +// package's codex.exe, which npm can't remove while it runs. One with a +// session on it, or none running, is left. +func TestStopIdleCodexDaemon(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script stands in for codex") + } + fakeDaemon(t) + out := fakeCodex(t, 0) + home := codexHome() + clients, daemon := 0, true + listProcesses = func(context.Context) ([]proc.Process, error) { + var ps []proc.Process + if daemon { + ps = append(ps, proc.Process{PID: 50, Args: home + "/packages/app-server-daemon/releases/0.162.0/bin/codex app-server --listen unix:///x --managed-daemon"}) + } + for i := range clients { + ps = append(ps, proc.Process{PID: 100 + i, Args: "codex"}) + } + return ps, nil + } + ran := func() string { + b, _ := os.ReadFile(out + ".args") + os.Remove(out + ".args") + return strings.TrimSpace(string(b)) + } + ctx := context.Background() + if stopped, err := StopIdleCodexDaemon(ctx); !stopped || err != nil || ran() != "app-server daemon stop" { + t.Fatalf("idle daemon: stopped %t, %v", stopped, err) + } + if b, _ := os.ReadFile(out + ".home"); strings.TrimSpace(string(b)) != home { + t.Errorf("CODEX_HOME %q, want %q", b, home) + } + clients = 1 + if stopped, err := StopIdleCodexDaemon(ctx); stopped || err != nil || ran() != "" { + t.Fatalf("a session on it: stopped %t, %v", stopped, err) + } + clients, daemon = 0, false + if stopped, err := StopIdleCodexDaemon(ctx); stopped || err != nil || ran() != "" { + t.Fatalf("no daemon: stopped %t, %v", stopped, err) + } +} diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.go index 13346ad9f..3f754ff68 100644 --- a/internal/provider/codex_models.go +++ b/internal/provider/codex_models.go @@ -10,8 +10,6 @@ import ( "net/http" "net/url" "os" - "path/filepath" - "runtime" "slices" "sort" "strings" @@ -230,19 +228,9 @@ var codexExecutable = func() string { if p, err := proc.LookPath("codex"); err == nil { return p } - names := []string{"codex"} - if runtime.GOOS == "windows" { - names = []string{"codex.cmd", "codex.exe", "codex"} - } - for _, d := range proc.UserBinDirs() { - for _, n := range names { - p := filepath.Join(d, n) - if st, err := os.Stat(p); err == nil && !st.IsDir() { - return p - } - } - } - return "" + // on Windows npm's codex.cmd, never the sh shim npm leaves alone when + // an install fails partway, which Windows can't run (CLJY on Discord) + return proc.ToolIn("codex", proc.UserBinDirs()) } // parseCodexModels reads the backend's list, the listed ones in its order.