diff --git a/internal/agent/agy.go b/internal/agent/agy.go index 78763173c..61f309cf2 100644 --- a/internal/agent/agy.go +++ b/internal/agent/agy.go @@ -38,7 +38,7 @@ const agyModels = "customModelsConfig.customModels" // (x-goog-api-key) alone. A command copied before, with the plain token, // still reaches magpie. func AgyLaunch(model string) string { - key := gateway.TokenFor("agy") + key := agentKey("agy") if runtime.GOOS == "windows" { return `$env:GEMINI_API_KEY="` + key + `"; $env:GOOGLE_GEMINI_BASE_URL="` + gateway.URL() + `"; agy --model '` + strings.ReplaceAll(model, "'", "''") + `'` } diff --git a/internal/agent/air.go b/internal/agent/air.go index fe46eac8f..f4fdf5f2d 100644 --- a/internal/agent/air.go +++ b/internal/agent/air.go @@ -40,7 +40,6 @@ import ( "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/edit" - "github.com/yetone/magpie/internal/gateway" ) // airAgent is the name magpie's agent has in acp.json, and so in Air's @@ -120,7 +119,7 @@ func air(home, cfg string) *Agent { return "Air's Magpie agent (" + filepath.Base(path) + ") is gone, so Air no longer reaches magpie" } return wiringOff("Air", ocPath, func(k string) (string, bool) { return edit.GetJSON(ocPath, "provider."+magpieID+".options."+k) }, - "baseURL", gatewayV1(), "apiKey", gateway.Token) + "baseURL", gatewayV1(), "apiKey", hereKey()) }, Sync: func() error { return syncJSONInOrder(ocPath, "provider."+magpieID, provider) diff --git a/internal/agent/alma.go b/internal/agent/alma.go index 7d284ea31..f5e0e9d8d 100644 --- a/internal/agent/alma.go +++ b/internal/agent/alma.go @@ -436,14 +436,16 @@ func almaWire() (string, error) { // almaKey is the key magpie's provider in Alma is given. Alma's requests // carry the AI SDK's User-Agent and nothing of Alma's, so the key is how // the gateway knows them for Alma's. -func almaKey() string { return gateway.TokenFor("alma") } +func almaKey() string { return agentKey("alma") } -// almaKeyed gives magpie's provider the key almaKey in place of the one it -// was given before there was one, gateway.Token; a key Alma gives back -// some other way (encrypted) is left be. The key alone is sent: a baseURL, -// even the same one, would have Alma drop its models. +// almaKeyed gives magpie's provider the key almaKey in place of one magpie +// gave it before: gateway.Token, from before there was one, or the key +// named for Alma while the gateway's address beyond loopback wants the LAN +// key, or the other way round (#1647); a key Alma gives back some other way +// (encrypted) is left be. The key alone is sent: a baseURL, even the same +// one, would have Alma drop its models. func almaKeyed(p *almaProvider) error { - if p.APIKey != gateway.Token { + if p.APIKey == almaKey() || !ourKey(p.APIKey) && p.APIKey != gateway.TokenFor("alma") { return nil } return almaDo("PUT", "/api/providers/"+p.ID, map[string]any{"apiKey": almaKey()}, nil) diff --git a/internal/agent/aside_native.go b/internal/agent/aside_native.go index 5fd66d4b9..d922ec1a4 100644 --- a/internal/agent/aside_native.go +++ b/internal/agent/aside_native.go @@ -312,7 +312,7 @@ func (c *asideConnection) provider() (string, string) { if p.Key == "" || p.URL == "" { return "foreign", "Aside's magpie provider has no ownership credential; it will not be overwritten" } - if p.Key != gateway.TokenFor("aside") { + if p.Key != gateway.TokenFor("aside") && p.Key != agentKeyAt("aside", c.at.gw()) { return "foreign", "Aside's magpie provider belongs to another configuration; it will not be overwritten" } if !sameGateway(p.URL, c.at.v1()) { @@ -326,7 +326,7 @@ func (c *asideConnection) provider() (string, string) { func (c *asideConnection) block() any { p := magpieProviderJSONAt("pi", "aside", c.at.gw()).(map[string]any) - p["apiKey"] = gateway.TokenFor("aside") + p["apiKey"] = agentKeyAt("aside", c.at.gw()) return p } diff --git a/internal/agent/cindy.go b/internal/agent/cindy.go index 7bfc80e75..400406616 100644 --- a/internal/agent/cindy.go +++ b/internal/agent/cindy.go @@ -47,7 +47,7 @@ func CindyLink(url string) string { Endpoints []cindyEndpoint `json:"endpoints"` }{ Kind: "custom", Name: "Magpie", ID: magpieID, - Auth: map[string]any{"method": "apiKey", "apiKey": gateway.TokenFor("cindy")}, + Auth: map[string]any{"method": "apiKey", "apiKey": agentKeyAt("cindy", url)}, Endpoints: []cindyEndpoint{ {"anthropic-messages", url, []string{"claude-code"}, models}, {"openai-responses", v1, []string{"codex"}, models}, diff --git a/internal/agent/claudedesktop.go b/internal/agent/claudedesktop.go index 54b0e5dbe..8f9947c67 100644 --- a/internal/agent/claudedesktop.go +++ b/internal/agent/claudedesktop.go @@ -205,7 +205,7 @@ func desktopCheck(p desktopPaths) string { return "Claude Desktop uses another gateway configuration now (appliedId in configLibrary/_meta.json), not magpie's" } return wiringOff("Claude Desktop", p.prof, func(k string) (string, bool) { return edit.GetJSON(p.prof, k) }, - "inferenceGatewayBaseUrl", gateway.URL(), "inferenceGatewayApiKey", gateway.TokenFor("claude-desktop")) + "inferenceGatewayBaseUrl", gateway.URL(), "inferenceGatewayApiKey", agentKey("claude-desktop")) } // desktopTierFields pick the model each of Claude Code's tiers runs on in @@ -377,7 +377,7 @@ func desktopOn(p desktopPaths) error { kvs := []edit.KV{ {Path: "inferenceProvider", Value: "gateway"}, {Path: "inferenceGatewayBaseUrl", Value: gateway.URL()}, - {Path: "inferenceGatewayApiKey", Value: gateway.TokenFor("claude-desktop")}, + {Path: "inferenceGatewayApiKey", Value: agentKey("claude-desktop")}, {Path: "inferenceGatewayAuthScheme", Value: "bearer"}, } // policies seeded once: the user may tighten them in Desktop diff --git a/internal/agent/copilotjetbrains.go b/internal/agent/copilotjetbrains.go index 40d722c6e..9e04d1c86 100644 --- a/internal/agent/copilotjetbrains.go +++ b/internal/agent/copilotjetbrains.go @@ -50,7 +50,6 @@ import ( "github.com/tidwall/gjson" "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/edit" - "github.com/yetone/magpie/internal/gateway" ) // copilotJBID is the agent's id, and what its token names. @@ -154,7 +153,7 @@ func copilotJetBrainsAt(path string, installed func() bool) *Agent { return url, url != "" } return edit.GetJSON(path, k) - }, "deploymentUrl", vscodeURL(), copilotJBKey, gateway.TokenFor(copilotJBID)) + }, "deploymentUrl", vscodeURL(), copilotJBKey, agentKey(copilotJBID)) }, // its picker lists the models picked for it (#1508) ListsModels: true, @@ -202,7 +201,7 @@ func copilotJBWrite(path string) error { models := copilotJBModelsJSON(hidden) kvs := []edit.KV{ {Path: copilotJBConfig, Value: map[string]string{"groupName": magpieID, "apiType": "chatCompletions"}}, - {Path: copilotJBKey, Value: gateway.TokenFor(copilotJBID)}, + {Path: copilotJBKey, Value: agentKey(copilotJBID)}, {Path: copilotJBModels, Value: models}, } // written only where it differs, so a sync with nothing new leaves the diff --git a/internal/agent/cursorlocal.go b/internal/agent/cursorlocal.go index b375e52a7..5bf121252 100644 --- a/internal/agent/cursorlocal.go +++ b/internal/agent/cursorlocal.go @@ -210,7 +210,7 @@ func plistExecutable(path string) string { // the app has the variables; opened from the Dock or Finder it has only // the login shell's. func CursorLocalLaunch(app, gw string) string { - key, base := gateway.TokenFor(CursorLocalID), gw+"/v1" + key, base := agentKeyAt(CursorLocalID, gw), gw+"/v1" if runtime.GOOS == "windows" { return `$env:CURSOR_LOCAL_AGENT_BASE_URL="` + base + `"; $env:CURSOR_LOCAL_AGENT_API_KEY="` + key + `"; & '` + strings.ReplaceAll(app, "'", "''") + `'` } @@ -222,7 +222,7 @@ var cursorLocalVars = []string{"CURSOR_LOCAL_AGENT_BASE_URL", "CURSOR_LOCAL_AGEN // cursorLocalEnv is what they are set to for the gateway at gw. func cursorLocalEnv(gw string) map[string]string { - return map[string]string{cursorLocalVars[0]: gw + "/v1", cursorLocalVars[1]: gateway.TokenFor(CursorLocalID)} + return map[string]string{cursorLocalVars[0]: gw + "/v1", cursorLocalVars[1]: agentKeyAt(CursorLocalID, gw)} } // cursorLocalMark is magpie's own note that the variables are set for the @@ -317,7 +317,7 @@ func cursorLocal() *Agent { }, }}, Notice: func() string { - return noticeCursorLocal.say("agent", cursorLocalName, "url", gateway.URL()+"/v1", "key", gateway.TokenFor(CursorLocalID)) + return noticeCursorLocal.say("agent", cursorLocalName, "url", gateway.URL()+"/v1", "key", agentKey(CursorLocalID)) }, } } diff --git a/internal/agent/gatewaykey.go b/internal/agent/gatewaykey.go index b03542dc9..d360a176d 100644 --- a/internal/agent/gatewaykey.go +++ b/internal/agent/gatewaykey.go @@ -36,6 +36,15 @@ func agentKeyAt(agent, gw string) string { return gateway.TokenFor(agent) } +// hereKey is keyAt for the gateway's own address, gateway.URL(): an agent +// on this machine given that address sends the gateway's own token, unless +// MAGPIE_ADDR pins it to an address beyond loopback, which the gateway +// takes only a named key from (#1647, ggbdpq). +func hereKey() string { return keyAt(gateway.URL()) } + +// agentKey is agentKeyAt for the gateway's own address, as hereKey. +func agentKey(agent string) string { return agentKeyAt(agent, gateway.URL()) } + // ourKey says k is a key magpie gives an agent: gateway.Token, or the LAN // sharing key one that reaches the gateway from elsewhere is given. func ourKey(k string) bool { diff --git a/internal/agent/gatewaykey_test.go b/internal/agent/gatewaykey_test.go index cfe2f2958..540120b15 100644 --- a/internal/agent/gatewaykey_test.go +++ b/internal/agent/gatewaykey_test.go @@ -1,11 +1,15 @@ package agent import ( + "encoding/base64" + "encoding/json" "path/filepath" + "regexp" "strings" "testing" "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/gateway" ) @@ -76,3 +80,171 @@ func TestGatewayKeyBeyondLoopback(t *testing.T) { } want(wsl, gateway.Token) } + +// T3 Code's magpie instance is Claude Code routed with the gateway's +// address and the token Claude Code is sent with: beyond loopback that is +// the LAN sharing key, as at.gwKey() routes Claude Code itself. +// gateway.Token is turned away there, so T3's every call was answered 401 +// (#1647, ggbdpq). +func TestT3CodeKeyBeyondLoopback(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + path := filepath.Join(home, ".t3", "userdata", "settings.json") + wsl := "http://172.23.80.1:3425" + + env := func(gw string) map[string]string { + t.Helper() + b, err := json.Marshal(t3InstanceJSON(path, gw)) + if err != nil { + t.Fatal(err) + } + e := t3Format(t, b) + out := map[string]string{} + for _, v := range e.Environment { + out[v.Name] = v.Value + } + return out + } + + if err := access.ConfigureLAN(true, false); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { access.ConfigureLAN(false, false) }) + lan := access.LANSecret() + if !strings.HasPrefix(lan, access.Prefix) { + t.Fatalf("LAN key %q", lan) + } + if e := env(wsl); e["ANTHROPIC_AUTH_TOKEN"] != lan { + t.Errorf("T3 Code at %s: token %q, want the LAN sharing key", wsl, e["ANTHROPIC_AUTH_TOKEN"]) + } + if e := env("http://127.0.0.1:3425"); e["ANTHROPIC_AUTH_TOKEN"] != gateway.Token { + t.Errorf("T3 Code on loopback: token %q, want %q", e["ANTHROPIC_AUTH_TOKEN"], gateway.Token) + } + if err := access.ConfigureLAN(false, false); err != nil { + t.Fatal(err) + } + if e := env(wsl); e["ANTHROPIC_AUTH_TOKEN"] != gateway.Token { + t.Errorf("T3 Code at %s with nothing shared: token %q, want %q", wsl, e["ANTHROPIC_AUTH_TOKEN"], gateway.Token) + } +} + +// Air's and OpenChamber's OpenCode provider block carries the key for the +// gateway's address, and each row's Check compares against it: beyond +// loopback, the LAN sharing key. Against gateway.Token there, the rows said +// "magpie's gateway won't take its requests" of the config Sync had just +// written and the gateway does take (#1647, ggbdpq). +func TestAirAndOpenChamberChecksTakeTheKeyForTheGateway(t *testing.T) { + home, _ := codexHome(t, "", "") + t.Setenv("MAGPIE_ADDR", "172.23.80.1:3425") + if err := access.ConfigureLAN(true, false); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { access.ConfigureLAN(false, false) }) + lan := access.LANSecret() + if !strings.HasPrefix(lan, access.Prefix) { + t.Fatalf("LAN key %q", lan) + } + if gateway.URL() != "http://172.23.80.1:3425" { + t.Fatalf("gateway URL %q", gateway.URL()) + } + + airDir := airDir(home, filepath.Join(home, ".config")) + was := airOpenCode + airOpenCode = func(string) string { return "/opt/bin/opencode" } + t.Cleanup(func() { airOpenCode = was }) + a := air(home, filepath.Join(home, ".config")) + if err := a.Apply("model", "magpie/fake/m1"); err != nil { + t.Fatal(err) + } + cfg := filepath.Join(airDir, "magpie-opencode.json") + if v, _ := edit.GetJSON(cfg, "provider.magpie.options.apiKey"); v != lan { + t.Fatalf("Air's config has key %q, want the LAN sharing key", v) + } + if d := a.Check(); d != "" { + t.Errorf("Air's check: %s", d) + } + + t.Setenv("OPENCODE_CONFIG_DIR", filepath.Join(home, "oc")) + dir := filepath.Join(home, ".config", "openchamber") + writeFile(t, filepath.Join(dir, "preferences.json"), `{"version":1,"fields":{"defaultModel":{"value":"anthropic/claude-sonnet-5","updatedAt":7}}}`) + writeFile(t, filepath.Join(dir, "settings.json"), `{"defaultModel":"anthropic/claude-sonnet-5"}`) + ch := openChamber(home, filepath.Join(home, ".config")) + if err := ch.Apply("model", "magpie/fake/m1"); err != nil { + t.Fatal(err) + } + ocCfg := filepath.Join(home, "oc", "opencode.json") + if v, _ := edit.GetJSON(ocCfg, "provider.magpie.options.apiKey"); v != lan { + t.Fatalf("OpenChamber's OpenCode config has key %q, want the LAN sharing key", v) + } + if d := ch.Check(); d != "" { + t.Errorf("OpenChamber's check: %s", d) + } +} + +// Every agent given the gateway's own address, gateway.URL(), with the key +// that names it (gateway.TokenFor) or gateway.Token, is given the LAN +// sharing key instead while MAGPIE_ADDR pins that address beyond loopback +// and sharing is on: the gateway takes neither from there (#1647's class). +func TestPinnedGatewayKeyForEveryWriter(t *testing.T) { + home, _ := codexHome(t, "", "") + t.Setenv("MAGPIE_ADDR", "172.23.80.1:3425") + gw := gateway.URL() + if gw != "http://172.23.80.1:3425" { + t.Fatalf("gateway URL %q", gw) + } + keys := func() map[string]string { + var cindy struct { + Auth struct { + APIKey string `json:"apiKey"` + } `json:"auth"` + } + data := CindyLink(gw)[strings.Index(CindyLink(gw), "data=")+len("data="):] + b, err := base64.RawURLEncoding.DecodeString(data) + if err != nil || json.Unmarshal(b, &cindy) != nil { + t.Fatalf("Cindy's link: %v %s", err, b) + } + jb := filepath.Join(home, "jb", "copilot.json") + if err := copilotJBWrite(jb); err != nil { + t.Fatal(err) + } + jbKey, _ := edit.GetJSON(jb, copilotJBKey) + _, zc := zcodeAddress(gw, gateway.Token) + agy := "" + if m := regexp.MustCompile(`GEMINI_API_KEY="?([^" ;]+)`).FindStringSubmatch(AgyLaunch("m")); m != nil { + agy = m[1] + } + return map[string]string{ + "agy": agy, + "alma": almaKey(), + "cindy": cindy.Auth.APIKey, + "copilotjb": jbKey, + "cursor": cursorLocalEnv(gw)[cursorLocalVars[1]], + "hanako": hanakoProvider().APIKey, + "pencil": pencilProviderJSON(gw)["apiKey"].(string), + "vscode": vscodeStable.token(), + "vscodium": vscodiumKind.token(), + "workbuddy": buddyModel("codebuddy", "m", "m", 0, 0, false, nil)["apiKey"].(string), + "zcode": zc, + } + } + plain := keys() + if err := access.ConfigureLAN(true, false); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { access.ConfigureLAN(false, false) }) + lan := access.LANSecret() + if !strings.HasPrefix(lan, access.Prefix) { + t.Fatalf("LAN key %q", lan) + } + for agent, k := range keys() { + if k != lan { + t.Errorf("%s at %s: key %q, want the LAN sharing key", agent, gw, k) + } + if plain[agent] == lan || !strings.HasPrefix(plain[agent], gateway.Token) { + t.Errorf("%s with nothing shared: key %q, want magpie's own", agent, plain[agent]) + } + } +} diff --git a/internal/agent/hanako.go b/internal/agent/hanako.go index 31d83a416..bafe5cd50 100644 --- a/internal/agent/hanako.go +++ b/internal/agent/hanako.go @@ -49,7 +49,6 @@ import ( "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/edit" - "github.com/yetone/magpie/internal/gateway" ) // hanakoProbe gives up quickly, as OpenHanako's own liveness probe does: @@ -116,7 +115,7 @@ func hanako(home string) *Agent { return "" } cur, _ := hanakoCurrent(dir) - file, kvs := path, []string{"base_url", gatewayV1(), "api_key", gateway.TokenFor("hanako")} + file, kvs := path, []string{"base_url", gatewayV1(), "api_key", agentKey("hanako")} if hanakoSealed(path) { // its key is sealed: unknown, not gone; the address is in the plugin file, kvs = filepath.Join(hanakoPlugin(dir), "providers", magpieID+".json"), kvs[:2] } @@ -228,7 +227,7 @@ func hanakoProvider() hanakoProviderEntry { Image: m.Images, Reasoning: len(m.Efforts) > 0, XHigh: slices.Contains(m.Efforts, "xhigh")}) } return hanakoProviderEntry{DisplayName: magpieID, BaseURL: gatewayV1(), API: "openai-completions", - APIKey: gateway.TokenFor("hanako"), Models: ms} + APIKey: agentKey("hanako"), Models: ms} } func hanakoPlugin(dir string) string { return filepath.Join(dir, "provider-plugins", magpieID) } diff --git a/internal/agent/legacy.go b/internal/agent/legacy.go index 6a428ea86..c93e5c92e 100644 --- a/internal/agent/legacy.go +++ b/internal/agent/legacy.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/yetone/magpie/internal/edit" - "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/provider" ) @@ -56,7 +55,7 @@ func RenameLegacy() { os.Remove(filepath.Join(a.Dir, legacyID+"-models.json")) case "claude": if t, _ := edit.GetJSON(a.Path, "env.ANTHROPIC_AUTH_TOKEN"); t == legacyID { - _ = edit.SetJSON(a.Path, edit.KV{Path: "env.ANTHROPIC_AUTH_TOKEN", Value: gateway.Token}) + _ = edit.SetJSON(a.Path, edit.KV{Path: "env.ANTHROPIC_AUTH_TOKEN", Value: hereKey()}) } } } diff --git a/internal/agent/openchamber.go b/internal/agent/openchamber.go index 06b5c9485..86a2c3444 100644 --- a/internal/agent/openchamber.go +++ b/internal/agent/openchamber.go @@ -31,7 +31,6 @@ import ( "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/edit" - "github.com/yetone/magpie/internal/gateway" ) // openChamberDir is where OpenChamber keeps its settings. @@ -205,7 +204,7 @@ func openChamber(home, cfg string) *Agent { return "" } return wiringOff("OpenChamber", ocPath, func(k string) (string, bool) { return edit.GetJSON(ocPath, "provider."+magpieID+".options."+k) }, - "baseURL", gatewayV1(), "apiKey", gateway.Token) + "baseURL", gatewayV1(), "apiKey", hereKey()) }, Sync: func() error { if _, ok := edit.GetJSON(ocPath, "provider."+magpieID); !ok && usesMagpie(s.model(), s.small()) { diff --git a/internal/agent/pencil.go b/internal/agent/pencil.go index e743232c7..0b44d527b 100644 --- a/internal/agent/pencil.go +++ b/internal/agent/pencil.go @@ -114,7 +114,7 @@ func pencilProviderJSON(gw string) map[string]any { ms = append(ms, e) } return map[string]any{"name": "magpie", "baseUrl": gw + "/v1", "api": "openai-completions", - "apiKey": gateway.TokenFor("pencil"), "models": ms} + "apiKey": agentKeyAt("pencil", gw), "models": ms} } // what pencil says after a change (notice.go) diff --git a/internal/agent/t3code.go b/internal/agent/t3code.go index fa01beb62..0b0b3e69a 100644 --- a/internal/agent/t3code.go +++ b/internal/agent/t3code.go @@ -138,7 +138,7 @@ func t3InstanceJSON(path, gw string) map[string]any { "driver": "claudeAgent", "displayName": "magpie", "enabled": true, "environment": []map[string]any{ {"name": "ANTHROPIC_BASE_URL", "value": gw, "sensitive": false}, - {"name": "ANTHROPIC_AUTH_TOKEN", "value": gateway.Token, "sensitive": false}, + {"name": "ANTHROPIC_AUTH_TOKEN", "value": keyAt(gw), "sensitive": false}, }, "config": config, } diff --git a/internal/agent/vscode.go b/internal/agent/vscode.go index 1cef63633..30082d84c 100644 --- a/internal/agent/vscode.go +++ b/internal/agent/vscode.go @@ -40,7 +40,6 @@ import ( "github.com/tidwall/gjson" "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/edit" - "github.com/yetone/magpie/internal/gateway" ) // vscodeDefault is chat.defaultModel, a key with a dot in it, escaped for @@ -109,9 +108,9 @@ var ( // as it always was. func (k vscodeKind) token() string { if k.ua != nil { - return gateway.Token + return hereKey() } - return gateway.TokenFor(k.id) + return agentKey(k.id) } // VS Code keeps its User folder under Application Support on macOS, Roaming diff --git a/internal/agent/workbuddy.go b/internal/agent/workbuddy.go index ac7e3128e..871b8c9c2 100644 --- a/internal/agent/workbuddy.go +++ b/internal/agent/workbuddy.go @@ -166,7 +166,7 @@ func buddyWriteAt(path, agent string, on bool, where place) error { } // the keys magpie's models are asked with: the gateway's, or that of a // magpie on another machine the user pointed them at - keys := map[string]bool{gateway.TokenFor(agent): true} + keys := map[string]bool{gateway.TokenFor(agent): true, agentKey(agent): true} if away { keys[agentKeyAt(agent, where.gw())] = true } @@ -288,7 +288,7 @@ func buddyModel(agent, id, name string, context, output int, images bool, effort } e := map[string]any{ "id": id, "name": name, "vendor": magpieID, - "apiKey": gateway.TokenFor(agent), "url": gatewayV1() + "/chat/completions", + "apiKey": agentKey(agent), "url": gatewayV1() + "/chat/completions", "maxInputTokens": context, "supportsToolCall": true, "supportsImages": images, "supportsReasoning": false, } diff --git a/internal/agent/zcode.go b/internal/agent/zcode.go index 6e24eb704..5778d8eed 100644 --- a/internal/agent/zcode.go +++ b/internal/agent/zcode.go @@ -141,7 +141,7 @@ func zcodeProviderJSON(path string, keep bool) any { if v, ok := edit.GetJSON(path, "provider."+magpieID+".enabled"); ok && v == "false" { on = false } - base, token := gateway.URL(), gateway.Token + base, token := gateway.URL(), hereKey() if keep { base, token = zcodeKept(filepath.Dir(path)) } @@ -178,8 +178,8 @@ func zcodeVariants(path string) map[string]string { // keeps with its key. An address on this machine's loopback is magpie's own // and follows the gateway. func zcodeAddress(was, wasKey string) (string, string) { - if !onAnotherMachine(was) { - return gateway.URL(), gateway.Token + if !onAnotherMachine(was) || sameGateway(was, gateway.URL()) { + return gateway.URL(), hereKey() } if wasKey == "" { wasKey = gateway.Token @@ -445,7 +445,7 @@ func zcodeRules(path string, on, keep bool) error { if ids == nil { ids = []string{} } - base, token := gateway.URL(), gateway.Token + base, token := gateway.URL(), hereKey() if keep { base, token = zcodeKept(filepath.Dir(path)) } diff --git a/internal/agent/zed_credential_other.go b/internal/agent/zed_credential_other.go index 394dbd69e..2f5687582 100644 --- a/internal/agent/zed_credential_other.go +++ b/internal/agent/zed_credential_other.go @@ -14,7 +14,6 @@ import ( "github.com/godbus/dbus/v5" - "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/proc" ) @@ -32,7 +31,7 @@ func saveZedCredential(url string) error { } // GPUI uses an Internet Password whose server is the full API URL. // Keep security trusted as well so it can update the key on later picks. - args = []string{"add-internet-password", "-U", "-T", app, "-T", "/usr/bin/security", "-s", url, "-a", "Bearer", "-w", gateway.TokenFor("zed")} + args = []string{"add-internet-password", "-U", "-T", app, "-T", "/usr/bin/security", "-s", url, "-a", "Bearer", "-w", agentKeyAt("zed", url)} case "linux", "freebsd": return saveZedSecret(ctx, url) default: @@ -149,7 +148,7 @@ func saveZedSecret(ctx context.Context, url string) error { "url": url, "username": "Bearer", }), } - secret := zedSecret{Session: session, Parameters: []byte{}, Value: []byte(gateway.TokenFor("zed")), ContentType: "text/plain; charset=utf8"} + secret := zedSecret{Session: session, Parameters: []byte{}, Value: []byte(agentKey("zed")), ContentType: "text/plain; charset=utf8"} var item dbus.ObjectPath if err := conn.Object("org.freedesktop.secrets", collection).CallWithContext(ctx, "org.freedesktop.Secret.Collection.CreateItem", 0, properties, secret, true).Store(&item, &prompt); err != nil { return err diff --git a/internal/agent/zed_credential_windows.go b/internal/agent/zed_credential_windows.go index eca378367..40a6ebf72 100644 --- a/internal/agent/zed_credential_windows.go +++ b/internal/agent/zed_credential_windows.go @@ -6,8 +6,6 @@ import ( "unsafe" "golang.org/x/sys/windows" - - "github.com/yetone/magpie/internal/gateway" ) // zedWindowsCredential matches CREDENTIALW. Zed's blob is UTF-8, not UTF-16. @@ -32,7 +30,7 @@ func saveZedCredential(url string) error { return err } user, _ := windows.UTF16PtrFromString("Bearer") - key := []byte(gateway.TokenFor("zed")) + key := []byte(agentKey("zed")) credential := zedWindowsCredential{ Type: 1, TargetName: target, UserName: user, // CRED_TYPE_GENERIC CredentialBlobSize: uint32(len(key)), CredentialBlob: &key[0],