diff --git a/README.md b/README.md index d407b3365..f0723ba48 100644 --- a/README.md +++ b/README.md @@ -176,8 +176,16 @@ to be installed and signed in. Cursor, Grok and Devin subscriptions likewise run through their own CLIs — none of them has an endpoint a borrowed key can be sent to — with Devin driven over ACP (`devin acp`) in a home of magpie's own that keeps only the -caller's MCP tools and shares just the sign-in. A Gemini CLI Google login is -planned. +caller's MCP tools and shares just the sign-in. +Google sign-ins — Gemini CLI's and Antigravity's — talk to Google's Code +Assist API directly: magpie reads Gemini CLI's own login from `~/.gemini` or +signs one in itself, and refreshes the token in memory. Google no longer +serves Gemini CLI's sign-in to individual accounts, only to Gemini Code +Assist Standard and Enterprise, which need a Google Cloud project named +(`magpie accounts project gemini `, or +`GOOGLE_CLOUD_PROJECT` in `~/.gemini/.env`). Google may suspend an +Antigravity account it sees used outside Antigravity, so magpie asks before +adding one; use an account you can afford to lose. ### Connecting anything else diff --git a/accounts_cli.go b/accounts_cli.go index fa3c472af..9dded9ef7 100644 --- a/accounts_cli.go +++ b/accounts_cli.go @@ -17,19 +17,42 @@ import ( ) // accountsCmd: `magpie accounts [agent] [--json]`, `magpie accounts add `, -// `magpie accounts switch|forget ` +// `magpie accounts switch|forget `, +// `magpie accounts project ` // — the subscriptions magpie remembers, how much of each one's allowance is // used, and switching the agent between them. func accountsCmd(args []string) error { - const usage = "usage: magpie accounts [claude|codex|grok|copilot] [--json] | magpie accounts add | magpie accounts switch|forget " + const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity] [--json] | magpie accounts add | magpie accounts switch|forget | magpie accounts project " agentID := func(s string) (string, error) { switch strings.ToLower(s) { case "claude", "cc": return "claude", nil case "codex": return "codex", nil + case "gemini", "gemini-cli": + return "gemini", nil + case "antigravity", "ag": + return "antigravity", nil } - return "", fmt.Errorf("%q: only Claude Code and Codex accounts can be switched\n%s", s, usage) + return "", fmt.Errorf("%q: only Claude Code, Codex, Gemini CLI and Antigravity accounts can be added and switched\n%s", s, usage) + } + if len(args) > 1 && args[1] == "project" { + if len(args) != 5 { + return fmt.Errorf("%s", usage) + } + id, err := agentID(args[2]) + if err != nil { + return err + } + if err := provider.SetGoogleProject(id, args[3], args[4]); err != nil { + return err + } + if strings.TrimSpace(args[4]) == "" { + fmt.Println(green.Render("✓"), args[3], "no longer names a Google Cloud project") + } else { + fmt.Println(green.Render("✓"), args[3], "now uses Google Cloud project", args[4]) + } + return nil } if len(args) > 1 && args[1] == "add" { if len(args) != 3 { @@ -59,6 +82,10 @@ func accountsCmd(args []string) error { if err := provider.SwitchLogin(id, args[3]); err != nil { return err } + if id == "gemini" || id == "antigravity" { + fmt.Println(green.Render("✓"), "magpie now uses", args[3], "for", id) + return nil + } fmt.Println(green.Render("✓"), id, "is now signed in as", args[3], muted.Render("· sessions already running keep their account until restarted")) return nil } @@ -85,7 +112,7 @@ func accountsCmd(args []string) error { return nil } if len(ls) == 0 { - fmt.Println(muted.Render("no accounts yet ·"), "add one: magpie accounts add ") + fmt.Println(muted.Render("no accounts yet ·"), "add one: magpie accounts add ") return nil } width := 0 @@ -213,6 +240,15 @@ func untilShort(d time.Duration) string { // addAccount signs in to one more subscription in the browser, the way the // window's "Add account" does. func addAccount(agentID string) error { + if agentID == "antigravity" { + fmt.Println(bold.Render("!"), provider.AntigravityRisk) + fmt.Print("Sign in anyway? [y/N] ") + var yes string + fmt.Scanln(&yes) + if !strings.EqualFold(strings.TrimSpace(yes), "y") && !strings.EqualFold(strings.TrimSpace(yes), "yes") { + return fmt.Errorf("sign-in canceled") + } + } st, err := provider.StartSignIn(agentID) if err != nil { return err diff --git a/internal/gateway/codeassist.go b/internal/gateway/codeassist.go new file mode 100644 index 000000000..7ef4488d5 --- /dev/null +++ b/internal/gateway/codeassist.go @@ -0,0 +1,480 @@ +package gateway + +import ( + "encoding/json" + "regexp" + "strings" +) + +// ---- Google Code Assist (provider side) -------------------------------------- +// +// Gemini CLI and Antigravity sign in with Google and talk to Code Assist +// (cloudcode-pa.googleapis.com), which takes a Gemini request wrapped in an +// envelope — {model, project, request} — and streams replies wrapped the +// same way, {response}. The gateway builds {model, request}; the account +// adds the project and the ids its app sends when it signs the request. + +// skipSignature stands in for a thought signature on a function call the +// model didn't make here: Google checks the ones Gemini 3 hands out, and +// this one tells it not to. +const skipSignature = "skip_thought_signature_validator" + +var unsafeToolID = regexp.MustCompile(`[^a-zA-Z0-9_-]`) + +// buildCodeAssist builds the Code Assist envelope for a request, for the +// app the account belongs to: "gemini" or "antigravity". +func buildCodeAssist(r *Request, model, agent string) []byte { + ag := agent == "antigravity" + claude := strings.Contains(strings.ToLower(model), "claude") + toolID := func(id string) string { + if !ag || id == "" { + return id + } + return unsafeToolID.ReplaceAllString(id, "_") + } + names := map[string]string{} + var contents []map[string]any + for _, m := range r.Messages { + role := "user" + if m.Role == "assistant" { + role = "model" + } + var parts []map[string]any + for _, p := range m.Parts { + switch p.Kind { + case Text: + if p.Text != "" { + parts = append(parts, map[string]any{"text": p.Text}) + } + case Image: + if p.Data != "" { + parts = append(parts, map[string]any{"inlineData": map[string]any{"mimeType": p.MediaType, "data": p.Data}}) + } else if p.URL != "" { + parts = append(parts, map[string]any{"fileData": map[string]any{"mimeType": p.MediaType, "fileUri": p.URL}}) + } + case ToolCall: + names[p.ID] = p.Name + call := map[string]any{"name": p.Name, "args": json.RawMessage(argsOf(p))} + if id := toolID(p.ID); id != "" { + call["id"] = id + } + parts = append(parts, map[string]any{"functionCall": call, "thoughtSignature": skipSignature}) + case ToolResult: + name := names[p.CallID] + if name == "" { + name = "tool" + } + key := "output" + switch { + case ag: + key = "result" + case p.IsError: + key = "error" + } + res := map[string]any{"name": name, "response": map[string]any{key: p.Text}} + if id := toolID(p.CallID); id != "" { + res["id"] = id + } + parts = append(parts, map[string]any{"functionResponse": res}) + } + // thinking isn't sent back: its signatures belong to whoever + // made them, and Google turns away ones it didn't + } + if len(parts) == 0 { + continue + } + if n := len(contents); n > 0 && contents[n-1]["role"] == role { + contents[n-1]["parts"] = append(contents[n-1]["parts"].([]map[string]any), parts...) + continue + } + contents = append(contents, map[string]any{"role": role, "parts": parts}) + } + req := map[string]any{"contents": contents} + if r.System != "" { + req["systemInstruction"] = map[string]any{"role": "user", "parts": []map[string]any{{"text": r.System}}} + } + + if len(r.Tools) > 0 && r.ToolChoice != "none" { + var decls []map[string]any + for _, t := range r.Tools { + d := map[string]any{"name": t.Name} + if t.Description != "" { + d["description"] = t.Description + } + schema := t.Schema + if len(schema) == 0 { + schema = json.RawMessage(`{"type":"object","properties":{}}`) + } + if ag { + d["parameters"] = plainSchema(schema) + } else { + d["parametersJsonSchema"] = schema + } + decls = append(decls, d) + } + req["tools"] = []map[string]any{{"functionDeclarations": decls}} + mode := "AUTO" + fc := map[string]any{} + switch { + case r.ToolChoice == "required": + mode = "ANY" + case strings.HasPrefix(r.ToolChoice, "name:"): + mode = "ANY" + fc["allowedFunctionNames"] = []string{strings.TrimPrefix(r.ToolChoice, "name:")} + case ag && claude: + // Antigravity's Claude wants its calls checked against the schema + mode = "VALIDATED" + } + fc["mode"] = mode + req["toolConfig"] = map[string]any{"functionCallingConfig": fc} + } + + gen := map[string]any{} + if r.MaxTokens > 0 && (!ag || claude) { + gen["maxOutputTokens"] = r.MaxTokens + } + if r.Temp != nil { + gen["temperature"] = *r.Temp + } + if r.TopP != nil { + gen["topP"] = *r.TopP + } + if len(r.Stop) > 0 { + gen["stopSequences"] = r.Stop + } + if tc := thinkingConfig(r, model, claude); tc != nil { + gen["thinkingConfig"] = tc + // Claude's answer has to have room past its thinking + if b, ok := tc["thinkingBudget"].(int); ok && claude && gen["maxOutputTokens"] == nil { + gen["maxOutputTokens"] = b + 32000 + } + } + if len(gen) > 0 { + req["generationConfig"] = gen + } + b, _ := json.Marshal(map[string]any{"model": model, "request": req}) + return b +} + +// thinkingConfig says how hard the model should think: a level for +// Gemini 3, a budget for the rest. A model that doesn't think gets none. +func thinkingConfig(r *Request, model string, claude bool) map[string]any { + m := strings.ToLower(model) + if strings.HasPrefix(m, "gpt-oss") || claude && !strings.Contains(m, "thinking") { + return nil + } + if r.Effort == "" && !r.Thinking { + // Claude asked to think still has to be told how much + if !claude { + return nil + } + } + tc := map[string]any{"includeThoughts": true} + if strings.HasPrefix(m, "gemini-3") || strings.HasPrefix(m, "gemini-pro-agent") { + if r.Effort != "" { + level := "high" + if r.Effort == "low" { + level = "low" + } + tc["thinkingLevel"] = level + } + return tc + } + budget := budgetOf(effortOf(r.Effort)) + if claude && r.MaxTokens > 0 && budget >= r.MaxTokens { + budget = r.MaxTokens - 1 + if budget < 1024 { + return nil + } + } + tc["thinkingBudget"] = budget + return tc +} + +// plainSchema is a JSON schema cut down to what Antigravity's function +// declarations take: an OpenAPI-style subset with no references, unions +// or keywords outside it. +func plainSchema(raw json.RawMessage) json.RawMessage { + var root map[string]any + if json.Unmarshal(raw, &root) != nil { + return raw + } + defs := map[string]any{} + for _, k := range []string{"$defs", "definitions"} { + if d, ok := root[k].(map[string]any); ok { + for n, v := range d { + defs[n] = v + } + } + } + var walk func(v any, depth int) any + walk = func(v any, depth int) any { + switch x := v.(type) { + case []any: + out := make([]any, len(x)) + for i, e := range x { + out[i] = walk(e, depth) + } + return out + case map[string]any: + if depth > 32 { + return map[string]any{"type": "object"} + } + if ref, ok := x["$ref"].(string); ok { + name := ref[strings.LastIndex(ref, "/")+1:] + if d, ok := defs[name]; ok { + return walk(d, depth+1) + } + return map[string]any{"type": "object"} + } + // allOf: one schema with all the members' fields + if all, ok := x["allOf"].([]any); ok { + merged := map[string]any{} + for k, v := range x { + if k != "allOf" { + merged[k] = v + } + } + for _, e := range all { + if m, ok := walk(e, depth+1).(map[string]any); ok { + for k, v := range m { + if k == "properties" { + props, _ := merged["properties"].(map[string]any) + if props == nil { + props = map[string]any{} + } + for pk, pv := range v.(map[string]any) { + props[pk] = pv + } + merged["properties"] = props + } else if _, has := merged[k]; !has { + merged[k] = v + } + } + } + } + return walk(merged, depth+1) + } + // anyOf / oneOf: the first member that isn't null, nullable + for _, k := range []string{"anyOf", "oneOf"} { + if alts, ok := x[k].([]any); ok { + var pick map[string]any + nullable := false + for _, a := range alts { + m, _ := a.(map[string]any) + if m["type"] == "null" { + nullable = true + } else if pick == nil && m != nil { + pick = m + } + } + out := map[string]any{} + if pick != nil { + if m, ok := walk(pick, depth+1).(map[string]any); ok { + out = m + } + } + if d, ok := x["description"].(string); ok && out["description"] == nil { + out["description"] = d + } + if nullable { + out["nullable"] = true + } + if out["type"] == nil { + out["type"] = "string" + } + return out + } + } + out := map[string]any{} + for k, v := range x { + switch k { + case "$schema", "$defs", "definitions", "$id", "$comment", "additionalProperties", "format", "default", + "examples", "example", "title", "patternProperties", "enumDescriptions", "prefill", "deprecated", + "propertyNames", "unevaluatedProperties", "readOnly", "writeOnly", "const": + case "type": + if ts, ok := v.([]any); ok { + for _, t := range ts { + if t == "null" { + out["nullable"] = true + } else if out["type"] == nil { + out["type"] = t + } + } + } else { + out["type"] = v + } + case "properties": + props := map[string]any{} + if m, ok := v.(map[string]any); ok { + for pk, pv := range m { + props[pk] = walk(pv, depth+1) + } + } + out[k] = props + case "items": + out[k] = walk(v, depth+1) + case "enum": + // Google takes string enums only + if es, ok := v.([]any); ok { + strs := make([]any, 0, len(es)) + for _, e := range es { + if s, ok := e.(string); ok { + strs = append(strs, s) + } + } + if len(strs) == len(es) { + out[k] = strs + } + } + default: + out[k] = walk(v, depth+1) + } + } + if c, ok := x["const"]; ok { + if s, ok := c.(string); ok { + out["enum"] = []any{s} + } + } + if out["type"] == nil { + switch { + case out["properties"] != nil: + out["type"] = "object" + case out["items"] != nil: + out["type"] = "array" + } + } + if req, ok := out["required"].([]any); ok { + // required names only the properties there are + props, _ := out["properties"].(map[string]any) + keep := []any{} + for _, n := range req { + if s, ok := n.(string); ok && props[s] != nil { + keep = append(keep, s) + } + } + if len(keep) == 0 { + delete(out, "required") + } else { + out["required"] = keep + } + } + return out + } + return v + } + b, err := json.Marshal(walk(root, 0)) + if err != nil { + return raw + } + return b +} + +// codeAssistDecoder reads Code Assist's stream: Gemini chunks, each wrapped +// in {response}. +type codeAssistDecoder struct { + started bool + tools bool + stopped bool + usage *Usage +} + +func (d *codeAssistDecoder) decode(data string, emit func(Event)) error { + var ch struct { + Response *geminiChunk `json:"response"` + Error *struct { + Message string `json:"message"` + } `json:"error"` + geminiChunk + } + if err := json.Unmarshal([]byte(data), &ch); err != nil { + return nil + } + if ch.Error != nil { + emit(Event{Kind: KError, Text: ch.Error.Message}) + return nil + } + c := ch.geminiChunk + if ch.Response != nil { + c = *ch.Response + } + if !d.started { + d.started = true + emit(Event{Kind: KStart, MsgID: c.ResponseID, Model: c.ModelVersion}) + } + if c.UsageMetadata != nil { + u := c.UsageMetadata + d.usage = &Usage{Input: max(u.Prompt-u.Cached, 0), CacheRead: u.Cached, + Output: u.Candidates + u.Thoughts, Reasoning: u.Thoughts} + } + for _, cand := range c.Candidates { + for _, p := range cand.Content.Parts { + switch { + case p.FunctionCall != nil: + id := p.FunctionCall.ID + if id == "" { + id = "call_" + newID() + } + args := p.FunctionCall.Args + if len(args) == 0 || string(args) == "null" { + args = json.RawMessage("{}") + } + d.tools = true + emit(Event{Kind: KToolStart, ID: id, Name: p.FunctionCall.Name}) + emit(Event{Kind: KToolArgs, Text: string(args)}) + case p.Thought: + if p.Text != "" { + emit(Event{Kind: KThink, Text: p.Text}) + } + if p.Signature != "" { + emit(Event{Kind: KSig, Text: p.Signature}) + } + case p.Text != "": + emit(Event{Kind: KText, Text: p.Text}) + } + } + if cand.FinishReason != "" && !d.stopped { + d.stopped = true + stop := stopFromGemini(cand.FinishReason) + if d.tools && stop == "stop" { + stop = "tool" + } + emit(Event{Kind: KStop, Stop: stop}) + } + } + if d.stopped && d.usage != nil { + emit(Event{Kind: KUsage, Usage: *d.usage}) + d.usage = nil + } + return nil +} + +type geminiChunk struct { + Candidates []struct { + Content struct { + Parts []gPart `json:"parts"` + } `json:"content"` + FinishReason string `json:"finishReason"` + } `json:"candidates"` + UsageMetadata *struct { + Prompt int `json:"promptTokenCount"` + Candidates int `json:"candidatesTokenCount"` + Thoughts int `json:"thoughtsTokenCount"` + Cached int `json:"cachedContentTokenCount"` + } `json:"usageMetadata"` + ModelVersion string `json:"modelVersion"` + ResponseID string `json:"responseId"` +} + +func stopFromGemini(s string) string { + switch s { + case "MAX_TOKENS": + return "length" + case "STOP", "FINISH_REASON_UNSPECIFIED", "OTHER": + return "stop" + case "MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL": + return "stop" + } + // SAFETY, RECITATION, BLOCKLIST, PROHIBITED_CONTENT, SPII, ... + return "filter" +} diff --git a/internal/gateway/codeassist_test.go b/internal/gateway/codeassist_test.go new file mode 100644 index 000000000..c9d5894ab --- /dev/null +++ b/internal/gateway/codeassist_test.go @@ -0,0 +1,143 @@ +package gateway + +import ( + "encoding/json" + "strings" + "testing" +) + +func codeAssistRequest(t *testing.T) *Request { + t.Helper() + r, err := parseAnthropic([]byte(`{"model":"x","max_tokens":2000,"system":"be brief","stream":true, + "thinking":{"type":"enabled","budget_tokens":4000}, + "tools":[{"name":"read","description":"read a file","input_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object", + "properties":{"path":{"type":["string","null"],"format":"uri"},"mode":{"const":"r"},"opts":{"$ref":"#/$defs/Opts"}, + "n":{"anyOf":[{"type":"integer"},{"type":"null"}]}},"required":["path","gone"],"additionalProperties":false, + "$defs":{"Opts":{"type":"object","properties":{"deep":{"type":"boolean","default":false}}}}}}], + "messages":[ + {"role":"user","content":"read a"}, + {"role":"assistant","content":[{"type":"thinking","thinking":"hm","signature":"sig-from-claude"}, + {"type":"text","text":"ok"},{"type":"tool_use","id":"toolu_01:x","name":"read","input":{"path":"a"}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01:x","content":"A!"}]}, + {"role":"user","content":"and?"}]}`)) + if err != nil { + t.Fatal(err) + } + return r +} + +func TestBuildCodeAssistForGemini(t *testing.T) { + var env struct { + Model string `json:"model"` + Request map[string]any `json:"request"` + } + json.Unmarshal(buildCodeAssist(codeAssistRequest(t), "gemini-2.5-pro", "gemini"), &env) + req := env.Request + if env.Model != "gemini-2.5-pro" { + t.Errorf("model %q", env.Model) + } + b, _ := json.Marshal(req) + s := string(b) + for _, want := range []string{ + `"systemInstruction":{"parts":[{"text":"be brief"}],"role":"user"}`, + `"functionCall":{"args":{"path":"a"},"id":"toolu_01:x","name":"read"},"thoughtSignature":"skip_thought_signature_validator"`, + `"functionResponse":{"id":"toolu_01:x","name":"read","response":{"output":"A!"}}`, + `"parametersJsonSchema":{`, + `"thinkingConfig":{"includeThoughts":true,"thinkingBudget":4096}`, + `"maxOutputTokens":2000`, + } { + if !strings.Contains(s, want) { + t.Errorf("missing %s in\n%s", want, s) + } + } + if strings.Contains(s, "sig-from-claude") || strings.Contains(s, `"hm"`) { + t.Error("thinking was sent back") + } + // the tool result and the next question are one user turn + contents := req["contents"].([]any) + if len(contents) != 3 || len(contents[2].(map[string]any)["parts"].([]any)) != 2 { + t.Errorf("contents = %v", contents) + } +} + +func TestBuildCodeAssistForAntigravity(t *testing.T) { + var env struct { + Request map[string]any `json:"request"` + } + json.Unmarshal(buildCodeAssist(codeAssistRequest(t), "claude-sonnet-4-6", "antigravity"), &env) + b, _ := json.Marshal(env.Request) + s := string(b) + for _, want := range []string{ + `"id":"toolu_01_x"`, + `"response":{"result":"A!"}`, + `"mode":"VALIDATED"`, + `"maxOutputTokens":2000`, + } { + if !strings.Contains(s, want) { + t.Errorf("missing %s in\n%s", want, s) + } + } + // Sonnet here doesn't think + if strings.Contains(s, "thinkingConfig") { + t.Error("thinking asked of a model that doesn't") + } + decl := env.Request["tools"].([]any)[0].(map[string]any)["functionDeclarations"].([]any)[0].(map[string]any) + params, _ := json.Marshal(decl["parameters"]) + want := `{"properties":{"mode":{"enum":["r"]},"n":{"nullable":true,"type":"integer"},"opts":{"properties":{"deep":{"type":"boolean"}},"type":"object"},"path":{"nullable":true,"type":"string"}},"required":["path"],"type":"object"}` + if string(params) != want { + t.Errorf("parameters =\n%s\nwant\n%s", params, want) + } + + // a Gemini model on Antigravity has no output cap sent, and a thinking + // Claude has room past its budget + json.Unmarshal(buildCodeAssist(codeAssistRequest(t), "gemini-3-flash", "antigravity"), &env) + if gen, _ := env.Request["generationConfig"].(map[string]any); gen["maxOutputTokens"] != nil { + t.Errorf("gen = %v", gen) + } + r := codeAssistRequest(t) + r.MaxTokens = 0 + env.Request = nil + json.Unmarshal(buildCodeAssist(r, "claude-opus-4-6-thinking", "antigravity"), &env) + gen := env.Request["generationConfig"].(map[string]any) + tc := gen["thinkingConfig"].(map[string]any) + if tc["thinkingBudget"].(float64) >= gen["maxOutputTokens"].(float64) { + t.Errorf("gen = %v", gen) + } +} + +func TestCodeAssistDecoder(t *testing.T) { + var got []Event + d := &codeAssistDecoder{} + for _, line := range []string{ + `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"let me see","thought":true}]}}],"modelVersion":"gemini-2.5-pro","responseId":"r1"},"traceId":"t"}`, + `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"Reading."}]}}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":3}}}`, + `{"response":{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"read","args":{"path":"a"}},"thoughtSignature":"abc"}]},"finishReason":"STOP"}], + "usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":10,"thoughtsTokenCount":20,"cachedContentTokenCount":40}}}`, + } { + d.decode(line, func(ev Event) { got = append(got, ev) }) + } + kinds := []EventKind{KStart, KThink, KText, KToolStart, KToolArgs, KStop, KUsage} + if len(got) != len(kinds) { + t.Fatalf("events = %+v", got) + } + for i, k := range kinds { + if got[i].Kind != k { + t.Fatalf("event %d = %+v, want kind %d", i, got[i], k) + } + } + if got[0].Model != "gemini-2.5-pro" || got[3].Name != "read" || got[3].ID == "" || got[4].Text != `{"path":"a"}` { + t.Errorf("events = %+v", got) + } + if got[5].Stop != "tool" { + t.Errorf("stop = %q", got[5].Stop) + } + if u := got[6].Usage; u != (Usage{Input: 60, CacheRead: 40, Output: 30, Reasoning: 20}) { + t.Errorf("usage = %+v", u) + } + + var errs []Event + (&codeAssistDecoder{}).decode(`{"error":{"code":429,"message":"quota"}}`, func(ev Event) { errs = append(errs, ev) }) + if len(errs) != 1 || errs[0].Kind != KError || errs[0].Text != "quota" { + t.Errorf("error events = %+v", errs) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 70a1d76b9..c7b7669cf 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -217,7 +217,7 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) { 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" || p.Account.Agent == "cursor" || p.Account.Agent == "grok" || p.Account.Agent == "devin") { + if ok && p.Account != nil && (p.Account.Agent == "claude" || p.Account.Agent == "cursor" || p.Account.Agent == "grok" || p.Account.Agent == "devin" || p.Account.Agent == "gemini" || p.Account.Agent == "antigravity") { req, err := parseAnthropic(body) if err != nil { writeError(w, provider.Anthropic, 400, err.Error()) @@ -733,6 +733,9 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to } for { body := build(to, req, model, p.Host(), p.RejectsTemperature(model)) + if to == provider.CodeAssist && p.Account != nil { + body = buildCodeAssist(req, model, p.Account.Agent) + } res, err := s.forward(ctx, p, to, pathOf(to), p.Prepare(body), in) if err != nil || res.StatusCode < 400 { return res, to, err @@ -854,6 +857,8 @@ func pathOf(proto provider.Protocol) string { return "/chat/completions" case provider.Responses: return "/responses" + case provider.CodeAssist: + return "/v1internal:streamGenerateContent?alt=sse" } return "/v1/messages" } @@ -888,6 +893,9 @@ func decoder(proto provider.Protocol) func(data string, emit func(Event)) error case provider.Responses: d := &responsesDecoder{} return d.decode + case provider.CodeAssist: + d := &codeAssistDecoder{} + return d.decode } return decodeAnthropic } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index a5e5102d0..f572a3427 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1171,6 +1171,7 @@ function accountPlan(a) { if (a.agent === "claude") return "Claude" + (a.plan ? " " + a.plan[0].toUpperCase() + a.plan.slice(1) : ""); if (a.agent === "cursor") return "Cursor" + (a.plan ? " " + a.plan[0].toUpperCase() + a.plan.slice(1) : ""); if (a.agent === "grok") return "Grok"; + if (a.agent === "gemini" || a.agent === "antigravity") return a.plan || "Google"; return t("signed in"); } @@ -2709,13 +2710,22 @@ const SUBS = [ { agent: "copilot", name: "Copilot", icon: "githubcopilot", plans: "Pro · Pro+ · Business", own: true }, // devin's credentials.toml keeps one account too { agent: "devin", name: "Devin", icon: "devin", plans: "Pro · Enterprise", single: true }, + // Google's sign-ins; Gemini CLI's own account is read too + { agent: "gemini", name: "Gemini CLI", icon: "geminicli-color", plans: "Code Assist Standard · Enterprise", own: true }, + { agent: "antigravity", name: "Antigravity", icon: "antigravity-color", plans: "Google AI Pro · Ultra · free", risk: true }, ]; const subOf = (agent) => SUBS.find((x) => x.agent === agent); let signing = null; // the sign-in under way: { id, agent, url, state, error } let justAdded = ""; // the account that just came in, to greet it -async function startSignIn(agent) { +async function startSignIn(agent, risky) { if (signing?.state === "waiting") api("signin/" + signing.id + "/cancel", {}).catch(() => {}); + // an account Google may suspend is added only once that is said + if (subOf(agent)?.risk && !risky) { + signing = { agent, state: "risk" }; + renderProviders(); + return; + } signing = { agent, state: "starting" }; renderProviders(); try { @@ -2763,12 +2773,24 @@ function cancelSignIn() { function renderSigning(sub) { const box = el("div", "signing" + (signing.state === "failed" ? " failed" : "")); const tt = el("span", "tt"); + if (signing.state === "risk") { + box.append(el("span", "mark", "!")); + tt.append(el("span", "n", t("{name} accounts can be suspended", { name: sub.name })), + el("span", "s", t("Google may suspend an Antigravity account it sees used outside Antigravity. Use one you can afford to lose."))); + box.append(tt); + const go = el("button", "text primary", t("Sign in anyway")); + go.onclick = () => startSignIn(sub.agent, true); + const close = el("button", "text", t("Cancel")); + close.onclick = cancelSignIn; + box.append(close, go); + return box; + } if (signing.state === "failed") { box.append(el("span", "mark", "!")); tt.append(el("span", "n", t("Sign-in didn't finish")), el("span", "s", signing.error || "")); box.append(tt); const again = el("button", "text primary", t("Try again")); - again.onclick = () => startSignIn(sub.agent); + again.onclick = () => startSignIn(sub.agent, true); const close = el("button", "text", t("Cancel")); close.onclick = cancelSignIn; box.append(close, again); @@ -2865,6 +2887,14 @@ function loginUsageOf(agent) { return u.data; } +// quotaError says why an allowance can't be read: a Google account with +// no Cloud project named can't be used at all until one is, so that is +// said outright; anything else is in the tooltip. +function quotaError(err) { + if (/magpie accounts project/.test(err)) return t("Needs a Google Cloud project — hover for how"); + return t("Usage unavailable"); +} + // accountQuota: an account's allowance as a line of small meters under its // name, the reset time on the ones nearly used up. function accountQuota(data, user) { @@ -2875,7 +2905,7 @@ function accountQuota(data, user) { } const q = data[user]; if (!q || q.error || !q.windows?.length) { - line.append(el("span", "aq-none", q?.error ? t("Usage unavailable") : t("No usage reported"))); + line.append(el("span", "aq-none", q?.error ? quotaError(q.error) : t("No usage reported"))); if (q?.error) line.title = q.error; return line; } @@ -3277,7 +3307,7 @@ function quotaWindows(sub) { return b; } if (sub.error) { - const e = el("div", "subscription-error", t("Usage unavailable")); + const e = el("div", "subscription-error", quotaError(sub.error)); e.title = sub.error; return e; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 0dcc75e49..4dadb3490 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -211,6 +211,9 @@ const I18N = { "1 account · add another": "1 个账号 · 再添加一个", "{n} accounts · add another": "{n} 个账号 · 再添加一个", "Finish signing in to {name} in your browser": "请在浏览器中完成 {name} 登录", + "{name} accounts can be suspended": "{name} 账号可能被封禁", + "Google may suspend an Antigravity account it sees used outside Antigravity. Use one you can afford to lose.": "Google 发现 Antigravity 账号在 Antigravity 之外使用时,可能会封禁该账号。请用一个丢了也无妨的账号。", + "Sign in anyway": "仍然登录", "magpie opened the sign-in page. The account shows up here as soon as you're done.": "magpie 已打开登录页面,完成后账号会立即出现在这里。", "Open again": "重新打开", "Copy link": "复制链接", @@ -407,6 +410,7 @@ const I18N = { "Auto + Composer": "Auto + Composer", "Total": "合计", "Usage unavailable": "暂时无法获取用量", + "Needs a Google Cloud project — hover for how": "需要指定 Google Cloud 项目,悬停查看方法", "Resets {when}": "重置于 {when}", "Allowance": "用量额度", "Chat requests": "聊天请求", diff --git a/internal/gui/assets/icons/antigravity-color.svg b/internal/gui/assets/icons/antigravity-color.svg new file mode 100644 index 000000000..3ed10ab65 --- /dev/null +++ b/internal/gui/assets/icons/antigravity-color.svg @@ -0,0 +1 @@ +Antigravity \ No newline at end of file diff --git a/internal/gui/providers.go b/internal/gui/providers.go index e76758024..90520a0dc 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -174,6 +174,8 @@ func providerInfo(p provider.Provider, agents []*agent.Agent) providerJSON { out.Account.Name, out.Account.Icon = "Cursor CLI", "cursor" } else if a.Agent == "grok" { out.Account.Name, out.Account.Icon = "Grok CLI", "xai" + } else if a.Agent == "antigravity" { + out.Account.Name, out.Account.Icon = "Antigravity", "antigravity-color" } out.Account.Logins = provider.Logins(a.Agent) } diff --git a/internal/provider/account.go b/internal/provider/account.go index f97a1ff2a..52f95f88c 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -50,6 +50,10 @@ type Account struct { // logins_on.go): the access token to run the agent's binary with. token func(ctx context.Context) (string, error) + // codeAssist is where a Gemini CLI or Antigravity account's requests + // go (google.go). + codeAssist string + sign func(ctx context.Context, req *http.Request, body []byte) error body func(body []byte) []byte // request tweaks the backend insists on models func() []catalog.Model @@ -581,6 +585,11 @@ func Accounts() []Provider { if p, ok := devinAccount(); ok { out = append(out, p) } + for _, agent := range []string{"gemini", "antigravity"} { + if p, ok := googleAccountOf(agent); ok { + out = append(out, p) + } + } return out } diff --git a/internal/provider/google.go b/internal/provider/google.go new file mode 100644 index 000000000..ddd801eaa --- /dev/null +++ b/internal/provider/google.go @@ -0,0 +1,1003 @@ +package provider + +// Google's subscriptions: Gemini CLI's and Antigravity's Google sign-ins. +// Both are served by Google's Code Assist backend (cloudcode-pa), which +// speaks Gemini's API wrapped in an envelope of its own, under a Google +// Cloud project Code Assist gives the account. magpie signs in with each +// app's own OAuth client, keeps the tokens in logins.json and refreshes +// them in memory; Gemini CLI's own sign-in (~/.gemini/oauth_creds.json) is +// read, never written. The gateway speaks the envelope (gateway/codeassist.go). +// +// Google no longer serves Gemini CLI's sign-in to individuals: only a Code +// Assist Standard or Enterprise account, with a Google Cloud project of +// its own, gets an answer. Antigravity's serves individuals, but Google +// may suspend an account it sees used outside Antigravity. + +import ( + "bufio" + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "runtime" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/catalog" +) + +// CodeAssist is Google's Code Assist API, which magpie only speaks +// upstream, to a Gemini CLI or Antigravity account. Not in Protocols: no +// other provider serves it. +const CodeAssist Protocol = "codeassist" + +// googleApp is one of Google's apps whose sign-in magpie borrows. +type googleApp struct { + agent, name, icon, website string + clientID, clientSecret string + scopes []string + callback string // the path the browser comes back to + loopback string // the host it comes back to + base string // where requests go + loadBase string // where the account's project is found +} + +// Google's endpoints; vars so tests can point them elsewhere. +var ( + googleAuthorizeURL = "https://accounts.google.com/o/oauth2/v2/auth" + googleTokenURL = "https://oauth2.googleapis.com/token" + googleUserInfoURL = "https://www.googleapis.com/oauth2/v2/userinfo?alt=json" + codeAssistProd = "https://cloudcode-pa.googleapis.com" + codeAssistDaily = "https://daily-cloudcode-pa.googleapis.com" + antigravityVersionURL = "https://antigravity-hub-auto-updater-974169037036.us-central1.run.app/manifest/latest-arm64-mac.yml" +) + +var geminiApp = googleApp{ + agent: "gemini", name: "Gemini CLI", icon: "geminicli-color", website: "https://github.com/google-gemini/gemini-cli", + // Gemini CLI's own OAuth client, an installed app's (its "secret" is + // no secret: it ships in the CLI) + clientID: "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com", + clientSecret: "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", + scopes: []string{"https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"}, + callback: "/oauth2callback", loopback: "127.0.0.1", +} + +var antigravityApp = googleApp{ + agent: "antigravity", name: "Antigravity", icon: "antigravity-color", website: "https://antigravity.google", + clientID: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com", + clientSecret: "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", + scopes: []string{"https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", + "https://www.googleapis.com/auth/cclog", "https://www.googleapis.com/auth/experimentsandconfigs"}, + callback: "/oauth-callback", loopback: "localhost", +} + +func googleAppOf(agent string) (googleApp, bool) { + switch agent { + case "gemini": + a := geminiApp + a.base, a.loadBase = codeAssistProd, codeAssistProd + return a, true + case "antigravity": + a := antigravityApp + a.base, a.loadBase = codeAssistDaily, codeAssistProd + return a, true + } + return googleApp{}, false +} + +// AntigravityRisk is what magpie says before an Antigravity account is +// added. +const AntigravityRisk = "Google may suspend an Antigravity account it sees used outside Antigravity. Use one you can afford to lose." + +// geminiCLIVersion is the Gemini CLI magpie says it is. +const geminiCLIVersion = "0.54.4" + +// googleAuth is a Google sign-in as logins.json keeps it; Gemini CLI's +// oauth_creds.json has the same fields. +type googleAuth struct { + AccessToken string `json:"access_token,omitempty"` + RefreshToken string `json:"refresh_token"` + Expiry int64 `json:"expiry_date,omitempty"` // Unix ms + // Project is the Google Cloud project requests are billed to: the one + // Code Assist gave the account, or one the user named (Code Assist + // Standard and Enterprise ask for one). + Project string `json:"project,omitempty"` +} + +// googleAccount is one signed-in Google account of an app. +type googleAccount struct { + app googleApp + user string + auth googleAuth + own bool // Gemini CLI's own sign-in +} + +// geminiDir is where Gemini CLI keeps its sign-in. +func geminiDir() string { + home, _ := os.UserHomeDir() + return filepath.Join(home, ".gemini") +} + +// geminiOwnLogin reads Gemini CLI's own Google sign-in. +func geminiOwnLogin() (googleAccount, bool) { + var a googleAuth + if !readJSON(filepath.Join(geminiDir(), "oauth_creds.json"), &a) || a.RefreshToken == "" { + return googleAccount{}, false + } + var accts struct { + Active string `json:"active"` + } + readJSON(filepath.Join(geminiDir(), "google_accounts.json"), &accts) + user := accts.Active + if user == "" { + user = "Google" + } + // the project Gemini CLI is told to use, in its own .env + a.Project = envFileValue(filepath.Join(geminiDir(), ".env"), "GOOGLE_CLOUD_PROJECT") + if a.Project == "" { + a.Project = savedGoogleProject("gemini", user) + } + app, _ := googleAppOf("gemini") + return googleAccount{app: app, user: user, auth: a, own: true}, true +} + +// envFileValue is one KEY=value of a dotenv file. +func envFileValue(path, key string) string { + f, err := os.Open(path) + if err != nil { + return "" + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + line = strings.TrimPrefix(line, "export ") + k, v, ok := strings.Cut(line, "=") + if !ok || strings.TrimSpace(k) != key { + continue + } + v = strings.TrimSpace(v) + if uq, err := strconv.Unquote(v); err == nil { + v = uq + } else { + v = strings.Trim(v, `'`) + } + return v + } + return "" +} + +// savedGoogleProject is the project the user named for the agent's own +// account, which logins.json keeps beside it. +func savedGoogleProject(agent, user string) string { + loginsMu.Lock() + defer loginsMu.Unlock() + for _, l := range readLogins() { + if l.Agent == agent && strings.EqualFold(l.User, user) { + return l.Project + } + } + return "" +} + +// googleSaved is the sign-in of an account magpie keeps. +func googleSaved(agent string, l savedLogin) (googleAccount, bool) { + var a googleAuth + if l.own() || json.Unmarshal(l.Auth, &a) != nil || a.RefreshToken == "" { + return googleAccount{}, false + } + if l.Project != "" { + a.Project = l.Project + } + app, _ := googleAppOf(agent) + return googleAccount{app: app, user: l.User, auth: a}, true +} + +type googleLogin struct { + Login + acct googleAccount +} + +// googleLogins lists an app's accounts, the first in use first. +func googleLogins(agent string) []googleLogin { + own, hasOwn := googleAccount{}, false + if agent == "gemini" { + own, hasOwn = geminiOwnLogin() + } + ownUser := "" + if hasOwn { + ownUser = own.user + } + var out []googleLogin + for _, l := range sideLogins(agent, ownUser, func(l savedLogin) bool { + _, ok := googleSaved(agent, l) + return ok + }) { + a := own + if !l.saved.own() { + a, _ = googleSaved(agent, l.saved) + } + a.user = l.User + out = append(out, googleLogin{l.Login, a}) + } + return out +} + +func googleSide(agent string) []sideLogin { + var out []sideLogin + for _, g := range googleLogins(agent) { + out = append(out, sideLogin{Login: g.Login}) + } + return out +} + +func googleLoginList(agent string) []Login { return loginsOf(googleSide(agent)) } + +func switchGoogleLogin(agent, user string) error { + return switchSideLogin(agent, user, googleSide(agent)) +} + +func setGoogleLoginOn(agent, user string, on bool) error { + return setSideLoginOn(agent, user, on, googleSide(agent)) +} + +func forgetGoogleLogin(agent, user string) error { + return forgetSideLogin(agent, user, "Gemini CLI's own sign-in; sign out there (/auth)", googleSide(agent), nil) +} + +// addGoogleLogin keeps an account magpie just signed in. +func addGoogleLogin(agent, user, plan string, a googleAuth) error { + auth, _ := json.Marshal(a) + return addSideLogin(savedLogin{Agent: agent, User: user, Plan: plan, Auth: auth, Project: a.Project}, func(savedLogin) {}) +} + +// SetGoogleProject names the Google Cloud project an account's requests +// go to, "" to let Code Assist pick; Code Assist Standard and Enterprise +// need one. +func SetGoogleProject(agent, user, project string) error { + if _, ok := googleAppOf(agent); !ok { + return fmt.Errorf("only Gemini CLI and Antigravity accounts have a Google Cloud project") + } + found := false + for _, l := range googleLogins(agent) { + if strings.EqualFold(l.User, user) { + found = true + } + } + if !found { + return fmt.Errorf("no %s account %q", agent, user) + } + googleState.Lock() + for k := range googleState.projects { + if strings.HasPrefix(k, agent+"\x00") { + delete(googleState.projects, k) + } + } + googleState.Unlock() + return editSideLogin(agent, user, func(ls []savedLogin, i int) ([]savedLogin, error) { + ls[i].Project = strings.TrimSpace(project) + return ls, nil + }) +} + +// googleState is what magpie learned of each sign-in while it runs: the +// access token, refreshed in memory (Google's refresh tokens don't turn +// over, so nothing needs writing back), and the project and plan Code +// Assist gave it. +var googleState = struct { + sync.Mutex + tokens map[string]googleAuth // by refresh token + projects map[string]googleProject +}{tokens: map[string]googleAuth{}, projects: map[string]googleProject{}} + +type googleProject struct { + id, plan string +} + +// token is a live access token for the account. +func (g googleAccount) token(ctx context.Context) (string, error) { + googleState.Lock() + t, ok := googleState.tokens[g.auth.RefreshToken] + googleState.Unlock() + if !ok { + t = g.auth + } + if t.AccessToken != "" && time.Until(time.UnixMilli(t.Expiry)) > 2*time.Minute { + return t.AccessToken, nil + } + form := url.Values{"grant_type": {"refresh_token"}, "refresh_token": {g.auth.RefreshToken}, + "client_id": {g.app.clientID}, "client_secret": {g.app.clientSecret}} + var fresh struct { + AccessToken string `json:"access_token"` + ExpiresIn int64 `json:"expires_in"` + } + if err := postToken(ctx, googleTokenURL, "application/x-www-form-urlencoded", []byte(form.Encode()), &fresh); err != nil || fresh.AccessToken == "" { + how := "sign in again from magpie" + if g.own { + how = "run gemini and sign in again" + } + msg := "no token" + if err != nil { + msg = err.Error() + } + return "", fmt.Errorf("%s is signed out (%s); %s", g.app.name, msg, how) + } + t = googleAuth{AccessToken: fresh.AccessToken, RefreshToken: g.auth.RefreshToken, + Expiry: time.Now().Add(time.Duration(fresh.ExpiresIn) * time.Second).UnixMilli()} + googleState.Lock() + googleState.tokens[g.auth.RefreshToken] = t + googleState.Unlock() + return t.AccessToken, nil +} + +// userAgent is what the app says it is to Code Assist. +func (g googleApp) userAgent(model string) string { + if g.agent == "antigravity" { + return "antigravity/hub/" + antigravityVersion() + " " + runtime.GOOS + "/" + runtime.GOARCH + } + platform := map[string]string{"darwin": "darwin", "windows": "win32", "linux": "linux"}[runtime.GOOS] + arch := map[string]string{"amd64": "x64", "arm64": "arm64"}[runtime.GOARCH] + if model == "" { + model = "gemini-2.5-pro" + } + return fmt.Sprintf("GeminiCLI/%s/%s (%s; %s; terminal)", geminiCLIVersion, model, platform, arch) +} + +var antigravityVer struct { + sync.Mutex + v string + at time.Time +} + +// antigravityVersion is the newest Antigravity's version, which its +// requests carry; asked of its updater at most every few hours. +func antigravityVersion() string { + antigravityVer.Lock() + defer antigravityVer.Unlock() + if antigravityVer.v != "" && time.Since(antigravityVer.at) < 6*time.Hour { + return antigravityVer.v + } + antigravityVer.at = time.Now() + if antigravityVer.v == "" { + antigravityVer.v = "2.9.1" + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, antigravityVersionURL, nil) + if err != nil { + return antigravityVer.v + } + req.Header.Set("User-Agent", "electron-builder") + res, err := http.DefaultClient.Do(req) + if err != nil { + return antigravityVer.v + } + defer res.Body.Close() + sc := bufio.NewScanner(io.LimitReader(res.Body, 64<<10)) + for sc.Scan() { + if v, ok := strings.CutPrefix(sc.Text(), "version:"); ok { + v = strings.Trim(strings.TrimSpace(v), `'"`) + if v != "" && strings.Trim(v, "0123456789.") == "" { + antigravityVer.v = v + } + break + } + } + return antigravityVer.v +} + +// call posts one of Code Assist's methods. +func (g googleAccount) call(ctx context.Context, base, method string, body, out any, headers map[string]string) error { + tok, err := g.token(ctx) + if err != nil { + return err + } + b, _ := json.Marshal(body) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/v1internal:"+method, bytes.NewReader(b)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+tok) + req.Header.Set("User-Agent", g.app.userAgent("")) + 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() + rb, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20)) + if res.StatusCode != http.StatusOK { + return fmt.Errorf("%s: %s", g.app.name, APIError(rb, res.Status)) + } + if out == nil { + return nil + } + return json.Unmarshal(rb, out) +} + +type codeAssistTier struct { + ID string `json:"id"` + Name string `json:"name"` + IsDefault bool `json:"isDefault"` + UserDefinedCloudaicompanionProject bool `json:"userDefinedCloudaicompanionProject"` +} + +// companionProject is Code Assist's project, which comes as an id or as +// {id, name}. +type companionProject string + +func (p *companionProject) UnmarshalJSON(b []byte) error { + var s string + if json.Unmarshal(b, &s) == nil { + *p = companionProject(s) + return nil + } + var o struct { + ID string `json:"id"` + } + if err := json.Unmarshal(b, &o); err != nil { + return nil + } + *p = companionProject(o.ID) + return nil +} + +// project is the Google Cloud project the account's requests go to, found +// (and the account set up for Code Assist, the first time) the way the +// app does it, and the plan it is on. +func (g googleAccount) project(ctx context.Context) (googleProject, error) { + key := g.app.agent + "\x00" + g.auth.RefreshToken + googleState.Lock() + p, ok := googleState.projects[key] + googleState.Unlock() + if ok { + return p, nil + } + var err error + if g.app.agent == "antigravity" { + p, err = g.antigravityProject(ctx) + } else { + p, err = g.geminiProject(ctx) + } + if err != nil { + return googleProject{}, err + } + googleState.Lock() + googleState.projects[key] = p + googleState.Unlock() + return p, nil +} + +type loadCodeAssistReply struct { + CurrentTier *codeAssistTier `json:"currentTier"` + PaidTier *codeAssistTier `json:"paidTier"` + AllowedTiers []codeAssistTier `json:"allowedTiers"` + CloudaicompanionProject companionProject `json:"cloudaicompanionProject"` + IneligibleTiers []struct { + ReasonCode string `json:"reasonCode"` + ReasonMessage string `json:"reasonMessage"` + TierID string `json:"tierId"` + } `json:"ineligibleTiers"` +} + +func (r loadCodeAssistReply) plan() string { + t := r.PaidTier + if t == nil || t.Name == "" { + t = r.CurrentTier + } + if t == nil { + return "" + } + if t.Name != "" { + return t.Name + } + return t.ID +} + +func (r loadCodeAssistReply) defaultTier() codeAssistTier { + for _, t := range r.AllowedTiers { + if t.IsDefault { + return t + } + } + if len(r.AllowedTiers) > 0 { + return r.AllowedTiers[0] + } + return codeAssistTier{ID: "legacy-tier", UserDefinedCloudaicompanionProject: true} +} + +// geminiProject sets the account up as Gemini CLI does (its setupUser). +func (g googleAccount) geminiProject(ctx context.Context) (googleProject, error) { + meta := map[string]any{"ideType": "IDE_UNSPECIFIED", "platform": "PLATFORM_UNSPECIFIED", "pluginType": "GEMINI"} + want := g.auth.Project + body := map[string]any{"metadata": meta} + if want != "" { + meta["duetProject"] = want + body["cloudaicompanionProject"] = want + } + var load loadCodeAssistReply + if err := g.call(ctx, g.app.loadBase, "loadCodeAssist", body, &load, nil); err != nil { + return googleProject{}, err + } + if load.CurrentTier != nil { + if load.CloudaicompanionProject != "" { + return googleProject{string(load.CloudaicompanionProject), load.plan()}, nil + } + if want != "" { + return googleProject{want, load.plan()}, nil + } + return googleProject{}, g.needsProject("") + } + tier := load.defaultTier() + if tier.UserDefinedCloudaicompanionProject && want == "" { + why := "" + for _, t := range load.IneligibleTiers { + if t.ReasonMessage != "" { + why = t.ReasonMessage + break + } + } + return googleProject{}, g.needsProject(why) + } + req := map[string]any{"tierId": tier.ID, "metadata": meta} + if tier.ID != "free-tier" { + req["cloudaicompanionProject"] = want + } + id, err := g.onboard(ctx, g.app.loadBase, req, nil) + if err != nil { + return googleProject{}, err + } + if id == "" { + id = want + } + if id == "" { + return googleProject{}, g.needsProject("") + } + return googleProject{id, tier.Name}, nil +} + +// needsProject says a Code Assist Standard or Enterprise account needs a +// Google Cloud project named, with Google's reason when it gave one. +func (g googleAccount) needsProject(why string) error { + msg := "Google serves Gemini CLI's sign-in only to Gemini Code Assist Standard and Enterprise, which bill a Google Cloud project: name it with `magpie accounts project gemini " + g.user + " `" + if g.own { + msg += " or GOOGLE_CLOUD_PROJECT in ~/.gemini/.env" + } + if why != "" { + msg = why + " — " + msg + } + return errors.New(msg) +} + +// antigravityProject sets the account up as Antigravity does. +func (g googleAccount) antigravityProject(ctx context.Context) (googleProject, error) { + if g.auth.Project != "" { + return googleProject{id: g.auth.Project}, nil + } + var load loadCodeAssistReply + body := map[string]any{"metadata": map[string]any{"ideType": "ANTIGRAVITY"}} + if err := g.call(ctx, g.app.loadBase, "loadCodeAssist", body, &load, nil); err != nil { + return googleProject{}, err + } + if load.CloudaicompanionProject != "" { + return googleProject{string(load.CloudaicompanionProject), load.plan()}, nil + } + tier := load.defaultTier() + if tier.ID == "" || tier.ID == "legacy-tier" { + tier.ID = "free-tier" + } + req := map[string]any{"tier_id": tier.ID, "metadata": map[string]any{ + "ide_type": "ANTIGRAVITY", "ide_version": antigravityVersion(), "ide_name": "antigravity"}} + hdr := map[string]string{ + "User-Agent": g.app.userAgent("") + " google-api-nodejs-client/10.3.0", + "X-Goog-Api-Client": "gl-node/22.21.1", + } + id, err := g.onboard(ctx, g.app.base, req, hdr) + if err != nil { + return googleProject{}, err + } + if id == "" { + return googleProject{}, errors.New("Antigravity gave this account no project; sign in to Antigravity once, then try again") + } + return googleProject{id, tier.Name}, nil +} + +// onboardPoll is how long onboarding waits between asks; a var for tests. +var onboardPoll = 2 * time.Second + +// onboard sets the account up for Code Assist, asking again until it is +// done, and returns the project it was given. +func (g googleAccount) onboard(ctx context.Context, base string, req map[string]any, hdr map[string]string) (string, error) { + for i := 0; i < 5; i++ { + var lro struct { + Done bool `json:"done"` + Response struct { + Project companionProject `json:"cloudaicompanionProject"` + } `json:"response"` + } + if err := g.call(ctx, base, "onboardUser", req, &lro, hdr); err != nil { + return "", err + } + if lro.Done { + return string(lro.Response.Project), nil + } + select { + case <-ctx.Done(): + return "", ctx.Err() + case <-time.After(onboardPoll): + } + } + return "", errors.New(g.app.name + ": setting the account up for Code Assist is taking long; try again in a minute") +} + +// ---- models ------------------------------------------------------------------- + +// geminiModels are the models Gemini CLI offers, when Code Assist doesn't +// say which this account has. +var geminiModels = []catalog.Model{ + {ID: "gemini-3.1-pro-preview", Name: "Gemini 3.1 Pro Preview"}, + {ID: "gemini-3-pro-preview", Name: "Gemini 3 Pro Preview"}, + {ID: "gemini-3-flash-preview", Name: "Gemini 3 Flash Preview"}, + {ID: "gemini-3.1-flash-lite-preview", Name: "Gemini 3.1 Flash Lite Preview"}, + {ID: "gemini-2.5-pro", Name: "Gemini 2.5 Pro"}, + {ID: "gemini-2.5-flash", Name: "Gemini 2.5 Flash"}, + {ID: "gemini-2.5-flash-lite", Name: "Gemini 2.5 Flash Lite"}, +} + +// antigravityModels are the models Antigravity offers, when it doesn't say. +var antigravityModels = []catalog.Model{ + {ID: "gemini-pro-agent", Name: "Gemini 3.1 Pro (High)"}, + {ID: "gemini-3.1-pro-low", Name: "Gemini 3.1 Pro (Low)"}, + {ID: "gemini-3-flash", Name: "Gemini 3 Flash"}, + {ID: "gemini-3.1-flash-lite", Name: "Gemini 3.1 Flash Lite"}, + {ID: "claude-opus-4-6-thinking", Name: "Claude Opus 4.6 (Thinking)"}, + {ID: "claude-sonnet-4-6", Name: "Claude Sonnet 4.6"}, + {ID: "gpt-oss-120b-medium", Name: "GPT-OSS 120B (Medium)"}, +} + +// antigravityHidden are the models Antigravity lists that aren't for chat. +var antigravityHidden = map[string]bool{ + "chat_20706": true, "chat_23310": true, "tab_flash_lite_preview": true, "tab_jump_flash_lite_preview": true, + "gemini-2.5-flash-thinking": true, "gemini-2.5-pro": true, +} + +// googleModelInfo is one model an account has, with how much of its +// allowance is left. +type googleModelInfo struct { + catalog.Model + remaining float64 // 0..1, -1 not known + resets time.Time +} + +// modelInfo asks Code Assist which models the account has. +func (g googleAccount) modelInfo(ctx context.Context) ([]googleModelInfo, error) { + p, err := g.project(ctx) + if err != nil { + return nil, err + } + var out []googleModelInfo + if g.app.agent == "antigravity" { + var res struct { + Models map[string]struct { + DisplayName string `json:"displayName"` + QuotaInfo *struct { + RemainingFraction *float64 `json:"remainingFraction"` + ResetTime string `json:"resetTime"` + } `json:"quotaInfo"` + } `json:"models"` + } + if err := g.call(ctx, g.app.base, "fetchAvailableModels", map[string]any{"project": p.id}, &res, nil); err != nil { + return nil, err + } + for id, m := range res.Models { + if antigravityHidden[id] || strings.HasPrefix(id, "chat_") || strings.HasPrefix(id, "tab_") { + continue + } + mi := googleModelInfo{Model: catalog.Model{ID: id, Name: m.DisplayName}, remaining: -1} + if q := m.QuotaInfo; q != nil { + if q.RemainingFraction != nil { + mi.remaining = *q.RemainingFraction + } else { + mi.remaining = 0 // Antigravity leaves it out once none is left + } + mi.resets, _ = time.Parse(time.RFC3339, q.ResetTime) + } + out = append(out, mi) + } + } else { + var res struct { + Buckets []struct { + ModelID string `json:"modelId"` + RemainingFraction *float64 `json:"remainingFraction"` + ResetTime string `json:"resetTime"` + TokenType string `json:"tokenType"` + } `json:"buckets"` + } + if err := g.call(ctx, g.app.base, "retrieveUserQuota", map[string]any{"project": p.id}, &res, nil); err != nil { + return nil, err + } + seen := map[string]bool{} + for _, b := range res.Buckets { + if b.ModelID == "" || seen[b.ModelID] || strings.HasSuffix(b.ModelID, "_vertex") { + continue + } + seen[b.ModelID] = true + mi := googleModelInfo{Model: catalog.Model{ID: b.ModelID}, remaining: -1} + if b.RemainingFraction != nil { + mi.remaining = *b.RemainingFraction + } + mi.resets, _ = time.Parse(time.RFC3339, b.ResetTime) + out = append(out, mi) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) + return out, nil +} + +// models is the account's models for the catalog, named as magpie knows +// them where Code Assist doesn't name them. +func (g googleAccount) models(ctx context.Context) ([]catalog.Model, error) { + infos, err := g.modelInfo(ctx) + if err != nil { + return nil, err + } + fallback := g.fallbackModels() + names := map[string]string{} + for _, m := range fallback { + names[m.ID] = m.Name + } + var out []catalog.Model + for _, mi := range infos { + m := mi.Model + if m.Name == "" { + m.Name = names[m.ID] + } + m.Images = !strings.HasPrefix(m.ID, "gpt-oss") + out = append(out, m) + } + if len(out) == 0 { + return fallback, nil + } + return out, nil +} + +func (g googleAccount) fallbackModels() []catalog.Model { + src := geminiModels + if g.app.agent == "antigravity" { + src = antigravityModels + } + out := make([]catalog.Model, len(src)) + for i, m := range src { + m.Images = !strings.HasPrefix(m.ID, "gpt-oss") + out[i] = m + } + return out +} + +// quota is how much of each model's allowance the account has used. +func (g googleAccount) quota(ctx context.Context, plan string) SubscriptionQuota { + q := SubscriptionQuota{Provider: g.app.agent, Name: g.app.name, Icon: g.app.icon, Plan: plan, User: g.user, Windows: []QuotaWindow{}} + infos, err := g.modelInfo(ctx) + if err != nil { + q.Error = err.Error() + return q + } + for _, mi := range infos { + if mi.remaining < 0 { + continue + } + w := QuotaWindow{Name: mi.ID, Used: (1 - mi.remaining) * 100, Model: mi.ID} + if mi.Name != "" { + w.Name = mi.Name + } + if !mi.resets.IsZero() { + t := mi.resets + w.ResetsAt = &t + w.ResetSecs = int64(max(time.Until(t), 0) / time.Second) + } + q.Windows = append(q.Windows, w) + } + if p, err := g.project(ctx); err == nil && q.Plan == "" { + q.Plan = p.plan + } + return q +} + +// ---- the provider ------------------------------------------------------------- + +// googleProvider is an app's Google account as a provider. +func googleProvider(g googleAccount, plan string) Provider { + acct := &Account{Agent: g.app.agent, User: g.user, Plan: plan, Stream: true, codeAssist: g.app.base} + acct.sign = func(ctx context.Context, req *http.Request, body []byte) error { + tok, err := g.token(ctx) + if err != nil { + return err + } + p, err := g.project(ctx) + if err != nil { + return err + } + out, model, err := codeAssistEnvelope(g.app.agent, body, p.id) + if err != nil { + return err + } + req.Body = io.NopCloser(bytes.NewReader(out)) + req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(out)), nil } + req.ContentLength = int64(len(out)) + req.Header.Set("Authorization", "Bearer "+tok) + req.Header.Set("User-Agent", g.app.userAgent(model)) + req.Header.Del("Accept") + return nil + } + acct.models = g.fallbackModels + acct.fetch = func(ctx context.Context) ([]catalog.Model, error) { + ms, err := g.models(ctx) + if err != nil { + return nil, err + } + return ms, catalog.SaveLive(g.app.agent, g.app.base, ms) + } + return Provider{ID: g.app.agent, Name: g.app.name, Icon: g.app.icon, Website: g.app.website, Account: acct} +} + +// codeAssistEnvelope finishes a request the gateway built — {model, +// request} — with what only the account knows: its project, and the ids +// the app sends along. +func codeAssistEnvelope(agent string, body []byte, project string) ([]byte, string, error) { + var env map[string]any + if err := json.Unmarshal(body, &env); err != nil { + return nil, "", err + } + model, _ := env["model"].(string) + env["project"] = project + id := randomToken(12) + if agent == "antigravity" { + env["userAgent"] = "antigravity" + env["requestType"] = "agent" + env["requestId"] = "agent-" + id + if r, ok := env["request"].(map[string]any); ok { + r["sessionId"] = antigravitySession(r) + } + } else { + env["user_prompt_id"] = id + } + out, err := json.Marshal(env) + return out, model, err +} + +// antigravitySession names the conversation as Antigravity does: from its +// first message, so every turn of one conversation has the same. +func antigravitySession(r map[string]any) string { + first := "" + if cs, ok := r["contents"].([]any); ok { + for _, c := range cs { + cm, _ := c.(map[string]any) + if cm["role"] != "user" { + continue + } + parts, _ := cm["parts"].([]any) + for _, p := range parts { + if t, ok := p.(map[string]any)["text"].(string); ok && t != "" { + first = t + break + } + } + break + } + } + if first == "" { + first = randomToken(16) + } + sum := sha256.Sum256([]byte(first)) + n := int64(binary.BigEndian.Uint64(sum[:8]) & 0x7fffffffffffffff) + return "-" + strconv.FormatInt(n, 10) +} + +// googleAccountOf is the app's account in use first. +func googleAccountOf(agent string) (Provider, bool) { + ls := googleLogins(agent) + if len(ls) == 0 { + return Provider{}, false + } + return googleProvider(ls[0].acct, ls[0].Plan), true +} + +// googleAlsoOn is the app's accounts in use behind the first. +func googleAlsoOn(agent string) []Provider { + var out []Provider + for _, l := range googleLogins(agent) { + if !l.Active && l.On { + out = append(out, googleProvider(l.acct, l.Plan)) + } + } + return out +} + +// googleLoginQuota is one account's allowance. +func googleLoginQuota(ctx context.Context, l Login) SubscriptionQuota { + for _, g := range googleLogins(l.Agent) { + if strings.EqualFold(g.User, l.User) { + return g.acct.quota(ctx, l.Plan) + } + } + return SubscriptionQuota{Provider: l.Agent, Plan: l.Plan, Windows: []QuotaWindow{}, Error: "not signed in"} +} + +// ---- signing in ----------------------------------------------------------------- + +// startGoogleSignIn builds the Google sign-in page's link for the app. +func startGoogleSignIn(s *signInFlow, app googleApp, port int, challenge string) { + s.redirect = fmt.Sprintf("http://%s:%d%s", app.loopback, port, app.callback) + q := url.Values{} + q.Set("client_id", app.clientID) + q.Set("redirect_uri", s.redirect) + q.Set("response_type", "code") + q.Set("scope", strings.Join(app.scopes, " ")) + q.Set("access_type", "offline") + q.Set("prompt", "consent") + q.Set("state", s.state) + q.Set("code_challenge", challenge) + q.Set("code_challenge_method", "S256") + s.st.URL = googleAuthorizeURL + "?" + q.Encode() +} + +// googleExchange trades the code for tokens, finds whose account it is and +// sets it up for Code Assist. +func googleExchange(ctx context.Context, app googleApp, code, verifier, redirect string) (googleAccount, string, error) { + form := url.Values{"grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {redirect}, + "client_id": {app.clientID}, "client_secret": {app.clientSecret}, "code_verifier": {verifier}} + var tok struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + ExpiresIn int64 `json:"expires_in"` + } + if err := postToken(ctx, googleTokenURL, "application/x-www-form-urlencoded", []byte(form.Encode()), &tok); err != nil { + return googleAccount{}, "", err + } + if tok.AccessToken == "" || tok.RefreshToken == "" { + return googleAccount{}, "", errors.New("Google sent back no token") + } + g := googleAccount{app: app, auth: googleAuth{AccessToken: tok.AccessToken, RefreshToken: tok.RefreshToken, + Expiry: time.Now().Add(time.Duration(tok.ExpiresIn) * time.Second).UnixMilli()}} + req, err := http.NewRequestWithContext(ctx, http.MethodGet, googleUserInfoURL, nil) + if err != nil { + return googleAccount{}, "", err + } + req.Header.Set("Authorization", "Bearer "+tok.AccessToken) + res, err := http.DefaultClient.Do(req) + if err != nil { + return googleAccount{}, "", err + } + defer res.Body.Close() + var who struct { + Email string `json:"email"` + } + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + if res.StatusCode != http.StatusOK || json.Unmarshal(b, &who) != nil || who.Email == "" { + return googleAccount{}, "", errors.New("Google didn't say whose account this is") + } + g.user = who.Email + // kept even when Code Assist has no project for it yet: a Standard + // account gets one named afterwards + plan := "" + if p, err := g.project(ctx); err == nil { + g.auth.Project, plan = p.id, p.plan + } + return g, plan, nil +} diff --git a/internal/provider/google_test.go b/internal/provider/google_test.go new file mode 100644 index 000000000..b78d2b2b6 --- /dev/null +++ b/internal/provider/google_test.go @@ -0,0 +1,246 @@ +package provider + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// fakeGoogle is Google's token endpoint and Code Assist, as far as magpie +// uses them. +type fakeGoogle struct { + mu sync.Mutex + refreshes int + loads []map[string]any + onboards []map[string]any + load string // loadCodeAssist's reply + onboard string // onboardUser's reply + heads map[string]http.Header +} + +func (f *fakeGoogle) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + if f.heads == nil { + f.heads = map[string]http.Header{} + } + f.heads[r.URL.Path] = r.Header + b, _ := io.ReadAll(r.Body) + var body map[string]any + json.Unmarshal(b, &body) + switch { + case r.URL.Path == "/token": + f.refreshes++ + form, _ := url.ParseQuery(string(b)) + if form.Get("refresh_token") == "" || form.Get("grant_type") != "refresh_token" { + http.Error(w, `{"error":"invalid_grant"}`, 400) + return + } + io.WriteString(w, `{"access_token":"fresh-token","expires_in":3600}`) + case strings.HasSuffix(r.URL.Path, ":loadCodeAssist"): + f.loads = append(f.loads, body) + io.WriteString(w, f.load) + case strings.HasSuffix(r.URL.Path, ":onboardUser"): + f.onboards = append(f.onboards, body) + io.WriteString(w, f.onboard) + case strings.HasSuffix(r.URL.Path, "latest-arm64-mac.yml"): + io.WriteString(w, "version: 3.1.4\npath: x.zip\n") + default: + http.NotFound(w, r) + } +} + +func googleSandbox(t *testing.T, f *fakeGoogle) { + t.Helper() + 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")) + srv := httptest.NewServer(f) + t.Cleanup(srv.Close) + oldToken, oldProd, oldDaily, oldVer, oldPoll := googleTokenURL, codeAssistProd, codeAssistDaily, antigravityVersionURL, onboardPoll + googleTokenURL, codeAssistProd, codeAssistDaily = srv.URL+"/token", srv.URL+"/prod", srv.URL+"/daily" + antigravityVersionURL, onboardPoll = srv.URL+"/latest-arm64-mac.yml", time.Millisecond + resetGoogleState() + t.Cleanup(func() { + googleTokenURL, codeAssistProd, codeAssistDaily, antigravityVersionURL, onboardPoll = oldToken, oldProd, oldDaily, oldVer, oldPoll + resetGoogleState() + }) +} + +func resetGoogleState() { + googleState.Lock() + googleState.tokens = map[string]googleAuth{} + googleState.projects = map[string]googleProject{} + googleState.Unlock() + antigravityVer.Lock() + antigravityVer.v, antigravityVer.at = "", time.Time{} + antigravityVer.Unlock() +} + +func writeGeminiLogin(t *testing.T, env string) { + t.Helper() + dir := geminiDir() + os.MkdirAll(dir, 0o700) + creds := `{"access_token":"old","refresh_token":"rt-own","expiry_date":1}` + os.WriteFile(filepath.Join(dir, "oauth_creds.json"), []byte(creds), 0o600) + os.WriteFile(filepath.Join(dir, "google_accounts.json"), []byte(`{"active":"me@example.com","old":[]}`), 0o600) + if env != "" { + os.WriteFile(filepath.Join(dir, ".env"), []byte(env), 0o600) + } +} + +// Gemini CLI's own sign-in is found, and its expired token is refreshed in +// memory: the file Gemini CLI keeps is left as it was. +func TestGeminiOwnLoginRefreshesInMemory(t *testing.T) { + f := &fakeGoogle{} + googleSandbox(t, f) + writeGeminiLogin(t, "") + before, _ := os.ReadFile(filepath.Join(geminiDir(), "oauth_creds.json")) + g, ok := geminiOwnLogin() + if !ok || g.user != "me@example.com" || !g.own { + t.Fatalf("own login = %+v, %v", g, ok) + } + for i := 0; i < 2; i++ { + tok, err := g.token(context.Background()) + if err != nil || tok != "fresh-token" { + t.Fatalf("token = %q, %v", tok, err) + } + } + if f.refreshes != 1 { + t.Errorf("refreshed %d times, want once", f.refreshes) + } + after, _ := os.ReadFile(filepath.Join(geminiDir(), "oauth_creds.json")) + if !bytes.Equal(before, after) { + t.Error("Gemini CLI's oauth_creds.json was written") + } +} + +// Google turns individuals away from Gemini CLI's sign-in; the account +// then needs a project, and magpie says how to name one. +func TestGeminiNeedsAProject(t *testing.T) { + f := &fakeGoogle{load: `{"allowedTiers":[{"id":"standard-tier","name":"Gemini Code Assist","userDefinedCloudaicompanionProject":true,"isDefault":true}], + "ineligibleTiers":[{"reasonCode":"UNSUPPORTED_CLIENT","reasonMessage":"This client is no longer supported","tierId":"free-tier"}]}`} + googleSandbox(t, f) + writeGeminiLogin(t, "") + g, _ := geminiOwnLogin() + _, err := g.project(context.Background()) + if err == nil || !strings.Contains(err.Error(), "magpie accounts project gemini me@example.com") || + !strings.Contains(err.Error(), "no longer supported") || !strings.Contains(err.Error(), "~/.gemini/.env") { + t.Fatalf("err = %v", err) + } + if len(f.onboards) != 0 { + t.Error("onboarded without a project") + } +} + +// With GOOGLE_CLOUD_PROJECT in Gemini CLI's .env the account is onboarded +// to it, as Gemini CLI does. +func TestGeminiProjectFromEnv(t *testing.T) { + f := &fakeGoogle{ + load: `{"allowedTiers":[{"id":"standard-tier","name":"Gemini Code Assist","userDefinedCloudaicompanionProject":true,"isDefault":true}]}`, + onboard: `{"done":true,"response":{"cloudaicompanionProject":{"id":"my-proj","name":"x"}}}`, + } + googleSandbox(t, f) + writeGeminiLogin(t, "# comment\nGOOGLE_CLOUD_PROJECT=\"my-proj\"\n") + g, _ := geminiOwnLogin() + p, err := g.project(context.Background()) + if err != nil || p.id != "my-proj" || p.plan != "Gemini Code Assist" { + t.Fatalf("project = %+v, %v", p, err) + } + if f.loads[0]["cloudaicompanionProject"] != "my-proj" || f.onboards[0]["tierId"] != "standard-tier" { + t.Errorf("load %v onboard %v", f.loads[0], f.onboards[0]) + } + if ua := f.heads["/prod/v1internal:loadCodeAssist"].Get("User-Agent"); !strings.HasPrefix(ua, "GeminiCLI/") { + t.Errorf("User-Agent = %q", ua) + } +} + +// An account named in magpie gets its project from `magpie accounts project`. +func TestSetGoogleProject(t *testing.T) { + f := &fakeGoogle{load: `{"currentTier":{"id":"standard-tier","name":"Gemini Code Assist Standard"}}`} + googleSandbox(t, f) + auth := googleAuth{AccessToken: "a", RefreshToken: "rt-2", Expiry: time.Now().Add(time.Hour).UnixMilli()} + if err := addGoogleLogin("gemini", "work@example.com", "", auth); err != nil { + t.Fatal(err) + } + ls := googleLogins("gemini") + if len(ls) != 1 { + t.Fatalf("logins = %+v", ls) + } + if _, err := ls[0].acct.project(context.Background()); err == nil { + t.Fatal("a project was found for an account with none") + } + if err := SetGoogleProject("gemini", "work@example.com", " proj-7 "); err != nil { + t.Fatal(err) + } + p, err := googleLogins("gemini")[0].acct.project(context.Background()) + if err != nil || p.id != "proj-7" || p.plan != "Gemini Code Assist Standard" { + t.Fatalf("project = %+v, %v", p, err) + } + if err := SetGoogleProject("gemini", "nobody@example.com", "x"); err == nil { + t.Error("set a project on an account that isn't there") + } +} + +// Antigravity's account is onboarded on the daily endpoint, asking until +// it is done, and its requests carry what Antigravity sends. +func TestAntigravityProjectAndEnvelope(t *testing.T) { + f := &fakeGoogle{ + load: `{"allowedTiers":[{"id":"free-tier","name":"Antigravity","isDefault":true}]}`, + onboard: `{"done":true,"response":{"cloudaicompanionProject":"ag-proj"}}`, + } + googleSandbox(t, f) + auth := googleAuth{AccessToken: "tok", RefreshToken: "rt-ag", Expiry: time.Now().Add(time.Hour).UnixMilli()} + if err := addGoogleLogin("antigravity", "ag@example.com", "", auth); err != nil { + t.Fatal(err) + } + p, ok := googleAccountOf("antigravity") + if !ok || p.Account == nil || p.Base(CodeAssist) != codeAssistDaily { + t.Fatalf("provider = %+v", p) + } + if s := p.Speaks(); len(s) != 1 || s[0] != CodeAssist { + t.Fatalf("speaks %v", s) + } + body := `{"model":"claude-sonnet-4-6","request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}` + req, _ := http.NewRequest("POST", p.Base(CodeAssist)+"/v1internal:streamGenerateContent?alt=sse", strings.NewReader(body)) + if err := p.Sign(context.Background(), req, CodeAssist, []byte(body)); err != nil { + t.Fatal(err) + } + if f.heads["/prod/v1internal:loadCodeAssist"] == nil || f.heads["/daily/v1internal:onboardUser"] == nil { + t.Errorf("asked %v", f.heads) + } + if f.onboards[0]["tier_id"] != "free-tier" { + t.Errorf("onboard = %v", f.onboards[0]) + } + var env map[string]any + b, _ := io.ReadAll(req.Body) + json.Unmarshal(b, &env) + r, _ := env["request"].(map[string]any) + if env["project"] != "ag-proj" || env["userAgent"] != "antigravity" || env["requestType"] != "agent" || + !strings.HasPrefix(env["requestId"].(string), "agent-") || r["sessionId"] == "" || r["sessionId"] == nil { + t.Errorf("envelope = %s", b) + } + if req.Header.Get("Authorization") != "Bearer tok" || !strings.HasPrefix(req.Header.Get("User-Agent"), "antigravity/hub/3.1.4 ") { + t.Errorf("headers = %v", req.Header) + } + // the same conversation keeps its session + req2, _ := http.NewRequest("POST", "http://x", nil) + p.Sign(context.Background(), req2, CodeAssist, []byte(body)) + b2, _ := io.ReadAll(req2.Body) + var env2 map[string]any + json.Unmarshal(b2, &env2) + if env2["request"].(map[string]any)["sessionId"] != r["sessionId"] { + t.Error("session changed between turns") + } +} diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go index 95b182aa4..5c51b9e3e 100644 --- a/internal/provider/login_usage.go +++ b/internal/provider/login_usage.go @@ -35,6 +35,8 @@ func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota logins = Logins(agent) case "copilot": logins = copilotLoginList() + case "gemini", "antigravity": + logins = googleLoginList(agent) case "cursor": // one account, the one cursor-agent is signed in to if user, plan, ok := cursorIdentity(); ok { logins = []Login{{Agent: agent, User: user, Plan: plan, Active: true, On: true}} @@ -80,6 +82,9 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota { if l.Agent == "cursor" { return cursorSubscriptionUsage(ctx, l.Plan) } + if l.Agent == "gemini" || l.Agent == "antigravity" { + return googleLoginQuota(ctx, l) + } if l.Agent == "copilot" { for _, c := range copilotLogins(copilotConfigDir()) { if strings.EqualFold(c.User, l.User) { diff --git a/internal/provider/logins.go b/internal/provider/logins.go index cd77ddb32..836566c60 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -50,6 +50,9 @@ type savedLogin struct { // Grok or Copilot account ahead of the agent's own (side_logins.go). Home string `json:"home,omitempty"` First bool `json:"first,omitempty"` + // Project is the Google Cloud project a Gemini CLI or Antigravity + // account's requests go to, when the user named one (google.go). + Project string `json:"project,omitempty"` } var ( @@ -318,8 +321,12 @@ func Logins(agent string) []Login { return grokLoginList() case "copilot": return copilotLoginList() + case "gemini", "antigravity": + return googleLoginList(agent) case "": side = append(grokLoginList(), copilotLoginList()...) + side = append(side, googleLoginList("gemini")...) + side = append(side, googleLoginList("antigravity")...) } rememberLogins(false) loginsMu.Lock() @@ -332,7 +339,7 @@ func Logins(agent string) []Login { } var out []Login for _, l := range readLogins() { - if (agent != "" && l.Agent != agent) || l.Agent == "grok" || l.Agent == "copilot" { + if (agent != "" && l.Agent != agent) || sideAgent(l.Agent) { continue } using := strings.EqualFold(active[l.Agent], l.User) @@ -351,6 +358,8 @@ func SwitchLogin(agent, user string) error { return switchGrokLogin(user) case "copilot": return switchCopilotLogin(user) + case "gemini", "antigravity": + return switchGoogleLogin(agent, user) } loginsMu.Lock() defer loginsMu.Unlock() @@ -452,6 +461,8 @@ func ForgetLogin(agent, user string) error { return forgetGrokLogin(user) case "copilot": return forgetCopilotLogin(user) + case "gemini", "antigravity": + return forgetGoogleLogin(agent, user) } loginsMu.Lock() defer loginsMu.Unlock() diff --git a/internal/provider/logins_on.go b/internal/provider/logins_on.go index 2589f2814..345c241bf 100644 --- a/internal/provider/logins_on.go +++ b/internal/provider/logins_on.go @@ -29,6 +29,8 @@ func SetLoginOn(agent, user string, on bool) error { return setGrokLoginOn(user, on) case "copilot": return setCopilotLoginOn(user, on) + case "gemini", "antigravity": + return setGoogleLoginOn(agent, user, on) } loginsMu.Lock() defer loginsMu.Unlock() @@ -57,6 +59,9 @@ func (p Provider) AlsoOn() []Provider { if p.Account != nil && p.Account.Agent == "copilot" { return copilotAlsoOn() } + if p.Account != nil && (p.Account.Agent == "gemini" || p.Account.Agent == "antigravity") { + return googleAlsoOn(p.Account.Agent) + } if p.Account == nil || p.Account.token != nil || (p.Account.Agent != "claude" && p.Account.Agent != "codex") { return nil } diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 674eb8ed6..266df9b64 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -309,7 +309,7 @@ func freeName(name string) string { } // accountIDs are the ids of the subscriptions magpie can list (account.go). -var accountIDs = []string{"claude", "codex", "copilot", "cursor", "devin", "grok"} +var accountIDs = []string{"antigravity", "claude", "codex", "copilot", "cursor", "devin", "gemini", "grok"} func stored(id string) bool { for _, p := range load().Providers { @@ -462,12 +462,20 @@ func (p Provider) Base(proto Protocol) string { return p.Responses case Anthropic: return p.Anthropic + case CodeAssist: + if p.Account != nil { + return p.Account.codeAssist + } } return "" } // Speaks lists the protocols the vendor serves natively, preferred first. func (p Provider) Speaks() []Protocol { + // a Google sign-in speaks Code Assist, and only that + if p.Account != nil && p.Account.codeAssist != "" { + return []Protocol{CodeAssist} + } var out []Protocol for _, pr := range Protocols { if p.Base(pr) != "" { @@ -479,7 +487,7 @@ func (p Provider) Speaks() []Protocol { // Host is the vendor's API host, for display. func (p Provider) Host() string { - for _, pr := range Protocols { + for _, pr := range p.Speaks() { if u := p.Base(pr); u != "" { return HostOf(u) } diff --git a/internal/provider/side_logins.go b/internal/provider/side_logins.go index 111a9bf64..aa4b16d65 100644 --- a/internal/provider/side_logins.go +++ b/internal/provider/side_logins.go @@ -179,3 +179,13 @@ func addSideLogin(l savedLogin, dup func(savedLogin)) error { l.On = true return writeLogins(append(ls, l)) } + +// sideAgent says an agent's accounts are kept this way, not in the +// agent's own store as Claude Code's and Codex's are. +func sideAgent(agent string) bool { + switch agent { + case "grok", "copilot", "gemini", "antigravity": + return true + } + return false +} diff --git a/internal/provider/signin.go b/internal/provider/signin.go index 27f39830d..8eb23f6cd 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -151,6 +151,13 @@ func StartSignIn(agent string) (SignInState, error) { if err := startCopilotSignIn(s); err != nil { return SignInState{}, err } + case "gemini", "antigravity": + // Google's sign-in, under the app's own OAuth client + app, _ := googleAppOf(agent) + if ln, err = net.Listen("tcp", "127.0.0.1:0"); err != nil { + return SignInState{}, err + } + startGoogleSignIn(s, app, ln.Addr().(*net.TCPAddr).Port, challenge) default: return SignInState{}, fmt.Errorf("magpie can't sign in to %s accounts", agent) } @@ -278,7 +285,7 @@ func (s *signInFlow) finish(out SignInState) bool { func (s *signInFlow) callback(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { - case "/callback", "/auth/callback": + case "/callback", "/auth/callback", "/oauth2callback", "/oauth-callback": case "/cancel": s.finish(SignInState{State: "canceled"}) w.WriteHeader(http.StatusNoContent) @@ -308,6 +315,10 @@ func (s *signInFlow) callback(w http.ResponseWriter, r *http.Request) { } ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() + if app, ok := googleAppOf(s.st.Agent); ok { + s.googleDone(ctx, w, app, q.Get("code")) + return + } l, err := s.exchange(ctx, q.Get("code")) if err == nil && s.st.Agent == "devin" { // devin keeps the one account it is signed in to: the exchange @@ -328,6 +339,26 @@ func (s *signInFlow) callback(w http.ResponseWriter, r *http.Request) { signInPage(w, false, "Sign-in didn't finish", err.Error()) } +// googleDone finishes a Gemini CLI or Antigravity sign-in: the account is +// kept beside the others, in use at once. +func (s *signInFlow) googleDone(ctx context.Context, w http.ResponseWriter, app googleApp, code string) { + g, plan, err := googleExchange(ctx, app, code, s.verifier, s.redirect) + if err == nil { + err = addGoogleLogin(app.agent, g.user, plan, g.auth) + } + if err != nil { + s.finish(SignInState{State: "failed", Error: err.Error()}) + signInPage(w, false, "Sign-in didn't finish", err.Error()) + return + } + using := false + if own, ok := geminiOwnLogin(); ok && app.agent == "gemini" && strings.EqualFold(own.user, g.user) { + using = true + } + s.finish(SignInState{State: "done", User: g.user, Plan: plan, Using: using}) + signInPage(w, true, "You're signed in", fmt.Sprintf("%s is added to magpie. You can close this tab.", g.user)) +} + // exchange trades the code for tokens and makes them into a login. func (s *signInFlow) exchange(ctx context.Context, code string) (savedLogin, error) { switch s.st.Agent { diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index b32c7dab5..d60874683 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -148,6 +148,14 @@ func fetchSubscriptionUsage() []SubscriptionQuota { } } } + for _, agent := range []string{"gemini", "antigravity"} { + if hidden[agent] { + continue + } + for _, l := range googleLogins(agent) { + fetches = append(fetches, func() SubscriptionQuota { return l.acct.quota(ctx, l.Plan) }) + } + } out := make([]SubscriptionQuota, len(fetches)) var wg sync.WaitGroup for i, f := range fetches { diff --git a/main.go b/main.go index 145526590..329639859 100644 --- a/main.go +++ b/main.go @@ -55,8 +55,9 @@ const usage = `magpie — one place to pick every agent's model magpie group add models=, [routing=smart|order|rotate|usage] [stays=auto|session|turn|off] magpie group | set k=v… | rm show, change or remove one (magpie group help for more) magpie accounts [agent] [--json] every subscription magpie knows, with each one's allowance used and when it resets - magpie accounts add sign in to one more Claude or ChatGPT subscription + magpie accounts add sign in to one more Claude, ChatGPT or Google (Gemini CLI, Antigravity) subscription magpie accounts switch sign the agent in to another of them + magpie accounts project the Google Cloud project a Google account's requests go to magpie serve run the gateway alone (the app runs it too) magpie usage [today|7d|30d|all] tokens and cost per agent and model (30d) diff --git a/site/public/icons/antigravity-color.svg b/site/public/icons/antigravity-color.svg new file mode 100644 index 000000000..3ed10ab65 --- /dev/null +++ b/site/public/icons/antigravity-color.svg @@ -0,0 +1 @@ +Antigravity \ No newline at end of file