diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 1d57a5364..e665915c0 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -145,7 +145,7 @@ something else shows up as drift. - Zoo Code's provider profiles are in VS Code's secret storage, so magpie writes a settings file for it (`magpie-import.json` in Zoo Code's `globalStorage/zoocodeorganization.zoo-code/settings`, not magpie's folder, so a sync keeps an address the user moved it to) and points Zoo Code's `zoo-code.autoImportSettingsPath` at it in VS Code's `settings.json` and each profile's, a user's own path stashed and put back ([`zoocode.go`](../../internal/agent/zoocode.go)). Zoo Code imports it on each start (`importSettingsFromPath`), merging it over the user's profiles and making `magpie` the current one. Disconnect stops the import and deletes the file; the profile already imported stays in Zoo Code, where magpie can't reach it. - An agent is detected by its config file, its folder, or its command on magpie's PATH (`Detected`). That PATH is the login shell's plus the folders users' tools go in (`proc.UserPath`: `~/.local/bin`, npm's prefixes, the Node nvm's default alias resolves to (the highest installed when it names none), bun, Homebrew, ...; on Windows the registry's PATH plus the Node fnm's default alias names, `%APPDATA%\fnm\aliases\default` or under `FNM_DIR`, which fnm puts on a terminal's PATH from the shell profile and never in the registry, #2685), so a CLI a terminal doesn't find can still be found and listed: an npm install under a Node the terminal no longer uses. `/api/agents/cli` then gives where it is (`path`) and `offPath` when the login shell's PATH (`proc.LoginPath`) lacks its folder, and the Agents row says "Not on your terminal's PATH", its tip naming the file (悠悠哥 on Discord: Codex 0.162.1 listed with no codex on PATH and no `~/.codex`). An unknown login PATH says nothing. A folder another tool writes too doesn't count (`dirShared`): Pi's for omp, `~/.copilot` for the Copilot CLI, which GitHub Copilot's JetBrains and VS Code plugins also write, and Qoder's and Qoder CN's, which Qoder's JetBrains plugin fills, and `~/.cursor` for Cursor CLI, which the Cursor editor makes on its own (`TestCursorFolderFromTheEditorIsNotTheCLI`, @G_Z_Y on X); only `cli-config.json` or `cursor-agent` finds Cursor CLI. A command another app ships under the agent's name doesn't count either: VS Code forks put a `code` launcher in their own bin folder (Cursor; Qoder IDE beside `qoder`), which their Windows installers put on PATH, so a `code`, `code-insiders` or `codium` counts as VS Code, Insiders or VSCodium only when the `product.json` beside it names that build (`applicationName`), or names none (`vscodeCodeBinary`; ggbr on Discord: Qoder IDE listed as VS Code too, `TestVSCodeDetected`, `TestVSCodeBuildLauncher`). A config file another tool writes first counts only when `pathOwn` says it is the agent's: Qoder's `settings.json` holding `enabledPlugins` alone is the plugin's (`qoderPluginOnly`; #1495, `TestCopilotFolderFromAnIDEPluginIsNotTheCLI`, `TestQoderSettingsFromAnIDEPluginIsNotTheCLI`). The Qoder app (the desktop app, which runs Qoder's CLI as its agent with the same folder) is found by the `.qoder-app-status.json` it writes there (`sign`, `qoderApp`; #2138, `TestQoderAppIsQoder`), as its `settings.json` can be its bundled plugin's `enabledPlugins` alone. Only the GUI and `daemon install` widen the PATH so; `magpie serve`, `web`, `tui` and the CLI keep the one they were started with, so an agent's CLI (`cliBin`, which its version and `omp`'s max effort are read from) is looked for in those folders (`proc.FindTool`) on every system when it isn't on the PATH, not only on Windows (whqtian on Discord: omp under `~/.bun/bin` on Ubuntu read as no version and offered xhigh in place of max; `TestOmpVersionOffPath`). - Detection goes by an agent's folder, which an uninstall leaves behind, so an agent found by that alone is shown as gone (`CLIMissing`; #843, #2177, #2173): its CLI is on no PATH and in none of `proc.FindTool`'s folders nor where its own installer puts it (`~/.claude/local`, `~/.codex/packages/standalone`, `~/.opencode/bin`, Hermes' `hermes-agent` checkout), and nothing else that reads the folder is here (`cliHeld`): its desktop app (`HasApp`), an editor's extension (`~/./extensions/-*`: `anthropic.claude-code`, `openai.chatgpt`, `saoudrizwan.claude-dev`), Claude.app, OpenCode.app and Goose.app on a Mac, a JetBrains IDE's settings (its AI Assistant's agents and Cline's plugin) or Zed's `external_agents` (its Claude Code and Codex adapters). Where magpie can't tell (every shared folder, `cliShared`, on Windows, whose readers can be a Store app, a portable editor or a PATH only a shell profile sets, #1482, and there too one a desktop app of the agent's reads, `desktopApps`: DeepSeek Harness Desktop installs to any folder and puts its `dsh.cmd` in one the user picks, #2300, #2304; OpenCode and Goose off a Mac, Gemini, an agent detected its own way or by a command name other tools share, one with no install command but `cliOnly`'s Hermes), it is never gone. A gone row in the GUI shows "CLI not found" and none of its settings, nor Apply again; while connected it keeps its switch and Disconnect, and it folds under Not set up once not. Get started never offers it (`connectKind` is "no"). The TUI leaves it out and `magpie ls` says "CLI not found" (`TestCLIMissing*`, `agent-cli-missing.test.cjs`, `getting-started.test.cjs`). -- Tests never touch the real machine. `TestMain` uses `testenv`, which points HOME, USERPROFILE, the XDG folders and APPDATA into a temporary folder, clears `agentenv.Vars` and puts failing stand-ins for keychain tools and agent CLIs on PATH. Agent-specific side effects (Aside, the Zed keychain, Codex's usage check) are also stubbed in `TestMain`. +- Tests never touch the real machine. `TestMain` uses `testenv`, which points HOME, USERPROFILE, the XDG folders and APPDATA into a temporary folder, clears `agentenv.Vars` and puts failing stand-ins for keychain tools and agent CLIs on PATH. Agent-specific side effects (Aside, the Zed keychain, Codex's usage check) are also stubbed in `TestMain`. The one thing tests keep between runs is the pi tests' Bun install cache, `magpie-test-bun-cache--` in the temp folder (`pinnedPiCache` in `internal/plugin`), outside the test home on purpose so a run doesn't fetch the pinned pi's 118 packages again (#2865): it is used only when it is this user's alone, never as root, and is a new folder every two days, so the temp folder's cleaner never takes a file out of the one in use. - OmO and Prime Agent write a Gemini-capable model as `google-generative-ai` at the gateway's `/v1beta` (`piModelJSON` in [`agents.go`](../../internal/agent/agents.go)); each one's Google client takes the version path from `baseUrl` (senpi-ai's `apiVersion = ""`, Prime Agent's `pa-ai` `providers/google.rs`). omp does the same in `models.yml` (`ompProviderAt` in [`omp.go`](../../internal/agent/omp.go), #4277): its `google-generative-ai` posts to `baseUrl/models/:streamGenerateContent?alt=sse` (pi-ai `providers/google.ts`, 16.0.0 to 18.14.0). Its Google client throws without a key, but under `auth: none` omp hands it its no-auth key `N/A`, which it sends as `x-goog-api-key` and loopback takes, so the provider stays keyless; a WSL omp under NAT sends its `apiKey` there. A Gemini 3 or later model thinks with `mode: google-level` (thinkingLevel MINIMAL to HIGH; xhigh and max go as HIGH), a Gemini 1.x or 2.x one with `budget`, which omp sends as `thinkingBudget: -1` (`ompGeminiMode`; `TestOmpGeminiModelsAskedOnGeminisAPI`). Checked with omp 18.14.0 against the gateway and a fake Gemini server. Pi and StepCode keep such a model on Chat, which the gateway translates (`piAsked`). StepCode registers no `google-generative-ai` stream, only `anthropic-messages`, `openai-completions` and `openai-responses` (Step-Code `packages/providers/src/compat.ts`), though its docs list it. Pi's own agent folder is read by apps that run Pi's SDK on it too: Raft's daemon (`@botiverse/raft-daemon`, pi-ai 0.83.0) opens `~/.pi/agent/models.json` and hands every request its own fetch, which pi-ai's Google adapter refuses before sending ("Custom fetch is not supported by the Google Generative AI adapter", in pi-ai 1.4.0 too; yunfei9958 on X, `TestPiFolderKeepsGeminiOnChatForRaft`). `magpieModels` in [`route.go`](../../internal/agent/route.go) includes Gemini and Code Assist capabilities when no native Chat, Responses or Messages API was selected; this includes a plugin model declaring `@ai-sdk/google`. Requests keep going through the gateway and the plugin's sign-in and fetch, with the gateway's usual translation where needed. A normal model sync updates existing entries. Routing groups retain their existing API choice, and Pencil remains on Chat. Pi resolves a level there to one of Gemini's four (minimal, low, medium, high) and throws on any other, so a level the model names otherwise is set to null in `thinkingLevelMap` (`TestPiGoogleThinkingLevelsAreGeminis`). ## Verification diff --git a/internal/plugin/pi_test.go b/internal/plugin/pi_test.go index 7b510b864..7d8d8ce67 100644 --- a/internal/plugin/pi_test.go +++ b/internal/plugin/pi_test.go @@ -11,7 +11,9 @@ import ( "os/exec" "path/filepath" "reflect" + "runtime" "slices" + "strconv" "strings" "testing" "time" @@ -444,7 +446,11 @@ func installPinnedPi(t *testing.T, ctx context.Context) { if err != nil { t.Fatal(err) } - if out, err := bunCommand(ctx, bun, Dir(), "install", "--frozen-lockfile", "--ignore-scripts").CombinedOutput(); err != nil { + cmd := bunCommand(ctx, bun, Dir(), "install", "--frozen-lockfile", "--ignore-scripts") + if cache := pinnedPiCache(time.Now()); cache != "" { + cmd.Env = append(cmd.Env, "BUN_INSTALL_CACHE_DIR="+cache) // os/exec takes a key's last + } + if out, err := cmd.CombinedOutput(); err != nil { t.Skipf("pi couldn't be installed: %v: %s", err, lastLines(string(out), 6)) } if v := Version(piAgent); v != pinnedPi { @@ -452,6 +458,91 @@ func installPinnedPi(t *testing.T, ctx context.Context) { } } +// pinnedPiCache is the Bun install cache installPinnedPi installs with at +// now, in the temp folder, which outlives the test's home: a run after the +// first installs pi from it, where the home's own cache started empty each +// run and every run fetched pi's 118 tarballs, most of TestPiPackage's 4 +// minutes on a busy machine (#2865). It is this user's (their uid in its +// name, as the temp folder is shared on Linux; Windows' is the user's +// own), and used only when no one else can read or write it and this +// user can write in it; else "", and the home's cache is used as before. +// Never as root: root passes those checks in a folder another user made. +// It is a new folder every two days (pinnedPiCacheDays), so none of its +// files is old enough for the temp folder's cleaner to have taken it +// (macOS' takes what went unread for 3 days): Bun installs a package +// whose cached folder lost a file as it is, and pi didn't load. The +// folder before stays for a run still using it; older ones go. Bun +// unpacks a package in a folder of its own and renames it into the +// cache, so two go test runs can share it. It isn't the app's cache +// (installCacheDir), which pruneInstallCache prunes. +func pinnedPiCache(now time.Time) string { + if os.Getuid() == 0 { + return "" + } + name := "magpie-test-bun-cache-" + strconv.Itoa(os.Getuid()) + "-" + n := now.Unix() / int64(pinnedPiCacheDays*24*time.Hour/time.Second) + old, _ := filepath.Glob(filepath.Join(os.TempDir(), name+"*")) + for _, o := range old { + if k, err := strconv.ParseInt(strings.TrimPrefix(filepath.Base(o), name), 10, 64); err == nil && k < n-1 { + os.RemoveAll(o) + } + } + dir := filepath.Join(os.TempDir(), name+strconv.FormatInt(n, 10)) + if err := os.MkdirAll(dir, 0o700); err != nil { + return "" + } + fi, err := os.Lstat(dir) + if err != nil || !fi.IsDir() || runtime.GOOS != "windows" && fi.Mode().Perm()&0o077 != 0 { + return "" + } + f, err := os.CreateTemp(dir, "probe-") + if err != nil { + return "" + } + f.Close() + os.Remove(f.Name()) + return dir +} + +// pinnedPiCacheDays is how long pinnedPiCache keeps one folder. +const pinnedPiCacheDays = 2 + +// The pinned pi's cache moves to a new folder every two days, the one +// before kept and older ones taken out, so the temp folder's cleaner +// never takes a file from the one in use (#2865). +func TestPinnedPiCacheMovesOn(t *testing.T) { + if os.Getuid() == 0 { + t.Skip("root gets no cache") + } + tmp := t.TempDir() + t.Setenv("TMPDIR", tmp) // os.TempDir: TMPDIR on Unix, TMP on Windows + t.Setenv("TMP", tmp) + day := 24 * time.Hour + period := int64(pinnedPiCacheDays * 24 * 3600) + start := time.Unix(1800000000/period*period, 0) // a folder's first second + a := pinnedPiCache(start) + if a == "" || filepath.Dir(a) != tmp { + t.Fatalf("the cache is %q, not a folder in %s", a, tmp) + } + if got := pinnedPiCache(start.Add(2*day - time.Second)); got != a { + t.Fatalf("within its two days the cache moved from %s to %s", a, got) + } + b := pinnedPiCache(start.Add(2 * day)) + if b == "" || b == a { + t.Fatalf("after two days the cache is %q, not a folder other than %s", b, a) + } + if _, err := os.Stat(a); err != nil { + t.Fatalf("the folder before was taken out while a run may use it: %v", err) + } + c := pinnedPiCache(start.Add(4 * day)) + if _, err := os.Stat(a); !os.IsNotExist(err) { + t.Fatalf("a folder four days old is kept (%v)", err) + } + if _, err := os.Stat(b); err != nil || c == "" || c == b { + t.Fatalf("after four days: %q, and the one before %s: %v", c, b, err) + } +} + // A pi package added without pi has pi installed with it (ensurePi), once; // with pi there already, and for an OpenCode plugin, nothing is installed. func TestEnsurePi(t *testing.T) {