diff --git a/README.md b/README.md index 7777a698f..4aff9f568 100644 --- a/README.md +++ b/README.md @@ -36,18 +36,22 @@ and there is a terminal version (`magpie tui`) and a plain CLI. OpenCode and the rest all point at `http://127.0.0.1:3425/v1` and pick from one catalog; the translation between APIs happens in magpie, streaming and tool calls included. -- **Your subscriptions, shared.** Sign in to Codex (ChatGPT) or Copilot - and that login shows up as a provider: every other agent can use its - models through the gateway, with nothing copied and no key to paste. +- **Your subscriptions, shared.** Sign in to Claude Code, Codex (ChatGPT) + or Copilot and that login shows up as a provider: every other agent can + use its models through the gateway, with nothing copied and no key to + paste. - **Providers with one field.** Pick a preset (Anthropic, OpenAI, Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, Mistral, Groq, xAI, OpenRouter, Together, Fireworks, SiliconFlow, AiHubMix, 302.AI, Ollama, LM Studio…), paste a key, done. Custom vendors need a name and a base URL. magpie never reads keys from your shell environment. -- **Real model lists.** With a key in hand magpie asks the vendor which models - it serves and offers exactly those; the [models.dev](https://models.dev) - catalog fills in names, reasoning efforts and the list for vendors that - have none. Choose which models each provider exposes, or expose them all. +- **Real model lists, nothing compiled in.** With a key in hand magpie asks + the vendor which models it serves and offers exactly those; the + [models.dev](https://models.dev) catalog fills in names, reasoning efforts + and the list for vendors that have none, and refreshes itself in the + background once it goes stale. Choose which models each provider exposes, + or expose them all — a model released this morning is in the picker on + the next refresh. - **Profiles.** Snapshot every agent's settings under a name and switch all of them back in one move. - **Real logos, no framework.** Plain HTML over the system webview; brand @@ -100,21 +104,29 @@ be overridden the same way. ### Signed-in agents as providers An agent you have signed in to is a subscription with models behind it, so -magpie offers it as a provider too. Codex (a ChatGPT login in +magpie offers it as a provider too. Claude Code (an OAuth login in the macOS +Keychain or `~/.claude/.credentials.json`), Codex (a ChatGPT login in `~/.codex/auth.json`) and Copilot (a GitHub login in `~/.config/github-copilot/apps.json`) appear in `magpie providers` and in the -Providers tab as *signed in as …*, with their models spelled `codex/gpt-5.5` -or `copilot/claude-sonnet-4.5` in every other agent's picker. magpie reads the -agent's own credential file each time, refreshes tokens the way the agent -does, and stores nothing but your model picks; sign out of the agent and -the provider is gone. The ChatGPT backend only streams and rejects a few -parameters, so magpie translates non-streaming requests and drops what it -would refuse. - -Claude Code is signed in too, but is deliberately not offered: Anthropic's -terms keep a Claude subscription for Claude Code itself. magpie says so under -the provider list rather than leaving you to wonder; use an Anthropic API -key as a provider instead. A Gemini CLI Google login is planned. +Providers tab as *signed in as …*, with their models spelled +`claude/claude-sonnet-5`, `codex/gpt-5.5` or `copilot/claude-sonnet-4.5` in +every other agent's picker. magpie reads the agent's own credentials each +time, refreshes tokens the way the agent does — writing a rotated token +back where the agent will find it — and stores nothing but your model +picks; sign out of the agent and the provider is gone. The model list is +the vendor's own too: magpie asks Anthropic's, Copilot's or Codex's API with +that same sign-in, so a model added upstream appears on the next refresh. +The ChatGPT backend only streams and rejects a few parameters, so magpie +translates non-streaming requests and drops what it would refuse. +Claude subscriptions are different: Anthropic classifies another agent's +system prompt as third-party traffic even when the OAuth request otherwise +looks like Claude Code. magpie therefore drives the genuine local `claude` +binary for every Claude subscription generation. The caller's tools are +bridged into that live turn over MCP, and tool results resume the same Claude +Code process; Pi, OpenCode and every other agent use this path automatically. +The generated harness stays out of Anthropic's system-prompt classifier while +its instructions remain part of the user context. This requires Claude Code +to be installed and signed in. A Gemini CLI Google login is planned. ### Connecting anything else diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 3a4d1606e..9cd64f31b 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -340,11 +340,11 @@ func copilot(home string) *Agent { Get: jsonGet(path, "model"), Set: jsonSet(path, "model"), Options: func(map[string]string) []Option { - out := options(catalog.Builtin("copilot"), "") - for i := range out { - if out[i].Value == "auto" { - out[i].Icon = "githubcopilot" - } + // "auto" is Copilot's own choice, not a model it lists; the rest + // come from the list magpie last fetched from Copilot. + out := []Option{{Value: "auto", Note: "let Copilot pick", Icon: "githubcopilot"}} + if live, _, ok := catalog.Live("copilot"); ok { + out = append(out, options(live, "")...) } return out }, diff --git a/internal/agent/claude.go b/internal/agent/claude.go index 4e78a84ed..82ec1cfe2 100644 --- a/internal/agent/claude.go +++ b/internal/agent/claude.go @@ -14,19 +14,12 @@ import ( // ANTHROPIC_MODEL (and the aliases opus/sonnet/haiku resolve through) is // all it takes to run it on any provider. -var claudeAliases = []Option{ - {Value: "opus", Note: "alias · latest Opus", Icon: "claude-color"}, - {Value: "sonnet", Note: "alias · latest Sonnet", Icon: "claude-color"}, - {Value: "haiku", Note: "alias · latest Haiku", Icon: "claude-color"}, - {Value: "opusplan", Note: "alias · Opus for planning, Sonnet for work", Icon: "claude-color"}, - {Value: "sonnet[1m]", Note: "alias · Sonnet with 1M context", Icon: "claude-color"}, -} - // env vars magpie sets while routing through the gateway. var claudeEnv = []string{ "ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", + "CLAUDE_CODE_SUBAGENT_MODEL", } func claude(home string) *Agent { @@ -70,6 +63,7 @@ func claude(home string) *Agent { edit.KV{Path: "env.ANTHROPIC_DEFAULT_SONNET_MODEL", Value: v}, edit.KV{Path: "env.ANTHROPIC_DEFAULT_HAIKU_MODEL", Value: v}, edit.KV{Path: "env.ANTHROPIC_SMALL_FAST_MODEL", Value: v}, + edit.KV{Path: "env.CLAUDE_CODE_SUBAGENT_MODEL", Value: v}, edit.KV{Path: "model", Value: v}, ) } @@ -116,8 +110,10 @@ func claude(home string) *Agent { if u := env("ANTHROPIC_BASE_URL"); u != "" && !routed() { name += " · " + hostOf(u) } - out := group(name, append(append([]Option{}, claudeAliases...), own...)) - return append(out, viaMagpie("")...) + // Only the catalog's models; Claude Code's own short aliases are + // not something any API lists, and a compiled-in copy would just + // go stale. + return append(group(name, own), viaMagpie("")...) }, }}, } diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index f7b1a3c4e..a4ca93334 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -19,12 +19,13 @@ import ( // Model is one entry the picker can offer. type Model struct { - ID string // e.g. "claude-sonnet-5" - Name string // display name - Provider string // models.dev provider id - Released string // YYYY-MM-DD, used for ordering - Efforts []string - Price *Price // USD per million tokens, when models.dev lists it + ID string // e.g. "claude-sonnet-5" + Name string // display name + Provider string // models.dev provider id + Released string // YYYY-MM-DD, used for ordering + Efforts []string + Temperature *bool // false when the model refuses temperature/top_p + Price *Price // USD per million tokens, when models.dev lists it } // Price is what a model costs, in USD per million tokens. @@ -53,6 +54,7 @@ type mdModel struct { ID string `json:"id"` Name string `json:"name"` ReleaseDate string `json:"release_date"` + Temperature *bool `json:"temperature"` // false: rejects temperature/top_p Reasoning []struct { Type string `json:"type"` Values []string `json:"values"` @@ -68,6 +70,8 @@ const modelsDevURL = "https://models.dev/api.json" var ( once sync.Once mdev map[string]mdProvider + + syncMu sync.Mutex ) // CachePath is where `magpie sync` stores the models.dev catalog. @@ -117,8 +121,11 @@ func Reset() { mdev = nil } -// Sync downloads the models.dev catalog into CachePath. +// Sync downloads the models.dev catalog into CachePath. It serializes with +// itself so a background refresh and a manual one cannot interleave writes. func Sync(ctx context.Context) error { + syncMu.Lock() + defer syncMu.Unlock() req, err := http.NewRequestWithContext(ctx, http.MethodGet, modelsDevURL, nil) if err != nil { return err @@ -190,30 +197,26 @@ func PriceOf(providerID, modelID string) (Price, bool) { } // Provider returns the text models of one models.dev provider, newest first. -// Built-in models are merged in so the list is usable without any cache. +// The list comes from the synced models.dev catalog; nothing is compiled in. +// A vendor's own /models answer, once fetched, is layered over it by the +// provider package (see provider.Provider.Available). func Provider(id string) []Model { - seen := map[string]bool{} - var out []Model - if p, ok := load()[id]; ok { - for _, m := range p.Models { - if !textModel(m) { - continue - } - mm := Model{ID: m.ID, Name: m.Name, Provider: id, Released: m.ReleaseDate, Price: m.Cost} - for _, r := range m.Reasoning { - if r.Type == "effort" { - mm.Efforts = r.Values - } - } - seen[m.ID] = true - out = append(out, mm) - } + p, ok := load()[id] + if !ok { + return nil } - for _, m := range builtin[id] { - if !seen[m.ID] { - m.Provider = id - out = append(out, m) + var out []Model + for _, m := range p.Models { + if !textModel(m) { + continue } + mm := Model{ID: m.ID, Name: m.Name, Provider: id, Released: m.ReleaseDate, Price: m.Cost, Temperature: m.Temperature} + for _, r := range m.Reasoning { + if r.Type == "effort" { + mm.Efforts = r.Values + } + } + out = append(out, mm) } sort.SliceStable(out, func(i, j int) bool { if out[i].Released != out[j].Released { @@ -255,12 +258,13 @@ func Providers() []string { return ids } -// Codex returns the models Codex itself lists (from its local cache). +// Codex returns the models Codex itself lists, straight from the cache the +// Codex CLI writes; there is no compiled-in list to fall back to. func Codex() []Model { home, _ := os.UserHomeDir() b, err := os.ReadFile(filepath.Join(home, ".codex", "models_cache.json")) if err != nil { - return builtin["codex"] + return nil } var cache struct { Models []struct { @@ -274,7 +278,7 @@ func Codex() []Model { } `json:"models"` } if json.Unmarshal(b, &cache) != nil || len(cache.Models) == 0 { - return builtin["codex"] + return nil } sort.SliceStable(cache.Models, func(i, j int) bool { return cache.Models[i].Priority < cache.Models[j].Priority }) var out []Model @@ -300,54 +304,3 @@ func Efforts(models []Model, id string) []string { } return nil } - -// builtin keeps the picker useful with no catalog on disk. -var builtin = map[string][]Model{ - "anthropic": { - {ID: "claude-fable-5-1", Name: "Claude Fable 5.1", Released: "2026-09-01"}, - {ID: "claude-opus-5", Name: "Claude Opus 5", Released: "2026-07-01"}, - {ID: "claude-sonnet-5", Name: "Claude Sonnet 5", Released: "2026-07-01"}, - {ID: "claude-haiku-4-5-20251001", Name: "Claude Haiku 4.5", Released: "2025-10-01"}, - }, - "openai": { - {ID: "gpt-5.6-sol", Name: "GPT-5.6 Sol"}, - {ID: "gpt-5.5", Name: "GPT-5.5"}, - {ID: "gpt-5.3-codex", Name: "GPT-5.3 Codex"}, - }, - "codex": { - {ID: "gpt-6-astra", Name: "GPT-6-Astra", Efforts: []string{"low", "medium", "high", "xhigh", "max", "ultra"}}, - {ID: "gpt-5.6-sol", Name: "GPT-5.6-Sol", Efforts: []string{"low", "medium", "high", "xhigh"}}, - {ID: "gpt-5.6-terra", Name: "GPT-5.6-Terra", Efforts: []string{"low", "medium", "high", "xhigh"}}, - {ID: "gpt-5.6-luna", Name: "GPT-5.6-Luna", Efforts: []string{"low", "medium", "high", "xhigh"}}, - {ID: "gpt-5.5", Name: "GPT-5.5", Efforts: []string{"low", "medium", "high", "xhigh"}}, - }, - "deepseek": { - {ID: "deepseek-flash", Name: "DeepSeek V4.1 Flash", Released: "2026-09-10", Efforts: []string{"low", "high", "max"}}, - {ID: "deepseek-v4-pro", Name: "DeepSeek V4 Pro", Released: "2026-08-12", Efforts: []string{"low", "high", "max"}}, - }, - "google": { - {ID: "gemini-3.1-pro", Name: "Gemini 3.1 Pro"}, - {ID: "gemini-3.5-flash", Name: "Gemini 3.5 Flash"}, - {ID: "gemini-2.5-pro", Name: "Gemini 2.5 Pro"}, - {ID: "gemini-2.5-flash", Name: "Gemini 2.5 Flash"}, - }, - "copilot": { - {ID: "auto", Name: "Let Copilot pick"}, - {ID: "claude-fable-5", Name: "Claude Fable 5"}, - {ID: "claude-opus-4.8", Name: "Claude Opus 4.8"}, - {ID: "claude-sonnet-4.5", Name: "Claude Sonnet 4.5"}, - {ID: "claude-haiku-4.5", Name: "Claude Haiku 4.5"}, - {ID: "gpt-5.6-sol", Name: "GPT-5.6 Sol"}, - {ID: "gpt-5.6-terra", Name: "GPT-5.6 Terra"}, - {ID: "gpt-5.6-luna", Name: "GPT-5.6 Luna"}, - {ID: "gpt-5.5", Name: "GPT-5.5"}, - {ID: "gpt-5.4", Name: "GPT-5.4"}, - {ID: "gpt-5.4-mini", Name: "GPT-5.4 mini"}, - {ID: "gpt-5.3-codex", Name: "GPT-5.3 Codex"}, - {ID: "gemini-3.6-flash", Name: "Gemini 3.6 Flash"}, - {ID: "gemini-3.5-flash", Name: "Gemini 3.5 Flash"}, - }, -} - -// Builtin exposes a built-in list by name (e.g. "copilot"). -func Builtin(name string) []Model { return builtin[name] } diff --git a/internal/catalog/catalog_test.go b/internal/catalog/catalog_test.go new file mode 100644 index 000000000..48264eeb4 --- /dev/null +++ b/internal/catalog/catalog_test.go @@ -0,0 +1,70 @@ +package catalog + +import ( + "os" + "path/filepath" + "testing" +) + +// writeCatalog puts a valid models.dev-shaped file where load() will find it; +// load() falls back to the machine's own caches, so a malformed file would +// silently read the developer's real catalog. +func writeCatalog(t *testing.T, body string) { + t.Helper() + dir := t.TempDir() + t.Setenv("XDG_CACHE_HOME", dir) + if err := os.MkdirAll(filepath.Join(dir, "magpie"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(CachePath(), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + Reset() + t.Cleanup(Reset) +} + +func TestProviderReadsTemperatureCapability(t *testing.T) { + writeCatalog(t, `{ + "openai": { + "models": { + "gpt-5.5": {"id":"gpt-5.5","name":"GPT-5.5","temperature":false, + "reasoning_options":[{"type":"effort","values":["low","high"]}]}, + "gpt-4.1": {"id":"gpt-4.1","name":"GPT-4.1","temperature":true} + } + } + }`) + + ms := Provider("openai") + if len(ms) != 2 { + t.Fatalf("models: %+v", ms) + } + byID := map[string]Model{} + for _, m := range ms { + byID[m.ID] = m + } + if p := byID["gpt-5.5"].Temperature; p == nil || *p { + t.Fatalf("gpt-5.5 temperature: %v", p) + } + if p := byID["gpt-4.1"].Temperature; p == nil || !*p { + t.Fatalf("gpt-4.1 temperature: %v", p) + } + if got := byID["gpt-5.5"].Efforts; len(got) != 2 || got[0] != "low" { + t.Fatalf("efforts: %v", got) + } +} + +func TestDecorateCarriesTemperature(t *testing.T) { + no, yes := false, true + live := []Model{{ID: "new-model"}, {ID: "gpt-5.5"}} + known := []Model{ + {ID: "gpt-5.5", Name: "GPT-5.5", Temperature: &no, Released: "2026-04-23"}, + {ID: "old", Temperature: &yes}, + } + out := Decorate(live, known) + if out[0].Temperature != nil { + t.Fatalf("an unknown model gained a capability: %v", *out[0].Temperature) + } + if out[1].Temperature == nil || *out[1].Temperature || out[1].Name != "GPT-5.5" { + t.Fatalf("decorated: %+v", out[1]) + } +} diff --git a/internal/catalog/live.go b/internal/catalog/live.go index f2612740a..f2436a45b 100644 --- a/internal/catalog/live.go +++ b/internal/catalog/live.go @@ -178,6 +178,9 @@ func Decorate(live []Model, known []Model) []Model { m.Name = k.Name } m.Efforts, m.Released, m.Provider = k.Efforts, k.Released, k.Provider + if k.Temperature != nil { + m.Temperature = k.Temperature + } } out = append(out, m) } diff --git a/internal/claudebridge/mcp.go b/internal/claudebridge/mcp.go new file mode 100644 index 000000000..8643c69f8 --- /dev/null +++ b/internal/claudebridge/mcp.go @@ -0,0 +1,138 @@ +// Package claudebridge contains the small stdio MCP helper used by magpie's +// Claude Subscription bridge. The helper is launched by the genuine Claude +// Code binary; tool execution is handed back to the parent magpie process. +package claudebridge + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "sync" +) + +type tool struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + InputSchema json.RawMessage `json:"inputSchema"` +} + +type rpcRequest struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id,omitempty"` + Method string `json:"method"` + Params json.RawMessage `json:"params,omitempty"` +} + +type callbackRequest struct { + ToolCallID string `json:"tool_call_id"` + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` +} + +type callbackResponse struct { + Content any `json:"content"` + IsError bool `json:"is_error,omitempty"` +} + +// RunMCP runs the hidden stdio MCP subprocess. args are callback URL and tools +// JSON path. It intentionally implements only the MCP methods Claude Code needs. +func RunMCP(args []string) error { + if len(args) != 2 { + return errors.New("claude MCP helper expects callback URL and tools file") + } + callbackURL, toolsPath := args[0], args[1] + b, err := os.ReadFile(toolsPath) + if err != nil { + return err + } + var tools []tool + if err := json.Unmarshal(b, &tools); err != nil { + return fmt.Errorf("read MCP tools: %w", err) + } + + client := &http.Client{} // a tools/call intentionally blocks until the agent returns its result + in := bufio.NewScanner(os.Stdin) + in.Buffer(make([]byte, 64<<10), 16<<20) + enc := json.NewEncoder(os.Stdout) + var outMu sync.Mutex + respond := func(v any) { + outMu.Lock() + _ = enc.Encode(v) + outMu.Unlock() + } + + for in.Scan() { + var req rpcRequest + if json.Unmarshal(in.Bytes(), &req) != nil { + continue + } + // Notifications have no id and must not receive a response. + if len(req.ID) == 0 { + continue + } + go func(req rpcRequest) { + result := any(nil) + var rpcErr any + switch req.Method { + case "initialize": + result = map[string]any{ + "protocolVersion": "2025-06-18", + "capabilities": map[string]any{"tools": map[string]any{}}, + "serverInfo": map[string]any{"name": "magpie", "version": "1"}, + } + case "tools/list": + result = map[string]any{"tools": tools} + case "tools/call": + var p struct { + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` + Meta map[string]any `json:"_meta"` + } + if err := json.Unmarshal(req.Params, &p); err != nil { + rpcErr = map[string]any{"code": -32602, "message": err.Error()} + break + } + id, _ := p.Meta["claudecode/toolUseId"].(string) + if id == "" { + rpcErr = map[string]any{"code": -32602, "message": "Claude Code omitted claudecode/toolUseId"} + break + } + payload, _ := json.Marshal(callbackRequest{ToolCallID: id, Name: p.Name, Arguments: p.Arguments}) + httpReq, _ := http.NewRequest(http.MethodPost, callbackURL, bytes.NewReader(payload)) + httpReq.Header.Set("Content-Type", "application/json") + res, err := client.Do(httpReq) + if err != nil { + rpcErr = map[string]any{"code": -32000, "message": err.Error()} + break + } + body, _ := io.ReadAll(io.LimitReader(res.Body, 32<<20)) + res.Body.Close() + if res.StatusCode != http.StatusOK { + rpcErr = map[string]any{"code": -32000, "message": string(body)} + break + } + var cb callbackResponse + if err := json.Unmarshal(body, &cb); err != nil { + rpcErr = map[string]any{"code": -32000, "message": err.Error()} + break + } + result = map[string]any{"content": cb.Content, "isError": cb.IsError} + default: + rpcErr = map[string]any{"code": -32601, "message": "method not found"} + } + response := map[string]any{"jsonrpc": "2.0", "id": json.RawMessage(req.ID)} + if rpcErr != nil { + response["error"] = rpcErr + } else { + response["result"] = result + } + respond(response) + }(req) + } + return in.Err() +} diff --git a/internal/gateway/capture.go b/internal/gateway/capture.go new file mode 100644 index 000000000..4821ad8d5 --- /dev/null +++ b/internal/gateway/capture.go @@ -0,0 +1,53 @@ +package gateway + +import ( + "bytes" + "net/http" +) + +// Recent-call bodies are diagnostics, not an unbounded traffic log. Keeping the +// first 256 KiB is enough to inspect ordinary prompts and responses while +// preventing images or long streams from multiplying into tens of MiB across +// 40 calls. +const callBodyLimit = 256 << 10 + +type capturedBody struct { + buf bytes.Buffer + truncated bool +} + +func (c *capturedBody) add(p []byte) { + if c.buf.Len() >= callBodyLimit { + c.truncated = c.truncated || len(p) > 0 + return + } + n := min(len(p), callBodyLimit-c.buf.Len()) + _, _ = c.buf.Write(p[:n]) + if n < len(p) { + c.truncated = true + } +} + +func (c *capturedBody) text() string { return c.buf.String() } + +func captureRequestBody(p []byte) (string, bool) { + var c capturedBody + c.add(p) + return c.text(), c.truncated +} + +type captureResponseWriter struct { + http.ResponseWriter + body capturedBody +} + +func (w *captureResponseWriter) Write(p []byte) (int, error) { + w.body.add(p) + return w.ResponseWriter.Write(p) +} + +func (w *captureResponseWriter) Flush() { + if f, ok := w.ResponseWriter.(http.Flusher); ok { + f.Flush() + } +} diff --git a/internal/gateway/capture_test.go b/internal/gateway/capture_test.go new file mode 100644 index 000000000..73bae7d3a --- /dev/null +++ b/internal/gateway/capture_test.go @@ -0,0 +1,27 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" +) + +func TestCaptureRequestBodyLimit(t *testing.T) { + body := []byte(strings.Repeat("x", callBodyLimit+17)) + got, truncated := captureRequestBody(body) + if len(got) != callBodyLimit || !truncated { + t.Fatalf("captured %d bytes, truncated=%v", len(got), truncated) + } +} + +func TestCaptureResponseWriterPreservesResponse(t *testing.T) { + r := httptest.NewRecorder() + w := &captureResponseWriter{ResponseWriter: r} + _, _ = w.Write([]byte(`{"ok":true}`)) + if got := w.body.text(); got != `{"ok":true}` { + t.Fatalf("capture = %q", got) + } + if got := r.Body.String(); got != `{"ok":true}` { + t.Fatalf("response = %q", got) + } +} diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 9de59ebc0..45e344ae8 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -158,19 +158,8 @@ func dataURL(p Part) string { return "data:" + p.MediaType + ";base64," + p.Data } -// reasoningModel is a model that rejects temperature and top_p. -func reasoningModel(model string) bool { - m := strings.ToLower(model) - for _, pre := range []string{"gpt-5", "o1", "o3", "o4", "codex"} { - if strings.HasPrefix(m, pre) || strings.Contains(m, "/"+pre) { - return true - } - } - return false -} - // buildChat renders a request for a Chat Completions upstream. -func buildChat(r *Request, model, host string) []byte { +func buildChat(r *Request, model, host string, rejectTemp bool) []byte { var msgs []map[string]any if r.System != "" { msgs = append(msgs, map[string]any{"role": "system", "content": r.System}) @@ -249,7 +238,7 @@ func buildChat(r *Request, model, host string) []byte { out["max_tokens"] = r.MaxTokens } } - if !reasoningModel(model) { + if !rejectTemp { if r.Temp != nil { out["temperature"] = *r.Temp } diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go new file mode 100644 index 000000000..c9cdc4a0e --- /dev/null +++ b/internal/gateway/claude_subscription.go @@ -0,0 +1,607 @@ +package gateway + +// Claude Subscription is driven through the genuine Claude Code binary rather +// than by replaying its OAuth token over HTTP. Anthropic applies subscription +// eligibility checks to request content (not just credentials/CCH); prompts +// generated by Pi, OpenCode and other harnesses can otherwise be routed to +// Extra Usage. The subprocess keeps Claude Code's real Agent/CLI identity. +// +// Caller tools are exposed as an MCP server. A tools/call blocks in the hidden +// stdio helper while magpie returns the tool_use to the caller. The caller's next +// HTTP request supplies tool_result blocks, which unblock the same Claude Code +// turn. This is the protocol-neutral equivalent of pi-claude-bridge's parked +// Agent SDK query (https://github.com/elidickinson/pi-claude-bridge, MIT). + +import ( + "bufio" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +type subscriptionBridge struct { + mu sync.Mutex + runs map[string]*subscriptionRun // callback token → run + calls map[string]*subscriptionRun // tool_use id → run + baseURL string +} + +type subscriptionRun struct { + bridge *subscriptionBridge + token string + model string + cmd *exec.Cmd + tmp string + + mu sync.Mutex + segment chan Event + pending map[string]chan mcpToolResult + closed bool + stderr strings.Builder + timer *time.Timer +} + +type mcpToolResult struct { + Content []map[string]any `json:"content"` + IsError bool `json:"is_error,omitempty"` +} + +type bridgeTool struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + InputSchema json.RawMessage `json:"inputSchema"` +} + +func newSubscriptionBridge() *subscriptionBridge { + return &subscriptionBridge{runs: map[string]*subscriptionRun{}, calls: map[string]*subscriptionRun{}} +} + +func randomToken() string { + var b [24]byte + if _, err := rand.Read(b[:]); err != nil { + return fmt.Sprintf("%d", time.Now().UnixNano()) + } + return hex.EncodeToString(b[:]) +} + +func claudeBinary() (string, error) { + if p, err := exec.LookPath("claude"); err == nil { + return p, nil + } + home, _ := os.UserHomeDir() + for _, p := range []string{filepath.Join(home, ".local", "bin", "claude"), "/usr/local/bin/claude", "/opt/homebrew/bin/claude"} { + if st, err := os.Stat(p); err == nil && !st.IsDir() { + return p, nil + } + } + return "", errors.New("Claude Code is not installed; install it and run `claude auth login`") +} + +func callbackBaseURL() string { + a := Addr() + host, port, ok := strings.Cut(a, ":") + if !ok { + return "http://" + a + } + if host == "" || host == "0.0.0.0" || host == "::" || host == "[::]" { + host = "127.0.0.1" + } + return "http://" + host + ":" + port +} + +func (b *subscriptionBridge) start(ctx context.Context, req *Request, model string) (*subscriptionRun, <-chan Event, error) { + binary, err := claudeBinary() + if err != nil { + return nil, nil, err + } + exe, err := os.Executable() + if err != nil { + return nil, nil, err + } + tmp, err := os.MkdirTemp("", "magpie-claude-") + if err != nil { + return nil, nil, err + } + cleanup := func() { _ = os.RemoveAll(tmp) } + + tools := make([]bridgeTool, 0, len(req.Tools)) + for _, t := range req.Tools { + if req.ToolChoice == "none" || (strings.HasPrefix(req.ToolChoice, "name:") && t.Name != strings.TrimPrefix(req.ToolChoice, "name:")) { + continue + } + schema := t.Schema + if len(schema) == 0 { + schema = json.RawMessage(`{"type":"object","properties":{}}`) + } + tools = append(tools, bridgeTool{Name: t.Name, Description: t.Description, InputSchema: schema}) + } + toolsPath := filepath.Join(tmp, "tools.json") + toolBytes, _ := json.Marshal(tools) + if err := os.WriteFile(toolsPath, toolBytes, 0o600); err != nil { + cleanup() + return nil, nil, err + } + + token := randomToken() + callback := callbackBaseURL() + "/_magpie/claude-mcp/" + token + mcpConfig, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{ + "magpie": map[string]any{"command": exe, "args": []string{"claude-mcp-helper", callback, toolsPath}}, + }}) + args := claudeCLIArgs(model, string(mcpConfig), req.Effort) + cmd := exec.CommandContext(context.Background(), binary, args...) + cmd.Dir = tmp + cmd.Env = cleanClaudeEnv(os.Environ()) + stdin, err := cmd.StdinPipe() + if err != nil { + cleanup() + return nil, nil, err + } + stdout, err := cmd.StdoutPipe() + if err != nil { + cleanup() + return nil, nil, err + } + stderr, err := cmd.StderrPipe() + if err != nil { + cleanup() + return nil, nil, err + } + + run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, pending: map[string]chan mcpToolResult{}} + // A caller may abandon a turn after receiving tool_use. Do not leave the + // parked Claude process and MCP request alive forever. + run.timer = time.AfterFunc(30*time.Minute, run.abort) + segment := run.attach() + b.mu.Lock() + b.runs[token] = run + b.mu.Unlock() + + if err := cmd.Start(); err != nil { + b.removeRun(run) + return nil, nil, err + } + go func() { + _, _ = io.Copy(&lockedWriter{run: run}, io.LimitReader(stderr, 1<<20)) + }() + go run.readOutput(stdout) + go func() { + _ = cmd.Wait() + run.finish() + }() + + prompt, err := renderClaudePrompt(req) + if err != nil { + run.abort() + return nil, nil, err + } + line, _ := json.Marshal(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": prompt}}) + if _, err := stdin.Write(append(line, '\n')); err != nil { + run.abort() + return nil, nil, err + } + _ = stdin.Close() + return run, segment, nil +} + +func claudeCLIArgs(model, mcpConfig, effort string) []string { + args := []string{ + "-p", "--output-format", "stream-json", "--input-format", "stream-json", + "--include-partial-messages", "--verbose", "--model", model, + "--tools", "", "--strict-mcp-config", "--mcp-config", mcpConfig, + "--setting-sources", "", "--dangerously-skip-permissions", + } + if effort != "" { + if effort == "xhigh" { + effort = "max" + } + args = append(args, "--effort", effort, "--thinking-display", "summarized") + } + return args +} + +func cleanClaudeEnv(env []string) []string { + blocked := map[string]bool{ + "ANTHROPIC_BASE_URL": true, "ANTHROPIC_API_KEY": true, "ANTHROPIC_AUTH_TOKEN": true, + "CLAUDECODE": true, "CLAUDE_CODE_ENTRYPOINT": true, "CLAUDE_CODE_SSE_PORT": true, + } + out := make([]string, 0, len(env)+3) + for _, e := range env { + k, _, _ := strings.Cut(e, "=") + if !blocked[k] { + out = append(out, e) + } + } + return append(out, "ENABLE_CLAUDEAI_MCP_SERVERS=0", "DISABLE_AUTO_COMPACT=1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1") +} + +type lockedWriter struct{ run *subscriptionRun } + +func (w *lockedWriter) Write(p []byte) (int, error) { + w.run.mu.Lock() + defer w.run.mu.Unlock() + if w.run.stderr.Len() < 1<<20 { + _, _ = w.run.stderr.Write(p) + } + return len(p), nil +} + +func (r *subscriptionRun) attach() chan Event { + r.mu.Lock() + defer r.mu.Unlock() + ch := make(chan Event, 64) + r.segment = ch + return ch +} + +func (r *subscriptionRun) emit(ev Event) { + r.mu.Lock() + defer r.mu.Unlock() + if r.segment != nil { + r.segment <- ev + } +} + +func (r *subscriptionRun) endSegment() { + r.mu.Lock() + ch := r.segment + r.segment = nil + r.mu.Unlock() + if ch != nil { + close(ch) + } +} + +func (r *subscriptionRun) readOutput(rd io.Reader) { + s := bufio.NewScanner(rd) + s.Buffer(make([]byte, 64<<10), 64<<20) + for s.Scan() { + var envelope struct { + Type string `json:"type"` + Subtype string `json:"subtype"` + IsError bool `json:"is_error"` + Result string `json:"result"` + Event struct { + Type string `json:"type"` + Index int `json:"index"` + Message struct { + ID string `json:"id"` + Model string `json:"model"` + Usage cliUsage `json:"usage"` + } `json:"message"` + ContentBlock struct { + Type string `json:"type"` + ID string `json:"id"` + Name string `json:"name"` + Text string `json:"text"` + } `json:"content_block"` + Delta struct { + Type string `json:"type"` + Text string `json:"text"` + Thinking string `json:"thinking"` + Signature string `json:"signature"` + PartialJSON string `json:"partial_json"` + StopReason string `json:"stop_reason"` + } `json:"delta"` + Usage cliUsage `json:"usage"` + } `json:"event"` + } + if json.Unmarshal(s.Bytes(), &envelope) != nil { + continue + } + if envelope.Type == "result" { + if envelope.IsError { + r.emit(Event{Kind: KError, Text: envelope.Result}) + } + continue + } + if envelope.Type != "stream_event" { + continue + } + e := envelope.Event + switch e.Type { + case "message_start": + r.emit(Event{Kind: KStart, MsgID: e.Message.ID, Model: e.Message.Model, Usage: e.Message.Usage.gateway()}) + case "content_block_start": + switch e.ContentBlock.Type { + case "tool_use": + r.emit(Event{Kind: KToolStart, ID: e.ContentBlock.ID, Name: strings.TrimPrefix(e.ContentBlock.Name, "mcp__magpie__")}) + case "text": + if e.ContentBlock.Text != "" { + r.emit(Event{Kind: KText, Text: e.ContentBlock.Text}) + } + } + case "content_block_delta": + switch e.Delta.Type { + case "text_delta": + r.emit(Event{Kind: KText, Text: e.Delta.Text}) + case "thinking_delta": + r.emit(Event{Kind: KThink, Text: e.Delta.Thinking}) + case "signature_delta": + r.emit(Event{Kind: KSig, Text: e.Delta.Signature}) + case "input_json_delta": + r.emit(Event{Kind: KToolArgs, Text: e.Delta.PartialJSON}) + } + case "message_delta": + r.emit(Event{Kind: KUsage, Usage: e.Usage.gateway()}) + if e.Delta.StopReason != "" { + r.emit(Event{Kind: KStop, Stop: stopFromAnthropic(e.Delta.StopReason)}) + } + case "message_stop": + r.endSegment() + } + } + if err := s.Err(); err != nil { + r.emit(Event{Kind: KError, Text: err.Error()}) + } +} + +type cliUsage struct { + Input int `json:"input_tokens"` + Output int `json:"output_tokens"` + CacheRead int `json:"cache_read_input_tokens"` + CacheWrite int `json:"cache_creation_input_tokens"` + OutputDetails struct { + Thinking int `json:"thinking_tokens"` + } `json:"output_tokens_details"` +} + +func (u cliUsage) gateway() Usage { + return Usage{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.OutputDetails.Thinking} +} + +func renderClaudePrompt(req *Request) ([]map[string]any, error) { + var blocks []map[string]any + var text strings.Builder + if req.System != "" || req.ToolChoice == "required" || strings.HasPrefix(req.ToolChoice, "name:") { + text.WriteString("\n") + text.WriteString(req.System) + switch { + case req.ToolChoice == "required": + text.WriteString("\nYou must call at least one available tool before answering.") + case strings.HasPrefix(req.ToolChoice, "name:"): + fmt.Fprintf(&text, "\nYou must call the %s tool.", strings.TrimPrefix(req.ToolChoice, "name:")) + } + text.WriteString("\n\n\n") + } + for _, m := range req.Messages { + label := "Human" + if m.Role == "assistant" { + label = "Assistant" + } + text.WriteString(label + ": ") + for _, p := range m.Parts { + switch p.Kind { + case Text: + text.WriteString(p.Text) + case Thinking: + text.WriteString(p.Text) + case ToolCall: + fmt.Fprintf(&text, "\n[tool call %s id=%s args=%s]", p.Name, p.ID, argsString(p)) + case ToolResult: + fmt.Fprintf(&text, "\n[tool result id=%s%s]\n%s", p.CallID, map[bool]string{true: " error"}[p.IsError], p.Text) + case Image: + if text.Len() > 0 { + blocks = append(blocks, map[string]any{"type": "text", "text": text.String()}) + text.Reset() + } + switch { + case p.Data != "": + blocks = append(blocks, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": p.MediaType, "data": p.Data}}) + case p.URL != "": + blocks = append(blocks, map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": p.URL}}) + } + } + } + text.WriteString("\n\n") + } + if text.Len() > 0 { + blocks = append(blocks, map[string]any{"type": "text", "text": text.String()}) + } + if len(blocks) == 0 { + blocks = append(blocks, map[string]any{"type": "text", "text": "[continue]"}) + } + return blocks, nil +} + +func (b *subscriptionBridge) findRun(req *Request) (*subscriptionRun, []Part) { + var all []Part + for _, m := range req.Messages { + for _, p := range m.Parts { + if p.Kind == ToolResult { + all = append(all, p) + } + } + } + // Claude emits message_stop just before its MCP calls are all scheduled. + // A very fast client can return a result while the callback is still being + // registered; give that tiny race a bounded grace period. + for attempt := 0; attempt < 20; attempt++ { + var found *subscriptionRun + var results []Part + b.mu.Lock() + for _, p := range all { + run := b.calls[p.CallID] + if run == nil { + continue + } + if found != nil && found != run { + found, results = nil, nil + break + } + found, results = run, append(results, p) + } + b.mu.Unlock() + if found != nil || len(all) == 0 || attempt == 19 { + return found, results + } + time.Sleep(25 * time.Millisecond) + } + return nil, nil +} + +func (r *subscriptionRun) continueWith(results []Part) (<-chan Event, error) { + if r.timer != nil { + r.timer.Reset(30 * time.Minute) + } + ch := r.attach() + for _, p := range results { + r.mu.Lock() + waiter := r.pending[p.CallID] + delete(r.pending, p.CallID) + r.mu.Unlock() + if waiter == nil { + r.abort() + return nil, fmt.Errorf("Claude Code is not waiting for tool result %s", p.CallID) + } + r.bridge.mu.Lock() + delete(r.bridge.calls, p.CallID) + r.bridge.mu.Unlock() + content := []map[string]any{{"type": "text", "text": p.Text}} + waiter <- mcpToolResult{Content: content, IsError: p.IsError} + close(waiter) + } + return ch, nil +} + +func (b *subscriptionBridge) mcpCall(w http.ResponseWriter, r *http.Request) { + token := r.PathValue("token") + b.mu.Lock() + run := b.runs[token] + b.mu.Unlock() + if run == nil { + http.Error(w, "unknown or expired Claude run", http.StatusNotFound) + return + } + var call struct { + ToolCallID string `json:"tool_call_id"` + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` + } + if json.NewDecoder(io.LimitReader(r.Body, 16<<20)).Decode(&call) != nil || call.ToolCallID == "" { + http.Error(w, "invalid tool call", http.StatusBadRequest) + return + } + waiter := make(chan mcpToolResult, 1) + run.mu.Lock() + run.pending[call.ToolCallID] = waiter + run.mu.Unlock() + b.mu.Lock() + b.calls[call.ToolCallID] = run + b.mu.Unlock() + select { + case result, ok := <-waiter: + if !ok { + http.Error(w, "Claude run ended", http.StatusGone) + return + } + writeJSON(w, 200, result) + case <-r.Context().Done(): + return + } +} + +func (r *subscriptionRun) finish() { + r.mu.Lock() + if r.closed { + r.mu.Unlock() + return + } + r.closed = true + if r.timer != nil { + r.timer.Stop() + } + pending := r.pending + r.pending = map[string]chan mcpToolResult{} + ch := r.segment + r.segment = nil + r.mu.Unlock() + for _, waiter := range pending { + close(waiter) + } + if ch != nil { + close(ch) + } + r.bridge.removeRun(r) +} + +func (r *subscriptionRun) abort() { + if r.cmd != nil && r.cmd.Process != nil { + _ = r.cmd.Process.Kill() + } + r.finish() +} + +func (b *subscriptionBridge) removeRun(run *subscriptionRun) { + b.mu.Lock() + delete(b.runs, run.token) + for id, owner := range b.calls { + if owner == run { + delete(b.calls, id) + } + } + b.mu.Unlock() + _ = os.RemoveAll(run.tmp) +} + +func (s *Server) serveClaudeSubscription(w http.ResponseWriter, r *http.Request, from provider.Protocol, model string, body []byte, usage *Usage) (int, string) { + req, err := parse(from, body) + if err != nil { + return writeError(w, from, 400, err.Error()), err.Error() + } + stream := req.Stream + req.Model = model + + run, results := s.subscription.findRun(req) + var events <-chan Event + if run != nil { + events, err = run.continueWith(results) + } else { + run, events, err = s.subscription.start(r.Context(), req, model) + } + if err != nil { + return writeError(w, from, 502, "Claude Code: "+err.Error()), err.Error() + } + + if stream { + enc := encoder(from, newSSEWriter(w), req.Model) + var failed string + for ev := range events { + if ev.Kind == KError { + failed = ev.Text + } + if ev.Kind == KStart || ev.Kind == KUsage { + usage.add(ev.Usage) + } + enc.event(ev) + } + enc.finish() + return 200, failed + } + var col collector + for ev := range events { + col.add(ev) + } + if col.err != "" && len(col.res.Parts) == 0 { + run.abort() + return writeError(w, from, 502, "Claude Code: "+col.err), col.err + } + res := col.finish() + usage.add(res.Usage) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, _ = w.Write(render(from, res, req.Model)) + return 200, col.err +} diff --git a/internal/gateway/claude_subscription_test.go b/internal/gateway/claude_subscription_test.go new file mode 100644 index 000000000..d701bfde1 --- /dev/null +++ b/internal/gateway/claude_subscription_test.go @@ -0,0 +1,57 @@ +package gateway + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestClaudeSubscriptionPromptKeepsForeignHarnessOutOfSystem(t *testing.T) { + r := &Request{ + System: "You are an expert coding assistant operating inside pi\nsee docs/custom-provider.md and docs/packages.md", + Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "hello"}}}}, + } + blocks, err := renderClaudePrompt(r) + if err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(blocks) + s := string(b) + if !strings.Contains(s, "external_system_instructions") || !strings.Contains(s, "operating inside pi") || !strings.Contains(s, "Human: hello") { + t.Fatalf("prompt lost content: %s", b) + } + // renderClaudePrompt is the user content passed to the genuine CLI. The + // foreign harness is never supplied through --system-prompt, where + // Anthropic's subscription classifier rejects it. + args := strings.Join(claudeCLIArgs("claude-sonnet-5", `{}`, "medium"), " ") + if strings.Contains(args, "system-prompt") { + t.Fatal("Claude bridge must retain the genuine Claude Code preset") + } + for _, want := range []string{"--input-format stream-json", "--include-partial-messages", "--strict-mcp-config", "--effort medium"} { + if !strings.Contains(args, want) { + t.Fatalf("missing CLI contract %q in %q", want, args) + } + } +} + +func TestCleanClaudeEnvRemovesGatewayOverrides(t *testing.T) { + got := cleanClaudeEnv([]string{ + "PATH=/bin", "ANTHROPIC_BASE_URL=http://127.0.0.1:3425", + "ANTHROPIC_API_KEY=x", "ANTHROPIC_AUTH_TOKEN=y", "CLAUDECODE=1", + "CLAUDE_CODE_ENTRYPOINT=cli", "CLAUDE_CODE_SSE_PORT=9999", "KEEP=yes", + }) + joined := strings.Join(got, "\n") + for _, forbidden := range []string{ + "ANTHROPIC_BASE_URL=", "ANTHROPIC_API_KEY=", "ANTHROPIC_AUTH_TOKEN=", "CLAUDECODE=", + "CLAUDE_CODE_ENTRYPOINT=", "CLAUDE_CODE_SSE_PORT=", + } { + if strings.Contains(joined, forbidden) { + t.Fatalf("kept %s in %q", forbidden, joined) + } + } + for _, want := range []string{"PATH=/bin", "KEEP=yes", "ENABLE_CLAUDEAI_MCP_SERVERS=0", "DISABLE_AUTO_COMPACT=1"} { + if !strings.Contains(joined, want) { + t.Fatalf("missing %s in %q", want, joined) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 916ef9a45..36bd85ad0 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -55,16 +55,20 @@ func Running() bool { // Call is one request the gateway handled, for the status views. type Call struct { - Time time.Time `json:"time"` - Agent string `json:"agent"` // who called, from the client's User-Agent - Model string `json:"model"` - Provider string `json:"provider"` - From provider.Protocol `json:"from"` - To provider.Protocol `json:"to"` - Status int `json:"status"` - Millis int64 `json:"ms"` - Error string `json:"error,omitempty"` - Usage Usage `json:"usage"` + Time time.Time `json:"time"` + Agent string `json:"agent"` // who called, from the client's User-Agent + Model string `json:"model"` + Provider string `json:"provider"` + From provider.Protocol `json:"from"` + To provider.Protocol `json:"to"` + Status int `json:"status"` + Millis int64 `json:"ms"` + Error string `json:"error,omitempty"` + Usage Usage `json:"usage"` + RequestBody string `json:"requestBody,omitempty"` + ResponseBody string `json:"responseBody,omitempty"` + RequestTruncated bool `json:"requestTruncated,omitempty"` + ResponseTruncated bool `json:"responseTruncated,omitempty"` } // Server is the gateway. @@ -72,7 +76,11 @@ type Server struct { client *http.Client mu sync.Mutex recent []Call - debug bool + // responseOnly remembers models rejected by Chat Completions, avoiding a + // known-failing probe on every Claude Code turn. + responseOnly map[string]bool + subscription *subscriptionBridge + debug bool } // New makes a gateway. @@ -85,7 +93,9 @@ func New() *Server { IdleConnTimeout: 90 * time.Second, ForceAttemptHTTP2: true, }}, - debug: os.Getenv("MAGPIE_DEBUG") != "", + responseOnly: make(map[string]bool), + subscription: newSubscriptionBridge(), + debug: os.Getenv("MAGPIE_DEBUG") != "", } } @@ -146,6 +156,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /v1/messages", s.handle(provider.Anthropic)) mux.HandleFunc("POST /messages", s.handle(provider.Anthropic)) mux.HandleFunc("POST /v1/messages/count_tokens", s.countTokens) + mux.HandleFunc("POST /_magpie/claude-mcp/{token}", s.subscription.mcpCall) mux.HandleFunc("GET /v1beta/models", s.geminiModels) mux.HandleFunc("POST /v1beta/models/{call...}", s.gemini) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { @@ -196,6 +207,17 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) { return } p, model, ok := provider.Resolve(modelOf(body)) + // Claude Subscription generations run through the Claude Code binary. Its + // OAuth token must not take a direct HTTP side path just for token counting. + if ok && p.Account != nil && p.Account.Agent == "claude" { + req, err := parseAnthropic(body) + if err != nil { + writeError(w, provider.Anthropic, 400, err.Error()) + return + } + writeJSON(w, 200, map[string]any{"input_tokens": estimate(req)}) + return + } if ok && p.Anthropic != "" { res, err := s.forward(r.Context(), p, provider.Anthropic, "/v1/messages/count_tokens", rewriteModel(body, model), r.Header) if err == nil { @@ -300,11 +322,18 @@ func estimate(req *Request) int { // serve routes one parsed-enough request to its provider. func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) { start := time.Now() - call := Call{Time: start, From: from, Model: modelOf(body), Agent: usage.AgentOf(r.Header.Get("User-Agent"))} + requestBody, requestTruncated := captureRequestBody(body) + capture := &captureResponseWriter{ResponseWriter: w} + w = capture + call := Call{Time: start, From: from, Model: modelOf(body), Agent: usage.AgentOf(r.Header.Get("User-Agent")), + RequestBody: requestBody, RequestTruncated: requestTruncated} + finishCapture := func() { + call.ResponseBody = capture.body.text() + call.ResponseTruncated = capture.body.truncated + } p, model, ok := provider.Resolve(call.Model) if !ok { call.Status, call.Error = 404, "unknown model" - s.record(call) msg := fmt.Sprintf("magpie knows no model %q", call.Model) if ids := provider.IDs(); len(ids) > 0 { msg += "; it has " + strings.Join(ids, ", ") @@ -312,9 +341,25 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro msg += "; add a provider in magpie first" } writeError(w, from, 404, msg) + finishCapture() + s.record(call) return } call.Provider = p.ID + // A Claude Code subscription must run through the genuine binary. Direct + // OAuth HTTP requests are content-classified as third-party traffic when + // they carry another agent's harness (Pi, OpenCode, and others). + if p.Account != nil && p.Account.Agent == "claude" { + call.To = provider.Anthropic + call.Status, call.Error = s.serveClaudeSubscription(w, r, from, model, body, &call.Usage) + call.Millis = time.Since(start).Milliseconds() + finishCapture() + s.record(call) + usage.Append(usage.Record{Time: start, Agent: call.Agent, Provider: p.ID, Model: model, + Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead, + CacheWrite: call.Usage.CacheWrite, Reasoning: call.Usage.Reasoning, Millis: call.Millis, Status: call.Status}) + return + } // a backend that only streams gets a non-streaming request translated // (the provider is always streamed on that path) rather than relayed relay := p.Base(from) != "" && (p.Account == nil || !p.Account.Stream || streamOf(body)) @@ -324,13 +369,18 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } else { to := p.Speaks() if len(to) == 0 { - writeError(w, from, 502, p.Name+" has no endpoint configured") + call.Status, call.Error = 502, p.Name+" has no endpoint configured" + writeError(w, from, call.Status, call.Error) + call.Millis = time.Since(start).Milliseconds() + finishCapture() + s.record(call) return } call.To = to[0] call.Status, call.Error = s.translate(w, r, p, from, to[0], model, body, &call.Usage) } call.Millis = time.Since(start).Milliseconds() + finishCapture() s.record(call) usage.Append(usage.Record{Time: start, Agent: call.Agent, Provider: p.ID, Model: model, Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead, @@ -431,17 +481,82 @@ func eventStream(res *http.Response) (io.Reader, bool) { return br, false } +func (s *Server) responseOnlyModel(providerID, model string) bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.responseOnly[providerID+"\x00"+model] +} + +func (s *Server) markResponseOnly(providerID, model string) { + s.mu.Lock() + s.responseOnly[providerID+"\x00"+model] = true + s.mu.Unlock() +} + +// forwardTranslated sends one translated, streaming request upstream. Chat is +// preferred by most OpenAI-compatible providers, but some models are exposed +// only by the Responses endpoint; retry that endpoint before failing, like +// Alma's Claude Code provider proxy does. +func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to provider.Protocol, req *Request, model string, in http.Header) (*http.Response, provider.Protocol, error) { + send := func(proto provider.Protocol) (*http.Response, error) { + body := build(proto, req, model, p.Host(), p.RejectsTemperature(model)) + return s.forward(ctx, p, proto, pathOf(proto), p.Prepare(body), in) + } + if to == provider.Chat && p.Responses != "" && s.responseOnlyModel(p.ID, model) { + to = provider.Responses + } + res, err := send(to) + if err != nil { + return nil, to, err + } + if to != provider.Chat || p.Responses == "" || res.StatusCode < 400 { + return res, to, nil + } + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body.Close() + if !notChatModel(res.StatusCode, b) { + res.Body = io.NopCloser(bytes.NewReader(b)) + return res, to, nil + } + s.markResponseOnly(p.ID, model) + res, err = send(provider.Responses) + return res, provider.Responses, err +} + +// notChatModel recognizes the errors used by OpenAI-compatible servers when a +// model can only be called through /responses. +func notChatModel(status int, body []byte) bool { + if status < 400 { + return false + } + msg := strings.ToLower(string(body)) + for _, phrase := range []string{ + "not a chat model", + "not supported in the v1/chat/completions", + "not supported in /v1/chat/completions", + "use v1/completions", + "use /v1/completions", + "use v1/responses", + "use /v1/responses", + } { + if strings.Contains(msg, phrase) { + return true + } + } + return false +} + // translate serves a client API the provider lacks by speaking another // one to it. The provider is always streamed; the client gets whichever // it asked for. func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Provider, from, to provider.Protocol, model string, body []byte, u *Usage) (int, string) { - req, err := parse(from, body) + request, err := parse(from, body) if err != nil { return writeError(w, from, 400, err.Error()), err.Error() } - stream := req.Stream - req.Stream = true - res, err := s.forward(r.Context(), p, to, pathOf(to), p.Prepare(build(to, req, model, p.Host())), r.Header) + stream := request.Stream + request.Stream = true + res, actual, err := s.forwardTranslated(r.Context(), p, to, request, model, r.Header) if err != nil { return writeError(w, from, 502, p.Name+": "+err.Error()), err.Error() } @@ -451,7 +566,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr msg := p.Name + ": " + provider.APIError(b, res.Status) return writeError(w, from, res.StatusCode, msg), msg } - dec := decoder(to) + dec := decoder(actual) rd, sse := eventStream(res) if !sse { // the provider ignored stream:true; read the whole reply as one @@ -461,7 +576,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr return writeError(w, from, 502, msg), msg } if stream { - enc := encoder(from, newSSEWriter(w), req.Model) + enc := encoder(from, newSSEWriter(w), request.Model) var failed string readSSE(rd, func(_, data string) error { return dec(data, func(ev Event) { @@ -486,7 +601,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr } res2 := col.finish() u.add(res2.Usage) - out := render(from, res2, req.Model) + out := render(from, res2, request.Model) w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) w.Write(out) @@ -517,12 +632,12 @@ func parse(proto provider.Protocol, body []byte) (*Request, error) { return parseAnthropic(body) } -func build(proto provider.Protocol, r *Request, model, host string) []byte { +func build(proto provider.Protocol, r *Request, model, host string, rejectTemp bool) []byte { switch proto { case provider.Chat: - return buildChat(r, model, host) + return buildChat(r, model, host, rejectTemp) case provider.Responses: - return buildResponses(r, model) + return buildResponses(r, model, rejectTemp) } return buildAnthropic(r, model) } diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index 3a71c9c16..7bb66cf71 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -97,6 +97,107 @@ func events(body string) []map[string]any { return out } +type fallbackFake struct { + chatBody []byte + responsesBody []byte + chatCalls int + responseCalls int +} + +func (f *fallbackFake) ServeHTTP(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + switch r.URL.Path { + case "/v1/chat/completions": + f.chatCalls++ + f.chatBody = body + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, `{"error":{"message":"This model is not supported in the v1/chat/completions endpoint. Use v1/responses."}}`) + case "/v1/responses": + f.responseCalls++ + f.responsesBody = body + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","model":"m1","usage":{"input_tokens":0,"output_tokens":0}}}`, + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"fallback ok"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","model":"m1","status":"completed","usage":{"input_tokens":4,"output_tokens":2}}}`, + )) + default: + http.NotFound(w, r) + } +} + +func TestAnthropicClientFallsBackFromChatToResponses(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + f := &fallbackFake{} + up := httptest.NewServer(f) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, + Chat: up.URL + "/v1", Responses: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + + handler := New().Handler() + call := func(body string) (int, string) { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)) + handler.ServeHTTP(rec, req) + return rec.Code, rec.Body.String() + } + code, body := call(`{"model":"m1","max_tokens":100,"messages":[{"role":"user","content":"hello"}]}`) + if code != 200 { + t.Fatalf("status %d: %s", code, body) + } + if f.chatCalls != 1 || f.responseCalls != 1 { + t.Fatalf("calls: chat=%d responses=%d", f.chatCalls, f.responseCalls) + } + var chat, responses map[string]any + if json.Unmarshal(f.chatBody, &chat) != nil || json.Unmarshal(f.responsesBody, &responses) != nil { + t.Fatalf("bad translated requests: chat=%s responses=%s", f.chatBody, f.responsesBody) + } + if chat["stream"] != true || responses["stream"] != true || responses["model"] != "m1" { + t.Errorf("requests: chat=%v responses=%v", chat, responses) + } + var out struct { + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"content"` + Usage aUsage `json:"usage"` + } + if err := json.Unmarshal([]byte(body), &out); err != nil { + t.Fatal(err) + } + if len(out.Content) != 1 || out.Content[0].Text != "fallback ok" || out.Usage.InputTokens != 4 || out.Usage.OutputTokens != 2 { + t.Errorf("reply: %s", body) + } + code, body = call(`{"model":"m1","max_tokens":100,"messages":[{"role":"user","content":"again"}]}`) + if code != 200 { + t.Fatalf("second status %d: %s", code, body) + } + if f.chatCalls != 1 || f.responseCalls != 2 { + t.Fatalf("cached calls: chat=%d responses=%d", f.chatCalls, f.responseCalls) + } +} + +func TestNotChatModel(t *testing.T) { + for _, tc := range []struct { + status int + body string + want bool + }{ + {400, `{"error":{"message":"not a chat model; use /v1/responses"}}`, true}, + {404, `use v1/completions`, true}, + {429, `rate limit`, false}, + {200, `use v1/responses`, false}, + } { + if got := notChatModel(tc.status, []byte(tc.body)); got != tc.want { + t.Errorf("notChatModel(%d, %q) = %v, want %v", tc.status, tc.body, got, tc.want) + } + } +} + func TestAnthropicClientChatUpstream(t *testing.T) { f := &fake{t: t, reply: sse( `data: {"id":"c1","model":"m1","choices":[{"delta":{"role":"assistant","reasoning_content":"hmm"}}]}`, diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index 74e71a2e0..abce84fcb 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -169,7 +169,7 @@ func responsesParts(raw json.RawMessage) []Part { } // buildResponses renders a request for a Responses upstream. -func buildResponses(r *Request, model string) []byte { +func buildResponses(r *Request, model string, rejectTemp bool) []byte { var input []map[string]any for _, m := range r.Messages { var content []map[string]any @@ -216,7 +216,7 @@ func buildResponses(r *Request, model string) []byte { if r.MaxTokens > 0 { out["max_output_tokens"] = r.MaxTokens } - if !reasoningModel(model) { + if !rejectTemp { if r.Temp != nil { out["temperature"] = *r.Temp } diff --git a/internal/gui/app.go b/internal/gui/app.go index de17dc50b..d754271e6 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -6,11 +6,14 @@ import ( "log" "os" "runtime" + "time" "github.com/wailsapp/wails/v3/pkg/application" "github.com/wailsapp/wails/v3/pkg/events" + "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" ) //go:embed tray.png @@ -72,6 +75,33 @@ func Run(version string, showMain bool) error { } }() } + // Model lists are fetched, never compiled in: whatever the agents can see + // comes from the models.dev catalog plus each vendor's own /models answer. + // Keep both halves warm without making the user click anything. + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + if catalog.Stale() { + if err := catalog.Sync(ctx); err != nil { + log.Println("catalog:", err) + } + } + cancel() + // A signed-in agent's list exists only at the vendor; fill it in the + // first time so the picker never shows a stale snapshot. + for _, p := range provider.All() { + if p.Account == nil || !p.Ready() { + continue + } + if _, ok := p.Fetched(); ok { + continue + } + c, cancel := context.WithTimeout(context.Background(), 20*time.Second) + if _, err := p.Fetch(c); err != nil { + log.Println(p.ID + ": " + err.Error()) + } + cancel() + } + }() // MAGPIE_THEME=light|dark forces the palette; handy for screenshots. theme := "" if t := os.Getenv("MAGPIE_THEME"); t != "" { diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 8dd707078..f40a975f2 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -184,6 +184,29 @@ body.panel .field.open { box-shadow: inset 0 0 0 1px var(--accent), var(--pill-s /* ---- usage ---------------------------------------------------------------- */ .usage-head { display: flex; align-items: center; gap: 10px; height: 34px; margin: 4px 0 6px; flex: none; } +.subscription-usage { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 7px; margin-bottom: 8px; flex: none; } +.subscription-card { padding: 10px 12px 11px; border: 1px solid var(--line); border-radius: 10px; background: var(--card); min-width: 0; } +.subscription-head { display: flex; align-items: center; gap: 7px; margin-bottom: 9px; } +.subscription-head .ic { width: 17px; height: 17px; } +.subscription-head b { font-size: 12.5px; font-weight: 600; } +.subscription-head .plan { margin-left: auto; font-size: 10.5px; color: var(--muted); text-transform: capitalize; } +.quota-windows { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px 14px; } +.quota-labels { display: flex; align-items: baseline; gap: 6px; margin-bottom: 4px; font-size: 10.5px; color: var(--muted); } +.quota-labels b { margin-left: auto; color: var(--fg-2); font-weight: 600; font-variant-numeric: tabular-nums; } +.quota-track { height: 4px; border-radius: 2px; background: var(--pill); overflow: hidden; } +.quota-track i { display: block; height: 100%; border-radius: inherit; background: var(--accent); } +.subscription-error { font-size: 11px; color: var(--faint); } +.skeleton { display: block; border-radius: 5px; background: linear-gradient(90deg, var(--pill) 25%, var(--pill-hover) 45%, var(--pill) 65%); background-size: 240% 100%; animation: skeleton-shift 1.4s ease-in-out infinite; } +@keyframes skeleton-shift { from { background-position: 100% 0; } to { background-position: -100% 0; } } +.sk-cost { width: 72px; height: 15px; } +.skeleton-card { min-height: 78px; display: flex; flex-direction: column; gap: 9px; justify-content: center; } +.sk-title { width: 38%; height: 12px; } +.sk-line { width: 100%; height: 5px; } +.sk-line.short { width: 64%; } +.loading-kpi { min-height: 67px; justify-content: center; gap: 7px; } +.loading-kpi .sk-number { width: 54%; height: 17px; } +.loading-kpi .sk-label { width: 36%; height: 8px; } +#view-usage.loading .opt { cursor: default; } .usage-cost { display: inline-flex; align-items: baseline; gap: 6px; font-variant-numeric: tabular-nums; color: var(--muted); font-size: 12px; } .usage-cost b { font-size: 15px; font-weight: 600; color: var(--fg); } .stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1px; background: var(--line); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; flex: none; } @@ -220,6 +243,8 @@ body.panel .field.open { box-shadow: inset 0 0 0 1px var(--accent), var(--pill-s .label { font-size: 11px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase; color: var(--muted); } .text { font-size: 12px; color: var(--muted); padding: 3px 7px; border-radius: 6px; transition: background .12s, color .12s; white-space: nowrap; } .text:hover { color: var(--fg); background: var(--pill); } +.text.action { height: 27px; padding: 0 10px; border: 1px solid var(--line); background: var(--card); color: var(--fg-2); box-shadow: 0 1px 1px rgba(0, 0, 0, .04); } +.text.action:hover { border-color: var(--muted); background: var(--card-2); color: var(--fg); } .text.primary { color: var(--accent-fg); background: var(--accent); font-weight: 500; } .text.primary:hover { filter: brightness(1.08); } .text.danger:hover { color: var(--red); background: var(--red-soft); } @@ -269,15 +294,72 @@ body.window .foot { padding-left: 18px; } .pop .search { display: flex; align-items: center; gap: 8px; padding: 0 12px; border-bottom: 1px solid var(--line-2); color: var(--faint); } .pop input { flex: 1; background: none; border: 0; outline: none; height: 36px; font-size: 13px; } .pop input::placeholder { color: var(--faint); } -.pop ul { list-style: none; overflow-y: auto; padding: 5px; } +.picker-body { display: flex; min-height: 0; flex: 1 1 auto; } +#pickerRail[hidden] { display: none; } +#pickerRail { position: relative; width: 43px; padding: 6px 5px; border-right: 1px solid var(--line-2); display: flex; flex-direction: column; align-items: center; gap: 3px; flex: none; overflow-y: auto; } +.rail-thumb { position: absolute; z-index: 0; top: 0; left: 5px; width: 31px; height: 31px; border-radius: 8px; opacity: 0; background: var(--sel); box-shadow: inset 0 0 0 1px var(--line-2), 0 1px 2px rgba(0, 0, 0, .06); pointer-events: none; transition: transform 260ms cubic-bezier(.22, 1, .36, 1), opacity 100ms ease-out; will-change: transform; } +.rail-item { position: relative; z-index: 1; width: 31px; height: 31px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; color: var(--muted); flex: none; transition: color 150ms ease-out, transform 150ms cubic-bezier(.25, 1, .5, 1); } +.rail-item:hover { color: var(--fg); background: color-mix(in srgb, var(--pill) 68%, transparent); } +.rail-item:active { transform: scale(.94); } +.rail-item.on { color: var(--fg); background: transparent; } +.rail-item .ic { width: 16px; height: 16px; transition: transform 220ms cubic-bezier(.22, 1, .36, 1); } +.rail-item.on .ic { transform: scale(1.04); } +.rail-sep { width: 24px; height: 1px; margin: 2px 0; background: var(--line-2); flex: none; } +.pop ul { list-style: none; overflow-y: auto; padding: 5px; min-width: 0; flex: 1 1 auto; contain: paint; } .pop li { display: flex; align-items: center; gap: 9px; height: 30px; padding: 0 8px; border-radius: 7px; white-space: nowrap; font-size: 12.5px; } .pop li .ic { width: 16px; height: 16px; } +.pop li .option-words { display: flex; align-items: center; min-width: 0; flex: 1 1 auto; gap: 9px; } .pop li .v { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; } .pop li .n { flex: 1 1 0; min-width: 0; font-size: 11.5px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; } +.pop li .favorite { display: none; align-items: center; justify-content: center; color: var(--faint); width: 24px; height: 24px; border-radius: 6px; flex: none; } +.pop li:hover .favorite, .pop li .favorite.on { display: inline-flex; } +.pop li .favorite:hover { color: var(--amber); background: var(--pill-hover); } +.pop li .favorite.on { color: var(--amber); } +.pop.model-picker { max-height: 420px; border: 1px solid var(--line); } +.pop.model-picker .search { min-height: 39px; } +.pop.model-picker .search input { height: 38px; } +.pop.model-picker li:not(.group) { height: 34px; padding: 0 8px; } +.pop.model-picker li .option-words { flex-direction: row; align-items: baseline; justify-content: flex-start; gap: 9px; } +.pop.model-picker li .v { max-width: 62%; font-size: 12.5px; line-height: 18px; flex: 0 1 auto; } +.pop.model-picker li .n { width: auto; flex: 1 1 0; font-size: 10.5px; line-height: 18px; } +.pop.model-picker li.group { height: 24px; padding-top: 7px; } +.pop.effort-picker { max-height: none; border: 1px solid rgba(255, 255, 255, .16); border-radius: 11px; color: #f2f2f4; background: rgba(32, 32, 35, .98); box-shadow: 0 16px 42px rgba(0, 0, 0, .52), 0 2px 8px rgba(0, 0, 0, .3), inset 0 1px rgba(255, 255, 255, .025); -webkit-backdrop-filter: blur(24px) saturate(1.08); backdrop-filter: blur(24px) saturate(1.08); } +.effort-control { padding: 13px 15px 14px; } +.effort-head { display: flex; align-items: baseline; gap: 12px; margin-bottom: 13px; font-size: 12px; } +.effort-head span { color: #98989f; font-weight: 600; } +.effort-head b { margin-left: auto; color: #a855f7; font-weight: 650; } +.effort-track { --fill: 0%; position: relative; height: 24px; } +.effort-sparkles { position: absolute; z-index: 1; left: 1px; right: 1px; top: 8px; height: 8px; border-radius: 999px; pointer-events: none; overflow: hidden; clip-path: inset(0 calc(100% - var(--fill)) 0 0 round 999px); } +.effort-sparkles::before, .effort-sparkles::after { content: ""; position: absolute; inset: 0 -28px; background-repeat: repeat-x; will-change: transform, opacity; } +.effort-sparkles::before { background-image: radial-gradient(circle, rgba(255,255,255,.92) 0 1px, transparent 1.3px), radial-gradient(circle, rgba(255,255,255,.62) 0 .7px, transparent 1px), radial-gradient(circle, rgba(255,255,255,.78) 0 .8px, transparent 1.1px); background-size: 31px 8px, 23px 8px, 41px 8px; background-position: 3px 1px, 13px 5px, 25px 3px; animation: effort-drift 5.2s linear infinite, effort-twinkle 2.1s ease-in-out infinite alternate; } +.effort-sparkles::after { background-image: radial-gradient(circle, rgba(255,255,255,.48) 0 .6px, transparent .9px), radial-gradient(circle, rgba(255,255,255,.7) 0 .75px, transparent 1px); background-size: 19px 8px, 37px 8px; background-position: 7px 2px, 19px 6px; animation: effort-drift-back 7s linear infinite, effort-twinkle 2.8s 500ms ease-in-out infinite alternate-reverse; } +.effort-sparkles i { position: absolute; z-index: 2; left: -10px; top: var(--y); width: 7px; height: 1px; border-radius: 999px; opacity: 0; background: linear-gradient(90deg, transparent, rgba(255,255,255,.96)); filter: drop-shadow(1px 0 .7px rgba(255,255,255,.72)); animation: effort-shoot var(--speed) var(--delay) linear infinite; will-change: transform, opacity; } +.effort-sparkles i:nth-child(1) { --y: 1px; --speed: 1.9s; --delay: -.4s; } +.effort-sparkles i:nth-child(2) { --y: 5px; --speed: 2.6s; --delay: -1.8s; width: 5px; } +.effort-sparkles i:nth-child(3) { --y: 3px; --speed: 2.2s; --delay: -1.1s; width: 4px; } +.effort-sparkles i:nth-child(4) { --y: 6px; --speed: 1.7s; --delay: -2.3s; } +.effort-sparkles i:nth-child(5) { --y: 2px; --speed: 2.9s; --delay: -.8s; width: 5px; } +.effort-sparkles i:nth-child(6) { --y: 4px; --speed: 2.4s; --delay: -2s; width: 4px; } +.effort-sparkles i:nth-child(7) { --y: 0; --speed: 2.1s; --delay: -1.5s; width: 6px; } +@keyframes effort-drift { to { transform: translate3d(28px, 0, 0); } } +@keyframes effort-drift-back { to { transform: translate3d(-28px, 0, 0); } } +@keyframes effort-twinkle { from { opacity: .48; } to { opacity: .95; } } +@keyframes effort-shoot { + 0%, 8% { opacity: 0; transform: translate3d(0, 0, 0) scaleX(.55); } + 16% { opacity: .9; } + 62% { opacity: .72; } + 76%, 100% { opacity: 0; transform: translate3d(225px, 0, 0) scaleX(1); } +} +.effort-control input[type="range"] { --fill: 0%; position: relative; z-index: 2; display: block; width: 100%; height: 24px; margin: 0; padding: 0; appearance: none; -webkit-appearance: none; background: transparent; outline: none; cursor: pointer; } +.effort-control input[type="range"]::-webkit-slider-runnable-track { height: 8px; border-radius: 999px; background: linear-gradient(90deg, #9b62db 0, #712ed0 var(--fill), #414147 var(--fill) 100%); box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .08); } +.effort-control input[type="range"]::-webkit-slider-thumb { width: 22px; height: 22px; margin-top: -7px; border: 0; border-radius: 50%; appearance: none; -webkit-appearance: none; background: #f7f7f8; box-shadow: 0 1px 5px rgba(0, 0, 0, .38), 0 0 0 1px rgba(0, 0, 0, .12); transition: transform 120ms cubic-bezier(.25, 1, .5, 1), box-shadow 120ms ease-out; } +.effort-control input[type="range"]:hover::-webkit-slider-thumb { transform: scale(1.04); } +.effort-control input[type="range"]:active::-webkit-slider-thumb { transform: scale(.96); box-shadow: 0 1px 3px rgba(0, 0, 0, .32), 0 0 0 5px rgba(168, 85, 247, .18); } +.effort-control input[type="range"]:focus-visible::-webkit-slider-thumb { box-shadow: 0 1px 4px rgba(0, 0, 0, .32), 0 0 0 4px rgba(168, 85, 247, .18), 0 0 0 1px #a855f7; } .pop li.sel { background: var(--sel); } .pop li .check { color: var(--accent); display: none; margin-left: auto; flex: none; } .pop li.cur .check { display: inline-flex; } @@ -293,6 +375,26 @@ body.window .foot { padding-left: 18px; } .pop .none b { color: var(--fg); font-weight: 500; } /* ---- gateway page --------------------------------------------------------- */ +/* Loading keeps the final geometry in place, so entering Gateway feels calm + even while provider discovery and account checks are still running. */ +.gw-sk-dot { width: 8px; height: 8px; margin: 0 7px; border-radius: 50%; flex: none; } +.gw-sk-who { display: flex; flex-direction: column; justify-content: center; gap: 6px; } +.gw-sk-title { width: 118px; height: 12px; } +.gw-sk-sub { width: min(330px, 72%); height: 8px; } +.gw-sk-url { width: 154px; height: 24px; border-radius: 6px; flex: none; } +.gw-sk-label { width: 46px; height: 8px; align-self: center; justify-self: end; } +.gw-sk-field { min-height: 30px; display: flex; flex-direction: column; justify-content: center; gap: 5px; } +.gw-sk-field .skeleton { width: min(310px, 72%); height: 10px; } +.gw-sk-field .skeleton.short { width: min(210px, 48%); height: 7px; } +.gw-sk-row { pointer-events: none; } +.gw-sk-model { width: 190px; height: 10px; } +.gw-sk-provider { width: 82px; height: 9px; } +.gw-sk-call { cursor: default; pointer-events: none; } +.gw-sk-call .skeleton { height: 8px; } +.gw-sk-call .time { width: 54px; } +.gw-sk-call .agent { width: 62px; } +.gw-sk-call .model { width: 150px; } +.gw-sk-call .result { width: 68px; } /* the status card: a dot where the logo would be, the URL as a pill */ .gwcard { margin: 4px 0 2px; } .gw .dot { width: 8px; height: 8px; margin: 0 7px; border-radius: 50%; background: var(--amber); flex: none; box-shadow: 0 0 0 3px var(--amber-soft); } @@ -336,14 +438,30 @@ body.window .foot { padding-left: 18px; } /* recent calls */ .activity { padding: 5px 8px 6px; font-size: 11.5px; } .activity .none { padding: 8px 6px; color: var(--muted); line-height: 1.45; } -.call { display: flex; align-items: center; gap: 10px; height: 24px; padding: 0 6px; border-radius: 6px; white-space: nowrap; } +.call-item + .call-item { border-top: 1px solid transparent; } +.call-item.open { margin: 2px 0 5px; border-radius: 8px; background: var(--card-2); box-shadow: inset 0 0 0 1px var(--line-2); overflow: hidden; } +.call { display: flex; align-items: center; gap: 10px; height: 24px; padding: 0 6px; border-radius: 6px; white-space: nowrap; cursor: pointer; outline: none; } .call:hover { background: var(--pill); } +.call:focus-visible { box-shadow: inset 0 0 0 1px var(--accent), 0 0 0 2px var(--accent-soft); } +.call-chev { width: 10px; height: 16px; display: inline-flex; align-items: center; justify-content: center; color: var(--faint); flex: none; transition: transform .15s ease-out, color .12s; } +.call:hover .call-chev { color: var(--muted); } +.call-item.open .call-chev { transform: rotate(90deg); } .call .when { color: var(--faint); font-variant-numeric: tabular-nums; } .call .a { color: var(--fg-2); flex: 0 0 auto; max-width: 90px; overflow: hidden; text-overflow: ellipsis; } .call .m { font-family: var(--code); font-size: 11px; color: var(--fg); overflow: hidden; text-overflow: ellipsis; } .call .p { color: var(--muted); } .call .st { color: var(--green); font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; max-width: 55%; } -.call.bad .st { color: var(--red); } +.call-item.bad .st { color: var(--red); } +.call-details { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1px; border-top: 1px solid var(--line-2); background: var(--line-2); } +.call-body { min-width: 0; background: var(--card); } +.call-body-head { height: 29px; padding: 0 8px 0 10px; display: flex; align-items: center; gap: 7px; color: var(--muted); } +.call-body-label { font-size: 10.5px; font-weight: 600; letter-spacing: .015em; } +.call-body-truncated { font-size: 9.5px; color: var(--amber); } +.call-body .copy { width: 20px; height: 20px; } +.call-body pre { margin: 0; padding: 9px 10px 11px; min-height: 54px; max-height: 280px; overflow: auto; border-top: 1px solid var(--line-2); background: var(--code-bg, var(--card-2)); } +.call-body code { display: block; font: 10.5px/1.5 var(--code); color: var(--fg-2); white-space: pre-wrap; overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; tab-size: 2; } +.call-body code.empty { color: var(--faint); font-family: var(--font); } +@media (max-width: 760px) { .call-details { grid-template-columns: 1fr; } } /* ---- providers page ------------------------------------------------------- */ .provider .chev { color: var(--faint); display: inline-flex; transition: transform .15s; } @@ -478,7 +596,7 @@ body.window .foot { padding-left: 18px; } .res.ok { background: var(--green-soft); color: var(--green); } .res.bad { background: var(--red-soft); color: var(--red); max-width: 60%; } .res.bad span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.eps .text { align-self: flex-start; margin: 3px 0 0 65px; } +.eps .text { align-self: flex-start; margin: 5px 0 0 72px; } /* model chips: click to expose, click again to hide */ .models { display: flex; flex-direction: column; gap: 6px; } @@ -494,9 +612,11 @@ body.window .foot { padding-left: 18px; } .mchip.on { color: var(--accent); background: var(--accent-soft); border-color: color-mix(in srgb, var(--accent) 45%, transparent); font-weight: 500; } .mchip.on::before { content: "✓"; font-size: 10px; } .mchip.own.on::before { content: "+"; } -.mchips .hint, .mfoot .hint { font-size: 11px; color: var(--faint); align-self: center; } -.mfoot { display: flex; align-items: center; gap: 6px; } -.mfoot input { max-width: 200px; height: 25px !important; } +.mchips .hint, .mfoot .hint { font-size: 11px; color: var(--faint); align-self: center; line-height: 27px; } +.mfoot { display: flex; align-items: center; gap: 8px; min-height: 27px; } +.mfoot > input { height: 27px; } +.mfoot .text.action { flex: none; } +.mfoot input { max-width: 200px; height: 27px !important; } .mfoot .text { padding: 2px 7px; } /* ---------- settings ---------- */ @@ -551,6 +671,9 @@ html.theming, html.theming *, html.theming *::before, html.theming *::after { .modal .dialog.swap { animation: content-in .22s var(--ease); } .modal.out .dialog { animation: dialog-out .16s var(--ease) forwards; } .modal .dialog::-webkit-scrollbar { width: 0; } +/* Keep native window chrome outside the scrim and dialog. In particular, the + macOS traffic lights must never sit on top of modal content. */ +body.window .modal { top: 50px; padding: 16px 24px 24px; } body.panel .modal { padding: 16px 12px; } @keyframes fade-in { from { opacity: 0; } } @keyframes fade-out { to { opacity: 0; } } @@ -560,4 +683,5 @@ body.panel .modal { padding: 16px 12px; } @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: .01ms !important; transition-duration: .01ms !important; } + .skeleton, .effort-sparkles::before, .effort-sparkles::after, .effort-sparkles i { animation: none !important; } } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index d9f6974de..b7a0734d6 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -20,6 +20,10 @@ let adding = false; // the preset sheet is open let flavor = params.get("flavor") || localStorage.getItem("magpie.flavor") || "openai"; // which API the snippets speak let lang = params.get("lang") || localStorage.getItem("magpie.lang") || "shell"; // which snippet let exampleModel = localStorage.getItem("magpie.model") || ""; // the model in the snippets +const expandedCalls = new Set(); // recent-call ids whose wire bodies are open +let savedModelFavorites = []; +try { savedModelFavorites = JSON.parse(localStorage.getItem("magpie.modelFavorites") || "[]"); } catch {} +const modelFavorites = new Set(Array.isArray(savedModelFavorites) ? savedModelFavorites : []); async function api(path, body) { const res = await fetch("/api/" + path, { @@ -120,7 +124,8 @@ function renderAgents() { b.title = t("{label}: {value}", { label: t(f.label), value: f.value || t("agent default") }) + (opt?.note ? ` · ${opt.note}` : ""); if (opt?.icon) b.append(icon(opt.icon)); else if (!wide(f) || !f.value) b.append(el("span", "k", t(f.label))); - b.append(el("span", "v" + (f.value ? "" : " empty"), opt?.label || f.value || t("default"))); + const shown = (f.key === "effort" || f.label === "effort" || f.label === "thinking") ? effortName(opt || { value: f.value }) : (opt?.label || f.value || t("default")); + b.append(el("span", "v" + (f.value ? "" : " empty"), shown)); const c = el("span", "chev"); c.append(svg(CHEV, 11, 1.7)); b.append(c); @@ -203,39 +208,177 @@ function openPicker(agent, field, anchor, ev, only) { closePicker(); const cur = field.value; let options = field.options.filter((o) => !only || only(o)); - // current value first, then the rest in catalog order + const effortPicker = !only && (field.key === "effort" || field.label === "effort" || field.label === "thinking"); + // Current model first, then the rest in catalog order. Effort levels keep + // their natural low → high order because their position is meaningful. const i = options.findIndex((o) => o.value === cur); - if (i > 0) { const [c] = options.splice(i, 1); options.unshift({ ...c, group: "" }); } + if (!effortPicker && i > 0) { const [c] = options.splice(i, 1); options.unshift({ ...c, group: "" }); } else if (i < 0 && cur && !only) options.unshift({ value: cur, note: t("current value") }); // the agent's own default: magpie's wiring comes out and the key is removed if (!only) options.unshift({ value: "", label: t("Default"), note: t("what {agent} ships with", { agent: agent.name }), icon: agent.icon, reset: true }); - pick = { agent, field, options, anchor, cursor: 0, free: !only }; + const modelPicker = ["model", "small", "large"].includes(field.label) && !only; + pick = { agent, field, options, anchor, cursor: 0, free: !only, modelPicker, effortPicker, groupFilter: "all" }; anchor.classList.add("open"); const pop = $("#pop"); + pop.classList.toggle("model-picker", modelPicker); + pop.classList.toggle("effort-picker", effortPicker); pop.hidden = false; - placePop(anchor, options.some((o) => o.note && o.note !== o.value) ? 372 : 300, 340); + $("#effortControl").hidden = !effortPicker; + pop.querySelector(".search").hidden = effortPicker; + pop.querySelector(".picker-body").hidden = effortPicker; + placePop(anchor, effortPicker ? 218 : modelPicker ? Math.min(490, innerWidth - 16) : (options.some((o) => o.note && o.note !== o.value) ? 372 : 300), effortPicker ? 90 : modelPicker ? Math.min(420, innerHeight - 16) : 340); + if (effortPicker) { + renderEffortPicker(); + $("#effortRange").focus(); + return; + } const q = $("#q"); q.value = ""; - q.placeholder = field.label === "model" ? (only ? t("Filter models…") : t("Filter, or type any model id…")) : t("Filter {field}…", { field: t(field.label) }); + q.placeholder = modelPicker ? t("Filter, or type any model id…") : t("Filter {field}…", { field: t(field.label) }); filter(); q.focus(); } +function effortName(option) { + if (!option?.value) return t("default"); + return t(option.label || option.value); +} + +function renderEffortPicker() { + const range = $("#effortRange"); + const options = pick.options; + const selected = Math.max(0, options.findIndex((o) => o.value === pick.field.value)); + range.max = String(Math.max(0, options.length - 1)); + range.value = String(selected); + $("#effortTitle").textContent = t(pick.field.label); + const update = () => { + const i = Number(range.value); + $("#effortValue").textContent = effortName(options[i]); + const fill = `${options.length > 1 ? 100 * i / (options.length - 1) : 0}%`; + range.style.setProperty("--fill", fill); + range.closest(".effort-track").style.setProperty("--fill", fill); + range.setAttribute("aria-valuetext", effortName(options[i])); + }; + range.oninput = update; + range.onchange = () => { + const opened = pick; + const option = options[Number(range.value)]; + if (!opened || !option || option.value === opened.field.value) return; + opened.field.value = option.value; + const value = opened.anchor.querySelector(".v"); + if (value) { + value.textContent = effortName(option); + value.classList.toggle("empty", !option.value); + } + // Persist every settled slider value, but keep the compact control open so + // the user can compare adjacent levels. Queue writes to preserve ordering + // when keyboard input changes several stops quickly. + opened.effortSave = (opened.effortSave || Promise.resolve()).then(async () => { + const next = await api("set", { agent: opened.agent.id, field: opened.field.key, value: option.value }); + state = next; + status(`${opened.agent.name} ${t(opened.field.label)} → ${effortName(option)}`, "ok"); + }).catch((e) => status(e.message, "err")); + }; + range.onkeydown = (ev) => { + if (ev.key === "Escape") { ev.preventDefault(); ev.stopPropagation(); closePicker(); } + }; + update(); +} + function filter() { if (!pick) return; const q = $("#q").value.trim().toLowerCase(); - const scored = pick.options.map((o, i) => ({ o, i, s: score(q, o) })).filter((x) => x.s > 0); + let source = pick.options; + if (pick.modelPicker && pick.groupFilter === "favorites") source = source.filter((o) => modelFavorites.has(o.value)); + else if (pick.modelPicker && pick.groupFilter !== "all") source = source.filter((o) => o.group === pick.groupFilter || o.reset); + const scored = source.map((o) => ({ o, i: pick.options.indexOf(o), s: score(q, o) })).filter((x) => x.s > 0); // with a query, best matches first; without, catalog order keeps the groups together if (q) scored.sort((a, b) => b.s - a.s || a.i - b.i); pick.items = scored.map((x) => x.o); const typed = $("#q").value.trim(); - if (typed && pick.free && pick.field.label === "model" && !pick.items.some((o) => o.value === typed)) { + if (typed && pick.free && ["model", "small", "large"].includes(pick.field.label) && !pick.items.some((o) => o.value === typed)) { pick.items.push({ value: typed, note: t("use as typed"), custom: true }); } pick.cursor = 0; + renderPickerRail(); renderList(); } +function updatePickerRailSelection() { + const rail = $("#pickerRail"); + const active = rail.querySelector(`.rail-item[data-group="${CSS.escape(pick?.groupFilter || "all")}"]`); + for (const b of rail.querySelectorAll(".rail-item")) b.classList.toggle("on", b === active); + const thumb = rail.querySelector(".rail-thumb"); + if (active && thumb) { + thumb.style.opacity = "1"; + thumb.style.transform = `translate3d(0, ${active.offsetTop}px, 0)`; + } +} + +function switchPickerGroup(id) { + if (!pick?.modelPicker || id === pick.groupFilter) return; + const railItems = [...$("#pickerRail").querySelectorAll(".rail-item")]; + const from = railItems.findIndex((b) => b.dataset.group === pick.groupFilter); + const to = railItems.findIndex((b) => b.dataset.group === id); + pick.groupFilter = id; + updatePickerRailSelection(); + $("#q").focus(); + + const list = $("#list"); + pick.groupAnimation?.cancel(); + const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches; + if (reduced) { filter(); return; } + const direction = to >= from ? 1 : -1; + const token = (pick.groupTransition || 0) + 1; + pick.groupTransition = token; + const out = list.animate([ + { opacity: 1, transform: "translate3d(0, 0, 0)" }, + { opacity: 0, transform: `translate3d(${-direction * 5}px, 0, 0)` }, + ], { duration: 75, easing: "cubic-bezier(.4, 0, 1, 1)", fill: "forwards" }); + pick.groupAnimation = out; + out.finished.then(() => { + if (!pick || pick.groupTransition !== token) return; + out.cancel(); + filter(); + const incoming = list.animate([ + { opacity: 0, transform: `translate3d(${direction * 7}px, 0, 0)` }, + { opacity: 1, transform: "translate3d(0, 0, 0)" }, + ], { duration: 190, easing: "cubic-bezier(.22, 1, .36, 1)" }); + pick.groupAnimation = incoming; + }).catch(() => {}); +} + +function renderPickerRail() { + const rail = $("#pickerRail"); + rail.hidden = !pick?.modelPicker; + if (!pick?.modelPicker) { rail.replaceChildren(); rail.dataset.signature = ""; return; } + const groups = []; + for (const o of pick.options) if (o.group && !groups.includes(o.group)) groups.push(o.group); + const signature = groups.join("\u001f"); + if (rail.dataset.signature !== signature) { + rail.replaceChildren(); + rail.dataset.signature = signature; + rail.append(el("span", "rail-thumb")); + const add = (id, title, child) => { + const b = el("button", "rail-item"); + b.dataset.group = id; + b.title = title; + b.setAttribute("aria-label", title); + b.append(child); + b.onclick = () => switchPickerGroup(id); + rail.append(b); + }; + add("all", t("All models"), svg("M3 3h4v4H3zM9 3h4v4H9zM3 9h4v4H3zM9 9h4v4H9z", 15, 1.4)); + add("favorites", t("Favorites"), svg("m8 2 1.8 3.7 4.1.6-3 2.9.7 4.1L8 11.4l-3.6 1.9.7-4.1-3-2.9 4.1-.6z", 16, 1.4)); + if (groups.length) rail.append(el("span", "rail-sep")); + for (const group of groups) { + const sample = pick.options.find((o) => o.group === group); + add(group, group, icon(sample?.icon || "generic")); + } + } + queueMicrotask(updatePickerRailSelection); +} + function renderList() { const list = $("#list"); list.replaceChildren(); @@ -249,10 +392,24 @@ function renderList() { const li = el("li", (idx === pick.cursor ? "sel" : "") + (o.value === pick.field.value ? " cur" : "") + (o.custom ? " custom" : "") + (o.reset ? " reset" : "")); li.dataset.i = idx; if (hasIcons) li.append(icon(o.icon)); - li.append(el("span", "v", o.label || o.value)); + const words = el("span", "option-words"); + words.append(el("span", "v", o.label || o.value)); let note = o.note && o.note !== (o.label || o.value) ? o.note : ""; if (q && o.group && !note) note = o.group; - if (note) li.append(el("span", "n", note)); + if (note) words.append(el("span", "n", note)); + li.append(words); + if (pick.modelPicker && o.value && !o.custom) { + const star = el("button", "favorite" + (modelFavorites.has(o.value) ? " on" : "")); + star.title = modelFavorites.has(o.value) ? t("Remove from favorites") : t("Add to favorites"); + star.append(svg("m8 2 1.8 3.7 4.1.6-3 2.9.7 4.1L8 11.4l-3.6 1.9.7-4.1-3-2.9 4.1-.6z", 14, 1.4)); + star.onclick = (ev) => { + ev.stopPropagation(); + if (modelFavorites.has(o.value)) modelFavorites.delete(o.value); else modelFavorites.add(o.value); + localStorage.setItem("magpie.modelFavorites", JSON.stringify([...modelFavorites])); + filter(); + }; + li.append(star); + } const ck = el("span", "check"); ck.append(svg(CHECK, 12, 1.8)); li.append(ck); @@ -291,8 +448,13 @@ async function commit(value) { function closePicker() { if (!pick) return; + pick.groupAnimation?.cancel(); pick.anchor.classList.remove("open"); $("#pop").hidden = true; + $("#pop").classList.remove("model-picker", "effort-picker"); + $("#pop .search").hidden = false; + $("#pop .picker-body").hidden = false; + $("#effortControl").hidden = true; pick = null; } @@ -348,6 +510,7 @@ $("#save").onclick = () => { // the local gateway in whichever API the agent speaks. async function loadProviders() { + if (view === "gateway") renderGatewayLoading(); providers = await api("providers"); if (!providers.providers.length && editing === null) adding = true; if (view === "gateway") renderGatewayView(); @@ -407,8 +570,8 @@ function renderProviders() { if (dialog) openModal(dialog); else closeModal(); } -// Sign-ins magpie found but leaves alone (Claude Code), so nobody wonders -// why an agent that is clearly logged in is not in the list. +// Sign-ins magpie found but leaves alone, so nobody wonders why an agent that +// is clearly logged in is not in the list. Empty today. function renderExcluded() { const box = $("#excluded"); box.replaceChildren(); @@ -424,6 +587,7 @@ function renderExcluded() { function accountPlan(a) { if (a.agent === "codex") return "ChatGPT" + (a.plan ? " " + a.plan[0].toUpperCase() + a.plan.slice(1) : ""); if (a.agent === "copilot") return "GitHub"; + if (a.agent === "claude") return "Claude" + (a.plan ? " " + a.plan[0].toUpperCase() + a.plan.slice(1) : ""); return t("signed in"); } @@ -444,7 +608,51 @@ function copyBtn(text, what) { return b; } +function renderGatewayLoading() { + const page = $("#view-gateway"); + page.classList.add("loading"); + page.setAttribute("aria-busy", "true"); + $("#connectNote").textContent = ""; + $("#callsNote").textContent = ""; + $("#copyModels").hidden = true; + + const gateway = $("#gateway"); + gateway.replaceChildren(); + const mark = el("span", "skeleton gw-sk-dot"); + const who = el("div", "who gw-sk-who"); + who.append(el("span", "skeleton gw-sk-title"), el("span", "skeleton gw-sk-sub")); + gateway.append(mark, who, el("span", "skeleton gw-sk-url")); + + const connect = $("#connect"); + connect.replaceChildren(); + for (let i = 0; i < 4; i++) { + connect.append(el("span", "skeleton gw-sk-label")); + const value = el("div", "gw-sk-field"); + value.append(el("span", "skeleton"), el("span", "skeleton short")); + connect.append(value); + } + + const models = $("#gwModels"); + models.replaceChildren(); + for (let i = 0; i < 4; i++) { + const row = el("div", "row model gw-sk-row"); + row.append(el("span", "skeleton gw-sk-model"), el("span", "grow"), el("span", "skeleton gw-sk-provider")); + models.append(row); + } + + const activity = $("#activity"); + activity.replaceChildren(); + for (let i = 0; i < 4; i++) { + const row = el("div", "call gw-sk-call"); + row.append(el("span", "skeleton time"), el("span", "skeleton agent"), el("span", "skeleton model"), el("span", "grow"), el("span", "skeleton result")); + activity.append(row); + } +} + function renderGatewayView() { + const page = $("#view-gateway"); + page.classList.remove("loading"); + page.removeAttribute("aria-busy"); renderGateway(); renderConnect(); renderGatewayModels(); @@ -682,6 +890,27 @@ function renderGatewayModels() { } } +function formatWireBody(raw) { + if (!raw) return ""; + try { return JSON.stringify(JSON.parse(raw), null, 2); } catch { return raw; } +} + +function callBodyPanel(label, raw, truncated) { + const panel = el("section", "call-body"); + const head = el("div", "call-body-head"); + head.append(el("span", "call-body-label", t(label))); + if (truncated) head.append(el("span", "call-body-truncated", t("first 256 KB"))); + const formatted = formatWireBody(raw); + if (formatted) head.append(el("span", "grow"), copyBtn(raw, t(label))); + panel.append(head); + const pre = el("pre"); + const code = el("code", "", formatted || t("No body captured")); + if (!formatted) code.classList.add("empty"); + pre.append(code); + panel.append(pre); + return panel; +} + function renderActivity() { const g = providers.gateway; const box = $("#activity"); @@ -690,15 +919,41 @@ function renderActivity() { const calls = g.calls.slice(0, 20); if (!calls.length) { box.append(el("div", "none", t("No requests yet. Point an agent at a model, or run the example above; every call shows up here as it happens."))); return; } for (const c of calls) { - const r = el("div", "call" + (c.status >= 400 ? " bad" : "")); + const id = `${c.time}|${c.agent}|${c.model}`; + const open = expandedCalls.has(id); + const item = el("div", "call-item" + (open ? " open" : "") + (c.status >= 400 ? " bad" : "")); + const r = el("div", "call"); + r.setAttribute("role", "button"); + r.setAttribute("tabindex", "0"); + r.setAttribute("aria-expanded", String(open)); + const chev = el("span", "call-chev"); + chev.append(svg(CHEV_R, 11, 1.6)); + r.append(chev); r.append(el("span", "when", new Date(c.time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }))); r.append(el("span", "a", c.agent || "—")); r.append(el("span", "m", c.model)); r.append(el("span", "p", c.from === c.to ? c.from : `${c.from} → ${c.to}`)); r.append(el("span", "grow")); r.append(el("span", "st", c.error ? `${c.status} ${c.error}` : `${c.status} · ${c.ms} ms`)); - r.title = c.error || `${c.provider} · ${c.ms} ms`; - box.append(r); + r.title = open ? t("Hide request and response bodies") : t("Show request and response bodies"); + const toggle = () => { + if (expandedCalls.has(id)) expandedCalls.delete(id); else expandedCalls.add(id); + renderActivity(); + }; + r.onclick = toggle; + r.onkeydown = (ev) => { + if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); toggle(); } + }; + item.append(r); + if (open) { + const details = el("div", "call-details"); + details.append( + callBodyPanel("Request Body", c.requestBody, c.requestTruncated), + callBodyPanel("Response Body", c.responseBody, c.responseTruncated), + ); + item.append(details); + } + box.append(item); } } @@ -938,7 +1193,7 @@ function renderEditor(p, presetID) { const cancel = el("button", "text", t("Cancel")); cancel.onclick = cancelEdit; const saveBtn = el("button", "text primary", t("Save")); - saveBtn.onclick = () => { saveBtn.classList.add("busy"); providerAction("save", { id: p.id, models: draft.chosen }, t("{name} saved", { name: p.name }), p.id); }; + saveBtn.onclick = () => { saveBtn.classList.add("busy"); providerAction("save", { id: p.id, models: draft.chosen }, t("{name} saved", { name: p.name })); }; bar.append(cancel, saveBtn); ed.append(bar); return ed; @@ -1012,7 +1267,7 @@ function renderEditor(p, presetID) { if (isNew && custom && !body.name) { name.focus(); return status(t("Give it a name"), "warn"); } if (isNew && custom && !body.chat && !body.anthropic) { url.focus(); return status(t("A base URL is needed"), "warn"); } saveBtn.classList.add("busy"); - providerAction("save", body, t(isNew ? "{name} added" : "{name} saved", { name: draft.name || draft.id }), body.id || slug(body.name)); + providerAction("save", body, t(isNew ? "{name} added" : "{name} saved", { name: draft.name || draft.id })); }; saveBtn.onclick = save; bar.append(cancel, saveBtn); @@ -1037,7 +1292,7 @@ function renderEndpoints(p, pr) { eps.append(e); } if (p) { - const test = el("button", "text", t("Test")); + const test = el("button", "text action", t("Test")); test.title = t("Send a tiny request through each endpoint"); test.onclick = async () => { test.classList.add("busy"); @@ -1098,7 +1353,7 @@ function renderModels(p) { if (e.key === "Enter" && add.value.trim()) { const id = add.value.trim(); if (!draft.chosen.includes(id)) draft.chosen.push(id); add.value = ""; draw(); } else if (e.key === "Escape") cancelEdit(); }; - const refresh = el("button", "text", t("Refresh")); + const refresh = el("button", "text action", t("Refresh")); refresh.title = t("Ask the vendor which models it serves"); refresh.onclick = async () => { refresh.classList.add("busy"); @@ -1120,10 +1375,10 @@ function renderModels(p) { return box; } -async function providerAction(action, body, okMsg, keep) { +async function providerAction(action, body, okMsg) { try { providers = await api("provider/" + action, body); - editing = action === "save" && keep ? keep : null; + editing = null; draft = null; adding = false; presetQuery = ""; @@ -1147,10 +1402,46 @@ $("#addProvider").onclick = () => { adding = true; editing = null; draft = null; const PERIODS = [["today", "Today"], ["7d", "7 days"], ["30d", "30 days"], ["all", "All"]]; async function loadUsage() { + renderUsageLoading(); usage = await api("usage?period=" + period); renderUsage(); } +function renderUsageLoading() { + const view = $("#view-usage"); + view.classList.add("loading"); + view.setAttribute("aria-busy", "true"); + const seg = $("#period"); + seg.replaceChildren(); + for (const [id, name] of PERIODS) { + const b = el("button", "opt" + (id === period ? " on" : ""), t(name)); + b.disabled = true; + seg.append(b); + } + slide(seg, "period"); + $("#usageCost").replaceChildren(el("span", "skeleton sk-cost")); + const subscriptions = $("#subscriptionUsage"); + subscriptions.hidden = false; + subscriptions.replaceChildren(); + for (let i = 0; i < 2; i++) { + const card = el("div", "subscription-card skeleton-card"); + card.append(el("span", "skeleton sk-title"), el("span", "skeleton sk-line"), el("span", "skeleton sk-line short")); + subscriptions.append(card); + } + const stats = $("#stats"); + stats.classList.remove("empty"); + stats.replaceChildren(); + for (let i = 0; i < 4; i++) { + const tile = el("div", "kpi loading-kpi"); + tile.append(el("span", "skeleton sk-number"), el("span", "skeleton sk-label")); + stats.append(tile); + } + $("#chart").hidden = true; + for (const id of ["usageAgents", "usageModels"]) $("#" + id).hidden = true; + for (const h of $$("#view-usage .row-head")) h.hidden = true; + $("#usageNote").textContent = ""; +} + function fmtN(n) { if (n >= 1e9) return (n / 1e9).toFixed(2) + "B"; if (n >= 1e7) return Math.round(n / 1e6) + "M"; @@ -1169,6 +1460,9 @@ const tokensOf = (t) => t.input + t.output; function renderUsage() { const u = usage; + const view = $("#view-usage"); + view.classList.remove("loading"); + view.removeAttribute("aria-busy"); const seg = $("#period"); seg.replaceChildren(); for (const [id, name] of PERIODS) { @@ -1187,6 +1481,37 @@ function renderUsage() { cost.append(el("span", "", t("no price for these models"))); } + const subscriptions = $("#subscriptionUsage"); + subscriptions.replaceChildren(); + subscriptions.hidden = !u.subscriptions?.length; + for (const sub of u.subscriptions || []) { + const card = el("div", "subscription-card"); + const head = el("div", "subscription-head"); + head.append(icon(sub.icon), el("b", "", sub.name)); + if (sub.plan) head.append(el("span", "plan", sub.plan)); + card.append(head); + if (sub.error) { + card.append(el("div", "subscription-error", t("Usage unavailable"))); + card.title = sub.error; + } else { + const windows = el("div", "quota-windows"); + for (const w of sub.windows) { + const quota = el("div", "quota"); + const labels = el("div", "quota-labels"); + labels.append(el("span", "", t(w.name)), el("b", "", w.display || `${Math.round(w.used)}%`)); + const track = el("div", "quota-track"); + const fill = el("i"); + fill.style.width = `${Math.max(0, Math.min(100, w.used))}%`; + track.append(fill); + quota.append(labels, track); + if (w.resetsAt) quota.title = t("Resets {when}", { when: new Date(w.resetsAt).toLocaleString() }); + windows.append(quota); + } + card.append(windows); + } + subscriptions.append(card); + } + const stats = $("#stats"); stats.replaceChildren(); const empty = !u.calls; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 42f728da9..bc2ae81ec 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -27,6 +27,13 @@ const I18N = { "auth": "认证", "agent default": "Agent 默认值", "default": "默认", + "off": "关闭", + "minimal": "最低", + "low": "低", + "medium": "中", + "high": "高", + "xhigh": "很高", + "max": "最高", "{label}: {value}": "{label}:{value}", "Profiles": "方案", "+ Save current": "+ 保存当前", @@ -173,11 +180,21 @@ const I18N = { "Put these in the shell (or the tool's settings) and the tool talks to magpie instead of the vendor.": "把这些放进 shell(或工具的设置)里,工具就会改为与 magpie 通信,而不是直连供应商。", "Copy all ids": "复制全部 ID", "No models exposed yet": "尚未暴露任何模型", + "All models": "全部模型", + "Favorites": "收藏", + "Add to favorites": "添加到收藏", + "Remove from favorites": "从收藏中移除", "Add a provider, or sign in to Codex or Copilot; their models show up here for every agent.": "添加一个供应商,或登录 Codex / Copilot;它们的模型会出现在这里,供所有 Agent 使用。", "Use this model in the snippets": "在示例中使用此模型", "Recent calls": "最近调用", "shown by the magpie that serves the gateway": "由提供网关的那个 magpie 显示", "No requests yet. Point an agent at a model, or run the example above; every call shows up here as it happens.": "还没有请求。让某个 Agent 使用一个模型,或运行上面的示例;每次调用都会实时显示在这里。", + "Show request and response bodies": "查看请求体和响应体", + "Hide request and response bodies": "收起请求体和响应体", + "Request Body": "请求体", + "Response Body": "响应体", + "No body captured": "未捕获到内容", + "first 256 KB": "前 256 KB", // usage "Today": "今天", @@ -189,6 +206,15 @@ const I18N = { "{n} calls had no known price and are not counted": "{n} 次调用没有已知价格,未计入", "At each model's list price on models.dev": "按 models.dev 上各模型的标价计算", "no price for these models": "这些模型没有价格信息", + "5 hours": "5 小时", + "7 days · Opus": "7 天 · Opus", + "7 days · Sonnet": "7 天 · Sonnet", + "Usage unavailable": "暂时无法获取用量", + "Resets {when}": "重置于 {when}", + "Allowance": "用量额度", + "Chat requests": "聊天请求", + "Completions": "代码补全", + "Premium requests": "高级请求", "No calls today.": "今天没有调用。", "No calls in the last 7 days.": "最近 7 天没有调用。", "No calls in the last 30 days.": "最近 30 天没有调用。", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index f8d6cb556..b520cbd91 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -67,6 +67,7 @@ +
Agents
@@ -106,7 +107,19 @@ - +
+ + +
+ diff --git a/internal/gui/usage.go b/internal/gui/usage.go index 2a19a727e..00441a8e3 100644 --- a/internal/gui/usage.go +++ b/internal/gui/usage.go @@ -1,7 +1,9 @@ package gui import ( + "context" "net/http" + "time" "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/provider" @@ -18,14 +20,17 @@ type usageGroup struct { type usageJSON struct { usage.Summary - Agents []usageGroup `json:"agents"` - Models []usageGroup `json:"models"` - Path string `json:"path"` + Agents []usageGroup `json:"agents"` + Models []usageGroup `json:"models"` + Path string `json:"path"` + Subscriptions []provider.SubscriptionQuota `json:"subscriptions"` } -func usageState(p usage.Period) usageJSON { +func usageState(ctx context.Context, p usage.Period) usageJSON { s := usage.Summarize(p) - out := usageJSON{Summary: s, Agents: []usageGroup{}, Models: []usageGroup{}, Path: tilde(usage.Path())} + quotaCtx, cancel := context.WithTimeout(ctx, 8*time.Second) + defer cancel() + out := usageJSON{Summary: s, Agents: []usageGroup{}, Models: []usageGroup{}, Path: tilde(usage.Path()), Subscriptions: provider.SubscriptionUsage(quotaCtx)} agents := map[string]*agent.Agent{} for _, a := range agent.All() { agents[a.ID] = a @@ -62,6 +67,6 @@ func usageRoutes(mux *http.ServeMux) { default: p = usage.Month } - writeJSON(rw, usageState(p)) + writeJSON(rw, usageState(r.Context(), p)) }) } diff --git a/internal/provider/account.go b/internal/provider/account.go index b27c74546..7e268ed76 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -2,14 +2,11 @@ package provider // Accounts: agents the user has signed in to, offered as providers. // -// A Codex CLI login (ChatGPT) or a Copilot login is a subscription with -// models behind it. magpie reads the credentials the agent itself keeps on -// disk, so every other agent can use those models through the gateway. -// Nothing is stored twice: sign out of the agent and the provider is gone. -// -// Claude Code is deliberately absent: Anthropic's terms keep a Claude -// subscription's OAuth token for Claude Code alone. Excluded says so when -// that sign-in exists, so its absence here is not a mystery. +// Claude Code, Codex CLI (ChatGPT), and Copilot logins are subscriptions with +// models behind them. magpie reads the credentials the agent itself keeps on +// disk or in the macOS Keychain, so every other agent can use those models +// through the gateway. Nothing is stored twice: sign out of the agent and the +// provider is gone. import ( "bytes" @@ -17,6 +14,7 @@ import ( "encoding/base64" "encoding/json" "errors" + "fmt" "io" "net/http" "net/url" @@ -75,43 +73,418 @@ type Exclusion struct { Why string `json:"why"` } -var ( - excludedMu sync.Mutex - excludedAt time.Time - excludedList []Exclusion +// Excluded lists sign-ins magpie detects but cannot expose. It is currently +// empty, but remains part of the API so the CLI and GUI can explain future +// account types that are detectable but not usable. +func Excluded() []Exclusion { return nil } + +const ( + claudeClientID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e" + // These values mirror the genuine Claude Code release used by Alma. The + // installed CLI version wins when it is newer, keeping UA and cc_version in + // lockstep as Claude's model gates require. + claudeVersionFloor = "2.1.280" + claudeSDKVersion = "0.112.1" + claudeRuntimeVersion = "v22.13.0" + claudeFingerprintSalt = "59cf53e54c78" + claudeCCHSeed uint64 = 0x6e52736ac806831e ) -// Excluded lists the sign-ins magpie leaves alone, and why. Claude Code's -// credentials live in the macOS Keychain or ~/.claude/.credentials.json; -// only their presence is checked, never their contents. -func Excluded() []Exclusion { - excludedMu.Lock() - defer excludedMu.Unlock() - if time.Since(excludedAt) < time.Minute { - return excludedList - } - excludedAt, excludedList = time.Now(), nil - if claudeSignedIn() { - excludedList = append(excludedList, Exclusion{Agent: "claude", - Why: "Anthropic's terms keep a Claude subscription for Claude Code itself, so magpie does not share it with other agents. Use an Anthropic API key as a provider instead."}) - } - return excludedList +var claudeHaikuBetas = "oauth-2025-04-20,interleaved-thinking-2025-05-14,redact-thinking-2026-02-12,context-management-2025-06-27,prompt-caching-scope-2026-01-05,claude-code-20250219" +var claudeDefaultBetas = "claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,redact-thinking-2026-02-12,context-management-2025-06-27,prompt-caching-scope-2026-01-05,advanced-tool-use-2025-11-20,effort-2025-11-24" + +// claudeBase is Anthropic's API root. A var so tests can point it elsewhere. +var claudeBase = "https://api.anthropic.com" + +// claudeTokenURL is where a Claude subscription's OAuth token is refreshed; +// a var so tests can point it elsewhere. +var claudeTokenURL = "https://platform.claude.com/v1/oauth/token" + +// claudeKeychain reads credentials from the macOS Keychain; a var so tests +// never touch the machine's own login. +var claudeKeychain = runtime.GOOS == "darwin" + +var ( + claudeMu sync.Mutex // serializes refresh; a rotated token is written back once + + claudeStatusMu sync.Mutex + claudeStatusAt time.Time + claudeStatusUser string + claudeStatusPlan string + + claudeCacheMu sync.Mutex + claudeCacheAt time.Time + claudeCacheC claudeCredentials + claudeCacheLoc claudeCredentialLocation + claudeCacheOK bool +) + +// claudeCacheTTL keeps All() from spawning `security` on every gateway +// request while still noticing a fresh login quickly. +const claudeCacheTTL = 10 * time.Second + +type claudeAuth struct { + AccessToken string `json:"accessToken"` + RefreshToken string `json:"refreshToken"` + ExpiresAt int64 `json:"expiresAt"` // milliseconds since the Unix epoch + RefreshExpiresAt int64 `json:"refreshTokenExpiresAt"` + Scopes []string `json:"scopes"` + SubscriptionType string `json:"subscriptionType"` + RateLimitTier string `json:"rateLimitTier"` } -func claudeSignedIn() bool { +// claudeCredentials keeps the whole credential blob in raw, so refreshing a +// token writes back everything else — MCP OAuth state included — untouched. +type claudeCredentials struct { + raw map[string]any + OAuth claudeAuth +} + +func parseClaudeCredentials(b []byte) (claudeCredentials, bool) { + var raw map[string]any + if json.Unmarshal(b, &raw) != nil { + return claudeCredentials{}, false + } + c := claudeCredentials{raw: raw} + if o, ok := raw["claudeAiOauth"].(map[string]any); ok { + ob, _ := json.Marshal(o) + json.Unmarshal(ob, &c.OAuth) + } + return c, c.OAuth.AccessToken != "" +} + +func (c claudeCredentials) marshal() ([]byte, error) { + raw := c.raw + if raw == nil { + raw = map[string]any{} + } + oauth, _ := raw["claudeAiOauth"].(map[string]any) + if oauth == nil { + oauth = map[string]any{} + } + oauth["accessToken"] = c.OAuth.AccessToken + oauth["refreshToken"] = c.OAuth.RefreshToken + oauth["expiresAt"] = c.OAuth.ExpiresAt + if c.OAuth.RefreshExpiresAt != 0 { + oauth["refreshTokenExpiresAt"] = c.OAuth.RefreshExpiresAt + } + if len(c.OAuth.Scopes) > 0 { + oauth["scopes"] = c.OAuth.Scopes + } + if c.OAuth.SubscriptionType != "" { + oauth["subscriptionType"] = c.OAuth.SubscriptionType + } + if c.OAuth.RateLimitTier != "" { + oauth["rateLimitTier"] = c.OAuth.RateLimitTier + } + raw["claudeAiOauth"] = oauth + return json.MarshalIndent(raw, "", " ") +} + +// claudeExpiry reads expiresAt whether a version stored seconds or ms. +func claudeExpiry(v int64) time.Time { + if v < 1e12 { + return time.Unix(v, 0) + } + return time.UnixMilli(v) +} + +type claudeCredentialLocation struct { + path string + account string + keychain bool +} + +func readClaudeCredential() (claudeCredentials, claudeCredentialLocation, bool) { dir := os.Getenv("CLAUDE_CONFIG_DIR") if dir == "" { home, _ := os.UserHomeDir() dir = filepath.Join(home, ".claude") } - if _, err := os.Stat(filepath.Join(dir, ".credentials.json")); err == nil { - return true + path := filepath.Join(dir, ".credentials.json") + if b, err := os.ReadFile(path); err == nil { + if c, ok := parseClaudeCredentials(b); ok { + return c, claudeCredentialLocation{path: path}, true + } } - if runtime.GOOS == "darwin" { - // listing the item needs no Keychain prompt; reading it would - return exec.Command("security", "find-generic-password", "-s", "Claude Code-credentials").Run() == nil + if !claudeKeychain { + return claudeCredentials{}, claudeCredentialLocation{}, false } - return false + out, err := exec.Command("security", "find-generic-password", "-s", "Claude Code-credentials", "-w").Output() + if err != nil { + return claudeCredentials{}, claudeCredentialLocation{}, false + } + c, ok := parseClaudeCredentials(bytes.TrimSpace(out)) + return c, claudeCredentialLocation{keychain: true, account: os.Getenv("USER")}, ok +} + +func claudeCredential() (claudeCredentials, claudeCredentialLocation, bool) { + claudeCacheMu.Lock() + defer claudeCacheMu.Unlock() + if time.Since(claudeCacheAt) < claudeCacheTTL { + return claudeCacheC, claudeCacheLoc, claudeCacheOK + } + c, loc, ok := readClaudeCredential() + claudeCacheC, claudeCacheLoc, claudeCacheOK, claudeCacheAt = c, loc, ok, time.Now() + return c, loc, ok +} + +func cacheClaudeCredential(c claudeCredentials, loc claudeCredentialLocation) { + claudeCacheMu.Lock() + claudeCacheC, claudeCacheLoc, claudeCacheOK, claudeCacheAt = c, loc, true, time.Now() + claudeCacheMu.Unlock() +} + +// forgetClaudeCredential drops the cache; tests use it between homes. +func forgetClaudeCredential() { + claudeCacheMu.Lock() + claudeCacheAt = time.Time{} + claudeCacheMu.Unlock() +} + +func saveClaudeCredential(loc claudeCredentialLocation, c claudeCredentials) error { + b, err := c.marshal() + if err != nil { + return err + } + if !loc.keychain { + if err := os.WriteFile(loc.path, append(b, '\n'), 0o600); err != nil { + return err + } + } else { + args := []string{"add-generic-password", "-U", "-s", "Claude Code-credentials"} + if loc.account != "" { + args = append(args, "-a", loc.account) + } + args = append(args, "-w", string(b)) + if out, err := exec.Command("security", args...).CombinedOutput(); err != nil { + return fmt.Errorf("save Claude Code credentials: %v: %s", err, strings.TrimSpace(string(out))) + } + } + cacheClaudeCredential(c, loc) + return nil +} + +func claudeExecutable() string { + if p, err := exec.LookPath("claude"); err == nil { + return p + } + home, _ := os.UserHomeDir() + for _, p := range []string{filepath.Join(home, ".local", "bin", "claude"), "/usr/local/bin/claude", "/opt/homebrew/bin/claude"} { + if st, err := os.Stat(p); err == nil && !st.IsDir() { + return p + } + } + return "" +} + +// claudeIdentity asks Claude Code itself which account is active. Its credential +// blob intentionally contains tokens and plan metadata but no display identity; +// `claude auth status --json` is the authoritative, non-secret view shown by the +// CLI. Cache it briefly because the providers screen refreshes often. +func claudeIdentity() (string, string) { + claudeStatusMu.Lock() + defer claudeStatusMu.Unlock() + if time.Since(claudeStatusAt) < 30*time.Second { + return claudeStatusUser, claudeStatusPlan + } + claudeStatusAt = time.Now() + path := claudeExecutable() + if path == "" { + return claudeStatusUser, claudeStatusPlan + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, path, "auth", "status", "--json").Output() + if err != nil { + return claudeStatusUser, claudeStatusPlan + } + var status struct { + LoggedIn bool `json:"loggedIn"` + Email string `json:"email"` + SubscriptionType string `json:"subscriptionType"` + } + if json.Unmarshal(out, &status) == nil && status.LoggedIn { + claudeStatusUser = strings.TrimSpace(status.Email) + claudeStatusPlan = strings.TrimSpace(status.SubscriptionType) + } + return claudeStatusUser, claudeStatusPlan +} + +func claudeAccount() (Provider, bool) { + c, _, ok := claudeCredential() + if !ok { + return Provider{}, false + } + user, statusPlan := claudeIdentity() + plan := c.OAuth.SubscriptionType + if statusPlan != "" { + plan = statusPlan + } + if user == "" { + user = "Claude account" + if plan != "" { + user = "Claude " + strings.ToUpper(plan[:1]) + plan[1:] + } + } + acct := &Account{Agent: "claude", User: user, Plan: plan} + acct.sign = func(ctx context.Context, req *http.Request, body []byte) error { + tok, err := claudeToken(ctx) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+tok) + req.Header.Set("User-Agent", claudeUserAgent()) + req.Header.Set("X-Claude-Code-Session-Id", claudeSessionID()) + req.Header.Set("anthropic-beta", claudeBetaHeader(claudeModelOf(body))) + req.Header.Set("anthropic-dangerous-direct-browser-access", "true") + req.Header.Set("x-app", "cli") + req.Header.Set("x-client-request-id", randomUUID()) + for k, v := range claudeStainlessHeaders() { + req.Header.Set(k, v) + } + return nil + } + acct.body = claudeBody + acct.models = func() []catalog.Model { return catalog.Provider("anthropic") } + acct.fetch = func(ctx context.Context) ([]catalog.Model, error) { + ms, err := claudeModels(ctx) + if err != nil { + return nil, err + } + return ms, catalog.SaveLive("claude", claudeBase, ms) + } + return Provider{ID: "claude", Name: "Claude Code", Icon: "claudecode-color", Anthropic: claudeBase, + Catalog: "anthropic", Website: "https://claude.ai", Account: acct}, true +} + +// claudeModels asks Anthropic's Models API, authenticated with the account's +// own OAuth token, so the picker follows the vendor instead of a snapshot. +// Nothing here is compiled in: a new model shows up the moment Anthropic +// lists it (which is what the refresh button runs). +func claudeModels(ctx context.Context) ([]catalog.Model, error) { + tok, err := claudeToken(ctx) + if err != nil { + return nil, err + } + var out []catalog.Model + after := "" + for { + u := claudeBase + "/v1/models?limit=1000" + if after != "" { + u += "&after_id=" + url.QueryEscape(after) + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+tok) + req.Header.Set("anthropic-version", "2023-06-01") + req.Header.Set("anthropic-beta", claudeBetaHeader("")) + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", claudeUserAgent()) + res, err := http.DefaultClient.Do(req) + if err != nil { + return nil, errors.New("Claude model list: " + err.Error()) + } + b, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20)) + res.Body.Close() + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("Claude model list: %s", res.Status) + } + var page struct { + Data []struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + } `json:"data"` + HasMore bool `json:"has_more"` + LastID string `json:"last_id"` + } + if json.Unmarshal(b, &page) != nil { + return nil, errors.New("Claude model list: unexpected payload") + } + for _, m := range page.Data { + if m.ID == "" { + continue + } + name := m.DisplayName + if name == "" { + name = m.ID + } + out = append(out, catalog.Model{ID: m.ID, Name: name, Provider: "anthropic"}) + } + if !page.HasMore || page.LastID == "" || page.LastID == after { + break + } + after = page.LastID + } + if len(out) == 0 { + return nil, errors.New("Claude listed no models") + } + return out, nil +} + +// claudeFresh reports whether a token is usable for the next few minutes. +func claudeFresh(c claudeCredentials) bool { + return c.OAuth.AccessToken != "" && + (c.OAuth.ExpiresAt == 0 || time.Until(claudeExpiry(c.OAuth.ExpiresAt)) > 5*time.Minute) +} + +// claudeToken returns a usable access token, refreshing it through Anthropic +// when it is about to expire. A refresh rotates the refresh token, so the new +// pair goes back where Claude Code will look for it. +func claudeToken(ctx context.Context) (string, error) { + claudeMu.Lock() + defer claudeMu.Unlock() + c, loc, ok := claudeCredential() + if !ok { + return "", errors.New("Claude Code is signed out; run claude auth login") + } + if !claudeFresh(c) { + // Claude Code itself may have rotated the token since the cache was + // filled; a stale refresh token would be rejected, so look again. + if latest, latestLoc, ok := readClaudeCredential(); ok { + c, loc = latest, latestLoc + } + } + if claudeFresh(c) { + return c.OAuth.AccessToken, nil + } + if c.OAuth.RefreshToken == "" { + return "", errors.New("Claude Code OAuth token expired; run claude auth login") + } + body, _ := json.Marshal(map[string]string{"grant_type": "refresh_token", "refresh_token": c.OAuth.RefreshToken, + "client_id": claudeClientID}) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, claudeTokenURL, bytes.NewReader(body)) + if err != nil { + return "", err + } + req.Header.Set("Content-Type", "application/json") + res, err := http.DefaultClient.Do(req) + if err != nil { + return "", errors.New("Claude Code token refresh: " + err.Error()) + } + defer res.Body.Close() + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + var fresh struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + ExpiresIn int64 `json:"expires_in"` + } + if res.StatusCode != http.StatusOK || json.Unmarshal(b, &fresh) != nil || fresh.AccessToken == "" { + return "", errors.New("Claude Code is signed out (token refresh failed); run claude auth login") + } + c.OAuth.AccessToken = fresh.AccessToken + if fresh.RefreshToken != "" { + c.OAuth.RefreshToken = fresh.RefreshToken + } + if fresh.ExpiresIn > 0 { + c.OAuth.ExpiresAt = time.Now().Add(time.Duration(fresh.ExpiresIn) * time.Second).UnixMilli() + } + if err := saveClaudeCredential(loc, c); err != nil { + return "", err + } + return fresh.AccessToken, nil } // Accounts lists the signed-in agents as providers. @@ -122,6 +495,9 @@ func Accounts() []Provider { cfg = filepath.Join(home, ".config") } var out []Provider + if p, ok := claudeAccount(); ok { + out = append(out, p) + } if p, ok := codexAccount(home); ok { out = append(out, p) } @@ -399,18 +775,6 @@ func copilotAccount(cfg string) (Provider, bool) { } return nil } - acct.models = func() []catalog.Model { - if live, _, ok := catalog.Live("copilot"); ok { - return live - } - var out []catalog.Model - for _, m := range catalog.Builtin("copilot") { - if m.ID != "auto" { - out = append(out, m) - } - } - return out - } acct.fetch = func(ctx context.Context) ([]catalog.Model, error) { ms, err := copilotModels(ctx, app.Token) if err != nil { diff --git a/internal/provider/account_test.go b/internal/provider/account_test.go index b2a490ee5..061372913 100644 --- a/internal/provider/account_test.go +++ b/internal/provider/account_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "encoding/json" + "fmt" "net/http" "net/http/httptest" "os" @@ -34,6 +35,7 @@ func writeFile(t *testing.T, path string, v any) { // signIn writes a Codex and a Copilot login into a temp home. func signIn(t *testing.T) string { t.Helper() + isolate(t) home := t.TempDir() t.Setenv("HOME", home) t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) @@ -47,12 +49,29 @@ func signIn(t *testing.T) string { "refresh_token": "r", "account_id": "acct-1", }, }) + // Codex lists its models in its own cache; magpie reads that, nothing else. + writeFile(t, filepath.Join(home, ".codex", "models_cache.json"), map[string]any{ + "models": []any{map[string]any{"slug": "gpt-5.5", "display_name": "GPT-5.5", "visibility": "list", "priority": 1}}, + }) writeFile(t, filepath.Join(home, ".config", "github-copilot", "apps.json"), map[string]any{ "github.com:Iv1.x": map[string]any{"user": "octocat", "oauth_token": "gho_x"}, }) return home } +// isolate keeps tests off the machine's own Claude Code Keychain login and +// forgets anything a previous test cached. +func isolate(t *testing.T) { + t.Helper() + oldKeychain, oldURL, oldBase := claudeKeychain, claudeTokenURL, claudeBase + claudeKeychain = false + forgetClaudeCredential() + t.Cleanup(func() { + claudeKeychain, claudeTokenURL, claudeBase = oldKeychain, oldURL, oldBase + forgetClaudeCredential() + }) +} + func TestAccountsAreProviders(t *testing.T) { signIn(t) all := All() @@ -68,7 +87,7 @@ func TestAccountsAreProviders(t *testing.T) { for _, e := range Catalog() { ids = append(ids, e.ID) } - if !contains(ids, "codex/gpt-5.5") || !contains(ids, "copilot/claude-sonnet-4.5") || contains(ids, "copilot/auto") { + if !contains(ids, "codex/gpt-5.5") { t.Fatalf("catalog: %v", ids) } p, model, ok := Resolve("codex/gpt-5.5") @@ -101,6 +120,184 @@ func TestAccountsAreProviders(t *testing.T) { if _, ok := find(All(), "copilot"); ok { t.Fatal("copilot still listed after sign-out") } + + // no Claude credential in this home: no claude provider + if _, ok := find(All(), "claude"); ok { + t.Fatal("claude listed without credentials") + } +} + +// claudeSignIn writes a Claude Code OAuth login into a temp home. +func claudeSignIn(t *testing.T, home string, expiry time.Time) string { + t.Helper() + path := filepath.Join(home, ".claude", ".credentials.json") + writeFile(t, path, map[string]any{ + "claudeAiOauth": map[string]any{ + "accessToken": "sk-ant-oat01-old", "refreshToken": "sk-ant-ort01-old", + "expiresAt": expiry.UnixMilli(), "subscriptionType": "max", + "scopes": []string{"user:inference", "user:profile"}, + }, + // what magpie must not clobber when it writes a refreshed token back + "mcpOAuth": map[string]any{"plugin:slack:slack|x": map[string]any{"serverName": "Slack"}}, + }) + return path +} + +// claudeHome sets up a temp home with the usual env; the caller adds credentials. +func claudeHome(t *testing.T) string { + t.Helper() + isolate(t) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + forgetClaudeCredential() + return home +} + +func TestClaudeAccountIsProvider(t *testing.T) { + home := claudeHome(t) + creds := claudeSignIn(t, home, time.Now().Add(time.Hour)) + + // Anthropic lists its models live; magpie trusts that answer, not the binary. + models := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/models" || r.Header.Get("Authorization") != "Bearer sk-ant-oat01-old" { + w.WriteHeader(401) + return + } + json.NewEncoder(w).Encode(map[string]any{"has_more": false, "data": []any{ + map[string]any{"id": "claude-sonnet-5", "display_name": "Claude Sonnet 5"}, + map[string]any{"id": "claude-opus-5-5", "display_name": "Claude Opus 5.5"}, + }}) + })) + defer models.Close() + claudeBase = models.URL + + p, ok := find(All(), "claude") + if !ok || p.Account == nil || p.Account.User != "Claude Max" || p.Account.Plan != "max" || !p.Ready() { + t.Fatalf("claude: %+v %v", p, ok) + } + if p.Anthropic != claudeBase || p.Chat != "" || p.Responses != "" || p.Host() == "" { + t.Fatalf("endpoints: %+v", p) + } + + // nothing is compiled in: before a fetch there is nothing to show, and + // afterwards exactly what the vendor listed, "Opus 5.5" included + if got := len(p.Available()); got != 0 { + t.Fatalf("available before a fetch: %d", got) + } + if ms, err := p.Fetch(context.Background()); err != nil || len(ms) != 2 { + t.Fatalf("fetch: %v %v", ms, err) + } + p, _ = find(All(), "claude") + if at, ok := p.Fetched(); !ok || time.Since(at) > time.Minute { + t.Fatalf("not marked fetched: %v %v", at, ok) + } + var ids []string + for _, e := range Catalog() { + ids = append(ids, e.ID) + } + if !contains(ids, "claude/claude-opus-5-5") { + t.Fatalf("catalog: %v", ids) + } + if rp, model, ok := Resolve("claude/claude-opus-5-5"); !ok || rp.ID != "claude" || model != "claude-opus-5-5" { + t.Fatalf("resolve: %+v %q %v", rp, model, ok) + } + + // picks are saved, the login never is + if err := Save(Provider{ID: "claude", Name: "x", Models: []string{"claude-opus-5-5"}}); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(Path()) + if strings.Contains(string(b), "sk-ant-") || !strings.Contains(string(b), `"claude-opus-5-5"`) { + t.Fatalf("stored: %s", b) + } + p, _ = find(All(), "claude") + if p.Account == nil || len(p.Exposed()) != 1 || p.Exposed()[0].ID != "claude-opus-5-5" { + t.Fatalf("picks: %+v", p.Exposed()) + } + + req, _ := http.NewRequest("POST", p.Anthropic+"/v1/messages", nil) + req.Header.Set("anthropic-beta", "fine-grained-tool-streaming-2025-05-14") + if err := p.Sign(context.Background(), req, Anthropic, nil); err != nil { + t.Fatal(err) + } + if req.Header.Get("Authorization") != "Bearer sk-ant-oat01-old" { + t.Fatalf("auth: %q", req.Header.Get("Authorization")) + } + beta := req.Header.Get("anthropic-beta") + for _, want := range []string{"interleaved-thinking-2025-05-14", "oauth-2025-04-20", "claude-code-20250219", "effort-2025-11-24"} { + if !strings.Contains(beta, want) { + t.Fatalf("betas: %q", beta) + } + } + if ua := req.Header.Get("User-Agent"); !strings.HasPrefix(ua, "claude-cli/") || !strings.HasSuffix(ua, " (external, cli)") { + t.Fatalf("user-agent: %q", ua) + } + for _, h := range []string{"X-Claude-Code-Session-Id", "X-Client-Request-Id", "X-Stainless-Package-Version", "X-Stainless-Runtime-Version"} { + if req.Header.Get(h) == "" { + t.Fatalf("missing %s: %v", h, req.Header) + } + } + if req.Header.Get("x-app") != "cli" || req.Header.Get("anthropic-dangerous-direct-browser-access") != "true" { + t.Fatalf("Claude Code headers: %v", req.Header) + } + if prepared := p.Prepare([]byte(`{"model":"claude-sonnet-5","messages":[]}`)); !strings.Contains(string(prepared), "x-anthropic-billing-header") { + t.Fatalf("prepare: %s", prepared) + } + + // signing out of Claude Code removes the provider + os.Remove(creds) + forgetClaudeCredential() + if _, ok := find(All(), "claude"); ok { + t.Fatal("claude still listed after sign-out") + } +} + +func TestClaudeRefreshesToken(t *testing.T) { + home := claudeHome(t) + creds := claudeSignIn(t, home, time.Now().Add(-time.Minute)) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]string + json.NewDecoder(r.Body).Decode(&body) + if body["grant_type"] != "refresh_token" || body["client_id"] != claudeClientID || body["refresh_token"] != "sk-ant-ort01-old" { + w.WriteHeader(400) + return + } + json.NewEncoder(w).Encode(map[string]any{"access_token": "sk-ant-oat01-new", "refresh_token": "sk-ant-ort01-new", "expires_in": 3600}) + })) + defer srv.Close() + claudeTokenURL = srv.URL + + p, _ := find(All(), "claude") + req, _ := http.NewRequest("POST", p.Anthropic+"/v1/messages", nil) + if err := p.Sign(context.Background(), req, Anthropic, nil); err != nil { + t.Fatal(err) + } + if req.Header.Get("Authorization") != "Bearer sk-ant-oat01-new" { + t.Fatalf("auth: %q", req.Header.Get("Authorization")) + } + + // the rotated pair is written back where Claude Code will find it, and + // everything else in the file survives + var raw map[string]any + if !readJSON(creds, &raw) { + t.Fatalf("credentials unreadable: %s", creds) + } + oauth, _ := raw["claudeAiOauth"].(map[string]any) + if oauth["accessToken"] != "sk-ant-oat01-new" || oauth["refreshToken"] != "sk-ant-ort01-new" || oauth["subscriptionType"] != "max" { + t.Fatalf("oauth: %v", oauth) + } + if exp, _ := oauth["expiresAt"].(float64); exp <= float64(time.Now().UnixMilli()) { + t.Fatalf("expiry not advanced: %v", oauth["expiresAt"]) + } + if mcp, _ := raw["mcpOAuth"].(map[string]any); mcp == nil { + t.Fatalf("mcpOAuth lost: %v", raw) + } + if b, _ := os.ReadFile(creds); strings.Contains(string(b), "sk-ant-ort01-old") { + t.Fatalf("old refresh token kept: %s", b) + } } func TestCodexSignAndBody(t *testing.T) { @@ -193,3 +390,66 @@ func TestCopilotSignAndModels(t *testing.T) { t.Fatalf("api saw %v", got) } } + +func TestClaudeXXHash64(t *testing.T) { + if got := fmt.Sprintf("%016x", xxHash64(nil, 0)); got != "ef46db3751d8e999" { + t.Fatalf("xxhash empty vector: %s", got) + } +} + +func TestClaudeBillingBody(t *testing.T) { + billingFirst := func(b []byte) bool { + var m struct { + System []struct { + Text string `json:"text"` + } `json:"system"` + } + if json.Unmarshal(b, &m) != nil || len(m.System) == 0 { + return false + } + return strings.Contains(m.System[0].Text, "x-anthropic-billing-header") + } + + out := claudeBody([]byte(`{"model":"claude-sonnet-5","max_tokens":16,"stream":true,"messages":[{"role":"user","content":"hi"}]}`)) + if !billingFirst(out) { + t.Fatalf("no system: %s", out) + } + + out = claudeBody([]byte(`{"model":"m","system":"you are helpful","messages":[]}`)) + if !billingFirst(out) || !strings.Contains(string(out), "you are helpful") { + t.Fatalf("string system: %s", out) + } + + out = claudeBody([]byte(`{"model":"m","system":[{"type":"text","text":"be nice"}],"messages":[]}`)) + if !billingFirst(out) || !strings.Contains(string(out), "be nice") { + t.Fatalf("list system: %s", out) + } + + // Claude Code's own stale block is normalized so UA, cc_version and CCH + // remain mutually consistent. + in := []byte(`{"model":"m","system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.100.7c4; cc_entrypoint=sdk-cli;"}],"messages":[]}`) + out = claudeBody(in) + if !strings.Contains(string(out), "cc_version="+claudeClaimedVersion()+".") || strings.Contains(string(out), "cch=00000") || !strings.Contains(string(out), "You are Claude Code") { + t.Fatalf("stale identity not normalized: %s", out) + } + var cloaked map[string]any + if json.Unmarshal(out, &cloaked) != nil { + t.Fatalf("cloaked JSON: %s", out) + } + metadata, _ := cloaked["metadata"].(map[string]any) + if user, _ := metadata["user_id"].(string); !strings.Contains(user, "device_id") || !strings.Contains(user, "session_id") { + t.Fatalf("metadata identity: %v", metadata) + } + + // unrelated fields and model names survive + out = claudeBody([]byte(`{"model":"claude-sonnet-5","tools":[{"name":"x"}],"messages":[]}`)) + var m map[string]any + if json.Unmarshal(out, &m) != nil || m["model"] != "claude-sonnet-5" || m["tools"] == nil { + t.Fatalf("fields lost: %s", out) + } + + // a body that is not JSON is passed through + if out := claudeBody([]byte(`not json`)); string(out) != "not json" { + t.Fatalf("non-json: %s", out) + } +} diff --git a/internal/provider/claude_cloak.go b/internal/provider/claude_cloak.go new file mode 100644 index 000000000..3d7ea08b1 --- /dev/null +++ b/internal/provider/claude_cloak.go @@ -0,0 +1,305 @@ +package provider + +// Claude subscription requests must match Claude Code's wire identity. Anthropic +// uses these fields both for model-version gates and to attribute usage to the +// Pro/Max subscription rather than the extra-usage API bucket. This mirrors the +// current implementation in Alma's claude-subscription-service. + +import ( + "bytes" + "crypto/rand" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "sync" + "time" +) + +var ( + claudeIdentityMu sync.Mutex + claudeVersionAt time.Time + claudeVersion = claudeVersionFloor + claudeSession string +) + +var claudeSemverRE = regexp.MustCompile(`\d+\.\d+\.\d+`) + +func compareClaudeVersion(a, b string) int { + pa, pb := strings.Split(a, "."), strings.Split(b, ".") + for i := 0; i < 3; i++ { + var av, bv int + if i < len(pa) { + av, _ = strconv.Atoi(pa[i]) + } + if i < len(pb) { + bv, _ = strconv.Atoi(pb[i]) + } + if av < bv { + return -1 + } + if av > bv { + return 1 + } + } + return 0 +} + +// claudeClaimedVersion follows the locally installed auto-updating CLI, with a +// verified floor for machines where it cannot be found. +func claudeClaimedVersion() string { + claudeIdentityMu.Lock() + defer claudeIdentityMu.Unlock() + if time.Since(claudeVersionAt) < 10*time.Minute { + return claudeVersion + } + claudeVersionAt = time.Now() + if path := claudeExecutable(); path != "" { + if out, err := exec.Command(path, "--version").Output(); err == nil { + if installed := claudeSemverRE.FindString(string(out)); installed != "" && compareClaudeVersion(installed, claudeVersionFloor) > 0 { + claudeVersion = installed + } else { + claudeVersion = claudeVersionFloor + } + } + } + return claudeVersion +} + +func claudeUserAgent() string { + return "claude-cli/" + claudeClaimedVersion() + " (external, cli)" +} + +func randomUUID() string { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return fmt.Sprintf("%d", time.Now().UnixNano()) + } + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]) +} + +func claudeSessionID() string { + claudeIdentityMu.Lock() + defer claudeIdentityMu.Unlock() + if claudeSession == "" { + claudeSession = randomUUID() + } + return claudeSession +} + +func claudeDeviceID() string { + dir := os.Getenv("XDG_CONFIG_HOME") + if dir == "" { + home, _ := os.UserHomeDir() + dir = filepath.Join(home, ".config") + } + path := filepath.Join(dir, "magpie", "claude-device-id") + if b, err := os.ReadFile(path); err == nil { + s := strings.TrimSpace(string(b)) + if len(s) == 64 { + return s + } + } + var raw [32]byte + if _, err := rand.Read(raw[:]); err != nil { + return strings.Repeat("0", 64) + } + id := hex.EncodeToString(raw[:]) + _ = os.MkdirAll(filepath.Dir(path), 0o700) + _ = os.WriteFile(path, []byte(id+"\n"), 0o600) + return id +} + +func claudeFingerprint(text, version string) string { + var chars strings.Builder + for _, i := range []int{4, 7, 20} { + if i < len(text) { + chars.WriteByte(text[i]) + } else { + chars.WriteByte('0') + } + } + h := sha256.Sum256([]byte(claudeFingerprintSalt + chars.String() + version)) + return hex.EncodeToString(h[:])[:3] +} + +func firstClaudeUserText(messages any) string { + for _, raw := range asSlice(messages) { + m, _ := raw.(map[string]any) + if m["role"] != "user" { + continue + } + if s, ok := m["content"].(string); ok { + return s + } + for _, rawBlock := range asSlice(m["content"]) { + b, _ := rawBlock.(map[string]any) + if b["type"] == "text" { + s, _ := b["text"].(string) + return s + } + } + } + return "" +} + +func asSlice(v any) []any { s, _ := v.([]any); return s } + +func isClaudeSystemBlock(v any, needle string) bool { + m, _ := v.(map[string]any) + s, _ := m["text"].(string) + return strings.Contains(s, needle) +} + +// claudeBody adds Claude Code's billing/prefix/metadata identity and signs the +// final serialized body with the CCH hash. Existing genuine Claude Code blocks +// are retained but normalized to the currently claimed version. +func claudeBody(body []byte) []byte { + dec := json.NewDecoder(bytes.NewReader(body)) + dec.UseNumber() + var m map[string]any + if dec.Decode(&m) != nil || m == nil { + return body + } + + version := claudeClaimedVersion() + var system []any + switch v := m["system"].(type) { + case string: + if v != "" { + system = append(system, map[string]any{"type": "text", "text": v}) + } + case []any: + system = append(system, v...) + } + var rest []any + for _, block := range system { + if !isClaudeSystemBlock(block, "x-anthropic-billing-header") && !isClaudeSystemBlock(block, "You are Claude Code") { + rest = append(rest, block) + } + } + billing := fmt.Sprintf("x-anthropic-billing-header: cc_version=%s.%s; cc_entrypoint=cli; cch=00000;", + version, claudeFingerprint(firstClaudeUserText(m["messages"]), version)) + prefix := map[string]any{"type": "text", "text": "You are Claude Code, Anthropic's official CLI for Claude.", + "cache_control": map[string]any{"type": "ephemeral"}} + m["system"] = append([]any{map[string]any{"type": "text", "text": billing}, prefix}, rest...) + + metadata, _ := m["metadata"].(map[string]any) + if metadata == nil { + metadata = map[string]any{} + } + userID, _ := json.Marshal(map[string]string{"device_id": claudeDeviceID(), "account_uuid": "", "session_id": claudeSessionID()}) + metadata["user_id"] = string(userID) + m["metadata"] = metadata + + out, err := json.Marshal(m) + if err != nil { + return body + } + const marker = "cch=00000;" + if !bytes.Contains(out, []byte(marker)) { + return out + } + hash := xxHash64(out, claudeCCHSeed) & 0xfffff + repl := fmt.Sprintf("cch=%05x;", hash) + return bytes.Replace(out, []byte(marker), []byte(repl), 1) +} + +func claudeBetaHeader(model string) string { + if strings.Contains(strings.ToLower(model), "haiku") { + return claudeHaikuBetas + } + return claudeDefaultBetas +} + +func claudeModelOf(body []byte) string { + var m struct { + Model string `json:"model"` + } + _ = json.Unmarshal(body, &m) + return m.Model +} + +func claudeStainlessHeaders() map[string]string { + arch := map[string]string{"amd64": "x64", "arm64": "arm64"}[runtime.GOARCH] + if arch == "" { + arch = "x86" + } + operatingSystem := map[string]string{"darwin": "MacOS", "windows": "Windows", "freebsd": "FreeBSD"}[runtime.GOOS] + if operatingSystem == "" { + operatingSystem = "Linux" + } + return map[string]string{ + "X-Stainless-Lang": "js", "X-Stainless-Package-Version": claudeSDKVersion, + "X-Stainless-Runtime": "node", "X-Stainless-Runtime-Version": claudeRuntimeVersion, + "X-Stainless-Arch": arch, "X-Stainless-Os": operatingSystem, + "X-Stainless-Timeout": "600", "X-Stainless-Retry-Count": "0", + } +} + +// xxHash64 is the exact XXH64 variant Claude Code uses for CCH body signing. +func xxHash64(b []byte, seed uint64) uint64 { + const p1 uint64 = 11400714785074694791 + const p2 uint64 = 14029467366897019727 + const p3 uint64 = 1609587929392839161 + const p4 uint64 = 9650029242287828579 + const p5 uint64 = 2870177450012600261 + rot := func(x uint64, r uint) uint64 { return x<>(64-r) } + round := func(acc, input uint64) uint64 { acc += input * p2; acc = rot(acc, 31); return acc * p1 } + merge := func(acc, v uint64) uint64 { v = round(0, v); acc ^= v; return acc*p1 + p4 } + i := 0 + var h uint64 + if len(b) >= 32 { + v1, v2, v3, v4 := seed+p1+p2, seed+p2, seed, seed-p1 + for i <= len(b)-32 { + v1 = round(v1, binary.LittleEndian.Uint64(b[i:])) + i += 8 + v2 = round(v2, binary.LittleEndian.Uint64(b[i:])) + i += 8 + v3 = round(v3, binary.LittleEndian.Uint64(b[i:])) + i += 8 + v4 = round(v4, binary.LittleEndian.Uint64(b[i:])) + i += 8 + } + h = rot(v1, 1) + rot(v2, 7) + rot(v3, 12) + rot(v4, 18) + h = merge(h, v1) + h = merge(h, v2) + h = merge(h, v3) + h = merge(h, v4) + } else { + h = seed + p5 + } + h += uint64(len(b)) + for i+8 <= len(b) { + k := round(0, binary.LittleEndian.Uint64(b[i:])) + h ^= k + h = rot(h, 27)*p1 + p4 + i += 8 + } + if i+4 <= len(b) { + h ^= uint64(binary.LittleEndian.Uint32(b[i:])) * p1 + h = rot(h, 23)*p2 + p3 + i += 4 + } + for i < len(b) { + h ^= uint64(b[i]) * p5 + h = rot(h, 11) * p1 + i++ + } + h ^= h >> 33 + h *= p2 + h ^= h >> 29 + h *= p3 + h ^= h >> 32 + return h +} diff --git a/internal/provider/models.go b/internal/provider/models.go index fda39cc34..1c95998ce 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -15,16 +15,23 @@ func errorf(format string, a ...any) error { return fmt.Errorf(format, a...) } // manyModels is where "expose everything" stops being helpful. const manyModels = 24 -// Available lists every model the vendor is known to serve: its own list -// when fetched (see Fetch), else the models.dev catalog for the vendor. +// Available lists every model the vendor is known to serve: the list fetched +// from the vendor itself when there is one, over the models.dev catalog (or, +// for an account, whatever the agent's own sign-in can see). func (p Provider) Available() []catalog.Model { - if p.Account != nil && p.Account.models != nil { - return p.Account.models() + signedIn := p.Account != nil && p.Account.models != nil + var known []catalog.Model + if signedIn { + known = p.Account.models() + } else { + known = catalog.Provider(p.Catalog) } - known := catalog.Provider(p.Catalog) if live, _, ok := catalog.Live(p.ID); ok { return catalog.Decorate(live, known) } + if signedIn { + return known + } var out []catalog.Model for _, m := range known { if !strings.Contains(m.ID, "-exp") && !strings.Contains(m.ID, "preview") { @@ -81,24 +88,26 @@ func (p Provider) Exposed() []catalog.Model { if len(p.Models) > 0 { return pick(p.Models) } - if pr := Preset(p.Preset); pr != nil && len(pr.Defaults) > 0 { - if _, fetched := p.Fetched(); !fetched { - return pick(pr.Defaults) - } - var have []string - for _, id := range pr.Defaults { - if _, ok := byID[id]; ok { - have = append(have, id) - } - } - if len(have) > 0 { - return pick(have) - } - } if len(avail) <= manyModels { return avail } - return nil + // More than an agent's picker wants. Show the first slice of the + // vendor's own list — theirs run newest first — and let the user pick + // from the rest; nothing here is compiled in. + return avail[:manyModels] +} + +// RejectsTemperature reports whether the model is known to refuse +// temperature and top_p. The answer comes from the catalog — models.dev +// plus the vendor's own list — so a model released after this binary was +// built is handled without a code change. +func (p Provider) RejectsTemperature(model string) bool { + for _, m := range p.Available() { + if m.ID == model && m.Temperature != nil { + return !*m.Temperature + } + } + return false } // Chosen reports whether a model is exposed. diff --git a/internal/provider/models_test.go b/internal/provider/models_test.go new file mode 100644 index 000000000..1daa580c5 --- /dev/null +++ b/internal/provider/models_test.go @@ -0,0 +1,28 @@ +package provider + +import ( + "testing" + + "github.com/yetone/magpie/internal/catalog" +) + +func TestRejectsTemperatureFromFetchedList(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CACHE_HOME", home) + + no, yes := false, true + if err := catalog.SaveLive("p", "http://x", []catalog.Model{ + {ID: "strict", Name: "Strict", Temperature: &no}, + {ID: "plain", Name: "Plain", Temperature: &yes}, + {ID: "silent", Name: "Silent"}, + }); err != nil { + t.Fatal(err) + } + p := Provider{ID: "p"} + for model, want := range map[string]bool{"strict": true, "plain": false, "silent": false, "unknown": false} { + if got := p.RejectsTemperature(model); got != want { + t.Errorf("RejectsTemperature(%q) = %v, want %v", model, got, want) + } + } +} diff --git a/internal/provider/presets.go b/internal/provider/presets.go index 347260cf5..11e6e3858 100644 --- a/internal/provider/presets.go +++ b/internal/provider/presets.go @@ -13,37 +13,33 @@ const ( // PresetDef describes one preset. type PresetDef struct { - ID string `json:"id"` - Name string `json:"name"` - Icon string `json:"icon"` - Kind Kind `json:"kind"` - Chat string `json:"chat,omitempty"` - Responses string `json:"responses,omitempty"` - Anthropic string `json:"anthropic,omitempty"` - Catalog string `json:"catalog,omitempty"` - Defaults []string `json:"defaults,omitempty"` // models to expose until the user picks - Website string `json:"website,omitempty"` - KeysURL string `json:"keysUrl,omitempty"` - NoKey bool `json:"noKey,omitempty"` // local servers: a key is optional - Sponsored bool `json:"sponsored,omitempty"` // shown first, with a tag - Note string `json:"note,omitempty"` // one line under the name + ID string `json:"id"` + Name string `json:"name"` + Icon string `json:"icon"` + Kind Kind `json:"kind"` + Chat string `json:"chat,omitempty"` + Responses string `json:"responses,omitempty"` + Anthropic string `json:"anthropic,omitempty"` + Catalog string `json:"catalog,omitempty"` + Website string `json:"website,omitempty"` + KeysURL string `json:"keysUrl,omitempty"` + NoKey bool `json:"noKey,omitempty"` // local servers: a key is optional + Sponsored bool `json:"sponsored,omitempty"` // shown first, with a tag + Note string `json:"note,omitempty"` // one line under the name } // presets are ordered as they appear in the picker. var presets = []PresetDef{ {ID: "anthropic", Name: "Anthropic", Icon: "claude-color", Kind: KindVendor, Catalog: "anthropic", Anthropic: "https://api.anthropic.com", - Defaults: []string{"claude-fable-5-1", "claude-opus-5", "claude-sonnet-5", "claude-haiku-4-5-20251001"}, Website: "https://console.anthropic.com", KeysURL: "https://console.anthropic.com/settings/keys"}, {ID: "openai", Name: "OpenAI", Icon: "openai", Kind: KindVendor, Catalog: "openai", Chat: "https://api.openai.com/v1", Responses: "https://api.openai.com/v1", - Defaults: []string{"gpt-5.6-sol", "gpt-5.5", "gpt-5.3-codex"}, - Website: "https://platform.openai.com", KeysURL: "https://platform.openai.com/api-keys"}, + Website: "https://platform.openai.com", KeysURL: "https://platform.openai.com/api-keys"}, {ID: "google", Name: "Google Gemini", Icon: "gemini-color", Kind: KindVendor, Catalog: "google", - Chat: "https://generativelanguage.googleapis.com/v1beta/openai", - Note: "Gemini Developer API", - Defaults: []string{"gemini-3.1-pro", "gemini-3.5-flash", "gemini-2.5-pro", "gemini-2.5-flash"}, - Website: "https://aistudio.google.com", KeysURL: "https://aistudio.google.com/apikey"}, + Chat: "https://generativelanguage.googleapis.com/v1beta/openai", + Note: "Gemini Developer API", + Website: "https://aistudio.google.com", KeysURL: "https://aistudio.google.com/apikey"}, {ID: "deepseek", Name: "DeepSeek", Icon: "deepseek-color", Kind: KindVendor, Catalog: "deepseek", Chat: "https://api.deepseek.com/v1", Responses: "https://api.deepseek.com/v1", Anthropic: "https://api.deepseek.com/anthropic", Website: "https://platform.deepseek.com", KeysURL: "https://platform.deepseek.com/api_keys"}, diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go new file mode 100644 index 000000000..5fec731a3 --- /dev/null +++ b/internal/provider/subscription_usage.go @@ -0,0 +1,252 @@ +package provider + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +// QuotaWindow is one rolling allowance reported by a subscription provider. +type QuotaWindow struct { + Name string `json:"name"` + Used float64 `json:"used"` + ResetsAt *time.Time `json:"resetsAt,omitempty"` + ResetSecs int64 `json:"resetSecs,omitempty"` + Display string `json:"display,omitempty"` +} + +// SubscriptionQuota is provider-reported allowance usage. This is separate +// from Dial's local token log: vendors expose percentages, not token totals. +type SubscriptionQuota struct { + Provider string `json:"provider"` + Name string `json:"name"` + Icon string `json:"icon"` + Plan string `json:"plan,omitempty"` + Windows []QuotaWindow `json:"windows"` + Error string `json:"error,omitempty"` +} + +var subscriptionUsageCache struct { + sync.Mutex + at time.Time + data []SubscriptionQuota +} + +// SubscriptionUsage returns rolling quotas for signed-in first-party agents. +// Results are cached because these private account endpoints are aggressively +// rate limited when several CLI sessions are active. +func SubscriptionUsage(ctx context.Context) []SubscriptionQuota { + subscriptionUsageCache.Lock() + defer subscriptionUsageCache.Unlock() + if time.Since(subscriptionUsageCache.at) < time.Minute && subscriptionUsageCache.data != nil { + return append([]SubscriptionQuota(nil), subscriptionUsageCache.data...) + } + var out []SubscriptionQuota + if _, _, ok := claudeCredential(); ok { + out = append(out, claudeSubscriptionUsage(ctx)) + } + if home, err := os.UserHomeDir(); err == nil { + if _, ok := codexAccount(home); ok { + out = append(out, codexSubscriptionUsage(ctx, filepath.Join(home, ".codex", "auth.json"))) + } + cfg := os.Getenv("XDG_CONFIG_HOME") + if cfg == "" { + cfg = filepath.Join(home, ".config") + } + if app, ok := copilotLogin(cfg); ok { + out = append(out, copilotSubscriptionUsage(ctx, app.Token)) + } + } + subscriptionUsageCache.at, subscriptionUsageCache.data = time.Now(), out + return append([]SubscriptionQuota(nil), out...) +} + +func accountJSON(ctx context.Context, url, token string, headers map[string]string, dst any) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Accept", "application/json") + for k, v := range headers { + req.Header.Set(k, v) + } + res, err := http.DefaultClient.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + if res.StatusCode < 200 || res.StatusCode >= 300 { + return &accountStatusError{status: res.StatusCode} + } + return json.Unmarshal(b, dst) +} + +type accountStatusError struct{ status int } + +func (e *accountStatusError) Error() string { return http.StatusText(e.status) } + +func claudeSubscriptionUsage(ctx context.Context) SubscriptionQuota { + q := SubscriptionQuota{Provider: "claude", Name: "Claude Code", Icon: "claude-color", Windows: []QuotaWindow{}} + token, err := claudeToken(ctx) + if err != nil { + q.Error = err.Error() + return q + } + _, plan := claudeIdentity() + q.Plan = plan + var data struct { + FiveHour *quotaWire `json:"five_hour"` + SevenDay *quotaWire `json:"seven_day"` + SevenDayOpus *quotaWire `json:"seven_day_opus"` + SevenDaySonnet *quotaWire `json:"seven_day_sonnet"` + } + err = accountJSON(ctx, "https://api.anthropic.com/api/oauth/usage", token, map[string]string{ + "anthropic-beta": "oauth-2025-04-20", "user-agent": "magpie", + }, &data) + if err != nil { + q.Error = err.Error() + return q + } + for _, x := range []struct { + name string + w *quotaWire + }{{"5 hours", data.FiveHour}, {"7 days", data.SevenDay}, {"7 days · Opus", data.SevenDayOpus}, {"7 days · Sonnet", data.SevenDaySonnet}} { + if x.w != nil { + q.Windows = append(q.Windows, x.w.window(x.name)) + } + } + return q +} + +type quotaWire struct { + Utilization float64 `json:"utilization"` + ResetsAt string `json:"resets_at"` +} + +func (w quotaWire) window(name string) QuotaWindow { + out := QuotaWindow{Name: name, Used: w.Utilization} + if t, err := time.Parse(time.RFC3339, w.ResetsAt); err == nil { + out.ResetsAt = &t + } + return out +} + +func codexSubscriptionUsage(ctx context.Context, path string) SubscriptionQuota { + q := SubscriptionQuota{Provider: "codex", Name: "Codex", Icon: "codex-color", Windows: []QuotaWindow{}} + token, accountID, err := codexToken(ctx, path) + if err != nil { + q.Error = err.Error() + return q + } + var data struct { + PlanType string `json:"plan_type"` + RateLimit struct { + Primary *codexWindow `json:"primary_window"` + Secondary *codexWindow `json:"secondary_window"` + } `json:"rate_limit"` + } + base := strings.TrimSuffix(CodexBase, "/codex") + err = accountJSON(ctx, base+"/wham/usage", token, map[string]string{"chatgpt-account-id": accountID}, &data) + if err != nil { + q.Error = err.Error() + return q + } + q.Plan = data.PlanType + if data.RateLimit.Primary != nil { + q.Windows = append(q.Windows, data.RateLimit.Primary.window()) + } + if data.RateLimit.Secondary != nil { + q.Windows = append(q.Windows, data.RateLimit.Secondary.window()) + } + return q +} + +type codexWindow struct { + UsedPercent float64 `json:"used_percent"` + LimitWindowSecs int64 `json:"limit_window_seconds"` + ResetAt int64 `json:"reset_at"` + ResetAfterSecs int64 `json:"reset_after_seconds"` +} + +func quotaDurationName(seconds int64) string { + if seconds > 0 && seconds%(24*60*60) == 0 { + return fmt.Sprintf("%d days", seconds/(24*60*60)) + } + if seconds > 0 && seconds%(60*60) == 0 { + return fmt.Sprintf("%d hours", seconds/(60*60)) + } + return "Allowance" +} + +func (w codexWindow) window() QuotaWindow { + out := QuotaWindow{Name: quotaDurationName(w.LimitWindowSecs), Used: w.UsedPercent, ResetSecs: w.ResetAfterSecs} + if w.ResetAt > 0 { + t := time.Unix(w.ResetAt, 0) + out.ResetsAt = &t + } + return out +} + +func copilotSubscriptionUsage(ctx context.Context, githubToken string) SubscriptionQuota { + q := SubscriptionQuota{Provider: "copilot", Name: "Copilot", Icon: "githubcopilot", Windows: []QuotaWindow{}} + var data struct { + Plan string `json:"copilot_plan"` + Snapshots map[string]copilotQuotaWire `json:"quota_snapshots"` + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.github.com/copilot_internal/user", nil) + if err == nil { + req.Header.Set("Authorization", "token "+githubToken) + req.Header.Set("Accept", "application/json") + for k, v := range copilotHeaders { + req.Header.Set(k, v) + } + var res *http.Response + res, err = http.DefaultClient.Do(req) + if err == nil { + defer res.Body.Close() + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + if res.StatusCode < 200 || res.StatusCode >= 300 { + err = &accountStatusError{status: res.StatusCode} + } else { + err = json.Unmarshal(b, &data) + } + } + } + if err != nil { + q.Error = err.Error() + return q + } + q.Plan = data.Plan + for _, x := range []struct{ id, name string }{{"chat", "Chat requests"}, {"completions", "Completions"}, {"premium_interactions", "Premium requests"}} { + w, ok := data.Snapshots[x.id] + if !ok || !w.HasQuota || w.Entitlement <= 0 { + continue + } + used := w.Entitlement - w.Remaining + q.Windows = append(q.Windows, QuotaWindow{Name: x.name, Used: 100 * used / w.Entitlement, + Display: fmt.Sprintf("%s / %s", compactNumber(used), compactNumber(w.Entitlement))}) + } + return q +} + +type copilotQuotaWire struct { + HasQuota bool `json:"has_quota"` + Entitlement float64 `json:"entitlement"` + Remaining float64 `json:"quota_remaining"` +} + +func compactNumber(n float64) string { + if n == float64(int64(n)) { + return fmt.Sprintf("%d", int64(n)) + } + return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", n), "0"), ".") +} diff --git a/internal/provider/subscription_usage_test.go b/internal/provider/subscription_usage_test.go new file mode 100644 index 000000000..b1032d9a9 --- /dev/null +++ b/internal/provider/subscription_usage_test.go @@ -0,0 +1,30 @@ +package provider + +import "testing" + +func TestCodexQuotaUsesProviderWindowDuration(t *testing.T) { + for _, tt := range []struct { + seconds int64 + want string + }{{5 * 60 * 60, "5 hours"}, {7 * 24 * 60 * 60, "7 days"}, {0, "Allowance"}} { + if got := quotaDurationName(tt.seconds); got != tt.want { + t.Errorf("quotaDurationName(%d) = %q, want %q", tt.seconds, got, tt.want) + } + } + + w := codexWindow{UsedPercent: 16, LimitWindowSecs: 7 * 24 * 60 * 60} + if got := w.window(); got.Name != "7 days" || got.Used != 16 { + t.Fatalf("Codex window = %+v", got) + } +} + +func TestCompactQuotaNumber(t *testing.T) { + for _, tt := range []struct { + in float64 + want string + }{{7, "7"}, {7.5, "7.5"}, {7.25, "7.25"}} { + if got := compactNumber(tt.in); got != tt.want { + t.Errorf("compactNumber(%v) = %q, want %q", tt.in, got, tt.want) + } + } +} diff --git a/main.go b/main.go index d53d0984b..a4665dc7e 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,7 @@ import ( "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/claudebridge" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/profile" "github.com/yetone/magpie/internal/settings" @@ -115,6 +116,8 @@ func run(args []string) error { return serve() case "usage": return usageCmd(args) + case "claude-mcp-helper": // internal: stdio MCP subprocess spawned by Claude Code + return claudebridge.RunMCP(args[1:]) } a, err := agent.Find(args[0])