provider + gateway: Google sign-ins — Gemini CLI's and Antigravity's — are subscriptions of magpie's, so any agent can use their models (#4); Gemini CLI's own login in ~/.gemini is read as it is, or an account is signed in from magpie with Google's OAuth, its token refreshed in memory, and each request goes to Code Assist wrapped as the app wraps it, with the project Code Assist set the account up with; Google now serves Gemini CLI's sign-in only to Code Assist Standard and Enterprise, which need a Cloud project, named with magpie accounts project or GOOGLE_CLOUD_PROJECT in ~/.gemini/.env and said so where the account is shown; Google may suspend an Antigravity account used outside Antigravity, so magpie says that and asks before adding one

This commit is contained in:
yetone
2026-09-25 15:53:33 +08:00
parent 14b353ed6c
commit 637b2458ee
21 changed files with 2066 additions and 16 deletions
+10 -2
View File
@@ -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 <email> <project-id>`, 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
+40 -4
View File
@@ -17,19 +17,42 @@ import (
)
// accountsCmd: `magpie accounts [agent] [--json]`, `magpie accounts add <agent>`,
// `magpie accounts switch|forget <agent> <email>`
// `magpie accounts switch|forget <agent> <email>`,
// `magpie accounts project <gemini|antigravity> <email> <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 <claude|codex> | magpie accounts switch|forget <claude|codex> <email>"
const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity] [--json] | magpie accounts add <claude|codex|gemini|antigravity> | magpie accounts switch|forget <claude|codex|gemini|antigravity> <email> | magpie accounts project <gemini|antigravity> <email> <gcp-project-id>"
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 <claude|codex>")
fmt.Println(muted.Render("no accounts yet ·"), "add one: magpie accounts add <claude|codex|gemini|antigravity>")
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
+480
View File
@@ -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"
}
+143
View File
@@ -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)
}
}
+9 -1
View File
@@ -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
}
+34 -4
View File
@@ -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;
}
+4
View File
@@ -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": "聊天请求",
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.5 KiB

+2
View File
@@ -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)
}
+9
View File
@@ -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
}
File diff suppressed because it is too large Load Diff
+246
View File
@@ -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")
}
}
+5
View File
@@ -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) {
+12 -1
View File
@@ -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()
+5
View File
@@ -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
}
+10 -2
View File
@@ -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)
}
+10
View File
@@ -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
}
+32 -1
View File
@@ -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 {
+8
View File
@@ -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 {
+2 -1
View File
@@ -55,8 +55,9 @@ const usage = `magpie — one place to pick every agent's model
magpie group add <name> models=<m1>,<m2> [routing=smart|order|rotate|usage] [stays=auto|session|turn|off]
magpie group <id> | set <id> k=v… | rm <id> 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 <agent> sign in to one more Claude or ChatGPT subscription
magpie accounts add <agent> sign in to one more Claude, ChatGPT or Google (Gemini CLI, Antigravity) subscription
magpie accounts switch <agent> <email> sign the agent in to another of them
magpie accounts project <gemini|antigravity> <email> <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)
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.5 KiB