diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index cbe773fcf..44761d4ab 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -295,6 +295,18 @@ call magpie had routed was counted again as a local session's whatever provider id ZCode wrote beside it (nori_tsukiji on X). Verification: `TestZCodeCallsPairWithTheGatewaysRecords`. +Pairing needs the tokens and end time to agree, so a routed call they don't +(a try the gateway and ZCode count differently) was still listed twice. A +call whose provider is the gateway is left out of ZCode's calls before any +pairing: the id magpie writes (`magpie`), and any provider the user added by +hand whose base URL in `config.json` or `provider_config.json` is this +machine (loopback, `localhost`, one of its addresses) at the gateway's port +(`zcodeGateway`, `gatewayBase`; jiangshangmuyun on X: "new-provider" at +`127.0.0.1:3425`, one call listed as "new-provider · Local session" among +the gateway's rows). It reads the configuration as it is now, as +`workbuddyGateway` does. Verification: `TestZCodeHandAddedGatewayProvider`, +`TestGatewayBase`. + The Claude subscription bridge's own Claude Code runs save their sessions in a Claude folder the readers list (the user's own, or a saved account's under `claude-accounts`), often in the caller's project. They aren't the diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 0306398de..31c00b310 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -68,6 +68,8 @@ const callCacheVersion = "calls-v15" // (gemini-4-argon-d) is its model's (GeminiDeployment). // zcode 3: a call names its session as a request does, without the sess_ // prefix (zcodeBareID), so the gateway's record of it pairs with it. +// zcode 4: a call to a provider the user added at the gateway's address +// is the gateway's, and left out (zcodeGateway). // agy 1: a call names the model its conversation's database names for its // step (agyStepModels). // pi 1, raft 1, cindy 2: a pi-subagents subagent's calls are its own @@ -75,7 +77,7 @@ const callCacheVersion = "calls-v15" // lead's (piSubagentsRead). // agy 2, antigravity 2: a call carries its time to the first token and // how long it took, from its step's row (stepTimesOf). -var callParseVersions = map[string]int{"agy": 2, "antigravity": 2, "cindy": 2, "codex": 3, "pi": 1, "raft": 1, "zcode": 3} +var callParseVersions = map[string]int{"agy": 2, "antigravity": 2, "cindy": 2, "codex": 3, "pi": 1, "raft": 1, "zcode": 4} // CallCacheVersion is callCacheVersion and callParseVersions, for a cache // of what is made of the calls (usage's requests-v1.bin and heatmap): a diff --git a/internal/sessions/calls_zcode.go b/internal/sessions/calls_zcode.go index bc57d0564..c77f31521 100644 --- a/internal/sessions/calls_zcode.go +++ b/internal/sessions/calls_zcode.go @@ -24,6 +24,8 @@ import ( // (ocGatewayProvider): ZCode records the provider it was told to use, and // the route magpie writes says "magpie", so unlike dsh's this one is a // provider id magpie itself chose and can be trusted to mean the gateway. +// A provider the user added by hand at the gateway's address is the gateway +// too, by its address (zcodeGateway, calls_zcode_gateway.go). // zcCallList is the last listing of ZCode's database, kept while the // database and its WAL are as they were. Its lock is the one ocCallList @@ -108,7 +110,7 @@ func readZCodeCalls(f file) (*callFile, bool) { } for i, b := range msgs { var m ocMessage - if json.Unmarshal(b, &m) != nil || m.Role != "assistant" || ocGatewayProvider(m.ProviderID) || copies[i] { + if json.Unmarshal(b, &m) != nil || m.Role != "assistant" || zcodeGateway(m.ProviderID) || copies[i] { continue } if c, ok := ocCall(st, m, info.Directory); ok { diff --git a/internal/sessions/calls_zcode_gateway.go b/internal/sessions/calls_zcode_gateway.go new file mode 100644 index 000000000..361efa330 --- /dev/null +++ b/internal/sessions/calls_zcode_gateway.go @@ -0,0 +1,136 @@ +package sessions + +import ( + "encoding/json" + "net" + "net/url" + "os" + "path/filepath" + "sync" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/settings" +) + +// A provider the user added in ZCode by hand, pointed at this magpie's +// gateway, has an id of ZCode's own ("new-provider", whatever its settings +// gave it), not the "magpie" magpie writes. ZCode records that id beside each +// reply, so ocGatewayProvider did not know the call for the gateway's, and a +// call the gateway also logged was listed a second time as a local session's +// whenever the two records did not pair by tokens and time +// (jiangshangmuyun on X: one Trae CN DeepSeek call under "new-provider · +// 本地会话" among the gateway's own rows for the same window). +// +// So the provider's address decides, read from both of ZCode's provider +// files (internal/agent's zcode.go says which ZCode reads which): a +// provider whose base URL is this machine's, on the gateway's port, is the +// gateway. Like workbuddyGateway, this reads the user's configuration as it +// is now, not a record of the call: a session read again after its provider +// was pointed elsewhere has its earlier calls read as its own. + +var zcGateway struct { + sync.Mutex + stamp string + ids map[string]bool +} + +// zcodeGateway is whether ZCode's provider id is magpie's gateway: the id +// magpie writes, or one whose base URL is this gateway's. +func zcodeGateway(id string) bool { + return ocGatewayProvider(id) || id != "" && zcodeGatewayIDs()[id] +} + +// zcodeGatewayIDs are the ids of ZCode's providers whose base URL is this +// gateway's, in either of its provider files; an empty set when neither +// names one (or can be read). +func zcodeGatewayIDs() map[string]bool { + home, _ := os.UserHomeDir() + dir := filepath.Join(appdir.ZCodeDataIn(home), ".zcode", "v2") + config, rules := filepath.Join(dir, "config.json"), filepath.Join(dir, "provider_config.json") + stamp := ocStamp(config) + ocStamp(rules) + settings.GatewayAddr() + "|" + settings.SavedAddr() + zcGateway.Lock() + defer zcGateway.Unlock() + if zcGateway.ids != nil && stamp == zcGateway.stamp { + return zcGateway.ids + } + ids := map[string]bool{} + var c struct { + Provider map[string]struct { + Options struct { + BaseURL string `json:"baseURL"` + } `json:"options"` + } `json:"provider"` + } + if b, err := os.ReadFile(config); err == nil && json.Unmarshal(b, &c) == nil { + for id, p := range c.Provider { + if gatewayBase(p.Options.BaseURL) { + ids[id] = true + } + } + } + var r struct { + Config struct { + ProviderConfigRules struct { + ProviderRules []struct { + ProviderID string `json:"providerId"` + Config struct { + API struct { + BaseURL string `json:"baseUrl"` + } `json:"api"` + } `json:"config"` + } `json:"providerRules"` + } `json:"providerConfigRules"` + } `json:"config"` + } + if b, err := os.ReadFile(rules); err == nil && json.Unmarshal(b, &r) == nil { + for _, p := range r.Config.ProviderConfigRules.ProviderRules { + if p.ProviderID != "" && gatewayBase(p.Config.API.BaseURL) { + ids[p.ProviderID] = true + } + } + } + zcGateway.stamp, zcGateway.ids = stamp, ids + return ids +} + +// gatewayBase is whether an agent's base URL is this magpie's gateway: http +// or https to this machine (loopback, localhost, or one of its own +// addresses, as a LAN-shared gateway is reached) on the gateway's port, the +// one it listens on (MAGPIE_ADDR) or the one its settings save. +func gatewayBase(base string) bool { + u, err := url.Parse(base) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" { + return false + } + port := u.Port() + if port == "" { + return false // magpie's gateway is never on 80 or 443 + } + ours := false + for _, a := range []string{settings.GatewayAddr(), settings.SavedAddr()} { + if _, p, err := net.SplitHostPort(a); err == nil && p == port { + ours = true + } + } + if !ours { + return false + } + h := u.Hostname() + if h == "localhost" { + return true + } + ip := net.ParseIP(h) + if ip == nil { + return false + } + if ip.IsLoopback() || ip.IsUnspecified() { + return true + } + addrs, _ := net.InterfaceAddrs() + for _, a := range addrs { + if n, ok := a.(*net.IPNet); ok && n.IP.Equal(ip) { + return true + } + } + return false +} diff --git a/internal/sessions/calls_zcode_test.go b/internal/sessions/calls_zcode_test.go index ed154d567..ad2bcc04c 100644 --- a/internal/sessions/calls_zcode_test.go +++ b/internal/sessions/calls_zcode_test.go @@ -1,6 +1,10 @@ package sessions import ( + "database/sql" + "os" + "path/filepath" + "strconv" "testing" "time" ) @@ -42,3 +46,64 @@ func TestZCodeCalls(t *testing.T) { t.Fatalf("ses_zcC's reply: %+v", c) } } + +// jiangshangmuyun on X: a provider the user added in ZCode by hand +// ("new-provider"), pointed at this magpie's gateway, is the gateway's as +// "magpie" is. Its calls were listed again as a local session's beside the +// gateway's rows for the same calls. A provider elsewhere, or on this +// machine at another port, keeps its calls. +func TestZCodeHandAddedGatewayProvider(t *testing.T) { + home := setupAgents(t) + t.Setenv("MAGPIE_ADDR", "127.0.0.1:3499") + dir := filepath.Join(home, ".zcode", "v2") + os.MkdirAll(dir, 0o755) + // ZCode 3.14 and later: provider_config.json's rules + os.WriteFile(filepath.Join(dir, "provider_config.json"), []byte(`{"schemaVersion":1,"config":{"providerConfigRules":{"providerRules":[ + {"providerId":"new-provider","providerName":"new-provider","enabled":true,"config":{"api":{"type":"anthropic-messages","baseUrl":"http://127.0.0.1:3499"}}}, + {"providerId":"zai","providerName":"Z.ai","enabled":true,"config":{"api":{"type":"anthropic-messages","baseUrl":"https://open.bigmodel.cn/api/anthropic"}}}, + {"providerId":"ollama","providerName":"Ollama","enabled":true,"config":{"api":{"type":"openai-chat-completions","baseUrl":"http://127.0.0.1:11434/v1"}}}]}}}`), 0o600) + // an older ZCode's config.json + os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"provider":{"mine":{"name":"mine","kind":"openai-compatible","options":{"baseURL":"http://localhost:3499/v1"}}}}`), 0o600) + db, err := sql.Open("sqlite", filepath.Join(home, ".zcode", "cli", "db", "db.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + for i, p := range []string{"new-provider", "mine", "zai", "ollama"} { + at := int64(1790496200000 + i*10000) + ocInsert(t, db, "ses_zcC", "msg_h"+p, at, at+5000, `{"id":"msg_h`+p+`","role":"assistant","modelId":"trae-cn/deepseek-v4.1-flash","providerID":"`+p+`","tokens":{"input":20,"output":2,"reasoning":0,"cache":{"read":0,"write":0}},"time":{"created":`+strconv.FormatInt(at, 10)+`,"completed":`+strconv.FormatInt(at+5000, 10)+`}}`) + } + Reset() + cs := zcodeCalls(t) + for _, gone := range []string{"msg_hnew-provider", "msg_hmine"} { + if c, ok := cs[gone]; ok { + t.Fatalf("a call to a provider at the gateway's address was read as a local session's: %+v", c) + } + } + for _, kept := range []string{"msg_hzai", "msg_hollama"} { + if _, ok := cs[kept]; !ok { + t.Fatalf("%s, to a provider elsewhere, was left out: %+v", kept, cs) + } + } +} + +func TestGatewayBase(t *testing.T) { + t.Setenv("MAGPIE_ADDR", "127.0.0.1:3499") + for base, want := range map[string]bool{ + "http://127.0.0.1:3499": true, + "http://localhost:3499/v1": true, + "https://127.0.0.1:3499/": true, + "http://[::1]:3499": true, + "http://0.0.0.0:3499": true, + "http://127.0.0.1:11434/v1": false, + "https://open.bigmodel.cn": false, + "http://example.com:3499": false, + "ws://127.0.0.1:3499": false, + "": false, + "127.0.0.1:3499": false, + } { + if got := gatewayBase(base); got != want { + t.Errorf("gatewayBase(%q) = %v, want %v", base, got, want) + } + } +}