diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 8ba13938e..163a1d0c0 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -136,6 +136,7 @@ something else shows up as drift. - 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 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`. +- Pi, 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` (pi-ai's and senpi-ai's `apiVersion = ""`, Prime Agent's `pa-ai` `providers/google.rs`). StepCode keeps such a model on Chat (`stepcodeProvider`): it 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. `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 @@ -143,6 +144,7 @@ something else shows up as drift. go test -tags nogui ./internal/agent -run '^TestStepCode' go test -tags nogui ./internal/agent ./internal/update ./internal/cli -run 'TestAgy|TestShellFunction|TestWithFnBlock|TestShellProfiles' node --test internal/gui/tests/agy-launch.test.cjs +go test -tags nogui ./internal/agent -run 'TestPiModelsAskedOnTheirNativeAPI|TestPiGoogle' go test -tags nogui ./internal/agent -run '^TestMothX' go test -tags nogui ./internal/agent -run '^TestPenguin' go test -tags nogui ./internal/agent -run 'TestClaudeAutoModeReview|TestClaudeReviewedOnlyWhereMessagesReachClaude|TestT3CodeAutoModeReview|TestConnect|TestDisconnect|Drift|TestKeptAddress|TestWSLAgentAddress|TestReachProbe|TestDryRunKnowsTheAskersProviders|TestReseat|TestPort|TestWSL|TestClaudeKeepsItsClaudeAISignIn|TestClaudeSignIn|TestClaudeOwnEndpointWithAnEmptyKey|TestClaudeAtAnOlderGatewayAddress' diff --git a/internal/agent/agents.go b/internal/agent/agents.go index f9ada2e66..75536bcb7 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -599,8 +599,8 @@ func objectPairs(raw []byte) orderedJSON { } // piModelJSON is one of magpie's models as an entry of Pi's models.json. -// native asks it on the API its provider speaks natively (a model's own -// api and baseUrl); without it the model is left on the provider's +// native selects the model's preferred gateway API (its own api and +// baseUrl); without it the model is left on the provider's // openai-completions (Pencil, pencil.go). func piModelJSON(m catalog.Model, gw string, native bool) map[string]any { // reasoning lets Pi offer its thinking levels for the model: as @@ -627,11 +627,24 @@ func piModelJSON(m catalog.Model, gw string, native bool) map[string]any { if gateway.AdaptiveThinking(m.ID) { e["compat"] = map[string]any{"forceAdaptiveThinking": true} } + case slices.Contains(m.APIs, string(provider.Gemini)): + e["api"], e["baseUrl"] = "google-generative-ai", gw+"/v1beta" } if m.Images { e["input"] = []string{"text", "image"} } if levels := piThinkingLevels(m.Efforts, e["api"] == "anthropic-messages" && gateway.ThinksOnlyWhenAsked(m.ID)); levels != nil { + // on google-generative-ai Pi resolves a level through the map to + // one of Gemini's four (pi-ai's resolveGoogleThinkingLevel) and + // throws before sending on any other name, so a level the model + // calls something else (xhigh, max) is hidden there (#3282) + if e["api"] == "google-generative-ai" { + for l, v := range levels { + if s, ok := v.(string); ok && l != "off" && !slices.Contains([]string{"minimal", "low", "medium", "high"}, strings.ToLower(s)) { + levels[l] = nil + } + } + } e["thinkingLevelMap"] = levels } // without it Pi takes every model for a 128K one, and compacts diff --git a/internal/agent/pi_api_test.go b/internal/agent/pi_api_test.go index b26b0aede..9e871864e 100644 --- a/internal/agent/pi_api_test.go +++ b/internal/agent/pi_api_test.go @@ -21,11 +21,16 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { {ID: "resp", Name: "Resp", Key: "k", Responses: "http://127.0.0.1:1/v1", Models: []string{"grok-5", "gpt-5.5"}}, {ID: "openai", Name: "OpenAI", Key: "k", Chat: "https://api.openai.com/v1", Responses: "https://api.openai.com/v1", Models: []string{"gpt-5.5", "whisper-x"}}, {ID: "anth", Name: "Anth", Key: "k", Anthropic: "http://127.0.0.1:1", Models: []string{"claude-sonnet-5", "kimi-k3"}}, + {ID: "gem", Name: "Gemini", Key: "k", Gemini: "http://127.0.0.1:1/v1beta", Models: []string{"gemini-3-flash"}}, + {ID: "hybrid", Name: "Hybrid", Key: "k", Chat: "http://127.0.0.1:1/v1", Gemini: "http://127.0.0.1:1/v1beta", Models: []string{"gemini-3-flash", "gemini-2.5-pro"}}, } { if err := provider.Save(p); err != nil { t.Fatal(err) } } + if err := provider.SetModelAPI("hybrid/gemini-3-flash", "gemini"); err != nil { + t.Fatal(err) + } // a group goes on Responses only when every member is best served there // (#1594): one with a Chat member, or of Messages ones, stays on Chat for _, g := range []provider.Group{ @@ -33,6 +38,7 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { {ID: "mixed", Name: "Mixed", Members: []string{"resp/grok-5", "relay/glm-4.6"}}, {ID: "claudes", Name: "Claudes", Members: []string{"anth/claude-sonnet-5", "anth/kimi-k3"}}, {ID: "outer", Name: "Outer", Members: []string{"group/gpts", "openai/gpt-5.5"}}, + {ID: "geminis", Name: "Geminis", Members: []string{"gem/gemini-3-flash"}}, } { if err := provider.SaveGroup(g); err != nil { t.Fatal(err) @@ -55,18 +61,22 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { apis[m["id"].(string)], entries[m["id"].(string)] = m["api"], m } for id, want := range map[string]any{ - "resp/grok-5": "openai-responses", - "resp/gpt-5.5": "openai-responses", - "openai/gpt-5.5": "openai-responses", - "openai/whisper-x": nil, - "relay/glm-4.6": nil, - "anth/claude-sonnet-5": "anthropic-messages", - "anth/kimi-k3": "anthropic-messages", - "auto/gpt-5.5": "openai-responses", - "group/gpts": "openai-responses", - "group/outer": "openai-responses", - "group/mixed": nil, - "group/claudes": nil, + "resp/grok-5": "openai-responses", + "resp/gpt-5.5": "openai-responses", + "openai/gpt-5.5": "openai-responses", + "openai/whisper-x": nil, + "relay/glm-4.6": nil, + "anth/claude-sonnet-5": "anthropic-messages", + "anth/kimi-k3": "anthropic-messages", + "gem/gemini-3-flash": "google-generative-ai", + "hybrid/gemini-3-flash": "google-generative-ai", + "hybrid/gemini-2.5-pro": nil, + "auto/gpt-5.5": "openai-responses", + "group/gpts": "openai-responses", + "group/outer": "openai-responses", + "group/mixed": nil, + "group/claudes": nil, + "group/geminis": nil, } { got, ok := apis[id] if !ok { @@ -90,4 +100,9 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { if _, ok := entries["resp/grok-5"]["baseUrl"]; ok { t.Errorf("a Responses model keeps the provider's baseUrl: %v", entries["resp/grok-5"]) } + for _, id := range []string{"gem/gemini-3-flash", "hybrid/gemini-3-flash"} { + if e := entries[id]; e["baseUrl"] != gateway.URL()+"/v1beta" { + t.Errorf("%s baseUrl: %v", id, e) + } + } } diff --git a/internal/agent/pi_google_test.go b/internal/agent/pi_google_test.go new file mode 100644 index 000000000..06b4a6ece --- /dev/null +++ b/internal/agent/pi_google_test.go @@ -0,0 +1,100 @@ +package agent + +import ( + "encoding/json" + "path/filepath" + "slices" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/settings" +) + +// #3282: Google plugin models use Code Assist internally, but Pi must +// send Gemini requests to the gateway, with its key rather than the plugin's. +func TestPiGooglePluginModels(t *testing.T) { + home := syncHome(t) + t.Setenv("MAGPIE_BUN", "") + const spec = "google-plugin-test" + writeFile(t, filepath.Join(settings.Dir(), "plugins.json"), `{"plugins":[{"spec":"`+spec+`"}]}`) + writeFile(t, filepath.Join(settings.Dir(), "plugin-auth.json"), `{"google-plugin":{"type":"api","key":"plugin-secret"}}`) + plugin.UseCached([]plugin.Provider{{ID: "google-plugin", Spec: spec, Name: "Google plugin", + Models: []plugin.Model{{ID: "gemini-3-flash", Name: "Gemini 3 Flash", NPM: "@ai-sdk/google"}}}}) + t.Cleanup(plugin.Settle) + const gw = "http://127.0.0.1:17325" + t.Setenv("MAGPIE_ADDR", "127.0.0.1:17325") + for _, a := range []*Agent{pi(home), omo(home), primeAgent(home), stepcode(home)} { + t.Run(a.ID, func(t *testing.T) { + if err := a.Field("model").Set("magpie/google-plugin/gemini-3-flash"); err != nil { + t.Fatal(err) + } + path := filepath.Join(filepath.Dir(a.Path), "models.json") + // Existing files must acquire the correction during normal sync too. + p := providerAt(t, path, "providers") + for _, raw := range p["models"].([]any) { + m := raw.(map[string]any) + delete(m, "api") + delete(m, "baseUrl") + } + b, _ := json.Marshal(map[string]any{"providers": map[string]any{"magpie": p}}) + writeFile(t, path, string(b)) + if err := a.Sync(); err != nil { + t.Fatal(err) + } + p = providerAt(t, path, "providers") + if p["api"] != "openai-completions" || p["baseUrl"] != gw+"/v1" || p["apiKey"] == "plugin-secret" { + t.Fatalf("provider defaults or gateway authentication changed: %v", p) + } + found := false + for _, raw := range p["models"].([]any) { + m := raw.(map[string]any) + if m["id"] != "google-plugin/gemini-3-flash" { + continue + } + found = true + // StepCode has no google-generative-ai stream: Chat there + if a.ID == "stepcode" { + if m["api"] != nil || m["baseUrl"] != nil { + t.Errorf("StepCode can't ask Gemini's API: %v", m) + } + } else if m["api"] != "google-generative-ai" || m["baseUrl"] != gw+"/v1beta" { + t.Errorf("Google model still inherits Chat: %v", m) + } + } + if !found { + t.Fatal("Google plugin model not offered") + } + }) + } + for _, m := range pencilProviderJSON(gw)["models"].([]map[string]any) { + if m["api"] != nil || m["baseUrl"] != nil { + t.Errorf("Pencil no longer uses its provider's Chat API: %v", m) + } + } +} + +// Pi's google-generative-ai resolves each level through thinkingLevelMap to +// minimal, low, medium or high and throws on any other name before it sends +// (pi-ai's resolveGoogleThinkingLevel), so a Gemini model's level by another +// name is hidden there, while the same levels on Chat stay as they were. +func TestPiGoogleThinkingLevelsAreGeminis(t *testing.T) { + m := catalog.Model{ID: "gem/gemini-3-pro", Name: "Gemini 3 Pro", APIs: []string{"gemini"}, Efforts: []string{"none", "low", "high", "xhigh", "max"}} + e := piModelJSON(m, "http://127.0.0.1:1", true) + if e["api"] != "google-generative-ai" { + t.Fatalf("api: %v", e["api"]) + } + levels := e["thinkingLevelMap"].(map[string]any) + for l, want := range map[string]any{"off": "none", "minimal": nil, "low": "low", "medium": nil, "high": "high", "xhigh": nil, "max": nil} { + if levels[l] != want { + t.Errorf("%s: %v, want %v", l, levels[l], want) + } + } + if got := piSupported(e); !slices.Equal(got, []string{"off", "low", "high"}) { + t.Errorf("Pi offers %v", got) + } + chat := piModelJSON(catalog.Model{ID: m.ID, Name: m.Name, Efforts: m.Efforts}, "http://127.0.0.1:1", true) + if l := chat["thinkingLevelMap"].(map[string]any); l["xhigh"] != "xhigh" || l["max"] != "max" { + t.Errorf("a Chat model lost its levels: %v", l) + } +} diff --git a/internal/agent/route.go b/internal/agent/route.go index b52303fb0..190289fc7 100644 --- a/internal/agent/route.go +++ b/internal/agent/route.go @@ -213,8 +213,8 @@ func magpieModels(agent string) []catalog.Model { yes := true m.ImageInput = &yes } - // APIs is the one to ask it on for the gateway to relay the request - // as it is. A group's members may each want another, so a group has + // APIs is the preferred client protocol, preserving the vendor's + // own content where possible. A group's members may differ, so a group has // one only when every member is served best on Responses (#1594, // ObsidianArch02): Pi, omp, droid and dsh then ask it there, and a // GPT group's tool-call arguments stream as the member sends them @@ -222,6 +222,16 @@ func magpieModels(agent string) []catalog.Model { if e.Group == "" { if n := e.Provider.Native(e.Model); n != "" { m.APIs = []string{string(n)} + } else { + // Gemini clients also reach Code Assist and Google plugins + // through the gateway's Gemini API, with translation as needed. + apis := e.Provider.APIs(e.Model) + for _, pr := range e.Provider.Speaks() { + if (pr == provider.Gemini || pr == provider.CodeAssist) && (apis == nil || slices.Contains(apis, pr)) { + m.APIs = []string{string(provider.Gemini)} + break + } + } } } else if allResponses(members(e.ID)) { m.APIs = []string{string(provider.Responses)} diff --git a/internal/agent/stepcode.go b/internal/agent/stepcode.go index dcc5154b9..8eac995b9 100644 --- a/internal/agent/stepcode.go +++ b/internal/agent/stepcode.go @@ -16,6 +16,7 @@ import ( "github.com/tidwall/jsonc" "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/provider" ) // StepCode keeps its configuration in ~/.stepcode/config.toml (or @@ -42,6 +43,12 @@ func stepcodeDir(at place) string { func stepcodeProvider(at place) any { ms := make([]map[string]any, 0) for _, m := range magpieModels("stepcode") { + // StepCode registers no google-generative-ai stream, only Pi's + // anthropic-messages, openai-completions and openai-responses + // (packages/providers/src/compat.ts BUILTIN_APIS, Step-Code at + // 90a57820), though its docs list it: a Gemini model stays on Chat + // there, which the gateway translates (#3282) + m.APIs = slices.DeleteFunc(slices.Clone(m.APIs), func(a string) bool { return a == string(provider.Gemini) }) ms = append(ms, piModelJSON(m, at.gw(), true)) } return map[string]any{ diff --git a/internal/gateway/plugin_test.go b/internal/gateway/plugin_test.go index ca6f41591..bb90f174f 100644 --- a/internal/gateway/plugin_test.go +++ b/internal/gateway/plugin_test.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "net/http" + "net/http/httptest" "path/filepath" "slices" "strings" @@ -124,6 +125,24 @@ func TestPluginProvider(t *testing.T) { } } + // Pi's Google API request still uses the plugin's loader and fetch, + // including its account key and model header (#3282). + req := httptest.NewRequest(http.MethodPost, "/v1beta/models/fakeco/fake-gemini:streamGenerateContent?alt=sse", + strings.NewReader(`{"contents":[{"role":"user","parts":[{"text":"hello from Pi"}]}]}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("x-goog-api-key", "magpie") + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "hi from gemini") { + t.Fatalf("Pi Gemini request: %d %s", rec.Code, rec.Body.String()) + } + mu.Lock() + piLast := got[len(got)-1] + mu.Unlock() + if piLast.path != "/v1/models/fake-gemini:streamGenerateContent?alt=sse" || piLast.auth != "Bearer k1" || piLast.model != "fake-gemini" || !strings.Contains(piLast.body, "hello from Pi") { + t.Fatalf("Pi Gemini request bypassed the plugin: %+v", piLast) + } + // the vendor refuses the first account's sign-in: it shows lapsed, as a // built-in's does, until a request on it goes through again lapsed := func() string {