zed: a Zed subscription (Pro, Student, Business) signed in from magpie, several accounts, served through Zed's own cloud (yosocoli5 on X: 买了 Zed 订阅,可以加进供应商吗 — yetone: 当然可以!) — magpie had no way to use Zed's hosted models. Zed is now a subscription in the add sheet (Zed's own logo from zed-industries/zed, lobe-icons has none), signed in as the Zed editor signs in (new internal/zed, the protocol): an RSA key is made, the browser opens zed.dev/native_app_signin with its PKCS#1 public half, magpie's loopback port and a system id, and comes back with user_id and the access token encrypted to the key (OAEP SHA-256, PKCS#1 v1.5 also read), answered with a redirect to zed.dev's succeeded page. The account is asked of /client/users/me (signed "<uid> <token>" with x-zed-system-id), kept with its GitHub login, its default organization and plan; an organization with hosted models turned off is refused. Several accounts can be added and switched like the other subscriptions. Requests get an LLM token from /client/llm_tokens (kept in memory, minted again when Zed answers 401 or x-zed-expired-token/x-zed-outdated-token, once; a refused pair marks the account lapsed, "sign in again"). The model list is Zed's /models for the account (disabled and unknown providers left out; context, output, images and effort levels kept). The gateway asks cloud.zed.dev/completions in Zed's envelope {provider, model, provider_request}, the request written in the model's own provider's API as Zed writes it — Anthropic Messages without stream, OpenAI Responses, xAI chat completions with max_completion_tokens, Gemini's request with models/<id> — and reads the NDJSON reply's events with that API's decoder: a failed status is an error with its status (upstream_http_N, rate limit 429, overloaded 529, payment 402), a reply without stream_ended is an error, not a shorter answer, a 402 says the plan doesn't include hosted models or its allowance is used up. relayQoder's status-keeping relay is now relayStatus, shared by Qoder and Zed. Usage shows the plan and its period's end; Zed reports no usage counter, so no windows. Signing in says first, as Antigravity's does, that Zed serves these models to its own editor and may treat magpie's use as third-party use (en and zh); the import box now uses a subscription's own risk note too. Tested in Go against fake zed.dev/cloud.zed.dev servers, no real account: internal/zed TestSignInKey, TestParseModels, TestReadLines; provider TestZedSignIn (the whole sign-in through the loopback callback, what is kept, the account and its models, the token kept and renewed, the quota's plan and end, a refused pair lapsing) and TestZedFreePlanQuota; gateway TestServeZedProviders (each of the four providers, streaming and not), TestServeZedFailures (stale token retried once, 402, upstream 529 with retry_after, a failed 429, cut short → 502), TestZedRequestShapes. New zed-sub.test.cjs in Chromium and WebKit, en and zh: the Zed row with its plans and logo, the risk note in Zed's words with nothing asked, then Sign in anyway asking for zed. add-sheet, add-button, old-webkit, signin-callback and own-signin-remove pass. go vet, go build -tags nogui (and GOOS=linux, GOOS=windows) and go test -tags nogui ./... pass. Not tried with a real Zed account: the sign-in page's real callback, the LLM token and completions endpoints' acceptance of magpie's headers, and each provider's real event shapes are from Zed's source, not seen on the wire.

This commit is contained in:
yetone
2026-09-30 03:19:19 +08:00
parent 575e694ed7
commit 28396deabd
23 changed files with 1947 additions and 8 deletions
+4 -2
View File
@@ -24,7 +24,7 @@ import (
// — 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|gemini|antigravity|dimagent] [--json] | magpie accounts add <claude|codex|gemini|antigravity|dimagent> | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|dimagent> <email> | magpie accounts project <gemini|antigravity> <email> <gcp-project-id>"
const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|dimagent|zed] [--json] | magpie accounts add <claude|codex|gemini|antigravity|dimagent|zed> | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|dimagent|zed> <email> | magpie accounts project <gemini|antigravity> <email> <gcp-project-id>"
agentID := func(s string) (string, error) {
switch strings.ToLower(s) {
case "claude", "cc":
@@ -37,8 +37,10 @@ func accountsCmd(args []string) error {
return "antigravity", nil
case "dimagent":
return "dimagent", nil
case "zed":
return "zed", nil
}
return "", fmt.Errorf("%q: only Claude Code, Codex, Gemini CLI, Antigravity and DimAgent accounts can be added and switched\n%s", s, usage)
return "", fmt.Errorf("%q: only Claude Code, Codex, Gemini CLI, Antigravity, DimAgent and Zed accounts can be added and switched\n%s", s, usage)
}
if len(args) > 1 && args[1] == "project" {
if len(args) != 5 {
+7 -1
View File
@@ -459,7 +459,7 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) {
p, model, ok := provider.Resolve(unprefixed(model))
// 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" || p.Account.Agent == "kiro" || p.Account.Agent == "qoder" || p.Account.Agent == "gemini" || p.Account.Agent == "antigravity") {
if ok && p.Account != nil && (p.Account.Agent == "claude" || p.Account.Agent == "cursor" || p.Account.Agent == "grok" || p.Account.Agent == "devin" || p.Account.Agent == "kiro" || p.Account.Agent == "qoder" || p.Account.Agent == "zed" || p.Account.Agent == "gemini" || p.Account.Agent == "antigravity") {
req, err := parseAnthropic(body)
if err != nil {
writeError(w, provider.Anthropic, 400, err.Error())
@@ -1112,6 +1112,12 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
call.To = from
return s.serveQoder(w, r, from, p, model, body, &call.Usage)
}
// Zed's through cloud.zed.dev, written in the API of the model's own
// provider, with the account magpie signed in to
if p.Account != nil && p.Account.Agent == "zed" {
call.To = from
return s.serveZed(w, r, from, p, model, body, &call.Usage)
}
// a backend that only streams gets a non-streaming request translated
// (the provider is always streamed on that path) rather than relayed
relay := slices.Contains(s.usable(p, model), from) && (p.Account == nil || !p.Account.Stream || streamOf(body))
+8 -2
View File
@@ -89,8 +89,14 @@ func (s *Server) serveQoder(w http.ResponseWriter, r *http.Request, from provide
// relayQoder preserves upstream failures before committing a response, including
// failures after partial non-streaming text. Streaming failures after output
// has begun are terminal error events. Keep this policy local to Qoder.
// has begun are terminal error events. Keep this policy to the backends that
// report their own statuses: Qoder's, and Zed's (relayStatus).
func relayQoder(w http.ResponseWriter, from provider.Protocol, req *Request, events <-chan Event, usage *Usage, abort context.CancelFunc) (int, string) {
return relayStatus(w, from, "Qoder", req, events, usage, abort)
}
// relayStatus is relayQoder for the backend called name.
func relayStatus(w http.ResponseWriter, from provider.Protocol, name string, req *Request, events <-chan Event, usage *Usage, abort context.CancelFunc) (int, string) {
fail := func(ev Event) (int, string) {
abort()
code := ev.Status
@@ -111,7 +117,7 @@ func relayQoder(w http.ResponseWriter, from provider.Protocol, req *Request, eve
}
}
if len(head) == 0 || head[len(head)-1].Kind == KStart || head[len(head)-1].Kind == KUsage {
return fail(Event{Text: "Qoder ended without an answer"})
return fail(Event{Text: name + " ended without an answer"})
}
enc := encoder(from, newSSEWriter(w), req)
see := func(ev Event) bool {
+217
View File
@@ -0,0 +1,217 @@
package gateway
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/zed"
)
// A Zed subscription is served through cloud.zed.dev/completions, the way the
// Zed editor asks it: the request is written in the API of the model's own
// provider — Anthropic's Messages, OpenAI's Responses, xAI's chat
// completions, Gemini's generateContent — wrapped in Zed's envelope, and the
// reply is those providers' own stream events, a JSON line each, which the
// matching decoder reads. The protocol lives in internal/zed.
// zedToken, zedProviderOf and zedBase stand in for the account, so tests
// can point them elsewhere.
var (
zedToken = provider.ZedToken
zedProviderOf = provider.ZedProviderOf
zedBase = provider.ZedCloud
)
// serveZed answers a request through Zed's API.
func (s *Server) serveZed(w http.ResponseWriter, r *http.Request, from provider.Protocol, p provider.Provider, model string, body []byte, usage *Usage) (int, string) {
req, err := parse(from, body)
if err != nil {
return writeError(w, from, 400, err.Error()), err.Error()
}
req.Model = model
ask := s.askZed(p.Account.User, model)
if req.WebSearch && !searching(r.Context()) {
if _, _, ok := searcher(); ok {
return s.searchReply(w, r, from, "Zed", req, usage, ask)
}
}
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
events, status, msg := ask(ctx, req)
if events == nil {
return writeError(w, from, status, msg), msg
}
// Zed's failures keep their statuses (a 429 or 402 is another account's
// turn), and a reply cut short is an error, not a shorter answer
return relayStatus(w, from, "Zed", req, events, usage, cancel)
}
// zedRequest is the provider's own request for req, and the protocol its
// stream comes back in.
func zedRequest(req *Request, vendor, model string) (json.RawMessage, provider.Protocol, error) {
q := *req
q.Stream = true
switch zed.Wire(vendor) {
case "anthropic":
// Zed's Anthropic request has no stream field: the cloud always streams
var m map[string]json.RawMessage
if err := json.Unmarshal(buildAnthropic(&q, model), &m); err != nil {
return nil, "", err
}
delete(m, "stream")
b, err := json.Marshal(m)
return b, provider.Anthropic, err
case "responses":
return buildResponses(&q, model, "api.openai.com", false), provider.Responses, nil
case "chat":
var m map[string]json.RawMessage
if err := json.Unmarshal(buildChat(&q, model, "api.x.ai", false), &m); err != nil {
return nil, "", err
}
// as Zed writes an xAI request
if v, ok := m["max_tokens"]; ok {
m["max_completion_tokens"] = v
delete(m, "max_tokens")
}
b, err := json.Marshal(m)
return b, provider.Chat, err
case "gemini":
// Code Assist's envelope holds Gemini's own request; Zed's is that
// request with the model named in it
inner := gjson.GetBytes(buildCodeAssist(&q, model, "gemini"), "request")
var m map[string]json.RawMessage
if err := json.Unmarshal([]byte(inner.Raw), &m); err != nil {
return nil, "", err
}
for _, k := range []string{"session_id", "sessionId"} {
delete(m, k)
}
m["model"], _ = json.Marshal("models/" + model)
b, err := json.Marshal(m)
return b, provider.CodeAssist, err
}
return nil, "", fmt.Errorf("magpie can't ask Zed's %q models", vendor)
}
// askZed is a round for Zed's API.
func (s *Server) askZed(user, model string) round {
return func(ctx context.Context, req *Request) (<-chan Event, int, string) {
vendor := zedProviderOf(user, model)
raw, proto, err := zedRequest(req, vendor, model)
if err != nil {
return nil, 400, "Zed: " + err.Error()
}
body := zed.CompletionBody(vendor, model, "", raw)
var res *http.Response
for try := 0; ; try++ {
tok, err := zedToken(ctx, user, try > 0)
if err != nil {
status := 502
if errors.Is(err, provider.ErrZedSignIn) {
status = 401
}
return nil, status, "Zed: " + err.Error()
}
hr, err := http.NewRequestWithContext(ctx, http.MethodPost, zed.CompletionURL(zedBase()), bytes.NewReader(body))
if err != nil {
return nil, 500, "Zed: " + err.Error()
}
zed.CompletionHeaders(hr.Header, tok)
if res, err = s.client.Do(hr); err != nil {
return nil, 502, "Zed: " + err.Error()
}
// a model token Zed calls stale is minted again, once
if try == 0 && zed.TokenStale(res.StatusCode, res.Header) {
io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20))
res.Body.Close()
continue
}
break
}
if res.StatusCode/100 != 2 {
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
status, msg := zedFailure(res.StatusCode, b)
return nil, status, msg
}
wrapped := res.Header.Get("x-zed-server-supports-status-messages") != ""
events := make(chan Event, 16)
go func() {
defer close(events)
defer res.Body.Close()
dec := decoder(proto)
send := func(ev Event) error {
select {
case events <- ev:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
var failed error
ended, stop := false, errors.New("stop")
err := zed.ReadLines(res.Body, wrapped, func(l zed.Line) error {
switch {
case l.Ended:
ended = true
case l.Failed != nil:
send(Event{Kind: KError, Status: l.Failed.Status(), Text: "Zed: " + l.Failed.Error()})
return stop
case len(l.Event) > 0:
if err := dec(string(l.Event), func(ev Event) {
if failed == nil {
failed = send(ev)
}
}); err != nil {
return err
}
}
return failed
})
switch {
case errors.Is(err, stop) || failed != nil || ctx.Err() != nil:
case err != nil:
send(Event{Kind: KError, Text: "Zed: " + err.Error()})
case wrapped && !ended:
// Zed ends every whole reply with stream_ended
send(Event{Kind: KError, Text: "Zed: the reply ended before it was complete"})
}
}()
return events, 0, ""
}
}
// zedFailure is the status and message for a refused request: Zed's
// {code, message, upstream_status}, a 402 as the plan it is.
func zedFailure(status int, b []byte) (int, string) {
if status == http.StatusPaymentRequired {
return 402, "Zed: payment required — this account's plan doesn't include Zed's hosted models, or its allowance is used up (see zed.dev/account)"
}
if status == http.StatusUnauthorized {
return 401, "Zed: the sign-in was refused — sign in again"
}
code := status
if up := gjson.GetBytes(b, "upstream_status").Int(); up >= 400 && up <= 599 {
code = int(up)
} else if c := gjson.GetBytes(b, "code").String(); c != "" {
if n := (&zed.Failed{Code: c}).Status(); n != 502 {
code = n
}
}
if code < 400 || code > 599 {
code = 502
}
msg := zed.Failure(status, b)
if ra := gjson.GetBytes(b, "retry_after"); ra.Exists() && ra.Float() > 0 {
msg += " (retry after " + strconv.FormatFloat(ra.Float(), 'f', -1, 64) + "s)"
}
return code, "Zed: " + msg
}
+212
View File
@@ -0,0 +1,212 @@
package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// zedUpstream stands in for cloud.zed.dev/completions: reply answers each
// request (by its envelope), and the account's model token is "llm-<n>",
// n counting how many were minted.
func zedUpstream(t *testing.T, vendor string, reply func(w http.ResponseWriter, body []byte, auth string)) *atomic.Int32 {
t.Helper()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
var minted atomic.Int32
minted.Store(1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/completions" || r.Method != http.MethodPost {
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
w.WriteHeader(404)
return
}
if r.Header.Get("x-zed-version") == "" || r.Header.Get("x-zed-client-supports-status-messages") != "true" ||
!strings.HasPrefix(r.Header.Get("User-Agent"), "Zed/") {
t.Errorf("not asked as Zed asks: %v", r.Header)
}
b, _ := io.ReadAll(r.Body)
reply(w, b, r.Header.Get("Authorization"))
}))
t.Cleanup(srv.Close)
oldTok, oldOf, oldBase := zedToken, zedProviderOf, zedBase
zedToken = func(_ context.Context, user string, renew bool) (string, error) {
if user != "octo" {
t.Errorf("token for %q", user)
}
if renew {
minted.Add(1)
}
return "llm-" + string(rune('0'+minted.Load())), nil
}
zedProviderOf = func(string, string) string { return vendor }
zedBase = func() string { return srv.URL }
t.Cleanup(func() { zedToken, zedProviderOf, zedBase = oldTok, oldOf, oldBase })
return &minted
}
func zedLines(w http.ResponseWriter, lines ...string) {
w.Header().Set("x-zed-server-supports-status-messages", "true")
w.WriteHeader(200)
io.WriteString(w, `{"status":"started"}`+"\n")
for _, l := range lines {
io.WriteString(w, l+"\n")
}
}
func zedEvent(ev string) string { return `{"event":` + ev + `}` }
const zedEnded = `{"status":"stream_ended"}`
func zedServe(t *testing.T, from provider.Protocol, model, body string) (int, string, string) {
t.Helper()
s := New()
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/", strings.NewReader(body))
var u Usage
status, msg := s.serveZed(w, r, from, provider.Provider{ID: "zed", Account: &provider.Account{Agent: "zed", User: "octo"}}, model, []byte(body), &u)
return status, msg, w.Body.String()
}
// Each of Zed's providers is asked in its own API inside Zed's envelope, and
// its own events come back through the client's protocol.
func TestServeZedProviders(t *testing.T) {
for _, tt := range []struct {
vendor, model string
check func(t *testing.T, req gjson.Result)
lines []string
}{
{"anthropic", "claude-sonnet-4-5", func(t *testing.T, req gjson.Result) {
if req.Get("stream").Exists() || req.Get("model").String() != "claude-sonnet-4-5" || req.Get("messages.0.content").Raw == "" || req.Get("max_tokens").Int() == 0 {
t.Errorf("anthropic request %s", req.Raw)
}
}, []string{
zedEvent(`{"type":"message_start","message":{"id":"m","role":"assistant","usage":{"input_tokens":7,"output_tokens":0}}}`),
zedEvent(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`),
zedEvent(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello from Claude"}}`),
zedEvent(`{"type":"content_block_stop","index":0}`),
zedEvent(`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}`),
zedEvent(`{"type":"message_stop"}`),
zedEnded,
}},
{"open_ai", "gpt-5", func(t *testing.T, req gjson.Result) {
if !req.Get("stream").Bool() || req.Get("input").Raw == "" || req.Get("model").String() != "gpt-5" {
t.Errorf("responses request %s", req.Raw)
}
}, []string{
zedEvent(`{"type":"response.created","response":{"id":"r"}}`),
zedEvent(`{"type":"response.output_text.delta","item_id":"i","output_index":0,"content_index":0,"delta":"Hello from GPT"}`),
zedEvent(`{"type":"response.completed","response":{"id":"r","status":"completed","usage":{"input_tokens":5,"output_tokens":3}}}`),
zedEnded,
}},
{"x_ai", "grok-4", func(t *testing.T, req gjson.Result) {
if req.Get("max_tokens").Exists() || req.Get("max_completion_tokens").Int() != 64 || req.Get("messages.0").Raw == "" {
t.Errorf("xAI request %s", req.Raw)
}
}, []string{
zedEvent(`{"id":"c","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello from Grok"}}]}`),
zedEvent(`{"id":"c","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":3}}`),
zedEnded,
}},
{"google", "gemini-2.5-pro", func(t *testing.T, req gjson.Result) {
if req.Get("model").String() != "models/gemini-2.5-pro" || req.Get("contents.0.parts.0.text").String() != "hi" || req.Get("request").Exists() {
t.Errorf("Gemini request %s", req.Raw)
}
}, []string{
zedEvent(`{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello from Gemini"}]}}]}`),
zedEvent(`{"candidates":[{"content":{"role":"model","parts":[{"text":""}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":3}}`),
zedEnded,
}},
} {
t.Run(tt.vendor, func(t *testing.T) {
zedUpstream(t, tt.vendor, func(w http.ResponseWriter, b []byte, auth string) {
env := gjson.ParseBytes(b)
if env.Get("provider").String() != tt.vendor || env.Get("model").String() != tt.model || !env.Get("provider_request").IsObject() {
t.Errorf("envelope %s", b)
}
if auth != "Bearer llm-1" {
t.Errorf("signed %q", auth)
}
tt.check(t, env.Get("provider_request"))
zedLines(w, tt.lines...)
})
for _, stream := range []bool{true, false} {
body := `{"model":"zed/` + tt.model + `","max_tokens":64,"stream":` + map[bool]string{true: "true", false: "false"}[stream] + `,"messages":[{"role":"user","content":"hi"}]}`
status, msg, out := zedServe(t, provider.Chat, tt.model, body)
if status != 200 || !strings.Contains(out, "Hello from") {
t.Fatalf("stream=%v: %d %q\n%s", stream, status, msg, out)
}
}
})
}
}
// A model token Zed calls stale is minted again and the request asked once
// more; a failure the stream reports, a refused plan and a reply cut short
// all reach the client as errors.
func TestServeZedFailures(t *testing.T) {
body := `{"model":"m","stream":false,"messages":[{"role":"user","content":"hi"}]}`
text := zedEvent(`{"id":"c","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"ok"}}]}`)
var asked atomic.Int32
minted := zedUpstream(t, "x_ai", func(w http.ResponseWriter, _ []byte, auth string) {
if asked.Add(1) == 1 {
w.Header().Set("x-zed-expired-token", "true")
w.WriteHeader(401)
return
}
if auth != "Bearer llm-2" {
t.Errorf("retried with %q", auth)
}
zedLines(w, text, zedEnded)
})
if status, msg, out := zedServe(t, provider.Chat, "grok-4", body); status != 200 || !strings.Contains(out, "ok") || minted.Load() != 2 {
t.Fatalf("stale token: %d %q %s (minted %d)", status, msg, out, minted.Load())
}
for _, tt := range []struct {
name string
reply func(w http.ResponseWriter)
status int
want string
}{
{"payment", func(w http.ResponseWriter) { w.WriteHeader(402) }, 402, "payment required"},
{"upstream", func(w http.ResponseWriter) {
w.WriteHeader(500)
io.WriteString(w, `{"code":"upstream_http_529","message":"Overloaded","upstream_status":529,"retry_after":2}`)
}, 529, "Overloaded"},
{"failed status", func(w http.ResponseWriter) {
zedLines(w, `{"status":{"failed":{"code":"upstream_http_429","message":"slow down"}}}`)
}, 429, "slow down"},
{"cut short", func(w http.ResponseWriter) { zedLines(w, text) }, 502, "ended before"},
} {
t.Run(tt.name, func(t *testing.T) {
zedUpstream(t, "x_ai", func(w http.ResponseWriter, _ []byte, _ string) { tt.reply(w) })
status, msg, out := zedServe(t, provider.Chat, "grok-4", body)
if status != tt.status || !strings.Contains(msg+out, tt.want) {
t.Fatalf("%d %q %s", status, msg, out)
}
})
}
}
func TestZedRequestShapes(t *testing.T) {
req := &Request{Model: "m", MaxTokens: 10, Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}}}}
for vendor, proto := range map[string]provider.Protocol{"anthropic": provider.Anthropic, "open_ai": provider.Responses, "x_ai": provider.Chat, "google": provider.CodeAssist} {
raw, p, err := zedRequest(req, vendor, "m")
if err != nil || p != proto || !json.Valid(raw) {
t.Errorf("%s: %v %s %s", vendor, err, p, raw)
}
}
if _, _, err := zedRequest(req, "mystery", "m"); err == nil {
t.Error("an unknown provider was written")
}
}
+5 -1
View File
@@ -1859,6 +1859,7 @@ function accountPlan(a) {
if (a.agent === "workbuddy-ai") return a.plan || "WorkBuddy AI";
if (a.agent === "commandcode-plan") return "Command Code" + (a.plan ? " " + t(a.plan) : "");
if (a.agent === "qoder") return "Qoder" + (a.plan ? " " + t(a.plan) : "");
if (a.agent === "zed") return "Zed" + (a.plan ? " " + t(a.plan) : "");
return t("signed in");
}
@@ -4146,6 +4147,9 @@ const SUBS = [
// DimAgent's own subscription: the browser's sign-in at dimagent.cn, its relay serving the vendor's models
{ agent: "dimagent", name: "DimAgent", icon: "dimagent", plans: "Credits", own: true, risk: true,
riskNote: "DimAgent serves this API to its own desktop client; magpie signs requests as that client would, which DimAgent may treat as third-party use and act on. Use an account you can afford to lose." },
// Zed's hosted models (Zed Pro, its trial), signed in at zed.dev as the editor is
{ agent: "zed", name: "Zed", icon: "zed", plans: "Pro · Student · Business", own: true, risk: true,
riskNote: "Zed serves these models to its own editor; magpie signs requests as the editor would, which Zed may treat as third-party use and act on. Use an account you can afford to lose." },
// Kiro's own sign-in page (Google, GitHub, Builder ID, Identity Center); kiro-cli's or the IDE's is read too
{ agent: "kiro", name: "Kiro", icon: "kiro-color", plans: "Free · Pro · Pro+ · Power", own: true },
// Google's sign-ins; Gemini CLI's own account is read too
@@ -4580,7 +4584,7 @@ function renderLoginImport(sub) {
const say = importSay(sub.agent);
tt.append(el("span", "n", t("Import {name} accounts", { name: sub.name })), el("span", "s", say.intro));
if (say.spent) tt.append(el("span", "s", say.spent));
if (sub.risk) tt.append(el("span", "s", t("Google may suspend an Antigravity account it sees used outside Antigravity. Use one you can afford to lose.")));
if (sub.risk) tt.append(el("span", "s", t(sub.riskNote || "Google may suspend an Antigravity account it sees used outside Antigravity. Use one you can afford to lose.")));
const area = el("textarea");
area.rows = 3;
area.spellcheck = false;
+1
View File
@@ -223,6 +223,7 @@ const I18N = {
// providers
"Qoder has no public API for this; magpie signs requests as its desktop client would, which Qoder may treat as third-party use and act on. Use an account you can afford to lose.": "Qoder 没有公开的 API;magpie 会按照其桌面客户端的方式签发请求,Qoder 可能将其视为第三方使用并采取措施。请用一个丢了也不心疼的账号。",
"DimAgent serves this API to its own desktop client; magpie signs requests as that client would, which DimAgent may treat as third-party use and act on. Use an account you can afford to lose.": "DimAgent 只向其桌面客户端提供这个 API;magpie 会按照该客户端的方式签发请求,DimAgent 可能将其视为第三方使用并采取措施。请用一个丢了也不心疼的账号。",
"Zed serves these models to its own editor; magpie signs requests as the editor would, which Zed may treat as third-party use and act on. Use an account you can afford to lose.": "Zed 只向自己的编辑器提供这些模型;magpie 会按照编辑器的方式签发请求,Zed 可能将其视为第三方使用并采取措施。请用一个丢了也不心疼的账号。",
"sponsored": "赞助",
"free": "免费",
"free: it doesn't use the plan's credits": "免费:不消耗套餐积分",
+1
View File
@@ -0,0 +1 @@
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 96 96" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Zed</title><path clip-rule="evenodd" d="M9 6C7.34315 6 6 7.34315 6 9V75H0V9C0 4.02944 4.02944 0 9 0H89.3787C93.3878 0 95.3955 4.84715 92.5607 7.68198L43.0551 57.1875H57V51H63V58.6875C63 61.1728 60.9853 63.1875 58.5 63.1875H37.0551L26.7426 73.5H73.5V36H79.5V73.5C79.5 76.8137 76.8137 79.5 73.5 79.5H20.7426L10.2426 90H87C88.6569 90 90 88.6569 90 87V21H96V87C96 91.9706 91.9706 96 87 96H6.62132C2.61224 96 0.604504 91.1529 3.43934 88.318L52.7574 39H39V45H33V37.5C33 35.0147 35.0147 33 37.5 33H58.7574L69.2574 22.5H22.5V60H16.5V22.5C16.5 19.1863 19.1863 16.5 22.5 16.5H75.2574L85.7574 6H9Z"/></svg>

After

Width:  |  Height:  |  Size: 760 B

+82
View File
@@ -0,0 +1,82 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A Zed subscription (yosocoli5 on X: bought Zed, can it be added?): the add
// sheet lists Zed under Subscriptions with its own logo, and starting its
// sign-in first says what Zed may do about it, in Zed's words rather than
// Antigravity's; nothing is asked of the backend until "Sign in anyway".
// English and Chinese; no backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
function server(lang, asked) {
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json({ providers: [{ id: "openai", name: "OpenAI", icon: "openai", preset: "openai", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/gateway/trace") return json({ routes: [] });
if (url.pathname === "/api/signin") {
asked.push(route.request().postDataJSON());
return json({ id: "s1", agent: "zed", state: "waiting", url: "https://zed.dev/native_app_signin?native_app_port=1" });
}
if (url.pathname.startsWith("/api/signin/")) return json({ id: "s1", agent: "zed", state: "waiting" });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const L = {
en: { title: "Zed accounts can be suspended", note: /Zed serves these models to its own editor/, anyway: "Sign in anyway" },
zh: { title: "Zed 账号可能被封禁", note: /Zed 只向自己的编辑器提供这些模型/, anyway: "仍然登录" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a Zed subscription", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh"]) {
await t.test(lang, async () => {
const w = L[lang];
const page = await (await browser.newContext({ viewport: { width: 900, height: 800 } })).newPage();
const errors = [], asked = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, asked));
await page.goto("http://magpie.test/?view=providers");
await page.locator("#addProvider").click();
const sheet = page.locator("#addSheet");
const row = sheet.locator('.tile[data-pick="Zed"]');
await row.waitFor();
assert.match(await row.getAttribute("title"), /Pro · Student · Business/);
// Zed's own logo, its SVG as the mask
assert.equal(await row.locator(".ic").getAttribute("data-icon"), "zed");
assert.match(await row.locator(".ic .mask").evaluate((m) => m.style.getPropertyValue("--i")), /icons\/zed\.svg/);
const logo = await page.evaluate(async () => { const r = await fetch("icons/zed.svg"); return [r.status, await r.text()]; });
assert.equal(logo[0], 200);
assert.match(logo[1], /<svg[^>]*viewBox="0 0 96 96"/);
await row.click();
const box = sheet.locator(".signing");
await box.waitFor();
assert.equal(await box.locator(".n").textContent(), w.title);
assert.match(await box.locator(".s").textContent(), w.note);
assert.doesNotMatch(await box.textContent(), /Antigravity|Google/);
assert.equal(asked.length, 0, "nothing asked before it is said");
await box.locator("button", { hasText: w.anyway }).click();
await page.waitForFunction(() => document.querySelector("#addSheet .signing")?.textContent.length > 0);
await assert.doesNotReject(async () => { for (let i = 0; i < 50 && !asked.length; i++) await page.waitForTimeout(50); });
assert.deepEqual(asked, [{ agent: "zed" }]);
assert.deepEqual(errors, []);
});
}
});
}
+3
View File
@@ -767,6 +767,9 @@ func Accounts() []Provider {
if p, ok := dimagentAccount(); ok {
out = append(out, p)
}
if p, ok := zedAccount(); ok {
out = append(out, p)
}
for _, agent := range []string{"gemini", "antigravity"} {
if p, ok := googleAccountOf(agent); ok {
out = append(out, p)
+5
View File
@@ -48,6 +48,8 @@ func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota
logins = loginsOf(qoderLogins())
case "dimagent":
logins = dimagentLoginList()
case "zed":
logins = zedLoginList()
case "gemini", "antigravity":
logins = googleLoginList(agent)
case "cursor": // one account, the one cursor-agent is signed in to
@@ -101,6 +103,9 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota {
if l.Agent == "dimagent" {
return dimagentLoginQuota(ctx, l)
}
if l.Agent == "zed" {
return zedLoginQuota(ctx, l)
}
if l.Agent == "cursor" {
return cursorSubscriptionUsage(ctx, l.Plan)
}
+7
View File
@@ -480,6 +480,8 @@ func Logins(agent string) []Login {
return loginsOf(qoderLogins())
case "dimagent":
return dimagentLoginList()
case "zed":
return zedLoginList()
case "gemini", "antigravity":
return googleLoginList(agent)
case "":
@@ -492,6 +494,7 @@ func Logins(agent string) []Login {
side = append(side, cmdLoginList()...)
side = append(side, loginsOf(qoderLogins())...)
side = append(side, dimagentLoginList()...)
side = append(side, zedLoginList()...)
side = append(side, googleLoginList("gemini")...)
side = append(side, googleLoginList("antigravity")...)
}
@@ -543,6 +546,8 @@ func SwitchLogin(agent, user string) error {
return switchSideLogin("qoder", user, qoderLogins())
case "dimagent":
return switchDimAgentLogin(user)
case "zed":
return switchZedLogin(user)
case "gemini", "antigravity":
return switchGoogleLogin(agent, user)
}
@@ -679,6 +684,8 @@ func ForgetLogin(agent, user string) error {
return forgetQoderLogin(user)
case "dimagent":
return forgetDimAgentLogin(user)
case "zed":
return forgetZedLogin(user)
case "gemini", "antigravity":
return forgetGoogleLogin(agent, user)
}
+5
View File
@@ -43,6 +43,8 @@ func SetLoginOn(agent, user string, on bool) error {
return setSideLoginOn("qoder", user, on, qoderLogins())
case "dimagent":
return setDimAgentLoginOn(user, on)
case "zed":
return setZedLoginOn(user, on)
case "gemini", "antigravity":
return setGoogleLoginOn(agent, user, on)
}
@@ -94,6 +96,9 @@ func (p Provider) AlsoOn() []Provider {
if p.Account != nil && p.Account.Agent == "dimagent" {
return dimagentAlsoOn()
}
if p.Account != nil && p.Account.Agent == "zed" {
return zedAlsoOn()
}
if p.Account != nil && (p.Account.Agent == "gemini" || p.Account.Agent == "antigravity") {
return googleAlsoOn(p.Account.Agent)
}
+1 -1
View File
@@ -421,7 +421,7 @@ func freeName(name string) string {
}
// accountIDs are the ids of the subscriptions magpie can list (account.go).
var accountIDs = []string{"antigravity", "claude", "codex", CommandCodePlanID, "copilot", "cursor", "devin", "dimagent", "gemini", "grok", "kiro", "qoder", "workbuddy", WorkBuddyAIID, "zcode"}
var accountIDs = []string{"antigravity", "claude", "codex", CommandCodePlanID, "copilot", "cursor", "devin", "dimagent", "gemini", "grok", "kiro", "qoder", "workbuddy", WorkBuddyAIID, "zcode", "zed"}
func stored(id string) bool {
for _, p := range load().Providers {
+1 -1
View File
@@ -255,7 +255,7 @@ func addSideLogin(l savedLogin, ownUser string, dup func(savedLogin)) error {
// agent's own store as Claude Code's and Codex's are.
func sideAgent(agent string) bool {
switch agent {
case "grok", "copilot", "zcode", "kiro", "devin", "workbuddy", WorkBuddyAIID, CommandCodePlanID, "gemini", "antigravity", "qoder", "dimagent":
case "grok", "copilot", "zcode", "kiro", "devin", "workbuddy", WorkBuddyAIID, CommandCodePlanID, "gemini", "antigravity", "qoder", "dimagent", "zed":
return true
}
return false
+6
View File
@@ -262,6 +262,12 @@ func (s *signInFlow) begin() error {
if err := startDimAgentSignIn(s); err != nil {
return err
}
case "zed":
// Zed's own sign-in: zed.dev sends the browser back to a port magpie
// listens on, with the account's token encrypted to magpie's key
if err := startZedSignIn(s); err != nil {
return err
}
case "zcode":
// Z.ai's sign-in, as ZCode makes it
if err := startZCodeSignIn(s); err != nil {
+3
View File
@@ -255,6 +255,9 @@ func fetchSubscriptionUsage() []SubscriptionQuota {
if !hidden["dimagent"] {
fetches = append(fetches, perLogin(via("dimagent"), dimagentLoginList(), "DimAgent", "dimagent")...)
}
if !hidden["zed"] {
fetches = append(fetches, perLogin(via("zed"), zedLoginList(), "Zed", "zed")...)
}
for _, agent := range []string{"gemini", "antigravity"} {
if hidden[agent] {
continue
+273
View File
@@ -0,0 +1,273 @@
package provider
// A Zed subscription is the account the Zed editor signs in to (Zed Pro, its
// trial, a student or business plan): the models Zed hosts — Anthropic's,
// OpenAI's, Google's and xAI's — asked through cloud.zed.dev with a
// short-lived token the account's sign-in is traded for.
//
// The sign-in is Zed's own, run by magpie (zed_signin.go) and kept in
// logins.json; the models are served by the gateway (gateway/zed.go), which
// writes each request in its model's own provider's API. The protocol lives
// in internal/zed.
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/zed"
)
// Where Zed's API and sign-in page are; vars so tests can point them
// elsewhere.
var (
zedCloud = zed.CloudURL
zedSite = zed.SiteURL
)
var zedClient = &http.Client{Timeout: 20 * time.Second}
// ErrZedSignIn is an account Zed no longer takes: it must be signed in again.
var ErrZedSignIn = errors.New("the Zed sign-in has expired — sign in again")
// zedCreds is what a Zed sign-in leaves: the account's id and access token
// (which last until Zed refuses them), the machine id they were issued with,
// the organization its models are asked under, and the model list last read.
type zedCreds struct {
UserID string `json:"userId"`
Access string `json:"accessToken"`
SystemID string `json:"systemId"`
Org string `json:"organizationId,omitempty"`
Login string `json:"login,omitempty"`
Name string `json:"name,omitempty"`
Plan string `json:"plan,omitempty"` // plan_v3, e.g. zed_pro
Models json.RawMessage `json:"models,omitempty"`
}
func zedSaved(l savedLogin) (zedCreds, bool) {
var c zedCreds
if json.Unmarshal(l.Auth, &c) != nil || c.UserID == "" || c.Access == "" {
return zedCreds{}, false
}
return c, true
}
type zedLogin struct {
Login
creds zedCreds
}
// zedLogins is every Zed account signed in, the one in use first.
func zedLogins() []zedLogin {
var out []zedLogin
for _, l := range sideLogins("zed", "", func(l savedLogin) bool {
_, ok := zedSaved(l)
return ok
}) {
c, _ := zedSaved(l.saved)
a := zedLogin{Login: l.Login, creds: c}
a.Lapsed = l.saved.Lapsed
out = append(out, a)
}
return out
}
func zedLoginList() []Login { return loginsOf(zedSide()) }
func zedSide() []sideLogin {
var out []sideLogin
for _, l := range zedLogins() {
out = append(out, sideLogin{Login: l.Login})
}
return out
}
func switchZedLogin(user string) error { return switchSideLogin("zed", user, zedSide()) }
func setZedLoginOn(user string, on bool) error { return setSideLoginOn("zed", user, on, zedSide()) }
func forgetZedLogin(user string) error {
if err := forgetSideLogin("zed", user, zedSide(), nil); err != nil {
return err
}
zedTokens.forget(user)
return nil
}
// zedLookup reads one saved account.
func zedLookup(user string) (zedCreds, bool) {
loginsMu.Lock()
defer loginsMu.Unlock()
for _, l := range readLogins() {
if l.Agent == "zed" && strings.EqualFold(l.User, user) {
return zedSaved(l)
}
}
return zedCreds{}, false
}
// zedEdit changes one saved account's credentials.
func zedEdit(user string, fn func(c *zedCreds, l *savedLogin)) error {
return editSideLogin("zed", user, func(ls []savedLogin, i int) ([]savedLogin, error) {
c, ok := zedSaved(ls[i])
if !ok {
return nil, errors.New("Zed: unreadable sign-in")
}
fn(&c, &ls[i])
b, err := json.Marshal(c)
if err != nil {
return nil, err
}
ls[i].Auth, ls[i].Seen = b, time.Now().UTC()
return ls, nil
})
}
// zedLapse records that Zed refused an account's sign-in.
func zedLapse(user string) error {
msg := user + "'s Zed sign-in has expired — sign in again"
_ = editSideLogin("zed", user, func(ls []savedLogin, i int) ([]savedLogin, error) {
ls[i].Lapsed = msg
return ls, nil
})
return fmt.Errorf("%s: %w", user, ErrZedSignIn)
}
// zedRefused is Zed turning the account's own sign-in away.
func zedRefused(err error) bool {
var st *zed.HTTPStatusError
return errors.As(err, &st) && st.StatusCode == http.StatusUnauthorized
}
// ---- the model token ----------------------------------------------------------
// zedTokens keeps each account's LLM token in memory: Zed mints them for an
// hour or so and says when one is stale, so none is written down.
var zedTokens = &zedTokenCache{m: map[string]string{}}
type zedTokenCache struct {
mu sync.Mutex // held while one is minted, so two requests don't both mint
m map[string]string
}
func (t *zedTokenCache) forget(user string) {
t.mu.Lock()
delete(t.m, strings.ToLower(user))
t.mu.Unlock()
}
// ZedToken is a live model token for an account, minted anew when renew is
// set (the last one was refused) or none is kept.
func ZedToken(ctx context.Context, user string, renew bool) (string, error) {
t := zedTokens
t.mu.Lock()
defer t.mu.Unlock()
key := strings.ToLower(user)
if tok := t.m[key]; tok != "" && !renew {
return tok, nil
}
c, ok := zedLookup(user)
if !ok {
return "", fmt.Errorf("no Zed account %q", user)
}
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
defer cancel()
tok, err := zed.LLMToken(ctx, zedClient, zedCloud, c.UserID, c.Access, c.SystemID, c.Org)
if err != nil {
delete(t.m, key)
if zedRefused(err) {
return "", zedLapse(user)
}
return "", err
}
t.m[key] = tok
return tok, nil
}
// ZedCloud is where the gateway asks an account's models.
func ZedCloud() string { return zedCloud }
// ZedProviderOf is the provider (anthropic, open_ai, google, x_ai) whose API
// a model is asked in, as the account's list said, else guessed from its id.
func ZedProviderOf(user, model string) string {
if c, ok := zedLookup(user); ok {
if p := zed.ProviderOf(c.Models, model); p != "" {
return p
}
}
return zed.GuessProvider(model)
}
// ---- models -----------------------------------------------------------------
func zedFetchModels(ctx context.Context, user string) ([]catalog.Model, error) {
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
var raw []byte
for try := 0; ; try++ {
tok, err := ZedToken(ctx, user, try > 0)
if err != nil {
return nil, err
}
var h http.Header
raw, h, err = zed.FetchModels(ctx, zedClient, zedCloud, tok)
var st *zed.HTTPStatusError
if err != nil && try == 0 && errors.As(err, &st) && zed.TokenStale(st.StatusCode, h) {
continue
}
if err != nil {
return nil, err
}
break
}
ms, err := zed.ParseModels(raw)
if errors.Is(err, zed.ErrNoModels) {
return nil, errors.New("Zed lists no models for this account — its plan may not include Zed's hosted models (see zed.dev/account)")
}
if err != nil {
return nil, err
}
if err := zedEdit(user, func(c *zedCreds, _ *savedLogin) { c.Models = raw }); err != nil {
return nil, err
}
return ms, catalog.SaveLive("zed", zedCloud, ms)
}
// ---- the provider -----------------------------------------------------------
func zedProvider(l zedLogin) Provider {
user := l.User
a := &Account{Agent: "zed", User: user, Plan: l.Plan, Stream: true}
a.models = func() []catalog.Model {
c, _ := zedLookup(user)
ms, _ := zed.ParseModels(c.Models)
return ms
}
a.fetch = func(ctx context.Context) ([]catalog.Model, error) { return zedFetchModels(ctx, user) }
return Provider{ID: "zed", Name: "Zed", Icon: "zed", Website: "https://zed.dev", Account: a}
}
func zedAccount() (Provider, bool) {
ls := zedLogins()
if len(ls) == 0 {
return Provider{}, false
}
return zedProvider(ls[0]), true
}
// zedAlsoOn is the Zed accounts in use behind the first.
func zedAlsoOn() []Provider {
var out []Provider
for _, l := range zedLogins() {
if !l.Active && l.On {
out = append(out, zedProvider(l))
}
}
return out
}
+123
View File
@@ -0,0 +1,123 @@
package provider
// Zed's sign-in, run by magpie as the editor runs it: a key is made, the
// browser opens zed.dev's sign-in page with its public half and the port
// magpie listens on, and comes back there with the account's id and its
// access token encrypted to the key.
import (
"context"
"crypto/rsa"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"strings"
"time"
"github.com/yetone/magpie/internal/zed"
)
func startZedSignIn(s *signInFlow) error {
key, pub, err := zed.NewKey()
if err != nil {
return fmt.Errorf("Zed sign-in: %w", err)
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return fmt.Errorf("Zed sign-in: %w", err)
}
systemID := zed.NewSystemID()
port := ln.Addr().(*net.TCPAddr).Port
type callback struct{ uid, token string }
got := make(chan callback, 1)
mux := http.NewServeMux()
// Zed's page sends the browser to the port on whatever path; the query is
// what counts
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
uid, tok := q.Get("user_id"), q.Get("access_token")
if uid == "" || tok == "" {
http.NotFound(w, r)
return
}
select {
case got <- callback{uid, tok}:
default:
}
http.Redirect(w, r, zedSite+"/native_app_signin_succeeded", http.StatusFound)
})
srv := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}
ctx, cancel := context.WithCancel(context.Background())
s.mu.Lock()
s.st.URL = zed.SignInURL(zedSite, port, pub, systemID)
s.srv, s.stop = srv, cancel
s.mu.Unlock()
go func() { _ = srv.Serve(ln) }()
go func() {
defer cancel()
var cb callback
select {
case cb = <-got:
case <-ctx.Done():
return
case <-time.After(signInTimeout):
s.finish(SignInState{State: "failed", Error: "the sign-in timed out; start it again"})
return
}
user, err := zedSignedInWith(ctx, key, cb.uid, cb.token, systemID)
if err != nil {
s.finish(SignInState{State: "failed", Error: err.Error()})
return
}
s.finish(SignInState{State: "done", User: user, Using: strings.EqualFold(activeOf(zedSide()), user)})
}()
return nil
}
// zedSignedInWith reads the callback's token, asks Zed who the account is,
// keeps it and reads its models.
func zedSignedInWith(ctx context.Context, key *rsa.PrivateKey, uid, ciphertext, systemID string) (string, error) {
access, err := zed.Decrypt(key, ciphertext)
if err != nil {
return "", fmt.Errorf("Zed sign-in: %w", err)
}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
me, err := zed.FetchMe(ctx, zedClient, zedCloud, uid, access, systemID)
if err != nil {
return "", err
}
org := me.Org()
if me.ModelsOff(org) {
return "", errors.New("Zed: this account's organization has Zed's hosted models turned off")
}
c := zedCreds{UserID: uid, Access: access, SystemID: systemID, Org: org,
Login: firstNonEmpty(me.User.GitHubLogin, me.User.Username), Name: me.User.Name, Plan: me.PlanID(org)}
who := me.Who()
// the account's own list, so the picker has it before its first request
if tok, err := zed.LLMToken(ctx, zedClient, zedCloud, uid, access, systemID, org); err == nil {
if raw, _, err := zed.FetchModels(ctx, zedClient, zedCloud, tok); err == nil {
if _, err := zed.ParseModels(raw); err == nil {
c.Models = raw
}
}
}
auth, err := json.Marshal(c)
if err != nil {
return "", err
}
if err := addSideLogin(savedLogin{Agent: "zed", User: who, Plan: zed.PlanName(c.Plan), Auth: auth}, "", func(savedLogin) {}); err != nil {
return "", err
}
// signed in again: whatever Zed refused before is over
_ = editSideLogin("zed", who, func(ls []savedLogin, i int) ([]savedLogin, error) {
ls[i].Lapsed = ""
return ls, nil
})
zedTokens.forget(who)
forgetAccountCaches()
return who, nil
}
+205
View File
@@ -0,0 +1,205 @@
package provider
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
)
// zedCloudStub stands in for cloud.zed.dev (and zed.dev's sign-in page): it
// checks every /client/* call is signed with the account's pair and the
// machine id it was issued with, and every /models call with the last model
// token it minted.
type zedCloudStub struct {
t *testing.T
minted atomic.Int32
refuse atomic.Bool // llm_tokens answers 401: the sign-in is gone
plan string
systemID string
}
func (z *zedCloudStub) serve(w http.ResponseWriter, r *http.Request) {
t := z.t
switch r.URL.Path {
case "/client/users/me", "/client/llm_tokens":
if r.Header.Get("Authorization") != "4242 plain-access" {
t.Errorf("%s signed %q", r.URL.Path, r.Header.Get("Authorization"))
}
if !strings.HasPrefix(r.Header.Get("User-Agent"), "Zed/") {
t.Errorf("%s User-Agent %q", r.URL.Path, r.Header.Get("User-Agent"))
}
if z.systemID != "" && r.Header.Get("x-zed-system-id") != z.systemID {
t.Errorf("%s from system %q, want %q", r.URL.Path, r.Header.Get("x-zed-system-id"), z.systemID)
}
if r.URL.Path == "/client/users/me" {
_, _ = io.WriteString(w, `{"user":{"legacy_user_id":4242,"github_login":"octo","name":"Octo Cat"},
"organizations":[{"id":"org-team","name":"Team"},{"id":"org-me","name":"Me","is_personal":true}],
"default_organization_id":"org-me","plans_by_organization":{"org-me":"`+z.plan+`"},
"plan":{"plan_v3":"`+z.plan+`","subscription_period":{"started_at":"2026-09-01T00:00:00Z","ended_at":"2026-10-01T00:00:00Z"},"has_overdue_invoices":false}}`)
return
}
if z.refuse.Load() {
w.WriteHeader(401)
return
}
var body struct {
Org string `json:"organization_id"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if body.Org != "org-me" {
t.Errorf("model token asked for organization %q, want the default one", body.Org)
}
n := z.minted.Add(1)
_, _ = io.WriteString(w, `{"token":"llm-`+string(rune('0'+n))+`"}`)
case "/models":
if want := "Bearer llm-" + string(rune('0'+z.minted.Load())); r.Header.Get("Authorization") != want {
t.Errorf("/models signed %q, want %q", r.Header.Get("Authorization"), want)
}
_, _ = io.WriteString(w, `{"models":[{"provider":"anthropic","id":"claude-sonnet-4-5","display_name":"Claude Sonnet 4.5","max_token_count":200000},
{"provider":"open_ai","id":"gpt-5","display_name":"GPT-5"}],"default_model":"claude-sonnet-4-5"}`)
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
w.WriteHeader(404)
}
}
func zedStub(t *testing.T, plan string) *zedCloudStub {
t.Helper()
z := &zedCloudStub{t: t, plan: plan}
srv := httptest.NewServer(http.HandlerFunc(z.serve))
t.Cleanup(srv.Close)
oldCloud, oldSite := zedCloud, zedSite
zedCloud, zedSite = srv.URL, "https://zed.test"
t.Cleanup(func() { zedCloud, zedSite = oldCloud, oldSite })
zedTokens.m = map[string]string{}
return z
}
// zedBrowser does what zed.dev's page does once the user signs in: sends
// the browser back to magpie's port with the token encrypted to its key.
func zedBrowser(t *testing.T, signInURL string) *http.Response {
t.Helper()
u, err := url.Parse(signInURL)
if err != nil || u.Host != "zed.test" || u.Path != "/native_app_signin" {
t.Fatalf("sign-in URL %q", signInURL)
}
q := u.Query()
der, err := base64.URLEncoding.DecodeString(q.Get("native_app_public_key"))
if err != nil {
t.Fatal(err)
}
pk, err := x509.ParsePKCS1PublicKey(der)
if err != nil {
t.Fatal(err)
}
ct, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pk, []byte("plain-access"), nil)
if err != nil {
t.Fatal(err)
}
back := "http://127.0.0.1:" + q.Get("native_app_port") + "/?user_id=4242&access_token=" + base64.URLEncoding.EncodeToString(ct)
c := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
res, err := c.Get(back)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
return res
}
func TestZedSignIn(t *testing.T) {
signIn(t)
z := zedStub(t, "zed_pro")
st, err := StartSignIn("zed")
if err != nil {
t.Fatal(err)
}
u, _ := url.Parse(st.URL)
z.systemID = u.Query().Get("system_id")
if z.systemID == "" {
t.Fatal("the sign-in URL carries no system id")
}
res := zedBrowser(t, st.URL)
if res.StatusCode != http.StatusFound || res.Header.Get("Location") != "https://zed.test/native_app_signin_succeeded" {
t.Fatalf("the browser was answered %d %q", res.StatusCode, res.Header.Get("Location"))
}
done := dimagentWaitSignIn(t, st.ID)
if done.State != "done" || done.User != "octo" {
t.Fatalf("sign-in ended %+v", done)
}
ls := Logins("zed")
if len(ls) != 1 || ls[0].User != "octo" || ls[0].Plan != "Pro" {
t.Fatalf("logins %+v", ls)
}
c, _ := zedLookup("octo")
if c.Access != "plain-access" || c.UserID != "4242" || c.Org != "org-me" || c.SystemID != z.systemID || len(c.Models) == 0 {
t.Fatalf("saved %+v", c)
}
var p Provider
for _, a := range Accounts() {
if a.ID == "zed" {
p = a
}
}
if p.Account == nil || p.Account.User != "octo" {
t.Fatalf("no Zed provider among the accounts")
}
if ms := p.Account.models(); len(ms) != 2 || ms[0].ID != "claude-sonnet-4-5" {
t.Fatalf("models %+v", ms)
}
if ZedProviderOf("octo", "gpt-5") != "open_ai" || ZedProviderOf("octo", "gemini-9") != "google" {
t.Fatal("ZedProviderOf")
}
// the model token is kept, and minted again only when asked to
ctx := context.Background()
a, _ := ZedToken(ctx, "octo", false)
b, _ := ZedToken(ctx, "octo", false)
fresh, _ := ZedToken(ctx, "octo", true)
if a != b || fresh == a {
t.Fatalf("tokens %q %q %q", a, b, fresh)
}
if ms, err := p.Account.fetch(ctx); err != nil || len(ms) != 2 {
t.Fatalf("fetch: %v %v", ms, err)
}
q := zedLoginQuota(ctx, ls[0])
if q.Error != "" || q.Plan != "Pro" || q.Until == nil || !q.Until.Equal(time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)) {
t.Fatalf("quota %+v", q)
}
// Zed refusing the account's pair ends it, and says so
z.refuse.Store(true)
if _, err := ZedToken(ctx, "octo", true); !errors.Is(err, ErrZedSignIn) {
t.Fatalf("a refused sign-in: %v", err)
}
if ls := Logins("zed"); len(ls) != 1 || ls[0].Lapsed == "" {
t.Fatalf("the refused account isn't marked: %+v", ls)
}
}
func TestZedFreePlanQuota(t *testing.T) {
signIn(t)
zedStub(t, "zed_free")
auth, _ := json.Marshal(zedCreds{UserID: "4242", Access: "plain-access", Org: "org-me"})
if err := addSideLogin(savedLogin{Agent: "zed", User: "octo", Auth: auth}, "", func(savedLogin) {}); err != nil {
t.Fatal(err)
}
q := zedLoginQuota(context.Background(), Logins("zed")[0])
if q.Plan != "No plan" || q.Error != "" {
t.Fatalf("quota %+v", q)
}
}
+53
View File
@@ -0,0 +1,53 @@
package provider
// What a Zed account says of its plan. Zed tells its editor the plan and its
// billing period, not how much of the model allowance is spent, so that is
// all magpie can show: the plan's name, when the period ends, and a plan
// Zed won't serve (overdue invoices) as the error it is.
import (
"context"
"time"
"github.com/yetone/magpie/internal/zed"
)
func zedLoginQuota(ctx context.Context, l Login) SubscriptionQuota {
q := SubscriptionQuota{Provider: "zed", Name: "Zed", Icon: "zed", Plan: l.Plan, User: l.User, Windows: []QuotaWindow{}}
c, ok := zedLookup(l.User)
if !ok {
q.Error = "no such Zed account"
return q
}
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
me, err := zed.FetchMe(ctx, zedClient, zedCloud, c.UserID, c.Access, c.SystemID)
if err != nil {
if zedRefused(err) {
err = zedLapse(l.User)
}
q.Error = err.Error()
return q
}
org := c.Org
if org == "" {
org = me.Org()
}
plan := me.PlanID(org)
q.Plan = zed.PlanName(plan)
if plan != c.Plan {
_ = zedEdit(l.User, func(c *zedCreds, s *savedLogin) { c.Plan, s.Plan = plan, q.Plan })
}
if p := me.Plan.SubscriptionPeriod; p != nil {
if at, err := time.Parse(time.RFC3339, p.EndedAt); err == nil {
q.Until = &at
}
}
switch {
case me.Plan.HasOverdueInvoice:
q.Error = "Zed: this account has an overdue invoice, so its models are paused (see zed.dev/account)"
case plan == "zed_free" || plan == "":
q.Plan = "No plan"
}
return q
}
+590
View File
@@ -0,0 +1,590 @@
// Package zed speaks to Zed's hosted models, the way the Zed editor does for
// a Zed Pro (or trial, student, business) account.
//
// Read from Zed's source (github.com/zed-industries/zed, 1.23.0):
//
// - Sign-in (crates/client/src/client.rs, crates/rpc/src/auth.rs): the app
// makes an RSA-2048 key, listens on a port of 127.0.0.1 and opens
// zed.dev/native_app_signin?native_app_port=&native_app_public_key=, the
// key PKCS#1 DER in padded URL-safe base64. The browser comes back to that
// port, on any path, with user_id and access_token, the token encrypted to
// the key (RSA-OAEP SHA-256, PKCS#1 v1.5 before that). The pair is sent
// as "Authorization: <user_id> <access_token>" to cloud.zed.dev/client/*
// and lasts until a 401.
// - GET /client/users/me is the account: its organizations, the plan.
// - POST /client/llm_tokens {"organization_id"} trades the pair for a
// short-lived LLM token, renewed on a 401 or an x-zed-expired-token /
// x-zed-outdated-token reply.
// - GET /models lists what the account may call; POST /completions takes
// {provider, model, provider_request} — the provider's own request:
// Anthropic Messages, OpenAI Responses, xAI chat completions, Gemini's
// generateContent — and streams newline-delimited JSON, each line
// {"event": <the provider's own stream event>} or a status.
package zed
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"runtime"
"strconv"
"strings"
"github.com/yetone/magpie/internal/catalog"
)
const (
// SiteURL is where the browser signs in.
SiteURL = "https://zed.dev"
// CloudURL is the account and model API.
CloudURL = "https://cloud.zed.dev"
// Version is the Zed release the requests say they come from.
Version = "1.23.0"
// SucceededURL is where the browser is sent once the callback is read,
// as Zed sends it.
SucceededURL = SiteURL + "/native_app_signin_succeeded"
)
// UserAgent is Zed's: Zed/<version> (<os>; <arch>), in Rust's names.
func UserAgent() string {
os := runtime.GOOS
if os == "darwin" {
os = "macos"
}
arch := map[string]string{"arm64": "aarch64", "amd64": "x86_64"}[runtime.GOARCH]
if arch == "" {
arch = runtime.GOARCH
}
return fmt.Sprintf("Zed/%s (%s; %s)", Version, os, arch)
}
// HTTPStatusError is a reply that wasn't a success, its status kept typed.
type HTTPStatusError struct {
StatusCode int
Body string
Header http.Header
}
func (e *HTTPStatusError) Error() string {
msg := Failure(e.StatusCode, []byte(e.Body))
return fmt.Sprintf("Zed: %s (%d)", msg, e.StatusCode)
}
// Failure is the message in an error body: {"code","message"}, else the body
// itself, else the status's name.
func Failure(status int, body []byte) string {
var e struct {
Code string `json:"code"`
Message string `json:"message"`
Error any `json:"error"`
}
if json.Unmarshal(body, &e) == nil {
if e.Message != "" {
return e.Message
}
if s, ok := e.Error.(string); ok && s != "" {
return s
}
if e.Code != "" {
return e.Code
}
}
if s := strings.TrimSpace(string(body)); s != "" && len(s) < 500 {
return s
}
if status == http.StatusPaymentRequired {
return "payment required: this Zed account has no plan that calls models, or its allowance is used up"
}
return http.StatusText(status)
}
// ---- sign-in ---------------------------------------------------------------
// NewKey is the key the access token comes back encrypted to, and its public
// half as the sign-in page takes it.
func NewKey() (*rsa.PrivateKey, string, error) {
k, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, "", err
}
return k, base64.URLEncoding.EncodeToString(x509.MarshalPKCS1PublicKey(&k.PublicKey)), nil
}
// SignInURL is the page to open for a sign-in coming back to port.
func SignInURL(site string, port int, publicKey, systemID string) string {
q := url.Values{}
q.Set("native_app_port", strconv.Itoa(port))
q.Set("native_app_public_key", publicKey)
if systemID != "" {
q.Set("system_id", systemID)
}
return site + "/native_app_signin?" + q.Encode()
}
// Decrypt reads the access token the callback carried.
func Decrypt(k *rsa.PrivateKey, ciphertext string) (string, error) {
ct, err := base64.URLEncoding.DecodeString(ciphertext)
if err != nil {
if ct, err = base64.RawURLEncoding.DecodeString(strings.TrimRight(ciphertext, "=")); err != nil {
return "", fmt.Errorf("the access token isn't base64: %w", err)
}
}
pt, err := rsa.DecryptOAEP(sha256.New(), nil, k, ct, nil)
if err != nil {
if pt, err = rsa.DecryptPKCS1v15(nil, k, ct); err != nil {
return "", errors.New("the access token couldn't be decrypted")
}
}
return string(pt), nil
}
// NewSystemID is a random UUID v4, what Zed calls the machine.
func NewSystemID() string {
var b [16]byte
_, _ = rand.Read(b[:])
b[6] = b[6]&0x0f | 0x40
b[8] = b[8]&0x3f | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}
// ---- the account -----------------------------------------------------------
// Me is GET /client/users/me, as far as magpie reads it.
type Me struct {
User struct {
LegacyID int64 `json:"legacy_user_id"`
Username string `json:"username"`
GitHubLogin string `json:"github_login"`
Name string `json:"name"`
} `json:"user"`
Organizations []struct {
ID string `json:"id"`
Name string `json:"name"`
IsPersonal bool `json:"is_personal"`
} `json:"organizations"`
DefaultOrganizationID string `json:"default_organization_id"`
PlansByOrganization map[string]string `json:"plans_by_organization"`
ConfigByOrganization map[string]struct {
ModelsEnabled *bool `json:"is_zed_model_provider_enabled"`
} `json:"configuration_by_organization"`
Plan struct {
V3 string `json:"plan_v3"`
SubscriptionPeriod *struct {
StartedAt string `json:"started_at"`
EndedAt string `json:"ended_at"`
} `json:"subscription_period"`
TrialStartedAt string `json:"trial_started_at"`
AccountTooYoung bool `json:"is_account_too_young"`
HasOverdueInvoice bool `json:"has_overdue_invoices"`
} `json:"plan"`
}
// Who names the account: its GitHub login, its username, its name, its id.
func (m *Me) Who() string {
for _, s := range []string{m.User.GitHubLogin, m.User.Username, m.User.Name} {
if s = strings.TrimSpace(s); s != "" {
return s
}
}
if m.User.LegacyID != 0 {
return strconv.FormatInt(m.User.LegacyID, 10)
}
return "Zed account"
}
// Org is the organization the account's models are asked under: its
// default one when it is among its organizations, else its first, as Zed
// picks it.
func (m *Me) Org() string {
for _, o := range m.Organizations {
if o.ID == m.DefaultOrganizationID {
return o.ID
}
}
if len(m.Organizations) > 0 {
return m.Organizations[0].ID
}
return m.DefaultOrganizationID
}
// PlanID is the organization's plan, else the account's.
func (m *Me) PlanID(org string) string {
if p := m.PlansByOrganization[org]; p != "" {
return p
}
return m.Plan.V3
}
// ModelsOff is set when the organization has Zed's models turned off.
func (m *Me) ModelsOff(org string) bool {
c, ok := m.ConfigByOrganization[org]
return ok && c.ModelsEnabled != nil && !*c.ModelsEnabled
}
// PlanName is a plan's id as a reader would name it.
func PlanName(id string) string {
switch id {
case "zed_pro":
return "Pro"
case "zed_pro_trial":
return "Pro Trial"
case "zed_business":
return "Business"
case "zed_student":
return "Student"
case "zed_vip":
return "VIP"
case "zed_free", "":
return "Free"
}
return strings.TrimPrefix(id, "zed_")
}
// cloud sends one /client/* request with the account's pair.
func cloud(ctx context.Context, c *http.Client, base, method, path, uid, token, systemID string, body any) ([]byte, error) {
var rd io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
rd = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, base+path, rd)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", uid+" "+token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", UserAgent())
if systemID != "" {
req.Header.Set("x-zed-system-id", systemID)
}
res, err := c.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
b, err := io.ReadAll(io.LimitReader(res.Body, 4<<20))
if err != nil {
return nil, err
}
if res.StatusCode/100 != 2 {
return nil, &HTTPStatusError{StatusCode: res.StatusCode, Body: string(b), Header: res.Header}
}
return b, nil
}
// FetchMe reads the account.
func FetchMe(ctx context.Context, c *http.Client, base, uid, token, systemID string) (*Me, error) {
b, err := cloud(ctx, c, base, http.MethodGet, "/client/users/me", uid, token, systemID, nil)
if err != nil {
return nil, err
}
var m Me
if err := json.Unmarshal(b, &m); err != nil {
return nil, fmt.Errorf("Zed: an unreadable account: %w", err)
}
return &m, nil
}
// LLMToken trades the account's pair for a token the models take.
func LLMToken(ctx context.Context, c *http.Client, base, uid, token, systemID, org string) (string, error) {
b, err := cloud(ctx, c, base, http.MethodPost, "/client/llm_tokens", uid, token, systemID, map[string]string{"organization_id": org})
if err != nil {
return "", err
}
var out struct {
Token string `json:"token"`
}
if json.Unmarshal(b, &out) != nil || out.Token == "" {
return "", errors.New("Zed: no model token in the reply")
}
return out.Token, nil
}
// TokenStale says a model request was turned away for its LLM token, which a
// new one would fix.
func TokenStale(status int, h http.Header) bool {
return status == http.StatusUnauthorized || h.Get("x-zed-expired-token") != "" || h.Get("x-zed-outdated-token") != ""
}
// ---- models ----------------------------------------------------------------
// ModelsHeaders are what a /models request carries beside its token.
func ModelsHeaders(h http.Header, llmToken string) {
h.Set("Authorization", "Bearer "+llmToken)
h.Set("x-zed-client-supports-x-ai", "true")
h.Set("User-Agent", UserAgent())
}
// FetchModels reads GET /models as it came.
func FetchModels(ctx context.Context, c *http.Client, base, llmToken string) ([]byte, http.Header, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/models", nil)
if err != nil {
return nil, nil, err
}
ModelsHeaders(req.Header, llmToken)
res, err := c.Do(req)
if err != nil {
return nil, nil, err
}
defer res.Body.Close()
b, err := io.ReadAll(io.LimitReader(res.Body, 4<<20))
if err != nil {
return nil, nil, err
}
if res.StatusCode/100 != 2 {
return nil, res.Header, &HTTPStatusError{StatusCode: res.StatusCode, Body: string(b), Header: res.Header}
}
return b, res.Header, nil
}
// Model is one model /models lists.
type Model struct {
Provider string `json:"provider"` // anthropic, open_ai, google, x_ai
ID string `json:"id"`
DisplayName string `json:"display_name"`
MaxTokens int `json:"max_token_count"`
MaxOutputTokens int `json:"max_output_tokens"`
SupportsImages bool `json:"supports_images"`
SupportsThink bool `json:"supports_thinking"`
Efforts []struct {
Value string `json:"value"`
IsDefault bool `json:"is_default"`
} `json:"supported_effort_levels"`
Disabled bool `json:"is_disabled"`
}
// Models is GET /models's reply.
type Models struct {
Models []Model `json:"models"`
Default string `json:"default_model"`
Recommended []string `json:"recommended_models"`
}
// ErrNoModels is a reply that lists nothing callable.
var ErrNoModels = errors.New("Zed lists no models for this account")
// ParseModels reads /models as the catalog's models, the disabled ones left
// out.
func ParseModels(raw []byte) ([]catalog.Model, error) {
if len(raw) == 0 {
return nil, ErrNoModels
}
var r Models
if err := json.Unmarshal(raw, &r); err != nil {
return nil, fmt.Errorf("Zed: an unreadable model list: %w", err)
}
var out []catalog.Model
for _, m := range r.Models {
if m.Disabled || m.ID == "" || Wire(m.Provider) == "" {
continue
}
cm := catalog.Model{ID: m.ID, Name: m.DisplayName, Provider: vendor(m.Provider),
Context: m.MaxTokens, Output: m.MaxOutputTokens, Images: m.SupportsImages}
if cm.Name == "" {
cm.Name = m.ID
}
img := m.SupportsImages
cm.ImageInput = &img
for _, e := range m.Efforts {
if e.Value != "" {
cm.Efforts = append(cm.Efforts, e.Value)
}
}
out = append(out, cm)
}
if len(out) == 0 {
return nil, ErrNoModels
}
return out, nil
}
// ProviderOf is the provider /models names for model, "" when it isn't
// listed.
func ProviderOf(raw []byte, model string) string {
var r Models
if json.Unmarshal(raw, &r) != nil {
return ""
}
for _, m := range r.Models {
if m.ID == model {
return m.Provider
}
}
return ""
}
// Wire is the API a provider's requests are written in: "anthropic",
// "responses", "chat" or "gemini"; "" for one magpie can't write.
func Wire(provider string) string {
switch provider {
case "anthropic":
return "anthropic"
case "open_ai":
return "responses"
case "x_ai":
return "chat"
case "google":
return "gemini"
}
return ""
}
// vendor is the models.dev id of a Zed provider.
func vendor(p string) string {
switch p {
case "open_ai":
return "openai"
case "x_ai":
return "xai"
}
return p
}
// GuessProvider is the provider of a model id that isn't in the list kept.
func GuessProvider(model string) string {
m := strings.ToLower(model)
switch {
case strings.HasPrefix(m, "claude"):
return "anthropic"
case strings.HasPrefix(m, "gemini"):
return "google"
case strings.HasPrefix(m, "grok"):
return "x_ai"
}
return "open_ai"
}
// ---- completions -----------------------------------------------------------
// CompletionURL is where a completion is asked.
func CompletionURL(base string) string { return base + "/completions" }
// CompletionHeaders are what a /completions request carries.
func CompletionHeaders(h http.Header, llmToken string) {
h.Set("Authorization", "Bearer "+llmToken)
h.Set("Content-Type", "application/json")
h.Set("x-zed-version", Version)
h.Set("x-zed-client-supports-status-messages", "true")
h.Set("x-zed-client-supports-stream-ended-request-completion-status", "true")
h.Set("User-Agent", UserAgent())
}
// CompletionBody wraps a provider's own request.
func CompletionBody(provider, model, threadID string, request json.RawMessage) []byte {
body := map[string]any{"provider": provider, "model": model, "provider_request": request}
if threadID != "" {
body["thread_id"] = threadID
}
b, _ := json.Marshal(body)
return b
}
// Line is one line of a completion's stream.
type Line struct {
Event json.RawMessage // the provider's own event, when it is one
Ended bool // "stream_ended": the reply is whole
Failed *Failed // the request failed along the way
}
// Failed is a failure the stream reports.
type Failed struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
RetryAfter float64 `json:"retry_after"`
}
// Status is the HTTP status a failure stands for: upstream_http_<n> or
// http_<n>, else what its code names.
func (f *Failed) Status() int {
for _, p := range []string{"upstream_http_", "http_"} {
if n, err := strconv.Atoi(strings.TrimPrefix(f.Code, p)); err == nil && strings.HasPrefix(f.Code, p) {
return n
}
}
switch {
case strings.Contains(f.Code, "rate_limit"):
return 429
case strings.Contains(f.Code, "overloaded"):
return 529
case strings.Contains(f.Code, "billing") || strings.Contains(f.Code, "payment"):
return 402
case strings.Contains(f.Code, "context_length"):
return 400
}
return 502
}
func (f *Failed) Error() string {
if f.Message != "" {
return f.Message
}
return f.Code
}
// ReadLines reads a completion's stream line by line. wrapped is whether
// the reply said it sends statuses (x-zed-server-supports-status-messages);
// without, each line is a bare event.
func ReadLines(r io.Reader, wrapped bool, fn func(Line) error) error {
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 64<<10), 16<<20)
for sc.Scan() {
b := bytes.TrimSpace(sc.Bytes())
if len(b) == 0 {
continue
}
if !wrapped {
if err := fn(Line{Event: append(json.RawMessage(nil), b...)}); err != nil {
return err
}
continue
}
var l struct {
Event json.RawMessage `json:"event"`
Status json.RawMessage `json:"status"`
}
if err := json.Unmarshal(b, &l); err != nil {
return fmt.Errorf("an unreadable line: %w", err)
}
switch {
case len(l.Event) > 0:
if err := fn(Line{Event: l.Event}); err != nil {
return err
}
case len(l.Status) > 0:
var s string
if json.Unmarshal(l.Status, &s) == nil {
if s == "stream_ended" {
if err := fn(Line{Ended: true}); err != nil {
return err
}
}
continue // "started"
}
var st struct {
Failed *Failed `json:"failed"`
}
if json.Unmarshal(l.Status, &st) == nil && st.Failed != nil {
if err := fn(Line{Failed: st.Failed}); err != nil {
return err
}
}
// {"queued": …} and statuses newer than this says nothing to act on
}
}
return sc.Err()
}
+135
View File
@@ -0,0 +1,135 @@
package zed
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"net/url"
"strings"
"testing"
)
// The sign-in's key and token round trip as Zed's page and app make them:
// the page encrypts to the PKCS#1 key it is given, OAEP SHA-256, and hands
// the ciphertext back in URL-safe base64.
func TestSignInKey(t *testing.T) {
k, pub, err := NewKey()
if err != nil {
t.Fatal(err)
}
der, err := base64.URLEncoding.DecodeString(pub)
if err != nil {
t.Fatalf("the public key isn't padded URL-safe base64: %v", err)
}
pk, err := x509.ParsePKCS1PublicKey(der)
if err != nil {
t.Fatalf("the public key isn't PKCS#1: %v", err)
}
ct, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pk, []byte("secret-token"), nil)
if err != nil {
t.Fatal(err)
}
for _, enc := range []*base64.Encoding{base64.URLEncoding, base64.RawURLEncoding} {
got, err := Decrypt(k, enc.EncodeToString(ct))
if err != nil || got != "secret-token" {
t.Fatalf("Decrypt = %q, %v", got, err)
}
}
// the older padding Zed's page used before OAEP
ct, _ = rsa.EncryptPKCS1v15(rand.Reader, pk, []byte("old-token"))
if got, err := Decrypt(k, base64.URLEncoding.EncodeToString(ct)); err != nil || got != "old-token" {
t.Fatalf("PKCS#1 v1.5: %q, %v", got, err)
}
if _, err := Decrypt(k, "not base64!"); err == nil {
t.Fatal("a mangled token was taken")
}
u, _ := url.Parse(SignInURL("https://zed.dev", 4242, pub, "sys"))
q := u.Query()
if u.Path != "/native_app_signin" || q.Get("native_app_port") != "4242" || q.Get("native_app_public_key") != pub || q.Get("system_id") != "sys" {
t.Fatalf("sign-in URL %s", u)
}
if id := NewSystemID(); len(id) != 36 || id[14] != '4' {
t.Fatalf("system id %q isn't a UUID v4", id)
}
}
func TestParseModels(t *testing.T) {
raw := []byte(`{"models":[
{"provider":"anthropic","id":"claude-sonnet-4-5","display_name":"Claude Sonnet 4.5","max_token_count":200000,"max_output_tokens":64000,"supports_images":true,
"supported_effort_levels":[{"name":"Low","value":"low"},{"name":"High","value":"high","is_default":true}]},
{"provider":"open_ai","id":"gpt-5","display_name":"GPT-5","max_token_count":400000},
{"provider":"google","id":"gemini-2.5-pro","display_name":"Gemini 2.5 Pro"},
{"provider":"x_ai","id":"grok-4","display_name":"Grok 4"},
{"provider":"anthropic","id":"claude-old","is_disabled":true},
{"provider":"mystery","id":"m-1"}
],"default_model":"claude-sonnet-4-5"}`)
ms, err := ParseModels(raw)
if err != nil {
t.Fatal(err)
}
var ids []string
for _, m := range ms {
ids = append(ids, m.Provider+"/"+m.ID)
}
if got := strings.Join(ids, " "); got != "anthropic/claude-sonnet-4-5 openai/gpt-5 google/gemini-2.5-pro xai/grok-4" {
t.Fatalf("models %s", got)
}
if m := ms[0]; m.Name != "Claude Sonnet 4.5" || m.Context != 200000 || m.Output != 64000 || !m.Images || strings.Join(m.Efforts, ",") != "low,high" {
t.Fatalf("claude %+v", m)
}
if ProviderOf(raw, "grok-4") != "x_ai" || ProviderOf(raw, "nope") != "" {
t.Fatal("ProviderOf")
}
if _, err := ParseModels([]byte(`{"models":[]}`)); err != ErrNoModels {
t.Fatalf("an empty list: %v", err)
}
for id, want := range map[string]string{"claude-x": "anthropic", "gemini-3": "google", "grok-5": "x_ai", "gpt-6": "open_ai"} {
if GuessProvider(id) != want {
t.Errorf("GuessProvider(%s)", id)
}
}
}
func TestReadLines(t *testing.T) {
var got []string
collect := func(l Line) error {
switch {
case l.Ended:
got = append(got, "ended")
case l.Failed != nil:
got = append(got, "failed:"+l.Failed.Code)
default:
got = append(got, string(l.Event))
}
return nil
}
body := `{"status":"started"}
{"status":{"queued":{"position":2}}}
{"event":{"type":"a"}}
{"event":{"type":"b"}}
{"status":{"failed":{"code":"upstream_http_429","message":"slow down","retry_after":3}}}
{"status":"stream_ended"}
`
if err := ReadLines(strings.NewReader(body), true, collect); err != nil {
t.Fatal(err)
}
if s := strings.Join(got, "|"); s != `{"type":"a"}|{"type":"b"}|failed:upstream_http_429|ended` {
t.Fatalf("wrapped: %s", s)
}
got = nil
if err := ReadLines(strings.NewReader("{\"type\":\"a\"}\n{\"type\":\"b\"}\n"), false, collect); err != nil {
t.Fatal(err)
}
if s := strings.Join(got, "|"); s != `{"type":"a"}|{"type":"b"}` {
t.Fatalf("bare: %s", s)
}
for code, want := range map[string]int{"upstream_http_429": 429, "http_503": 503, "upstream_http_error": 502, "rate_limit_exceeded": 429, "overloaded": 529, "payment_required": 402} {
if n := (&Failed{Code: code}).Status(); n != want {
t.Errorf("%s → %d, want %d", code, n, want)
}
}
}