provider: Qoder's built-in is retired; its plugin serves it
qoder and qoder-cn join retiredBuiltins, as Zed did in c0605abc2. @magpie-community/opencode-qoder-auth serves both, moved or not. Removed (built-in only): - gateway: the Qoder dispatch in gateway.go and gateway/qoder.go (the translator), with its tests (qoder_test, qoder_busy_test, qoder_cn_test). - provider: qoder_usage.go; the Accounts() loop, builtinLogins case and loginQuota branch, the Logins/side-list/switch/forget cases, SetLoginOn and alsoOn, the sign-in case, the subscription_usage fetch, and qoder in asksOwnBackend; qoderLogins(); the built-in tests (qoder_test, qoder_cn_test, qoder_free_test). - internal/qoder: codec, cosy, models, oauth, usage, userinfo, ids, store and their tests. Kept, and why: - migrate_qoder.go (the mover) and the legacy qoder.json migration it reaches through qoderLoginsOf. It now reads a pair with qoderSaved. - qoder_checkin.go: the check-in walks plugin accounts (heldPlugins). - internal/qoder/endpoints.go: the provider keys, Site/SiteOf, the Credential the mover reads and NewMachineID, with the notice. - The PLUGIN-SERVED notice in provider/qoder.go and internal/qoder. - gateway's relayStatus/retryAfterOn, which commandcode.go uses, moved to relay_status.go; the tests' qoderRoundTrip is now roundTripFunc (roundtrip_test.go), no change in meaning. Tests changed in meaning: - TestOwnStoreSignInAgainDropsTheReading lost its qoder case. - New TestQoderLegacyFileMoves: a legacy qoder.json moves through the mover and is removed. Red when migrateQoder is skipped (tried by hand). Run (machine load ~300, so narrow by request): - gofmt -l internal: empty - go vet -tags nogui ./...; GOOS=linux and GOOS=windows the same: clean - go test -tags nogui -count=1 -timeout 45m -run 'Qoder|qoder|Migrat|migrat|Mover|Moved|Retired|SignIn|AsksOwnBackend|Plugin|Afresh|Checkin' ./internal/provider ./internal/gateway ./internal/cli ./internal/gui ./internal/qoder provider ok 114s, gateway ok 201s, cli ok 18s, gui ok 12s, qoder no tests Not run: the whole packages, the full suite, the GUI node suite.
This commit is contained in:
@@ -23,7 +23,7 @@ func TestOpenCodeFastVariantReachesCodex(t *testing.T) {
|
||||
to, _ := url.Parse(provider.CodexBase)
|
||||
provider.CodexBase = "https://chatgpt.com/backend-api/codex"
|
||||
s := New()
|
||||
s.client = &http.Client{Transport: qoderRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
r.URL.Scheme, r.URL.Host = to.Scheme, to.Host
|
||||
return http.DefaultTransport.RoundTrip(r)
|
||||
})}
|
||||
|
||||
@@ -3480,12 +3480,6 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
|
||||
call.To = from
|
||||
return s.serveDevin(w, r, from, p.Account.Home, model, own, &call.Usage)
|
||||
}
|
||||
// Qoder is served through the API the client talks to, signed with the
|
||||
// COSY envelope, with the account magpie signed in to.
|
||||
if p.Account != nil && (p.Account.Agent == "qoder" || p.Account.Agent == provider.QoderCNID) {
|
||||
call.To = from
|
||||
return s.serveQoder(w, r, from, p, model, own, &call.Usage)
|
||||
}
|
||||
// Command Code's Go plan has no Provider API: it is asked where the
|
||||
// CLI asks, in the CLI's own format; its other plans go on as keys do
|
||||
if p.Account != nil && p.Account.Agent == provider.CommandCodePlanID {
|
||||
|
||||
@@ -106,7 +106,7 @@ func fasted(t *testing.T) (*Server, *fastUp) {
|
||||
}
|
||||
}
|
||||
s := New()
|
||||
s.client = &http.Client{Transport: qoderRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
up.mu.Lock()
|
||||
up.host = r.URL.Host
|
||||
up.mu.Unlock()
|
||||
|
||||
@@ -1,849 +0,0 @@
|
||||
package gateway
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/qoder"
|
||||
)
|
||||
|
||||
// A Qoder subscription is served through the API the Qoder client talks to
|
||||
// (api3.qoder.sh agent_chat_generation SSE), signed with the COSY envelope and
|
||||
// encoded with the client's body codec, the way a Devin one is (devin.go).
|
||||
// Qoder exposes tool calls as XML in its text, so the request is given the
|
||||
// matching contract and the reply is adapted back into tool-call events.
|
||||
// The protocol lives in internal/qoder.
|
||||
//
|
||||
// The XML markers below are written with hex escapes for their angle brackets
|
||||
// so this source holds no literal tag the tooling would mistake for a call.
|
||||
const (
|
||||
qoderCallOpen = "\x3ctool_call\x3e"
|
||||
qoderCallClose = "\x3c/tool_call\x3e"
|
||||
)
|
||||
|
||||
var (
|
||||
qoderFunc = regexp.MustCompile(`(?s)\x3cfunction=([^>]+)\x3e(.*?)\x3c/function\x3e`)
|
||||
qoderArg = regexp.MustCompile(`(?s)\x3cparameter=([^>]+)\x3e(.*?)\x3c/parameter\x3e`)
|
||||
)
|
||||
|
||||
const qoderSys = "You are a Qoder agent. Use the instructions below and the tools available to you to assist the user."
|
||||
|
||||
// qoderAuth hands a request the signed-in account's uid and a live job
|
||||
// token, and qoderURL the chat endpoint on the credential's site (qoder.com's
|
||||
// or Qoder CN's); vars so tests can stand in for them, the way a Devin round
|
||||
// stands in for devinAuth.
|
||||
var (
|
||||
qoderAuth = provider.QoderCredentialOf
|
||||
qoderModel = provider.QoderModelOf
|
||||
qoderURL = func(c *qoder.Credential) string { return c.OnSite().ChatURL() }
|
||||
)
|
||||
|
||||
// serveQoder answers a request through Qoder's API.
|
||||
func (s *Server) serveQoder(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()
|
||||
}
|
||||
// the vendor's own API is told the answer's format in words
|
||||
req = req.inSystem()
|
||||
req.Model = model
|
||||
ask := s.askQoder(p.Account.Agent, model, p.Account.User)
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
defer cancel()
|
||||
q := req
|
||||
var tool string
|
||||
if req.WebSearch && !searching(r.Context()) {
|
||||
if canSearch() {
|
||||
copy := *req
|
||||
copy.WebSearch = false
|
||||
search := searchTool(copy.Tools)
|
||||
copy.Tools = append(slices.Clone(copy.Tools), search)
|
||||
copy.Messages = slices.Clone(copy.Messages)
|
||||
q, tool = ©, search.Name
|
||||
}
|
||||
}
|
||||
events, status, msg, wait := s.askQoderWait(p.Account.Agent, model, p.Account.User)(ctx, q)
|
||||
if events == nil {
|
||||
retryAfterOn(w, wait)
|
||||
return writeError(w, from, status, msg), msg
|
||||
}
|
||||
if tool != "" {
|
||||
first := events
|
||||
out := make(chan Event, 16)
|
||||
go func() {
|
||||
defer close(out)
|
||||
s.searchRounds(ctx, q, tool, first, ask, out)
|
||||
}()
|
||||
events = out
|
||||
}
|
||||
return relayQoder(w, from, req, events, usage, cancel)
|
||||
}
|
||||
|
||||
// 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 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
|
||||
if code < 400 || code > 599 {
|
||||
code = 502
|
||||
}
|
||||
retryAfterOn(w, ev.Wait)
|
||||
return writeError(w, from, code, ev.Text), ev.Text
|
||||
}
|
||||
if req.Stream {
|
||||
var head []Event
|
||||
for ev := range events {
|
||||
if ev.Kind == KError {
|
||||
return fail(ev)
|
||||
}
|
||||
head = append(head, ev)
|
||||
if ev.Kind != KStart && ev.Kind != KUsage {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(head) == 0 || head[len(head)-1].Kind == KStart || head[len(head)-1].Kind == KUsage {
|
||||
return fail(Event{Text: name + " ended without an answer"})
|
||||
}
|
||||
sw := newSSEWriter(w)
|
||||
enc := encoder(from, sw, req, usage)
|
||||
var failed string
|
||||
see := func(ev Event) bool {
|
||||
if ev.Kind == KStart || ev.Kind == KUsage {
|
||||
usage.add(ev.Usage)
|
||||
}
|
||||
enc.event(ev)
|
||||
if ev.Kind == KError {
|
||||
failed = ev.Text
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
for _, ev := range head {
|
||||
see(ev)
|
||||
}
|
||||
// kept from the client's idle timeout while none comes (#436)
|
||||
relayEvents(events, sw, enc, see)
|
||||
if failed != "" {
|
||||
abort()
|
||||
return 200, failed
|
||||
}
|
||||
enc.finish()
|
||||
return 200, ""
|
||||
}
|
||||
var col collector
|
||||
for ev := range events {
|
||||
if ev.Kind == KError {
|
||||
return fail(ev)
|
||||
}
|
||||
col.add(ev)
|
||||
}
|
||||
res := col.finish()
|
||||
usage.add(res.Usage)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(200)
|
||||
w.Write(renderUsage(from, res, req, usage))
|
||||
return 200, ""
|
||||
}
|
||||
|
||||
// retryAfterOn sends, with an error about to be written to w, how long
|
||||
// the vendor said to wait before asking again, when it said: the agent
|
||||
// reads it, and so does the gateway's busy handling (noteBusy).
|
||||
func retryAfterOn(w http.ResponseWriter, wait time.Duration) {
|
||||
if wait > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(math.Ceil(wait.Seconds()))))
|
||||
}
|
||||
}
|
||||
|
||||
// askQoder is a round for Qoder's API, on the site agent ("qoder" or
|
||||
// "qoder-cn") names.
|
||||
func (s *Server) askQoder(agent, model, user string) round {
|
||||
ask := s.askQoderWait(agent, model, user)
|
||||
return func(ctx context.Context, req *Request) (<-chan Event, int, string) {
|
||||
events, status, msg, _ := ask(ctx, req)
|
||||
return events, status, msg
|
||||
}
|
||||
}
|
||||
|
||||
// askQoderWait is askQoder that also says, of a failure, how long Qoder
|
||||
// said to wait before asking again (its queue's retryAfterSeconds), for
|
||||
// serveQoder to send as Retry-After.
|
||||
func (s *Server) askQoderWait(agent, model, user string) func(ctx context.Context, req *Request) (<-chan Event, int, string, time.Duration) {
|
||||
return func(ctx context.Context, req *Request) (<-chan Event, int, string, time.Duration) {
|
||||
cred, err := qoderAuth(ctx, agent, user)
|
||||
if err != nil {
|
||||
// only a sign-in that is gone asks the agent to log in again;
|
||||
// a refresh that timed out or never reached Qoder may pass
|
||||
status := 502
|
||||
if errors.Is(err, provider.ErrQoderSignIn) {
|
||||
status = 401
|
||||
}
|
||||
return nil, status, "Qoder: " + err.Error(), 0
|
||||
}
|
||||
config, err := qoderModel(ctx, agent, user, model)
|
||||
if err != nil {
|
||||
return nil, 400, err.Error(), 0
|
||||
}
|
||||
plain, err := qoderChatBody(req, config)
|
||||
if err != nil {
|
||||
return nil, 500, "Qoder: " + err.Error(), 0
|
||||
}
|
||||
wire := qoder.EncodeRequestBody(plain)
|
||||
ts := time.Now().Unix()
|
||||
chat := qoderURL(cred)
|
||||
headers, err := qoder.BuildCosyHeaders(chat, &qoder.User{UID: cred.UID, Token: cred.Token,
|
||||
Name: cred.Name, Email: cred.Email, MachineID: cred.MachineID}, wire, ts)
|
||||
if err != nil {
|
||||
return nil, 500, "Qoder: " + err.Error(), 0
|
||||
}
|
||||
hr, err := http.NewRequestWithContext(ctx, http.MethodPost, chat, strings.NewReader(wire))
|
||||
if err != nil {
|
||||
return nil, 500, "Qoder: " + err.Error(), 0
|
||||
}
|
||||
for k, v := range headers {
|
||||
hr.Header.Set(k, v)
|
||||
}
|
||||
hr.Header.Set("Accept", "text/event-stream")
|
||||
hr.Header.Set("Cache-Control", "no-cache")
|
||||
hr.Header.Set("Accept-Encoding", "identity")
|
||||
hr.Header.Set("X-Model-Key", config.Key)
|
||||
hr.Header.Set("X-Model-Source", config.Source)
|
||||
res, err := s.client.Do(hr)
|
||||
if err != nil {
|
||||
return nil, 502, "Qoder: " + err.Error(), 0
|
||||
}
|
||||
res = notAnAPIReply(res, "") // a web page served 200 (#1012)
|
||||
if res.StatusCode/100 != 2 {
|
||||
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
res.Body.Close()
|
||||
status, msg, wait := qoderFailure(res.StatusCode, b)
|
||||
return nil, status, msg, wait
|
||||
}
|
||||
events := make(chan Event, 32)
|
||||
go decodeQoder(ctx, res, events, model)
|
||||
return events, 0, "", 0
|
||||
}
|
||||
}
|
||||
|
||||
// Qoder's own error codes, read as Qoder's client reads them (the
|
||||
// QoderErrorCode table in Qoder.app's qoder-agent-sdk worker), and as the
|
||||
// plugin does (@magpie-community/opencode-qoder-auth 0.2.14): only 105
|
||||
// (loginExpired) is a lapsed sign-in there, so a 401/403 that carries
|
||||
// another code isn't one here either (plugins #98: the model's queue,
|
||||
// 10605, came as a 403 and read as "sign in again").
|
||||
const qoderQueued = "10605"
|
||||
|
||||
var (
|
||||
// the codes Qoder's client counts as a plan's usage or credits used up
|
||||
qoderQuotaCodes = map[string]bool{"110": true, "112": true, "113": true, "114": true, "115": true,
|
||||
"116": true, "117": true, "118": true, "119": true, "122": true}
|
||||
// refusals of this request, not of the account: sensitive content,
|
||||
// not supported, input too long, too many media, a custom model's
|
||||
// service (Qoder's table has no 100402)
|
||||
qoderRequestCodes = map[string]bool{"406": true, "416": true, "430": true, "80411": true, "80412": true,
|
||||
"100400": true, "100401": true, "100403": true}
|
||||
)
|
||||
|
||||
// qoderBusyWait is how long a queued request waits when Qoder names no time.
|
||||
const qoderBusyWait = 30 * time.Second
|
||||
|
||||
// qoderFailure maps a bad upstream status to magpie's status and message,
|
||||
// and how long Qoder said to wait before asking again (0 when it didn't).
|
||||
// Qoder's code in the body says what the failure is, whatever the status.
|
||||
func qoderFailure(status int, body []byte) (int, string, time.Duration) {
|
||||
if status < 400 || status > 599 {
|
||||
status = 502
|
||||
}
|
||||
msg := strings.TrimSpace(string(body))
|
||||
var code string
|
||||
var queue gjson.Result
|
||||
if gjson.ValidBytes(body) {
|
||||
code = gjson.GetBytes(body, "code").String()
|
||||
m := gjson.GetBytes(body, "message").String()
|
||||
if m != "" {
|
||||
msg = m
|
||||
}
|
||||
// the model vendor's own reason, e.g. an effort the model refuses
|
||||
if d := gjson.Get(gjson.GetBytes(body, "details").String(), "error.message").String(); d != "" {
|
||||
msg += ": " + d
|
||||
}
|
||||
// the queue's state: a field, or the message itself as JSON
|
||||
if q := gjson.GetBytes(body, "queue"); q.IsObject() {
|
||||
queue = q
|
||||
} else if q := gjson.Parse(m); strings.HasPrefix(strings.TrimSpace(m), "{") && q.IsObject() &&
|
||||
(q.Get("isQueued").Exists() || q.Get("serviceAvailable").Exists() || q.Get("retryAfterSeconds").Exists()) {
|
||||
queue = q
|
||||
}
|
||||
}
|
||||
if msg == "" {
|
||||
msg = http.StatusText(status)
|
||||
}
|
||||
// Qoder's queue for the model: busy for now, with when to ask again.
|
||||
// The sign-in is fine (the same token reads the models and the usage),
|
||||
// so it is a 503 with Retry-After, which the gateway counts as busy and
|
||||
// asks again after, and never "sign in again"
|
||||
if code == qoderQueued || queue.Get("isQueued").Type == gjson.True || queue.Get("serviceAvailable").Type == gjson.False {
|
||||
wait := qoderBusyWait
|
||||
if n := queue.Get("retryAfterSeconds").Float(); n > 0 {
|
||||
wait = time.Duration(math.Ceil(n)) * time.Second
|
||||
}
|
||||
what := "is busy"
|
||||
if queue.Get("isQueued").Type == gjson.True {
|
||||
what = "queued the request"
|
||||
}
|
||||
if k := queue.Get("modelKey").String(); k != "" {
|
||||
what += " for " + k
|
||||
}
|
||||
if t := queue.Get("queueType").String(); t != "" {
|
||||
what += " (this plan's queue: " + t + ")"
|
||||
}
|
||||
return 503, fmt.Sprintf("Qoder %s; try again in %ds", what, int(wait/time.Second)), wait
|
||||
}
|
||||
switch {
|
||||
case qoderQuotaCodes[code]:
|
||||
return 429, "usage limit reached: " + msg, 0
|
||||
case qoderRequestCodes[code]:
|
||||
return 400, fmt.Sprintf("Qoder refused the request (%s): %s", code, msg), 0
|
||||
case status == http.StatusUnauthorized || status == http.StatusForbidden:
|
||||
return 401, "Qoder: the sign-in lapsed — sign in again", 0
|
||||
case status == http.StatusTooManyRequests || strings.Contains(strings.ToLower(msg), "quota"):
|
||||
return 429, "usage limit reached: " + msg, 0
|
||||
}
|
||||
return status, "Qoder: " + msg, 0
|
||||
}
|
||||
|
||||
// qoderChatBody is the plaintext JSON Qoder's agent_chat_generation takes,
|
||||
// built from magpie's IR request the way the reference does: messages as
|
||||
// content blocks, tool calls and results as OpenAI tool turns, and the
|
||||
// caller's tools beside them.
|
||||
func qoderChatBody(req *Request, model qoder.ModelInfo) ([]byte, error) {
|
||||
if model.Key == "" || len(model.Config) == 0 {
|
||||
return nil, fmt.Errorf("Qoder: missing model configuration")
|
||||
}
|
||||
sys := map[string]any{"type": "text", "text": qoderSysText(req)}
|
||||
all := []any{map[string]any{"role": "system", "content": []any{sys}}}
|
||||
|
||||
asked := req.Effort
|
||||
if req.ThinkOff {
|
||||
asked = "none" // Effort reads none as low
|
||||
}
|
||||
thinking, effort := qoderEffort(asked, model)
|
||||
maxTok := int64(32000)
|
||||
if req.MaxTokens > 0 {
|
||||
maxTok = int64(req.MaxTokens)
|
||||
}
|
||||
params := map[string]any{"enable_thinking": thinking, "max_tokens": maxTok}
|
||||
if effort != "" {
|
||||
params["reasoning_effort"] = effort
|
||||
}
|
||||
if model.MaxInputTokens > 0 {
|
||||
params["context_length"] = model.MaxInputTokens
|
||||
}
|
||||
body := map[string]any{
|
||||
"parameters": params,
|
||||
"business": map[string]any{
|
||||
"product": "app", "version": "1.1.49", "type": "agent",
|
||||
"id": qoder.NewID(), "name": "magpie session",
|
||||
"begin_at": time.Now().UnixMilli(), "stage": "start",
|
||||
},
|
||||
"agent_id": "agent_common",
|
||||
"task_id": "common",
|
||||
"session_type": "app",
|
||||
"model_config": model.Config,
|
||||
"system": []any{sys},
|
||||
"messages": append(all, qoderMessages(req.Messages)...),
|
||||
}
|
||||
if req.ToolChoice != "none" && len(req.Tools) > 0 {
|
||||
body["tools"] = qoderTools(req.Tools)
|
||||
}
|
||||
return json.Marshal(body)
|
||||
}
|
||||
|
||||
// qoderMessages renders magpie's turns as OpenAI turns, the format Qoder's
|
||||
// chat endpoint takes: an assistant's tool calls as tool_calls and their
|
||||
// results as tool turns named by tool_call_id, so a result is paired with
|
||||
// its call and not by order. A tool turn holds text only, so the images a
|
||||
// tool returned go after the tool turns in a user turn — as the start of
|
||||
// the user's own turn when one comes next — the way buildChat sends them.
|
||||
func qoderMessages(ms []Message) []any {
|
||||
var out []any
|
||||
names := map[string]string{}
|
||||
var seen []any
|
||||
seeLater := func(p Part) int {
|
||||
var ims []any
|
||||
for _, im := range p.Images {
|
||||
if im.Data != "" {
|
||||
ims = append(ims, map[string]any{"type": "image_url",
|
||||
"image_url": map[string]any{"url": "data:" + im.MediaType + ";base64," + im.Data}})
|
||||
}
|
||||
}
|
||||
if len(ims) == 0 {
|
||||
return 0
|
||||
}
|
||||
of := "tool call " + p.CallID
|
||||
if name := cmp.Or(names[p.CallID], p.Name); name != "" {
|
||||
of = name + " (" + of + ")"
|
||||
}
|
||||
seen = append(seen, map[string]any{"type": "text", "text": "[From the result of " + of + ":]"})
|
||||
seen = append(seen, ims...)
|
||||
return len(ims)
|
||||
}
|
||||
showSeen := func() {
|
||||
if len(seen) > 0 {
|
||||
out = append(out, map[string]any{"role": "user", "content": seen})
|
||||
seen = nil
|
||||
}
|
||||
}
|
||||
for _, m := range ms {
|
||||
var blocks []any
|
||||
var calls []map[string]any
|
||||
var text string
|
||||
flush := func() {
|
||||
if len(blocks) == 0 {
|
||||
return
|
||||
}
|
||||
if m.Role == "user" && len(seen) > 0 {
|
||||
blocks, seen = append(seen, blocks...), nil
|
||||
}
|
||||
out = append(out, map[string]any{"role": m.Role, "content": blocks})
|
||||
blocks = nil
|
||||
}
|
||||
if m.Role != "user" {
|
||||
showSeen()
|
||||
}
|
||||
for _, p := range m.Parts {
|
||||
switch p.Kind {
|
||||
case Text:
|
||||
blocks = append(blocks, map[string]any{"type": "text", "text": p.Text})
|
||||
if text == "" {
|
||||
text = p.Text
|
||||
}
|
||||
case Image:
|
||||
if p.Data != "" {
|
||||
blocks = append(blocks, map[string]any{"type": "image_url",
|
||||
"image_url": map[string]any{"url": "data:" + p.MediaType + ";base64," + p.Data}})
|
||||
}
|
||||
case ToolCall:
|
||||
if m.Role != "assistant" {
|
||||
continue
|
||||
}
|
||||
id := p.ID
|
||||
if id == "" {
|
||||
id = "call_" + qoder.NewID()
|
||||
}
|
||||
names[id] = p.Name
|
||||
calls = append(calls, map[string]any{"id": id, "type": "function",
|
||||
"function": map[string]any{"name": p.Name, "arguments": string(argsOf(p))}})
|
||||
case ToolResult:
|
||||
flush()
|
||||
txt := p.Text
|
||||
if p.IsError {
|
||||
txt = "Error: " + txt
|
||||
}
|
||||
if n := seeLater(p); n > 0 {
|
||||
note := fmt.Sprintf("[The tool returned %d images; they follow in the next message.]", n)
|
||||
if n == 1 {
|
||||
note = "[The tool returned an image; it follows in the next message.]"
|
||||
}
|
||||
if strings.TrimSpace(txt) != "" {
|
||||
txt += "\n\n"
|
||||
}
|
||||
txt += note
|
||||
}
|
||||
out = append(out, map[string]any{"role": "tool", "tool_call_id": p.CallID, "content": txt})
|
||||
}
|
||||
}
|
||||
if m.Role == "assistant" && len(calls) > 0 {
|
||||
out = append(out, map[string]any{"role": "assistant", "content": text, "tool_calls": calls})
|
||||
continue
|
||||
}
|
||||
flush()
|
||||
}
|
||||
showSeen()
|
||||
return out
|
||||
}
|
||||
|
||||
// qoderTools is the caller's tools as Qoder's own native function tools.
|
||||
func qoderTools(ts []Tool) []any {
|
||||
var out []any
|
||||
for _, t := range ts {
|
||||
fn := map[string]any{"name": t.Name, "description": t.Description}
|
||||
sch := t.Schema
|
||||
if strings.TrimSpace(string(sch)) == "" {
|
||||
sch = json.RawMessage(`{"type":"object","properties":{}}`)
|
||||
}
|
||||
fn["parameters"] = json.RawMessage(sch)
|
||||
out = append(out, map[string]any{"type": "function", "function": fn})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// qoderEffort is whether to think and at which of the model's own efforts
|
||||
// ("" to send none). Asked for none, a model that always thinks thinks at
|
||||
// its lowest; asked for nothing, or for a level Qoder doesn't name, it
|
||||
// thinks at its own default.
|
||||
func qoderEffort(asked string, model qoder.ModelInfo) (bool, string) {
|
||||
want := strings.ToLower(asked)
|
||||
if !slices.Contains(effortRank, want) {
|
||||
want = ""
|
||||
}
|
||||
if !model.Thinks || want == "none" && !model.AlwaysThinks {
|
||||
return false, ""
|
||||
}
|
||||
if len(model.Efforts) == 0 {
|
||||
return true, ""
|
||||
}
|
||||
switch want {
|
||||
case "":
|
||||
return true, model.DefaultEffort
|
||||
case "none":
|
||||
return true, model.Efforts[0]
|
||||
}
|
||||
return true, fitEffort(want, model.Efforts)
|
||||
}
|
||||
|
||||
// qoderSysText is the system prompt: Qoder's own line plus the caller's.
|
||||
// The caller's tools go to Qoder as native function tools.
|
||||
func qoderSysText(req *Request) string {
|
||||
sys := qoderSys
|
||||
if req.System != "" {
|
||||
sys = sys + "\n\n" + req.System
|
||||
}
|
||||
if req.ToolChoice == "required" && len(req.Tools) > 0 {
|
||||
sys += "\nYou must call an available function in this response."
|
||||
}
|
||||
return sys
|
||||
}
|
||||
|
||||
// decodeQoder turns Qoder's SSE reply into events: each "data:" line carries an
|
||||
// envelope whose "body" is a standard OpenAI chunk, whose content may hold
|
||||
// embedded tool calls to lift out.
|
||||
func decodeQoder(ctx context.Context, res *http.Response, out chan<- Event, model string) {
|
||||
defer func() { res.Body.Close(); close(out) }()
|
||||
send := func(ev Event) bool {
|
||||
select {
|
||||
case out <- ev:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
if !send(Event{Kind: KStart, MsgID: "msg_" + randomToken(), Model: model}) {
|
||||
return
|
||||
}
|
||||
a := qoderText{tool: -1}
|
||||
// emit lifts one piece of the split text into events: a call, the text,
|
||||
// or a call that can't be read, which ends the turn as an error so the
|
||||
// agent can try it again (plugins#132, as the moved qoder plugin's).
|
||||
// False when the turn ends here: the consumer went, or an error was
|
||||
// sent — an error frame carries no finish.
|
||||
emit := func(frag qoderFrag) bool {
|
||||
switch {
|
||||
case frag.err != "":
|
||||
send(Event{Kind: KError, Status: 502, Text: frag.err})
|
||||
return false
|
||||
case frag.call != nil:
|
||||
if !send(Event{Kind: KToolStart, ID: "call_" + qoder.NewID(), Name: frag.call.name}) {
|
||||
return false
|
||||
}
|
||||
return send(Event{Kind: KToolArgs, Text: frag.call.args})
|
||||
case frag.text != "":
|
||||
return send(Event{Kind: KText, Text: frag.text})
|
||||
}
|
||||
return true
|
||||
}
|
||||
finish := func() {
|
||||
for _, frag := range a.flush() {
|
||||
if !emit(frag) {
|
||||
return
|
||||
}
|
||||
}
|
||||
stop := "stop"
|
||||
if a.sawTool {
|
||||
stop = "tool"
|
||||
}
|
||||
send(Event{Kind: KStop, Stop: stop})
|
||||
}
|
||||
sc := bufio.NewScanner(res.Body)
|
||||
sc.Buffer(make([]byte, 0, 64<<10), 32<<20)
|
||||
for sc.Scan() {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
if !strings.HasPrefix(line, "data:") {
|
||||
continue
|
||||
}
|
||||
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
|
||||
if payload == "" || !gjson.Valid(payload) {
|
||||
continue
|
||||
}
|
||||
inner := gjson.Get(payload, "body").String()
|
||||
if status := gjson.Get(payload, "statusCodeValue"); status.Exists() && status.Int() != 200 {
|
||||
data := []byte(inner)
|
||||
if len(data) == 0 {
|
||||
data = []byte(payload)
|
||||
}
|
||||
code, msg, wait := qoderFailure(int(status.Int()), data)
|
||||
send(Event{Kind: KError, Status: code, Text: msg, Wait: wait})
|
||||
return
|
||||
}
|
||||
if inner == "" || !json.Valid([]byte(inner)) {
|
||||
continue
|
||||
}
|
||||
delta := gjson.Get(inner, "choices.0.delta")
|
||||
if rc := delta.Get("reasoning_content").String(); rc != "" {
|
||||
if !send(Event{Kind: KThink, Text: rc}) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if content := delta.Get("content"); content.Exists() {
|
||||
for _, frag := range a.feed(content.String()) {
|
||||
if !emit(frag) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
// Qoder also serves tool calls in the OpenAI way: the id it sends
|
||||
// is the one a result is answered with, so it is kept.
|
||||
for _, tc := range delta.Get("tool_calls").Array() {
|
||||
idx := int(tc.Get("index").Int())
|
||||
if idx != a.tool {
|
||||
a.tool = idx
|
||||
for _, frag := range a.flush() {
|
||||
if !emit(frag) {
|
||||
return
|
||||
}
|
||||
}
|
||||
id := tc.Get("id").String()
|
||||
if id == "" {
|
||||
id = "call_" + qoder.NewID()
|
||||
}
|
||||
if !send(Event{Kind: KToolStart, ID: id, Name: tc.Get("function.name").String()}) {
|
||||
return
|
||||
}
|
||||
a.sawTool = true
|
||||
}
|
||||
if args := tc.Get("function.arguments").String(); args != "" {
|
||||
if !send(Event{Kind: KToolArgs, Text: args}) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if fr := gjson.Get(inner, "choices.0.finish_reason").String(); fr != "" {
|
||||
if u := gjson.Get(inner, "usage"); u.Exists() {
|
||||
send(Event{Kind: KUsage, Usage: Usage{
|
||||
Input: int(u.Get("prompt_tokens").Int()), Output: int(u.Get("completion_tokens").Int())}})
|
||||
}
|
||||
finish()
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := sc.Err(); err != nil {
|
||||
send(Event{Kind: KError, Status: 502, Text: "Qoder: reading stream: " + err.Error()})
|
||||
return
|
||||
}
|
||||
finish()
|
||||
}
|
||||
|
||||
// qoderText is the streaming tool-call splitter: it holds text until a full
|
||||
// tool-call block arrives, then emits it as a call. A block on its way to
|
||||
// being a call that can't be read, or that the stream ends inside, is an
|
||||
// error, never the answer (plugins#132, as the moved qoder plugin's 0.2.16):
|
||||
// the turn fails, so it can be tried again. A block whose JSON is whole when
|
||||
// the stream ends without its close is still the call; one that is no call
|
||||
// at all, or one inside code, stays text.
|
||||
type qoderText struct {
|
||||
textBuf string
|
||||
callBuf string
|
||||
inCall bool
|
||||
sawTool bool
|
||||
sent string // the text given out so far, to tell a block in code from a call
|
||||
tool int // index of the native tool call being assembled, -1 for none
|
||||
}
|
||||
|
||||
type qoderFrag struct {
|
||||
text string
|
||||
call *qoderCall
|
||||
err string
|
||||
}
|
||||
type qoderCall struct{ name, args string }
|
||||
|
||||
// qoderQuoted says text ends inside a code fence or an inline code span: a
|
||||
// tool-call block there is prose about one, not a call.
|
||||
func qoderQuoted(text string) bool {
|
||||
if strings.Count(text, "```")%2 == 1 {
|
||||
return true
|
||||
}
|
||||
line := text[strings.LastIndex(text, "\n")+1:]
|
||||
return strings.Count(strings.ReplaceAll(line, "```", ""), "`")%2 == 1
|
||||
}
|
||||
|
||||
// qoderCallish says a block was on its way to being a call: its JSON began,
|
||||
// or the XML function form.
|
||||
func qoderCallish(v string) bool {
|
||||
return strings.HasPrefix(strings.TrimLeft(v, " \t\r\n"), "{") || strings.Contains(v, "\x3cfunction=")
|
||||
}
|
||||
|
||||
const (
|
||||
qoderCallUnreadable = "Qoder: the model's tool call, written as text, can't be read; it is not sent on as the answer"
|
||||
qoderCallCutShort = "Qoder: the model's tool call, written as text, was cut short; it is not sent on as the answer"
|
||||
)
|
||||
|
||||
func (a *qoderText) feed(input string) []qoderFrag {
|
||||
var out []qoderFrag
|
||||
for input != "" {
|
||||
if !a.inCall {
|
||||
comb := a.textBuf + input
|
||||
a.textBuf = ""
|
||||
i := strings.Index(comb, qoderCallOpen)
|
||||
if i < 0 {
|
||||
if keep := qoderSuffix(comb); keep < len(comb) {
|
||||
a.text(comb[:len(comb)-keep])
|
||||
out = append(out, qoderFrag{text: comb[:len(comb)-keep]})
|
||||
a.textBuf = comb[len(comb)-keep:]
|
||||
} else {
|
||||
a.textBuf = comb
|
||||
}
|
||||
break
|
||||
}
|
||||
if i > 0 {
|
||||
a.text(comb[:i])
|
||||
out = append(out, qoderFrag{text: comb[:i]})
|
||||
}
|
||||
input = comb[i+len(qoderCallOpen):]
|
||||
a.inCall = true
|
||||
continue
|
||||
}
|
||||
comb := a.callBuf + input
|
||||
a.callBuf = ""
|
||||
j := strings.Index(comb, qoderCallClose)
|
||||
if j < 0 {
|
||||
a.callBuf = comb
|
||||
break
|
||||
}
|
||||
body := comb[:j]
|
||||
if c, ok := qoderParseCall(body); ok {
|
||||
a.sawTool = true
|
||||
out = append(out, qoderFrag{call: &c})
|
||||
} else if qoderCallish(body) && !qoderQuoted(a.sent) {
|
||||
a.inCall = false
|
||||
return append(out, qoderFrag{err: qoderCallUnreadable})
|
||||
} else {
|
||||
a.text(qoderCallOpen + body + qoderCallClose)
|
||||
out = append(out, qoderFrag{text: qoderCallOpen + body + qoderCallClose})
|
||||
}
|
||||
input = comb[j+len(qoderCallClose):]
|
||||
a.inCall = false
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// text hands a piece of text out, remembering it: whether the next block is
|
||||
// inside code is told from what came before it.
|
||||
func (a *qoderText) text(t string) { a.sent += t }
|
||||
|
||||
func (a *qoderText) flush() []qoderFrag {
|
||||
if a.inCall {
|
||||
body := a.callBuf
|
||||
a.inCall, a.callBuf = false, ""
|
||||
if qoderCallish(body) && !qoderQuoted(a.sent) {
|
||||
if c, ok := qoderParseCall(body); ok {
|
||||
a.sawTool = true
|
||||
return []qoderFrag{{call: &c}}
|
||||
}
|
||||
return []qoderFrag{{err: qoderCallCutShort}}
|
||||
}
|
||||
t := qoderCallOpen + body
|
||||
a.text(t)
|
||||
if t != "" {
|
||||
return []qoderFrag{{text: t}}
|
||||
}
|
||||
}
|
||||
if a.textBuf != "" {
|
||||
t := a.textBuf
|
||||
a.textBuf = ""
|
||||
a.text(t)
|
||||
return []qoderFrag{{text: t}}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// qoderSuffix is the length of the tail that could still become a call marker.
|
||||
func qoderSuffix(v string) int {
|
||||
for size := len(qoderCallOpen) - 1; size > 0; size-- {
|
||||
if strings.HasSuffix(v, qoderCallOpen[:size]) {
|
||||
return size
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// qoderParseCall reads one tool-call block: a JSON {name,arguments}, or the
|
||||
// XML function/parameter form.
|
||||
func qoderParseCall(v string) (qoderCall, bool) {
|
||||
var framed struct {
|
||||
Name string `json:"name"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
}
|
||||
if json.Unmarshal([]byte(strings.TrimSpace(v)), &framed) == nil && strings.TrimSpace(framed.Name) != "" {
|
||||
var m map[string]json.RawMessage
|
||||
if json.Unmarshal(framed.Arguments, &m) == nil && m != nil {
|
||||
return qoderCall{name: strings.TrimSpace(framed.Name), args: string(framed.Arguments)}, true
|
||||
}
|
||||
}
|
||||
m := qoderFunc.FindStringSubmatch(v)
|
||||
if len(m) != 3 {
|
||||
return qoderCall{}, false
|
||||
}
|
||||
name := strings.TrimSpace(m[1])
|
||||
if name == "" {
|
||||
return qoderCall{}, false
|
||||
}
|
||||
args := map[string]any{}
|
||||
for _, pm := range qoderArg.FindAllStringSubmatch(m[2], -1) {
|
||||
key := strings.TrimSpace(pm[1])
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
// A value is taken as it stands: nothing is told to escape them.
|
||||
val := strings.TrimSpace(pm[2])
|
||||
var dec any
|
||||
if json.Unmarshal([]byte(val), &dec) != nil {
|
||||
dec = val
|
||||
}
|
||||
args[key] = dec
|
||||
}
|
||||
b, err := json.Marshal(args)
|
||||
if err != nil {
|
||||
return qoderCall{}, false
|
||||
}
|
||||
return qoderCall{name: name, args: string(b)}, true
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/qoder"
|
||||
)
|
||||
|
||||
// plugins #98: Qoder's queue refusing a chat (code 10605) is Qoder being
|
||||
// busy for the plan, not a lapsed sign-in. The body is the one Qoder gave a
|
||||
// real trial account on 2026-10-12, byte for byte from the issue
|
||||
// (testdata/qoder_queued_10605.json). The other codes are read as Qoder's
|
||||
// own client reads them (QoderErrorCode in Qoder.app's qoder-agent-sdk
|
||||
// worker), as the plugin reads them since 0.2.14: only 105 is loginExpired.
|
||||
|
||||
func qoderQueuedBody(t *testing.T) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile("testdata/qoder_queued_10605.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
// qoderRefusing stands in for api3.qoder.sh answering every chat with
|
||||
// status and body, as qoderUpstream does with a stream.
|
||||
func qoderRefusing(t *testing.T, status int, body string) {
|
||||
t.Helper()
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
io.WriteString(w, body)
|
||||
}))
|
||||
auth, url, model := qoderAuth, qoderURL, qoderModel
|
||||
qoderAuth = func(context.Context, string, string) (*qoder.Credential, error) {
|
||||
return &qoder.Credential{UID: "uid-test", Token: "jt-test", MachineID: "machine-test"}, nil
|
||||
}
|
||||
qoderModel = func(context.Context, string, string, string) (qoder.ModelInfo, error) { return testQoderModel(t), nil }
|
||||
qoderURL = func(*qoder.Credential) string { return up.URL }
|
||||
t.Cleanup(func() { up.Close(); qoderAuth, qoderURL, qoderModel = auth, url, model })
|
||||
}
|
||||
|
||||
const qoderBusyWant = "Qoder is busy for efficient (this plan's queue: p3); try again in 30s"
|
||||
|
||||
// serveQoderOnce sends one chat through serveQoder, as the gateway does.
|
||||
func serveQoderOnce(t *testing.T, stream bool) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body := `{"model":"qfmodel","stream":` + map[bool]string{true: "true", false: "false"}[stream] + `,"messages":[{"role":"user","content":"hi"}]}`
|
||||
w := httptest.NewRecorder()
|
||||
r := httptest.NewRequest("POST", "/", strings.NewReader(body))
|
||||
var u Usage
|
||||
s := New()
|
||||
s.serveQoder(w, r, provider.Chat, provider.Provider{Account: &provider.Account{Agent: "qoder", User: "one@x"}}, "qfmodel", []byte(body), &u)
|
||||
return w
|
||||
}
|
||||
|
||||
// checkQoderBusy: a 503 with Qoder's own wait as Retry-After, worded as
|
||||
// busy, never "sign in again" — and the gateway's busy handling takes it
|
||||
// as busy (asked again after the pause) and waits its Retry-After.
|
||||
func checkQoderBusy(t *testing.T, w *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
msg := gjson.Get(w.Body.String(), "error.message").String()
|
||||
if w.Code != 503 || w.Header().Get("Retry-After") != "30" || msg != qoderBusyWant {
|
||||
t.Fatalf("got %d Retry-After %q %q, want 503 Retry-After 30 %q", w.Code, w.Header().Get("Retry-After"), msg, qoderBusyWant)
|
||||
}
|
||||
if strings.Contains(strings.ToLower(w.Body.String()), "sign in") {
|
||||
t.Fatalf("a queued request asks to sign in again: %s", w.Body.String())
|
||||
}
|
||||
if !busy(w.Code, w.Body.Bytes()) {
|
||||
t.Fatalf("the gateway doesn't take it as busy (failure %q): %s", failure(w.Code, w.Body.Bytes()), w.Body.String())
|
||||
}
|
||||
if d := retryAfter(w.Header(), time.Now()); d != 30*time.Second {
|
||||
t.Fatalf("the gateway waits %s, want Qoder's 30s", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQoderQueuedIsBusy(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
queued := qoderQueuedBody(t)
|
||||
|
||||
t.Run("http 403", func(t *testing.T) {
|
||||
qoderRefusing(t, 403, queued)
|
||||
for _, stream := range []bool{false, true} {
|
||||
checkQoderBusy(t, serveQoderOnce(t, stream))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("in the stream before any answer", func(t *testing.T) {
|
||||
env, _ := json.Marshal(map[string]any{"headers": map[string]any{}, "body": queued, "statusCodeValue": 403, "statusCode": "FORBIDDEN"})
|
||||
done := qoderUpstream(t, []string{string(env)})
|
||||
defer done()
|
||||
for _, stream := range []bool{false, true} {
|
||||
checkQoderBusy(t, serveQoderOnce(t, stream))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The queue's own wait is used, rounded up; a queued request says so; with
|
||||
// no wait it is 30s; and a queue state under another status is the same.
|
||||
func TestQoderQueueWait(t *testing.T) {
|
||||
q := func(status int, code string, queue map[string]any) (int, string, time.Duration) {
|
||||
m, _ := json.Marshal(queue)
|
||||
b, _ := json.Marshal(map[string]any{"code": code, "message": string(m)})
|
||||
return qoderFailure(status, b)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
status int
|
||||
code string
|
||||
queue map[string]any
|
||||
want string
|
||||
wait time.Duration
|
||||
}{
|
||||
{"queued", 403, "10605", map[string]any{"isQueued": true, "modelKey": "ultimate", "retryAfterSeconds": 12.2}, "Qoder queued the request for ultimate; try again in 13s", 13 * time.Second},
|
||||
{"no wait", 403, "10605", map[string]any{"serviceAvailable": false}, "Qoder is busy; try again in 30s", 30 * time.Second},
|
||||
{"queue state on a 429, no code", 429, "", map[string]any{"serviceAvailable": false, "retryAfterSeconds": 5}, "Qoder is busy; try again in 5s", 5 * time.Second},
|
||||
} {
|
||||
status, msg, wait := q(tt.status, tt.code, tt.queue)
|
||||
if status != 503 || msg != tt.want || wait != tt.wait {
|
||||
t.Errorf("%s: %d %q %s, want 503 %q %s", tt.name, status, msg, wait, tt.want, tt.wait)
|
||||
}
|
||||
}
|
||||
// the code alone, the message plain text; a numeric code too
|
||||
for _, b := range []string{`{"code":"10605","message":"busy"}`, `{"code":10605,"message":"busy"}`} {
|
||||
if status, _, wait := qoderFailure(403, []byte(b)); status != 503 || wait != 30*time.Second {
|
||||
t.Errorf("%s: %d %s, want 503 30s", b, status, wait)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Qoder's other codes on a 401/403 aren't a lapsed sign-in either; 105
|
||||
// and no code are.
|
||||
func TestQoderErrorCodes(t *testing.T) {
|
||||
f := func(status int, code, message string) (int, string, time.Duration) {
|
||||
b, _ := json.Marshal(map[string]any{"code": code, "message": message})
|
||||
return qoderFailure(status, b)
|
||||
}
|
||||
for _, status := range []int{401, 403} {
|
||||
for _, code := range []string{"110", "112", "113", "114", "115", "116", "117", "118", "119", "122"} {
|
||||
if got, msg, _ := f(status, code, "credits used up"); got != 429 || msg != "usage limit reached: credits used up" {
|
||||
t.Errorf("%d code %s: %d %q, want 429", status, code, got, msg)
|
||||
}
|
||||
}
|
||||
for _, code := range []string{"406", "416", "430", "80411", "80412", "100400", "100401", "100403"} {
|
||||
if got, msg, _ := f(status, code, "no"); got != 400 || msg != "Qoder refused the request ("+code+"): no" {
|
||||
t.Errorf("%d code %s: %d %q, want 400", status, code, got, msg)
|
||||
}
|
||||
}
|
||||
for _, b := range []string{`{"code":"105","message":"login expired"}`, `{"message":"forbidden"}`, ``} {
|
||||
if got, msg, wait := qoderFailure(status, []byte(b)); got != 401 || msg != "Qoder: the sign-in lapsed — sign in again" || wait != 0 {
|
||||
t.Errorf("%d %s: %d %q %s, want the 401", status, b, got, msg, wait)
|
||||
}
|
||||
}
|
||||
}
|
||||
// a quota without a code reads as before
|
||||
if got, _, _ := qoderFailure(429, []byte(`{"message":"额度已耗尽"}`)); got != 429 {
|
||||
t.Errorf("a 429: %d", got)
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/qoder"
|
||||
)
|
||||
|
||||
// TestQoderCNGateway: a Qoder CN account is served through the gateway like
|
||||
// the global Qoder's, its credential asked for as Qoder CN's and its chat sent
|
||||
// to Qoder CN's inference host, gateway.qoder.com.cn; a global account still
|
||||
// goes to api3.qoder.sh.
|
||||
func TestQoderCNGateway(t *testing.T) {
|
||||
real := qoderURL
|
||||
done := qoderUpstream(t, []string{qoderChunk(qoderContent(t, "ok"))})
|
||||
defer done()
|
||||
up, _ := url.Parse(qoderURL(nil))
|
||||
qoderURL = real
|
||||
for _, tt := range []struct{ agent, site, host string }{
|
||||
{provider.QoderCNID, qoder.CNProviderKey, "gateway.qoder.com.cn"},
|
||||
{"qoder", "", "api3.qoder.sh"},
|
||||
} {
|
||||
var asked []string
|
||||
qoderAuth = func(_ context.Context, agent, user string) (*qoder.Credential, error) {
|
||||
asked = append(asked, agent+" "+user)
|
||||
return &qoder.Credential{UID: "uid-test", Token: "jt-test", MachineID: "machine-test", Site: tt.site}, nil
|
||||
}
|
||||
qoderModel = func(_ context.Context, agent, _, _ string) (qoder.ModelInfo, error) {
|
||||
asked = append(asked, "model "+agent)
|
||||
return testQoderModel(t), nil
|
||||
}
|
||||
var host, path string
|
||||
s := New()
|
||||
s.client = &http.Client{Transport: qoderRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
host, path = r.URL.Host, r.URL.Path
|
||||
r.URL.Scheme, r.URL.Host = up.Scheme, up.Host
|
||||
return http.DefaultTransport.RoundTrip(r)
|
||||
})}
|
||||
p := provider.Provider{ID: tt.agent, Account: &provider.Account{Agent: tt.agent, User: "one@x"}}
|
||||
body := `{"model":"qfmodel","messages":[{"role":"user","content":"hi"}]}`
|
||||
w := httptest.NewRecorder()
|
||||
var call Call
|
||||
status, msg := s.attempt(w, httptest.NewRequest("POST", "/", strings.NewReader(body)), provider.Chat, p, "qfmodel", []byte(body), &call)
|
||||
if status != 200 || !strings.Contains(w.Body.String(), "ok") {
|
||||
t.Fatalf("%s: %d %s %s", tt.agent, status, msg, w.Body.String())
|
||||
}
|
||||
if host != tt.host || path != strings.Split(qoder.ChatPath, "?")[0] {
|
||||
t.Errorf("%s: chat went to %s%s, want %s", tt.agent, host, path, tt.host)
|
||||
}
|
||||
if len(asked) != 2 || asked[0] != tt.agent+" one@x" || asked[1] != "model "+tt.agent {
|
||||
t.Errorf("%s: asked %v", tt.agent, asked)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type qoderRoundTrip func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f qoderRoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
@@ -1,639 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/qoder"
|
||||
)
|
||||
|
||||
func testQoderModel(t *testing.T) qoder.ModelInfo {
|
||||
t.Helper()
|
||||
ms, err := qoder.ModelConfigs([]byte(`{"chat":[{"key":"qfmodel","enable":true,"display_name":"Qwen3.8-Flash","format":"openai","source":"system","is_vl":true,"is_reasoning":true,"max_input_tokens":200000,
|
||||
"thinking_config":{"disabled":{"description":"Disable thinking"},"enabled":{"is_default":true,"efforts":{"xhigh":{},"medium":{"is_default":true},"low":{}}}}}]}`))
|
||||
if err != nil || len(ms) != 1 {
|
||||
t.Fatalf("model fixture: %v", err)
|
||||
}
|
||||
return ms[0]
|
||||
}
|
||||
|
||||
// qoderUpstream stands in for api3.qoder.sh: it checks the wire body decodes to
|
||||
// a well-formed Qoder chat body carrying the COSY envelope, then streams a
|
||||
// Qoder SSE reply (each line an OpenAI chunk inside the envelope). It returns a
|
||||
// cleanup that restores the real auth/URL hooks.
|
||||
func qoderUpstream(t *testing.T, lines []string, modelKeys ...string) func() {
|
||||
t.Helper()
|
||||
modelKey := "qfmodel"
|
||||
if len(modelKeys) > 0 {
|
||||
modelKey = modelKeys[0]
|
||||
}
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
if !strings.HasPrefix(r.Header.Get("Authorization"), "Bearer COSY.") {
|
||||
t.Errorf("missing COSY Authorization")
|
||||
}
|
||||
if r.Header.Get("X-Model-Key") != modelKey {
|
||||
t.Errorf("X-Model-Key = %q", r.Header.Get("X-Model-Key"))
|
||||
}
|
||||
plain := qoder.DecodeRequestBody(string(raw))
|
||||
if !gjson.ValidBytes(plain) {
|
||||
t.Errorf("decoded body is not JSON: %q", plain)
|
||||
}
|
||||
if gjson.GetBytes(plain, "model_config.key").String() != modelKey {
|
||||
t.Errorf("wrong body model configuration")
|
||||
}
|
||||
if gjson.GetBytes(plain, "agent_id").String() != "agent_common" {
|
||||
t.Errorf("agent_id = %q", gjson.GetBytes(plain, "agent_id").String())
|
||||
}
|
||||
if !gjson.GetBytes(plain, "messages").IsArray() {
|
||||
t.Errorf("no messages array in decoded body")
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
for _, l := range lines {
|
||||
io.WriteString(w, "data: "+l+"\n")
|
||||
}
|
||||
}))
|
||||
auth, url, model := qoderAuth, qoderURL, qoderModel
|
||||
qoderAuth = func(ctx context.Context, agent, user string) (*qoder.Credential, error) {
|
||||
return &qoder.Credential{UID: "uid-test", Token: "jt-test", MachineID: "machine-test"}, nil
|
||||
}
|
||||
qoderModel = func(context.Context, string, string, string) (qoder.ModelInfo, error) { return testQoderModel(t), nil }
|
||||
qoderURL = func(*qoder.Credential) string { return up.URL }
|
||||
return func() { up.Close(); qoderAuth, qoderURL, qoderModel = auth, url, model }
|
||||
}
|
||||
|
||||
func TestQoderSelectedModel(t *testing.T) {
|
||||
done := qoderUpstream(t, []string{qoderChunk(qoderContent(t, "ok"))}, "other-model")
|
||||
defer done()
|
||||
ms, err := qoder.ModelConfigs([]byte(`{"chat":[{"key":"other-model","enable":true,"display_name":"Other","format":"custom","source":"system","is_vl":false,"is_reasoning":false,"max_input_tokens":64000,"custom_field":17}]}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
qoderModel = func(_ context.Context, _, user, key string) (qoder.ModelInfo, error) {
|
||||
if user != "selected@x" || key != "other-model" {
|
||||
t.Errorf("selected user/model %s %s", user, key)
|
||||
}
|
||||
return ms[0], nil
|
||||
}
|
||||
s := New()
|
||||
ch, status, msg := s.askQoder("qoder", "other-model", "selected@x")(context.Background(), &Request{Model: "other-model", Effort: "max"})
|
||||
if ch == nil {
|
||||
t.Fatalf("ask: %d %s", status, msg)
|
||||
}
|
||||
for range ch {
|
||||
}
|
||||
b, err := qoderChatBody(&Request{Effort: "high"}, ms[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gjson.GetBytes(b, "model_config.custom_field").Int() != 17 || gjson.GetBytes(b, "parameters.context_length").Int() != 64000 || gjson.GetBytes(b, "parameters.enable_thinking").Bool() || gjson.GetBytes(b, "parameters.reasoning_effort").Exists() {
|
||||
t.Fatalf("selected config: %s", b)
|
||||
}
|
||||
qoderModel = func(context.Context, string, string, string) (qoder.ModelInfo, error) {
|
||||
return qoder.ModelInfo{}, errors.New("unknown model")
|
||||
}
|
||||
ch, status, _ = s.askQoder("qoder", "unknown", "selected@x")(context.Background(), &Request{})
|
||||
if ch != nil || status != 400 {
|
||||
t.Fatalf("unknown model: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
// Qoder's efforts come from thinking_config; asked for nothing, or for one
|
||||
// the model doesn't offer, it thinks at its own default.
|
||||
func TestQoderReasoning(t *testing.T) {
|
||||
model := testQoderModel(t)
|
||||
if model.DefaultEffort != "medium" || !model.Thinks || model.AlwaysThinks {
|
||||
t.Fatalf("thinking_config read: %+v", model)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
want, got string
|
||||
thinking bool
|
||||
}{
|
||||
{"", "medium", true}, {"xhigh", "xhigh", true}, {"max", "xhigh", true}, {"none", "", false}, {"invalid", "medium", true},
|
||||
} {
|
||||
b, err := qoderChatBody(&Request{Effort: tt.want}, model)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gjson.GetBytes(b, "parameters.reasoning_effort").String() != tt.got || gjson.GetBytes(b, "parameters.enable_thinking").Bool() != tt.thinking {
|
||||
t.Fatalf("effort %q: %s", tt.want, b)
|
||||
}
|
||||
}
|
||||
// a model that can't stop thinking thinks at its lowest when asked for none
|
||||
always, err := qoder.ModelConfigs([]byte(`{"chat":[{"key":"gf","enable":true,"is_reasoning":true,"thinking_config":{"enabled":{"is_default":true,"efforts":{"max":{"is_default":true},"high":{},"low":{}}}}}]}`))
|
||||
if err != nil || !always[0].AlwaysThinks {
|
||||
t.Fatalf("always-thinking model: %+v %v", always, err)
|
||||
}
|
||||
b, _ := qoderChatBody(&Request{Effort: "none"}, always[0])
|
||||
if !gjson.GetBytes(b, "parameters.enable_thinking").Bool() || gjson.GetBytes(b, "parameters.reasoning_effort").String() != "low" {
|
||||
t.Fatalf("always-thinking asked for none: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
// A tool call and its result are sent as OpenAI tool turns, so the result is
|
||||
// paired with the call by id, not by order.
|
||||
func TestQoderToolTurns(t *testing.T) {
|
||||
msgs := qoderMessages([]Message{
|
||||
{Role: "user", Parts: []Part{{Kind: Text, Text: "read it"}}},
|
||||
{Role: "assistant", Parts: []Part{
|
||||
{Kind: ToolCall, ID: "call_A", Name: "read", Args: json.RawMessage(`{"path":"/tmp/x & y"}`)},
|
||||
{Kind: ToolCall, ID: "call_B", Name: "bash", Args: json.RawMessage(`{"command":"ls"}`)}}},
|
||||
{Role: "user", Parts: []Part{
|
||||
{Kind: ToolResult, CallID: "call_B", Text: "second result"},
|
||||
{Kind: ToolResult, CallID: "call_A", Text: "first result", IsError: true}}},
|
||||
})
|
||||
b, _ := json.Marshal(msgs)
|
||||
if len(msgs) != 4 {
|
||||
t.Fatalf("turns %s", b)
|
||||
}
|
||||
got := gjson.ParseBytes(b)
|
||||
if got.Get("1.tool_calls.0.id").String() != "call_A" || got.Get("1.tool_calls.1.id").String() != "call_B" {
|
||||
t.Fatalf("tool_calls %s", got.Get("1").Raw)
|
||||
}
|
||||
// arguments reach Qoder as they stand, not HTML-escaped
|
||||
if got.Get("1.tool_calls.0.function.arguments").String() != `{"path":"/tmp/x & y"}` {
|
||||
t.Fatalf("arguments %s", got.Get("1.tool_calls.0").Raw)
|
||||
}
|
||||
if got.Get("2.role").String() != "tool" || got.Get("2.tool_call_id").String() != "call_B" ||
|
||||
got.Get("2.content").String() != "second result" {
|
||||
t.Fatalf("tool turn %s", got.Get("2").Raw)
|
||||
}
|
||||
}
|
||||
|
||||
// The caller's tools go to Qoder as native function tools.
|
||||
func TestQoderNativeTools(t *testing.T) {
|
||||
b, err := qoderChatBody(&Request{Tools: []Tool{{Name: "read", Description: "Read a file",
|
||||
Schema: json.RawMessage(`{"type":"object"}`)}}}, testQoderModel(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gjson.GetBytes(b, "tools.0.type").String() != "function" || gjson.GetBytes(b, "tools.0.function.name").String() != "read" {
|
||||
t.Fatalf("tools %s", b)
|
||||
}
|
||||
none, _ := qoderChatBody(&Request{ToolChoice: "none", Tools: []Tool{{Name: "read"}}}, testQoderModel(t))
|
||||
if gjson.GetBytes(none, "tools").Exists() {
|
||||
t.Fatalf("tools sent for tool_choice none: %s", none)
|
||||
}
|
||||
}
|
||||
|
||||
// Qoder's own tool_calls come back with the id they are answered with.
|
||||
func TestQoderNativeToolCall(t *testing.T) {
|
||||
calls := []string{
|
||||
`{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_up1","type":"function","function":{"name":"read","arguments":""}}]}}]}`,
|
||||
`{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"path\": \"/tmp/x"}}]}}]}`,
|
||||
`{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":" \\u0026 y\"}"}}]}}]}`,
|
||||
`{"choices":[{"delta":{"tool_calls":[{"index":1,"id":"call_up2","type":"function","function":{"name":"bash","arguments":"{\"command\":\"ls\"}"}}]}}]}`,
|
||||
`{"choices":[{"delta":{},"finish_reason":"tool_calls"}]}`,
|
||||
}
|
||||
var env []string
|
||||
for _, c := range calls {
|
||||
env = append(env, qoderChunk(c))
|
||||
}
|
||||
events := qoderDecoded(env...)
|
||||
var ids []string
|
||||
var args, stop string
|
||||
for _, ev := range events {
|
||||
switch ev.Kind {
|
||||
case KToolStart:
|
||||
ids = append(ids, ev.ID)
|
||||
case KToolArgs:
|
||||
args += ev.Text
|
||||
case KStop:
|
||||
stop = ev.Stop
|
||||
}
|
||||
}
|
||||
if len(ids) != 2 || ids[0] != "call_up1" || ids[1] != "call_up2" {
|
||||
t.Fatalf("call ids %v", ids)
|
||||
}
|
||||
// arguments are handed on as they arrive: nothing is unescaped twice
|
||||
if args != `{"path": "/tmp/x \u0026 y"}{"command":"ls"}` {
|
||||
t.Fatalf("arguments %q", args)
|
||||
}
|
||||
if stop != "tool" {
|
||||
t.Fatalf("stop %q", stop)
|
||||
}
|
||||
}
|
||||
|
||||
func qoderDecoded(lines ...string) []Event {
|
||||
var wire strings.Builder
|
||||
for _, line := range lines {
|
||||
fmt.Fprintf(&wire, "data: %s\n\n", line)
|
||||
}
|
||||
ch := make(chan Event, 32)
|
||||
go decodeQoder(context.Background(), &http.Response{Body: io.NopCloser(strings.NewReader(wire.String()))}, ch, "qfmodel")
|
||||
var events []Event
|
||||
for ev := range ch {
|
||||
events = append(events, ev)
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
func TestQoderEOF(t *testing.T) {
|
||||
call := qoderCallOpen + `{"name":"read","arguments":{"path":"x"}}` + qoderCallClose
|
||||
for _, tt := range []struct{ input, text, stop string }{
|
||||
{"a < b and x <", "a < b and x <", "stop"},
|
||||
{call + "tail <", "tail <", "tool"},
|
||||
{"before " + qoderCallOpen + "incomplete", "before " + qoderCallOpen + "incomplete", "stop"},
|
||||
{"", "", "stop"},
|
||||
} {
|
||||
events := qoderDecoded(qoderChunk(qoderContent(t, tt.input)), "[DONE]")
|
||||
var text, stop string
|
||||
stops := 0
|
||||
for _, ev := range events {
|
||||
if ev.Kind == KText {
|
||||
text += ev.Text
|
||||
}
|
||||
if ev.Kind == KStop {
|
||||
stop = ev.Stop
|
||||
stops++
|
||||
}
|
||||
}
|
||||
if text != tt.text || stop != tt.stop || stops != 1 {
|
||||
t.Fatalf("EOF %q => %q %q stops %d", tt.input, text, stop, stops)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A tool call written into the text that can't be read ends the turn as an
|
||||
// error, never as the answer (plugins#132, as the moved qoder plugin's
|
||||
// 0.2.16): a whole block whose JSON doesn't parse is a 502, and one the
|
||||
// stream ends inside is the call when its JSON is whole, else a 502. A
|
||||
// marker that is no call at all, or a block inside code, stays text.
|
||||
func TestQoderUnreadableToolCall(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
bad := qoderCallOpen + `{"path":}` + qoderCallClose
|
||||
cutWhole := qoderCallOpen + `{"name":"read","arguments":{"path":"x"}}`
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
lines []string
|
||||
stream bool
|
||||
want int
|
||||
noText string // never in the reply
|
||||
text string // the whole reply's text, when text is wanted
|
||||
frame string // in the reply as it came, when a frame is wanted
|
||||
hasCall string // a tool call named so, when one is wanted
|
||||
}{
|
||||
{
|
||||
name: "unreadable block, whole reply",
|
||||
lines: []string{qoderChunk(qoderContent(t, bad)), qoderChunk(`{"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)},
|
||||
stream: false,
|
||||
want: 502,
|
||||
noText: "tool_call>",
|
||||
},
|
||||
{
|
||||
name: "unreadable block, streamed",
|
||||
lines: []string{qoderChunk(qoderContent(t, bad)), qoderChunk(`{"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)},
|
||||
stream: true,
|
||||
want: 502,
|
||||
noText: "tool_call>",
|
||||
},
|
||||
{
|
||||
// text was already going out, so the 200 stands: the reason is
|
||||
// an error frame, and no finish follows it
|
||||
name: "unreadable block after text, streamed",
|
||||
lines: []string{qoderChunk(qoderContent(t, "Sure. ")), qoderChunk(qoderContent(t, bad)), qoderChunk(`{"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)},
|
||||
stream: true,
|
||||
want: 200,
|
||||
noText: `"finish_reason":"stop"`,
|
||||
frame: "can't be read",
|
||||
},
|
||||
{
|
||||
name: "stream ends inside, JSON whole",
|
||||
lines: []string{qoderChunk(qoderContent(t, cutWhole)), qoderChunk(`{"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)},
|
||||
stream: false,
|
||||
want: 200,
|
||||
noText: "tool_call>",
|
||||
hasCall: "read",
|
||||
},
|
||||
{
|
||||
name: "stream ends inside, unreadable",
|
||||
lines: []string{qoderChunk(qoderContent(t, qoderCallOpen+`{"path":`)), qoderChunk(`{"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)},
|
||||
stream: false,
|
||||
want: 502,
|
||||
noText: "tool_call>",
|
||||
},
|
||||
{
|
||||
name: "a marker that is no call stays text",
|
||||
lines: []string{qoderChunk(qoderContent(t, "before "+qoderCallOpen+"incomplete")), qoderChunk(`{"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)},
|
||||
stream: false,
|
||||
want: 200,
|
||||
text: "before " + qoderCallOpen + "incomplete",
|
||||
},
|
||||
{
|
||||
name: "a block inside code stays text",
|
||||
lines: []string{qoderChunk(qoderContent(t, "```text\n"+bad+"\n```")), qoderChunk(`{"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)},
|
||||
stream: false,
|
||||
want: 200,
|
||||
text: bad,
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
done := qoderUpstream(t, tt.lines)
|
||||
defer done()
|
||||
s := New()
|
||||
w := httptest.NewRecorder()
|
||||
body := `{"model":"qfmodel","stream":` + map[bool]string{true: "true", false: "false"}[tt.stream] + `,"messages":[{"role":"user","content":"hi"}]}`
|
||||
r := httptest.NewRequest("POST", "/", strings.NewReader(body))
|
||||
var u Usage
|
||||
status, msg := s.serveQoder(w, r, provider.Chat, provider.Provider{Account: &provider.Account{User: "test"}}, "qfmodel", []byte(body), &u)
|
||||
out := w.Body.String()
|
||||
if status != tt.want {
|
||||
t.Fatalf("status %d msg %q want %d\n%s", status, msg, tt.want, out)
|
||||
}
|
||||
if tt.noText != "" && strings.Contains(out, tt.noText) {
|
||||
t.Fatalf("the unreadable block went out as the answer:\n%s", out)
|
||||
}
|
||||
if tt.text != "" && !strings.Contains(gjson.Get(out, "choices.0.message.content").String(), tt.text) {
|
||||
t.Fatalf("text was changed to %q:\n%s", gjson.Get(out, "choices.0.message.content").String(), out)
|
||||
}
|
||||
if tt.frame != "" && !strings.Contains(out, tt.frame) {
|
||||
t.Fatalf("the reply doesn't carry the reason:\n%s", out)
|
||||
}
|
||||
if tt.hasCall != "" {
|
||||
if gjson.Get(out, "choices.0.message.tool_calls.0.function.name").String() != tt.hasCall {
|
||||
t.Fatalf("the whole-JSON call cut short is not a call:\n%s", out)
|
||||
}
|
||||
if gjson.Get(out, "choices.0.finish_reason").String() != "tool_calls" {
|
||||
t.Fatalf("finish %q, want tool_calls:\n%s", gjson.Get(out, "choices.0.finish_reason").String(), out)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQoderEnvelopeErrors(t *testing.T) {
|
||||
for _, status := range []int{401, 403, 429, 500} {
|
||||
for _, proto := range []provider.Protocol{provider.Chat, provider.Responses, provider.Anthropic, provider.Gemini} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
for _, partial := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/%d/stream=%t/partial=%t", proto, status, stream, partial), func(t *testing.T) {
|
||||
var lines []string
|
||||
if partial {
|
||||
lines = append(lines, qoderChunk(qoderContent(t, "some text")))
|
||||
}
|
||||
b, _ := json.Marshal(map[string]any{"statusCodeValue": status, "body": `{"message":"upstream failure"}`})
|
||||
if status == 429 {
|
||||
b, _ = json.Marshal(map[string]any{"statusCodeValue": status, "body": `{"message":"额度已耗尽"}`})
|
||||
}
|
||||
lines = append(lines, string(b))
|
||||
done := qoderUpstream(t, lines)
|
||||
defer done()
|
||||
s := New()
|
||||
req := &Request{Model: "qfmodel", Stream: stream}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
events, _, _ := s.askQoder("qoder", "qfmodel", "test")(ctx, req)
|
||||
w := httptest.NewRecorder()
|
||||
var usage Usage
|
||||
code, msg := relayQoder(w, proto, req, events, &usage, cancel)
|
||||
want := status
|
||||
if want == 403 {
|
||||
want = 401
|
||||
}
|
||||
if stream && partial {
|
||||
want = 200
|
||||
}
|
||||
if code != want || w.Code != want || msg == "" || !strings.Contains(w.Body.String(), "error") {
|
||||
t.Fatalf("code %d/%d want %d, msg %s body %s", code, w.Code, want, msg, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQoderSearchEnvelopeError(t *testing.T) {
|
||||
for _, stream := range []bool{false, true} {
|
||||
for _, partial := range []bool{false, true} {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
in := make(chan Event, 3)
|
||||
in <- Event{Kind: KStart}
|
||||
if partial {
|
||||
in <- Event{Kind: KText, Text: "partial answer"}
|
||||
}
|
||||
in <- Event{Kind: KError, Status: 503, Text: "Qoder upstream unavailable"}
|
||||
close(in)
|
||||
out := make(chan Event, 4)
|
||||
req := &Request{Model: "qfmodel", Stream: stream}
|
||||
go func() {
|
||||
defer close(out)
|
||||
New().searchRounds(ctx, req, "search", in, nil, out)
|
||||
}()
|
||||
w := httptest.NewRecorder()
|
||||
var usage Usage
|
||||
code, msg := relayQoder(w, provider.Chat, req, out, &usage, cancel)
|
||||
cancel()
|
||||
want := 503
|
||||
if stream && partial {
|
||||
want = 200
|
||||
}
|
||||
if code != want || w.Code != want || msg == "" || !strings.Contains(w.Body.String(), "error") {
|
||||
t.Fatalf("stream=%t partial=%t: code %d/%d want %d, msg %s body %s", stream, partial, code, w.Code, want, msg, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// qoderChunk wraps an OpenAI chat.completion.chunk as Qoder's SSE envelope.
|
||||
func qoderChunk(inner string) string {
|
||||
b, _ := json.Marshal(map[string]any{
|
||||
"headers": map[string][]string{"Content-Type": {"application/json"}},
|
||||
"body": inner, "statusCodeValue": 200, "statusCode": "OK",
|
||||
})
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// TestQoderChatBody checks the IR request becomes a Qoder body: the caller's
|
||||
// system prompt and tool contract ride in the system field, tool calls are
|
||||
// replayed as XML, and tool results fold into a user turn.
|
||||
func TestQoderChatBody(t *testing.T) {
|
||||
req := &Request{
|
||||
System: "Be terse.",
|
||||
ToolChoice: "",
|
||||
Tools: []Tool{{Name: "read", Description: "Read a file", Schema: json.RawMessage(`{"type":"object"}`)}},
|
||||
Messages: []Message{
|
||||
{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}},
|
||||
{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "c1", Name: "read", Args: json.RawMessage(`{"path":"x"}`)}}},
|
||||
{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "c1", Text: "the file"}}},
|
||||
},
|
||||
}
|
||||
b, err := qoderChatBody(req, testQoderModel(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gjson.GetBytes(b, "agent_id").String() != "agent_common" {
|
||||
t.Fatalf("agent_id")
|
||||
}
|
||||
if gjson.GetBytes(b, "model_config.key").String() != "qfmodel" {
|
||||
t.Fatalf("model key")
|
||||
}
|
||||
// the caller's tools go as Qoder's own function tools, not in the prompt
|
||||
if gjson.GetBytes(b, "tools.0.function.name").String() != "read" ||
|
||||
!strings.Contains(gjson.GetBytes(b, "system.0.text").String(), "Be terse.") {
|
||||
t.Fatalf("system/tools: %s", b)
|
||||
}
|
||||
msgs := gjson.GetBytes(b, "messages")
|
||||
if msgs.Get("0.role").String() != "system" {
|
||||
t.Fatalf("first message is %s, want system", msgs.Get("0.role").String())
|
||||
}
|
||||
// assistant tool call and tool result are tool turns named by id
|
||||
if msgs.Get("2.tool_calls.0.id").String() != "c1" ||
|
||||
msgs.Get("3.role").String() != "tool" || msgs.Get("3.tool_call_id").String() != "c1" ||
|
||||
msgs.Get("3.content").String() != "the file" {
|
||||
t.Fatalf("tool turns: %s", msgs.Raw)
|
||||
}
|
||||
}
|
||||
|
||||
// qoderContent builds an OpenAI chunk inner JSON whose delta carries content,
|
||||
// assembled through encoding/json so a Qoder tool-call block, written here with
|
||||
// hex-escaped brackets, reaches the wire as real angle brackets without any
|
||||
// literal tag in this source.
|
||||
func qoderContent(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(map[string]any{
|
||||
"choices": []any{map[string]any{"delta": map[string]any{"content": content}}},
|
||||
"object": "chat.completion.chunk",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// TestServeQoder runs a request through serveQoder against a stubbed Qoder:
|
||||
// text, a reasoning delta, an embedded tool call lifted into events, and usage
|
||||
// all reach the client's protocol.
|
||||
func TestServeQoder(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
call := "\x3ctool_call\x3e\n\x3cfunction=read\x3e\n\x3cparameter=path\x3ex\x3c/parameter\x3e\n\x3c/function\x3e\n\x3c/tool_call\x3e"
|
||||
done := qoderUpstream(t, []string{
|
||||
qoderChunk(`{"choices":[{"delta":{"role":"assistant","reasoning_content":"thinking"}}],"object":"chat.completion.chunk"}`),
|
||||
qoderChunk(`{"choices":[{"delta":{"content":"Hi there"}}],"object":"chat.completion.chunk"}`),
|
||||
qoderChunk(qoderContent(t, call)),
|
||||
qoderChunk(`{"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5}}`),
|
||||
`{"firstTokenDuration":50,"totalDuration":200}`,
|
||||
})
|
||||
defer done()
|
||||
s := New()
|
||||
w := httptest.NewRecorder()
|
||||
r := httptest.NewRequest("POST", "/", strings.NewReader(`{"model":"qoder/qfmodel","stream":true,"messages":[{"role":"user","content":"hi"}]}`))
|
||||
var u Usage
|
||||
if status, msg := s.serveQoder(w, r, provider.Chat, provider.Provider{Account: &provider.Account{User: "test"}}, "qfmodel", []byte(`{"model":"qfmodel","stream":true,"messages":[{"role":"user","content":"hi"}]}`), &u); status != 200 {
|
||||
t.Fatalf("status %d msg %q", status, msg)
|
||||
}
|
||||
out := w.Body.String()
|
||||
for _, kw := range []string{"thinking", "Hi there", "read", "path", "x"} {
|
||||
if !strings.Contains(out, kw) {
|
||||
t.Fatalf("streamed output missing %q:\n%s", kw, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Thinking turned off reaches Qoder as off: reasoning_effort "none", which
|
||||
// Effort reads as low for other vendors, and Anthropic's thinking disabled.
|
||||
func TestQoderThinkingOff(t *testing.T) {
|
||||
model := testQoderModel(t)
|
||||
always, err := qoder.ModelConfigs([]byte(`{"chat":[{"key":"gf","enable":true,"is_reasoning":true,"thinking_config":{"enabled":{"is_default":true,"efforts":{"max":{"is_default":true},"high":{},"low":{}}}}}]}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
from provider.Protocol
|
||||
body string
|
||||
}{
|
||||
{provider.Chat, `{"model":"m","reasoning_effort":"none","messages":[{"role":"user","content":"hi"}]}`},
|
||||
{provider.Responses, `{"model":"m","reasoning":{"effort":"none"},"input":"hi"}`},
|
||||
{provider.Anthropic, `{"model":"m","max_tokens":100,"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"hi"}]}`},
|
||||
} {
|
||||
req, err := parse(tt.from, []byte(tt.body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tt.from != provider.Anthropic && req.Effort != "low" {
|
||||
t.Errorf("%s: other vendors' effort changed: %q", tt.from, req.Effort)
|
||||
}
|
||||
b, _ := qoderChatBody(req, model)
|
||||
if gjson.GetBytes(b, "parameters.enable_thinking").Bool() || gjson.GetBytes(b, "parameters.reasoning_effort").Exists() {
|
||||
t.Errorf("%s: thinking off on a model that can stop: %s", tt.from, gjson.GetBytes(b, "parameters").Raw)
|
||||
}
|
||||
b, _ = qoderChatBody(req, always[0])
|
||||
if !gjson.GetBytes(b, "parameters.enable_thinking").Bool() || gjson.GetBytes(b, "parameters.reasoning_effort").String() != "low" {
|
||||
t.Errorf("%s: thinking off on an always-thinking model: %s", tt.from, gjson.GetBytes(b, "parameters").Raw)
|
||||
}
|
||||
}
|
||||
// thinking not mentioned is the model's own default, as before
|
||||
req, _ := parse(provider.Anthropic, []byte(`{"model":"m","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`))
|
||||
b, _ := qoderChatBody(req, always[0])
|
||||
if gjson.GetBytes(b, "parameters.reasoning_effort").String() != "max" {
|
||||
t.Errorf("unmentioned thinking: %s", gjson.GetBytes(b, "parameters").Raw)
|
||||
}
|
||||
}
|
||||
|
||||
// Only a sign-in that is gone is a 401 (the agent asks to log in again); a
|
||||
// refresh that timed out or failed on the network is a 502.
|
||||
func TestQoderCredentialStatus(t *testing.T) {
|
||||
done := qoderUpstream(t, nil)
|
||||
defer done()
|
||||
s := New()
|
||||
for _, tt := range []struct {
|
||||
err error
|
||||
want int
|
||||
}{
|
||||
{fmt.Errorf("Qoder: refresh: %w", context.DeadlineExceeded), 502},
|
||||
{errors.New("dial tcp: connection refused"), 502},
|
||||
{fmt.Errorf("one@x's Qoder sign-in has expired — sign in again (%w)", provider.ErrQoderSignIn), 401},
|
||||
} {
|
||||
qoderAuth = func(context.Context, string, string) (*qoder.Credential, error) { return nil, tt.err }
|
||||
ch, status, _ := s.askQoder("qoder", "qfmodel", "one@x")(context.Background(), &Request{Model: "qfmodel"})
|
||||
if ch != nil || status != tt.want {
|
||||
t.Errorf("%v: status %d, want %d", tt.err, status, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A tool turn holds text only, so a tool's images follow in a user turn,
|
||||
// joined to the user's own next turn.
|
||||
func TestQoderToolResultImages(t *testing.T) {
|
||||
png := Part{Kind: Image, MediaType: "image/png", Data: "iVBOR"}
|
||||
msgs := qoderMessages([]Message{
|
||||
{Role: "user", Parts: []Part{{Kind: Text, Text: "look"}}},
|
||||
{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "call_A", Name: "screenshot", Args: json.RawMessage(`{}`)}}},
|
||||
{Role: "user", Parts: []Part{
|
||||
{Kind: ToolResult, CallID: "call_A", Text: "shot taken", Images: []Part{png}},
|
||||
{Kind: Text, Text: "what do you see?"}}},
|
||||
{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "call_B", Name: "screenshot", Args: json.RawMessage(`{}`)}}},
|
||||
{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "call_B", Images: []Part{png, png}}}},
|
||||
})
|
||||
b, _ := json.Marshal(msgs)
|
||||
got := gjson.ParseBytes(b)
|
||||
if len(msgs) != 7 {
|
||||
t.Fatalf("turns %s", b)
|
||||
}
|
||||
if got.Get("2.role").String() != "tool" || !strings.Contains(got.Get("2.content").String(), "shot taken") ||
|
||||
!strings.Contains(got.Get("2.content").String(), "an image; it follows") {
|
||||
t.Fatalf("tool turn %s", got.Get("2").Raw)
|
||||
}
|
||||
u := got.Get("3")
|
||||
if u.Get("role").String() != "user" || !strings.Contains(u.Get("content.0.text").String(), "screenshot (tool call call_A)") ||
|
||||
u.Get("content.1.image_url.url").String() != "data:image/png;base64,iVBOR" || u.Get("content.2.text").String() != "what do you see?" {
|
||||
t.Fatalf("images with the user's turn %s", u.Raw)
|
||||
}
|
||||
if got.Get("5.role").String() != "tool" || !strings.Contains(got.Get("5.content").String(), "2 images") {
|
||||
t.Fatalf("second tool turn %s", got.Get("5").Raw)
|
||||
}
|
||||
if got.Get("6.role").String() != "user" || got.Get("6.content.#").Int() != 3 {
|
||||
t.Fatalf("trailing images %s", got.Get("6").Raw)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// relayStatus relays a backend's events and keeps its upstream failures
|
||||
// before a response is committed, including failures after partial
|
||||
// non-streaming text; once streaming output has begun a failure is a
|
||||
// terminal error event. It is for the backends that report their own
|
||||
// statuses; name is the backend's, for an answer that never came.
|
||||
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
|
||||
if code < 400 || code > 599 {
|
||||
code = 502
|
||||
}
|
||||
retryAfterOn(w, ev.Wait)
|
||||
return writeError(w, from, code, ev.Text), ev.Text
|
||||
}
|
||||
if req.Stream {
|
||||
var head []Event
|
||||
for ev := range events {
|
||||
if ev.Kind == KError {
|
||||
return fail(ev)
|
||||
}
|
||||
head = append(head, ev)
|
||||
if ev.Kind != KStart && ev.Kind != KUsage {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(head) == 0 || head[len(head)-1].Kind == KStart || head[len(head)-1].Kind == KUsage {
|
||||
return fail(Event{Text: name + " ended without an answer"})
|
||||
}
|
||||
sw := newSSEWriter(w)
|
||||
enc := encoder(from, sw, req, usage)
|
||||
var failed string
|
||||
see := func(ev Event) bool {
|
||||
if ev.Kind == KStart || ev.Kind == KUsage {
|
||||
usage.add(ev.Usage)
|
||||
}
|
||||
enc.event(ev)
|
||||
if ev.Kind == KError {
|
||||
failed = ev.Text
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
for _, ev := range head {
|
||||
see(ev)
|
||||
}
|
||||
// kept from the client's idle timeout while none comes (#436)
|
||||
relayEvents(events, sw, enc, see)
|
||||
if failed != "" {
|
||||
abort()
|
||||
return 200, failed
|
||||
}
|
||||
enc.finish()
|
||||
return 200, ""
|
||||
}
|
||||
var col collector
|
||||
for ev := range events {
|
||||
if ev.Kind == KError {
|
||||
return fail(ev)
|
||||
}
|
||||
col.add(ev)
|
||||
}
|
||||
res := col.finish()
|
||||
usage.add(res.Usage)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(200)
|
||||
w.Write(renderUsage(from, res, req, usage))
|
||||
return 200, ""
|
||||
}
|
||||
|
||||
// retryAfterOn sends, with an error about to be written to w, how long
|
||||
// the vendor said to wait before asking again, when it said: the agent
|
||||
// reads it, and so does the gateway's busy handling (noteBusy).
|
||||
func retryAfterOn(w http.ResponseWriter, wait time.Duration) {
|
||||
if wait > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(math.Ceil(wait.Seconds()))))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package gateway
|
||||
|
||||
import "net/http"
|
||||
|
||||
// roundTripFunc is an http.RoundTripper made of a function, for a test
|
||||
// that sends the gateway's client somewhere of its own.
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
@@ -166,7 +166,7 @@ func TestFastPickKeepsTheClientsUltrafast(t *testing.T) {
|
||||
to, _ := url.Parse(provider.CodexBase)
|
||||
provider.CodexBase = "https://chatgpt.com/backend-api/codex"
|
||||
s := New()
|
||||
s.client = &http.Client{Transport: qoderRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
r.URL.Scheme, r.URL.Host = to.Scheme, to.Host
|
||||
return http.DefaultTransport.RoundTrip(r)
|
||||
})}
|
||||
@@ -205,7 +205,7 @@ func TestCodexFastForOtherAgents(t *testing.T) {
|
||||
to, _ := url.Parse(provider.CodexBase)
|
||||
provider.CodexBase = "https://chatgpt.com/backend-api/codex"
|
||||
s := New()
|
||||
s.client = &http.Client{Transport: qoderRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
r.URL.Scheme, r.URL.Host = to.Scheme, to.Host
|
||||
return http.DefaultTransport.RoundTrip(r)
|
||||
})}
|
||||
@@ -252,7 +252,7 @@ func TestTierRecordedPerTry(t *testing.T) {
|
||||
to, _ := url.Parse(provider.CodexBase)
|
||||
provider.CodexBase = "https://chatgpt.com/backend-api/codex"
|
||||
s := New()
|
||||
s.client = &http.Client{Transport: qoderRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
r.URL.Scheme, r.URL.Host = to.Scheme, to.Host
|
||||
return http.DefaultTransport.RoundTrip(r)
|
||||
})}
|
||||
@@ -327,7 +327,7 @@ func TestUltraPickSentUltrafast(t *testing.T) {
|
||||
to, _ := url.Parse(provider.CodexBase)
|
||||
provider.CodexBase = "https://chatgpt.com/backend-api/codex"
|
||||
s := New()
|
||||
s.client = &http.Client{Transport: qoderRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
r.URL.Scheme, r.URL.Host = to.Scheme, to.Host
|
||||
return http.DefaultTransport.RoundTrip(r)
|
||||
})}
|
||||
|
||||
@@ -875,11 +875,6 @@ func Accounts() []Provider {
|
||||
if p, ok := commandCodeAccount(); ok {
|
||||
out = append(out, p)
|
||||
}
|
||||
for _, agent := range qoderAgents {
|
||||
if p, ok := qoderAccountOf(agent); ok {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
if p, ok := factoryAccount(); ok {
|
||||
out = append(out, p)
|
||||
}
|
||||
|
||||
@@ -274,8 +274,6 @@ func builtinLogins(agent string) (logins []Login, ok bool) {
|
||||
logins = wbLoginList(wbSiteOf(agent))
|
||||
case CommandCodePlanID:
|
||||
logins = cmdLoginList()
|
||||
case "qoder", QoderCNID:
|
||||
logins = loginsOf(qoderLoginsOf(agent))
|
||||
case "devin":
|
||||
logins = devinLoginList()
|
||||
case "factory":
|
||||
@@ -307,9 +305,6 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota {
|
||||
if strings.HasPrefix(l.Agent, "plugin:") {
|
||||
return pluginLoginQuota(ctx, l)
|
||||
}
|
||||
if l.Agent == "qoder" || l.Agent == QoderCNID {
|
||||
return qoderLoginQuota(ctx, l)
|
||||
}
|
||||
if l.Agent == "devin" {
|
||||
return devinLoginQuota(ctx, l)
|
||||
}
|
||||
|
||||
@@ -817,8 +817,6 @@ func Logins(agent string) []Login {
|
||||
return wbLoginList(wbSiteOf(agent))
|
||||
case CommandCodePlanID:
|
||||
return cmdLoginList()
|
||||
case "qoder", QoderCNID:
|
||||
return loginsOf(qoderLoginsOf(agent))
|
||||
case "factory":
|
||||
return factoryLoginList()
|
||||
case MiMoID:
|
||||
@@ -847,8 +845,7 @@ func Logins(agent string) []Login {
|
||||
{"grok", grokLoginList}, {"copilot", copilotLoginList}, {"zcode", zcodeLoginList},
|
||||
{"devin", devinLoginList}, {"workbuddy", func() []Login { return wbLoginList(wbCN) }},
|
||||
{WorkBuddyAIID, func() []Login { return wbLoginList(wbAI) }}, {CommandCodePlanID, cmdLoginList},
|
||||
{"qoder", func() []Login { return loginsOf(qoderLogins()) }},
|
||||
{QoderCNID, func() []Login { return loginsOf(qoderLoginsOf(QoderCNID)) }}, {"factory", factoryLoginList},
|
||||
{"factory", factoryLoginList},
|
||||
{MiMoID, mimoLoginList}, {ChatGPTAPIID, siwcLoginList}, {"gemini", func() []Login { return googleLoginList("gemini") }},
|
||||
{"antigravity", func() []Login { return googleLoginList("antigravity") }},
|
||||
} {
|
||||
@@ -1055,8 +1052,6 @@ func switchLogin(agent, user string) error {
|
||||
return switchWorkBuddyLogin(wbSiteOf(agent), user)
|
||||
case CommandCodePlanID:
|
||||
return switchCommandCodeLogin(user)
|
||||
case "qoder", QoderCNID:
|
||||
return switchSideLogin(agent, user, qoderLoginsOf(agent))
|
||||
case "factory":
|
||||
return switchFactoryLogin(user)
|
||||
case MiMoID:
|
||||
@@ -1245,8 +1240,6 @@ func ForgetLogin(agent, user string) error {
|
||||
return forgetWorkBuddyLogin(wbSiteOf(agent), user)
|
||||
case CommandCodePlanID:
|
||||
return forgetCommandCodeLogin(user)
|
||||
case "qoder", QoderCNID:
|
||||
return forgetQoderLogin(agent, user)
|
||||
case "factory":
|
||||
return forgetFactoryLogin(user)
|
||||
case MiMoID:
|
||||
|
||||
@@ -47,8 +47,6 @@ func SetLoginOn(agent, user string, on bool) error {
|
||||
return setWorkBuddyLoginOn(wbSiteOf(agent), user, on)
|
||||
case CommandCodePlanID:
|
||||
return setCommandCodeLoginOn(user, on)
|
||||
case "qoder", QoderCNID:
|
||||
return setSideLoginOn(agent, user, on, qoderLoginsOf(agent))
|
||||
case "factory":
|
||||
return setFactoryLoginOn(user, on)
|
||||
case MiMoID:
|
||||
@@ -166,9 +164,6 @@ func (p Provider) alsoOn() []Provider {
|
||||
if p.Account != nil && p.Account.Agent == CommandCodePlanID {
|
||||
return commandCodeAlsoOn()
|
||||
}
|
||||
if p.Account != nil && (p.Account.Agent == "qoder" || p.Account.Agent == QoderCNID) {
|
||||
return qoderAlsoOn(p.Account.Agent)
|
||||
}
|
||||
if p.Account != nil && p.Account.Agent == "factory" {
|
||||
return factoryAlsoOn()
|
||||
}
|
||||
|
||||
@@ -264,9 +264,11 @@ func BuiltinRetired(id string) bool { return Movable(id) && retiredBuiltins[id]
|
||||
|
||||
// retiredBuiltins are the built-in subscriptions whose code is gone.
|
||||
var retiredBuiltins = map[string]bool{
|
||||
"zed": true,
|
||||
"kiro": true,
|
||||
"cursor": true,
|
||||
"zed": true,
|
||||
"kiro": true,
|
||||
"cursor": true,
|
||||
"qoder": true,
|
||||
QoderCNID: true,
|
||||
}
|
||||
|
||||
// PluginServes is whether the built-in id's subscription is its plugin's to
|
||||
|
||||
@@ -2,6 +2,8 @@ package provider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -97,6 +99,22 @@ func TestQoderMover(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// A Qoder account still in the single-account qoder.json of before
|
||||
// logins.json moves too: the move reads it into logins.json first, with a
|
||||
// machine id of its own, and the old file is gone.
|
||||
func TestQoderLegacyFileMoves(t *testing.T) {
|
||||
claudeHome(t)
|
||||
legacy := filepath.Join(filepath.Dir(Path()), "qoder.json")
|
||||
writeFile(t, legacy, qoder.Credential{UID: "u1", Email: "one@q.com", Token: "t1", RefreshToken: "r1"})
|
||||
accts, err := movers["qoder"].out()
|
||||
if err != nil || len(accts) != 1 || accts[0].User != "one@q.com" || !accts[0].First || accts[0].Auth["machineId"] == "" {
|
||||
t.Fatalf("the legacy account didn't move: %+v %v", accts, err)
|
||||
}
|
||||
if _, err := os.Stat(legacy); !os.IsNotExist(err) {
|
||||
t.Fatalf("qoder.json is still there: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A Qoder CN account keeps its site, and one that chats on its device
|
||||
// token keeps doing so.
|
||||
func TestQoderCNMover(t *testing.T) {
|
||||
|
||||
@@ -27,13 +27,13 @@ func qoderMover(id string) *mover {
|
||||
min: "0.2.18", // a 10605 trimmed or wrapped is the model's queue busy, not a lapsed sign-in (plugins #185); 0.2.17: the daily check-in through auth.checkin (plugins #179); 0.2.16: a tool call written into the text that can't be read, or that the stream ends inside, ends the turn as an error (a 502, or the stream's error frame with no finish), never as the answer (plugins #132); 0.2.14: Qoder's 403 code 10605 (the model's queue busy) is a 503 with Retry-After, not a lapsed sign-in; quota and credit codes (110, 112–119, 122) are 429, refusals of the request (406, 416, 430, 80411, 80412, 100400, 100401, 100403) are 400, and only 105 or no code is "sign in again" (plugins #98); 0.2.13: models are listed from Qoder's app scene first, so its new default Fast 0.8× shows (plugins #97); 0.2.12: a chat Qoder refuses keeps Qoder's own reason in the error; 0.2.11: a Qoder CN enterprise VPC account keeps its model list and renewal mark apart from a public account with the same uid (plugins#40); international check-in finds the device identity runtime Qoder CLI caches on macOS and Linux and the Linux desktop installs in /opt/Qoder (ARNO on Discord); sends Qoder's native device identity, without which the daily 100 credits aren't listed (#1268); Qoder CN enterprise VPC (0.2.8); the daily credits claimed through the account's fetch (ARNO on Discord); Qoder CN as "qoder-cn", its device-token chat as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; token usage read; each model's context the largest window Qoder offers it (#722); the window a request is sent holds the reply's max_tokens (#700)
|
||||
agents: []string{id},
|
||||
out: func() ([]Moving, error) {
|
||||
// no refresh of the built-in's runs while the pairs are read
|
||||
// nothing else writes the pairs while they are read
|
||||
ls := qoderLoginsOf(id)
|
||||
qoderMu.Lock()
|
||||
defer qoderMu.Unlock()
|
||||
var out []Moving
|
||||
for _, l := range ls {
|
||||
c, ok, _ := qoderCurrent(l.saved)
|
||||
c, ok := qoderSaved(l.saved)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1268,10 +1268,5 @@ func (p Provider) asksOwnBackend() bool {
|
||||
case "claude", "devin", CommandCodePlanID:
|
||||
return true
|
||||
}
|
||||
// Qoder is one backend however many sites it is signed in to, and the
|
||||
// gateway's dispatch covers the whole family rather than the site the
|
||||
// account was made on, so the family is asked of rather than one id of
|
||||
// it: a name refused for the one subscription has to be refused for
|
||||
// the other too, which is as much magpie's own there.
|
||||
return slices.Contains(qoderAgents, p.Account.Agent)
|
||||
return false
|
||||
}
|
||||
|
||||
+9
-449
@@ -1,35 +1,29 @@
|
||||
package provider
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
// are retired built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, moved or not. Their built-in
|
||||
// sign-in, models, requests and usage are gone; what is left here reads
|
||||
// the built-in accounts in logins.json for the move (migrate_qoder.go).
|
||||
// A fix belongs in the plugin (github.com/magpie-community/plugins,
|
||||
// packages/qoder), with the movers' min raised in
|
||||
// internal/provider/migrate_qoder.go.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/qoder"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// qoderMu serializes checking, rotating and saving tokens, including sign-in
|
||||
// and removal. Credentials are decoded into private values on every read.
|
||||
// qoderMu keeps a Qoder account's saved pairs still while the move reads
|
||||
// them. Credentials are decoded into private values on every read.
|
||||
var qoderMu sync.Mutex
|
||||
var qoderClient = &http.Client{Timeout: 20 * time.Second}
|
||||
|
||||
// Qoder's two sites are two subscriptions: "qoder" (qoder.com) and "qoder-cn"
|
||||
// (qoder.cn), whose accounts exist only there. Each keeps its own accounts in
|
||||
@@ -39,109 +33,6 @@ var qoderAgents = []string{qoder.ProviderKey, QoderCNID}
|
||||
// QoderCNID is the Qoder CN subscription's id, the same as Qoder CN's agent.
|
||||
const QoderCNID = qoder.CNProviderKey
|
||||
|
||||
func qoderSiteOf(agent string) *qoder.Site { return qoder.SiteOf(agent) }
|
||||
|
||||
// A rotated pair whose disk write failed must never spend its predecessor
|
||||
// again. Retry persisting this private blob on the next access.
|
||||
var qoderPending = map[string]struct{ before, after json.RawMessage }{}
|
||||
|
||||
func qoderPendingKey(agent, user string) string {
|
||||
if agent != qoder.ProviderKey {
|
||||
user = agent + ":" + user
|
||||
}
|
||||
return loginsPath() + ":" + strings.ToLower(user)
|
||||
}
|
||||
|
||||
func qoderCurrent(l savedLogin) (qoder.Credential, bool, bool) {
|
||||
key := qoderPendingKey(l.Agent, l.User)
|
||||
if p, ok := qoderPending[key]; ok {
|
||||
if string(p.before) == string(l.Auth) {
|
||||
c, valid := qoderSaved(savedLogin{Agent: l.Agent, Auth: p.after})
|
||||
return c, valid, true
|
||||
}
|
||||
delete(qoderPending, key)
|
||||
}
|
||||
c, ok := qoderSaved(l)
|
||||
return c, ok, false
|
||||
}
|
||||
|
||||
// qoderRefreshTimeout bounds a token refresh, which runs apart from the
|
||||
// request that needed it: once Qoder has rotated the pair, the reply must be
|
||||
// kept even if that request is gone.
|
||||
const qoderRefreshTimeout = 20 * time.Second
|
||||
|
||||
// qoderLookup reads one saved account. loginsMu is held only for the read, so
|
||||
// a Qoder refresh never stalls the other subscriptions; qoderMu, held by the
|
||||
// caller, keeps every Qoder auth write out while it is refreshed.
|
||||
func qoderLookup(agent, user string) (savedLogin, bool) {
|
||||
loginsMu.Lock()
|
||||
defer loginsMu.Unlock()
|
||||
for _, l := range readLogins() {
|
||||
if l.Agent == agent && strings.EqualFold(l.User, user) {
|
||||
return l, true
|
||||
}
|
||||
}
|
||||
return savedLogin{}, false
|
||||
}
|
||||
|
||||
// qoderPersist writes c back into the account l as logins.json is now. The
|
||||
// caller holds qoderMu, so l.Auth is still what is saved; the rest of the
|
||||
// file is re-read under loginsMu so changes made meanwhile are kept.
|
||||
func qoderPersist(l savedLogin, c qoder.Credential, renewed bool) error {
|
||||
auth, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key := qoderPendingKey(l.Agent, l.User)
|
||||
loginsMu.Lock()
|
||||
defer loginsMu.Unlock()
|
||||
ls := readLogins()
|
||||
err = fmt.Errorf("%s: couldn't read the saved sign-in of %s back", qoder.SiteOf(l.Agent).Name, l.User)
|
||||
for i := range ls {
|
||||
if ls[i].Agent != l.Agent || !strings.EqualFold(ls[i].User, l.User) {
|
||||
continue
|
||||
}
|
||||
ls[i].Auth = auth
|
||||
if renewed {
|
||||
ls[i].Renewed, ls[i].Lapsed = time.Now().UTC(), ""
|
||||
}
|
||||
err = writeLogins(ls)
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
qoderPending[key] = struct{ before, after json.RawMessage }{l.Auth, auth}
|
||||
return err
|
||||
}
|
||||
delete(qoderPending, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ErrQoderSignIn is under every error that says the Qoder sign-in itself is
|
||||
// gone — not signed in, unreadable, or its refresh refused — as against a
|
||||
// refresh that timed out or never reached Qoder, which may pass.
|
||||
var ErrQoderSignIn = errors.New("Qoder sign-in")
|
||||
|
||||
// qoderRefreshFailed marks the account lapsed when Qoder refused its job
|
||||
// refresh token: that sign-in is gone and has to be made again. A refresh
|
||||
// that never got an answer marks nothing.
|
||||
func qoderRefreshFailed(agent, user string, err error) error {
|
||||
var job *qoder.JobTokenRefreshHTTPError
|
||||
if !errors.As(err, &job) || job.StatusCode != http.StatusUnauthorized && job.StatusCode != http.StatusForbidden {
|
||||
return err
|
||||
}
|
||||
msg := user + "'s " + qoder.SiteOf(agent).Name + " sign-in has expired — sign in again"
|
||||
loginsMu.Lock()
|
||||
defer loginsMu.Unlock()
|
||||
ls := readLogins()
|
||||
for i := range ls {
|
||||
if ls[i].Agent == agent && strings.EqualFold(ls[i].User, user) {
|
||||
ls[i].Lapsed = msg
|
||||
}
|
||||
}
|
||||
_ = writeLogins(ls)
|
||||
return fmt.Errorf("%s (%w)", msg, errors.Join(ErrQoderSignIn, err))
|
||||
}
|
||||
|
||||
func qoderWho(c qoder.Credential) string { return firstNonEmpty(c.Email, c.UID) }
|
||||
|
||||
func qoderSaved(l savedLogin) (qoder.Credential, bool) {
|
||||
@@ -210,9 +101,6 @@ func migrateQoder() error {
|
||||
return os.Remove(path)
|
||||
}
|
||||
|
||||
// qoderLogins are the global site's accounts.
|
||||
func qoderLogins() []sideLogin { return qoderLoginsOf(qoder.ProviderKey) }
|
||||
|
||||
func qoderLoginsOf(agent string) []sideLogin {
|
||||
if agent == qoder.ProviderKey && migrateQoder() != nil {
|
||||
return nil
|
||||
@@ -223,331 +111,3 @@ func qoderLoginsOf(agent string) []sideLogin {
|
||||
}
|
||||
return ls
|
||||
}
|
||||
|
||||
func QoderSignedIn() bool { return len(qoderLogins()) > 0 }
|
||||
|
||||
// QoderCredential returns an independent snapshot for the selected account
|
||||
// on the global site.
|
||||
func QoderCredential(ctx context.Context, user string) (*qoder.Credential, error) {
|
||||
return QoderCredentialOf(ctx, qoder.ProviderKey, user)
|
||||
}
|
||||
|
||||
// QoderCredentialOf is QoderCredential for the site agent names ("qoder" or
|
||||
// "qoder-cn").
|
||||
func QoderCredentialOf(ctx context.Context, agent, user string) (*qoder.Credential, error) {
|
||||
name := qoder.SiteOf(agent).Name
|
||||
if agent == qoder.ProviderKey {
|
||||
if err := migrateQoder(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if user == "" {
|
||||
ls := qoderLoginsOf(agent)
|
||||
if len(ls) == 0 {
|
||||
return nil, fmt.Errorf("%s: not signed in (%w)", name, ErrQoderSignIn)
|
||||
}
|
||||
user = ls[0].User
|
||||
}
|
||||
qoderMu.Lock()
|
||||
defer qoderMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l, found := qoderLookup(agent, user)
|
||||
if !found {
|
||||
return nil, fmt.Errorf("no %s account %q (%w)", name, user, ErrQoderSignIn)
|
||||
}
|
||||
c, ok, changed := qoderCurrent(l)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s: unreadable sign-in (%w)", name, ErrQoderSignIn)
|
||||
}
|
||||
if c.MachineID == "" {
|
||||
c.MachineID = qoder.NewMachineID()
|
||||
changed = true
|
||||
}
|
||||
renewed := false
|
||||
if !c.Valid() {
|
||||
rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), qoderRefreshTimeout)
|
||||
fresh, err := c.Refresh(rctx, qoderClient)
|
||||
cancel()
|
||||
if err != nil {
|
||||
if c.RefreshToken == "" { // nothing to refresh with: sign in again
|
||||
err = errors.Join(ErrQoderSignIn, err)
|
||||
}
|
||||
return nil, qoderRefreshFailed(agent, l.User, err)
|
||||
}
|
||||
c, changed, renewed = fresh, true, true
|
||||
}
|
||||
if changed {
|
||||
if err := qoderPersist(l, c, renewed); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func qoderUser(c *qoder.Credential) *qoder.User {
|
||||
return &qoder.User{UID: c.UID, Token: c.Token, Name: c.Name, Email: c.Email, MachineID: c.MachineID}
|
||||
}
|
||||
|
||||
// qoderSave keeps c under its site's accounts.
|
||||
func qoderSave(c qoder.Credential) (err error) {
|
||||
site := c.OnSite()
|
||||
agent := site.ID
|
||||
if c.UID == "" || c.Token == "" {
|
||||
return fmt.Errorf("%s: incomplete sign-in", site.Name)
|
||||
}
|
||||
if agent == qoder.ProviderKey {
|
||||
c.Site = "" // a global sign-in is saved as it always was
|
||||
if err := migrateQoder(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// its kept usage reading was read under the old sign-in (as
|
||||
// addSideLogin drops it), once the locks are let go
|
||||
defer func() {
|
||||
if err == nil {
|
||||
StaleAllowance(agent, qoderWho(c))
|
||||
}
|
||||
}()
|
||||
qoderMu.Lock()
|
||||
defer qoderMu.Unlock()
|
||||
if c.MachineID == "" {
|
||||
c.MachineID = qoder.NewMachineID()
|
||||
}
|
||||
auth, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
loginsMu.Lock()
|
||||
defer loginsMu.Unlock()
|
||||
ls := readLogins()
|
||||
for i := range ls {
|
||||
if ls[i].Agent != agent {
|
||||
continue
|
||||
}
|
||||
old, ok := qoderSaved(ls[i])
|
||||
if ok && old.UID == c.UID {
|
||||
oldKey := qoderPendingKey(agent, ls[i].User)
|
||||
ls[i].Auth, ls[i].User, ls[i].Seen, ls[i].Lapsed = auth, qoderWho(c), time.Now().UTC(), ""
|
||||
if err := writeLogins(ls); err != nil {
|
||||
return err
|
||||
}
|
||||
delete(qoderPending, oldKey)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return writeLogins(append(ls, savedLogin{Agent: agent, User: qoderWho(c), Auth: auth, On: true, Seen: time.Now().UTC()}))
|
||||
}
|
||||
|
||||
func qoderFetchModels(ctx context.Context, agent, user string) ([]catalog.Model, error) {
|
||||
c, err := QoderCredentialOf(ctx, agent, user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
raw, err := qoder.FetchModels(ctx, qoderClient, c.OnSite().API, qoderUser(c))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ms, err := qoder.ParseModels(raw, agent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qoderMu.Lock()
|
||||
err = editSideLogin(agent, qoderWho(*c), func(ls []savedLogin, i int) ([]savedLogin, error) {
|
||||
latest, ok := qoderSaved(ls[i])
|
||||
if !ok || latest.UID != c.UID {
|
||||
return nil, fmt.Errorf("%s: account changed while fetching models", qoder.SiteOf(agent).Name)
|
||||
}
|
||||
latest.Models = raw
|
||||
ls[i].Auth, _ = json.Marshal(latest)
|
||||
return ls, nil
|
||||
})
|
||||
qoderMu.Unlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ms, catalog.SaveLive(agent, "", ms)
|
||||
}
|
||||
|
||||
// QoderModel accepts only an enabled model in this account's own model list.
|
||||
func QoderModel(ctx context.Context, user, key string) (qoder.ModelInfo, error) {
|
||||
return QoderModelOf(ctx, qoder.ProviderKey, user, key)
|
||||
}
|
||||
|
||||
// QoderModelOf is QoderModel for the site agent names.
|
||||
func QoderModelOf(ctx context.Context, agent, user, key string) (qoder.ModelInfo, error) {
|
||||
c, err := QoderCredentialOf(ctx, agent, user)
|
||||
if err != nil {
|
||||
return qoder.ModelInfo{}, err
|
||||
}
|
||||
if len(c.Models) == 0 {
|
||||
if _, err := qoderFetchModels(ctx, agent, qoderWho(*c)); err != nil {
|
||||
return qoder.ModelInfo{}, err
|
||||
}
|
||||
c, err = QoderCredentialOf(ctx, agent, qoderWho(*c))
|
||||
if err != nil {
|
||||
return qoder.ModelInfo{}, err
|
||||
}
|
||||
}
|
||||
ms, err := qoder.ModelConfigs(c.Models)
|
||||
if err != nil {
|
||||
return qoder.ModelInfo{}, err
|
||||
}
|
||||
for _, m := range ms {
|
||||
if m.Key == key {
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
return qoder.ModelInfo{}, fmt.Errorf("%s: unknown or disabled model %q", qoder.SiteOf(agent).Name, key)
|
||||
}
|
||||
|
||||
func qoderProvider(agent string, l sideLogin) Provider {
|
||||
user := l.User
|
||||
site := qoder.SiteOf(agent)
|
||||
a := &Account{Agent: agent, User: user, Plan: l.Plan, Stream: true}
|
||||
a.models = func() []catalog.Model {
|
||||
loginsMu.Lock()
|
||||
defer loginsMu.Unlock()
|
||||
for _, l := range readLogins() {
|
||||
if l.Agent == agent && strings.EqualFold(l.User, user) {
|
||||
c, _ := qoderSaved(l)
|
||||
ms, _ := qoder.ParseModels(c.Models, agent)
|
||||
return ms
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
a.fetch = func(ctx context.Context) ([]catalog.Model, error) { return qoderFetchModels(ctx, agent, user) }
|
||||
return Provider{ID: agent, Name: site.Name, Icon: "qoder", Website: site.Web, Account: a}
|
||||
}
|
||||
|
||||
func qoderAccount() (Provider, bool) { return qoderAccountOf(qoder.ProviderKey) }
|
||||
|
||||
func qoderAccountOf(agent string) (Provider, bool) {
|
||||
ls := qoderLoginsOf(agent)
|
||||
if len(ls) == 0 {
|
||||
return Provider{}, false
|
||||
}
|
||||
return qoderProvider(agent, ls[0]), true
|
||||
}
|
||||
|
||||
func qoderAlsoOn(agent string) []Provider {
|
||||
var out []Provider
|
||||
for _, l := range qoderLoginsOf(agent) {
|
||||
if !l.Active && l.On {
|
||||
out = append(out, qoderProvider(agent, l))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func forgetQoderLogin(agent, user string) error {
|
||||
if agent == qoder.ProviderKey {
|
||||
if err := migrateQoder(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
qoderMu.Lock()
|
||||
defer qoderMu.Unlock()
|
||||
err := editSideLogin(agent, user, func(ls []savedLogin, i int) ([]savedLogin, error) {
|
||||
return append(ls[:i], ls[i+1:]...), nil
|
||||
})
|
||||
if err == nil {
|
||||
delete(qoderPending, qoderPendingKey(agent, user))
|
||||
forgetAccountCaches()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type qoderFlow struct {
|
||||
verifier, nonce string
|
||||
client *qoder.DeviceFlow
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
const qoderSignInTimeout = 15 * time.Minute
|
||||
|
||||
// QoderAuthURL starts a sign-in on the global site.
|
||||
func QoderAuthURL() (url string, flow *qoderFlow, err error) { return qoderAuthURL(qoder.Global) }
|
||||
|
||||
func qoderAuthURL(site *qoder.Site) (url string, flow *qoderFlow, err error) {
|
||||
f := qoder.NewDeviceFlow(qoderClient, site)
|
||||
url, verifier, nonce, err := f.Authorization()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return url, &qoderFlow{verifier: verifier, nonce: nonce, client: f, deadline: time.Now().Add(qoderSignInTimeout)}, nil
|
||||
}
|
||||
|
||||
func QoderCompleteSignIn(ctx context.Context, fl *qoderFlow) (user string, err error) {
|
||||
ctx, cancel := context.WithDeadline(ctx, fl.deadline)
|
||||
defer cancel()
|
||||
site := fl.client.Site()
|
||||
dt, err := fl.client.PollDeviceToken(ctx, fl.nonce, fl.verifier, 2*time.Second)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cred := qoder.Credential{UID: dt.UserID, DeviceToken: dt.Token, DeviceRefresh: dt.RefreshToken,
|
||||
MachineID: fl.client.MachineID()}
|
||||
if site != qoder.Global {
|
||||
cred.Site = site.ID
|
||||
}
|
||||
jt, err := fl.client.JobToken(ctx, dt.Token)
|
||||
var refused *qoder.JobTokenHTTPError
|
||||
switch {
|
||||
case err == nil:
|
||||
life := jt.Expiry()
|
||||
if life <= 0 {
|
||||
life = 24 * time.Hour
|
||||
}
|
||||
cred.Token, cred.RefreshToken, cred.ExpiresAt = jt.Token, jt.RefreshToken, time.Now().Add(life).UnixMilli()
|
||||
case site == qoder.CN && errors.As(err, &refused) && refused.StatusCode/100 == 4:
|
||||
// Qoder CN's CLI never makes a job token: its device token is what
|
||||
// signs the model calls. If qoder.cn won't make one for the CLI's
|
||||
// client id, the account works the CLI's way.
|
||||
cred.Token, cred.RefreshToken, cred.DeviceChat = dt.Token, dt.RefreshToken, true
|
||||
cred.ExpiresAt = qoder.DeviceExpiry(*dt).UnixMilli()
|
||||
default:
|
||||
return "", err
|
||||
}
|
||||
if ui, err := qoder.FetchUserInfo(ctx, qoderClient, site, dt.Token); err == nil && ui != nil {
|
||||
cred.Email, cred.Name = ui.Email, ui.Name
|
||||
}
|
||||
if cred.Name == "" {
|
||||
cred.Name = dt.UserName
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := keepLogin(ctx, func() error { return qoderSave(cred) }); err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, _ = qoderFetchModels(ctx, site.ID, qoderWho(cred))
|
||||
forgetAccountCaches()
|
||||
return qoderWho(cred), nil
|
||||
}
|
||||
|
||||
func startQoderSignIn(s *signInFlow, site *qoder.Site) error {
|
||||
authURL, fl, err := qoderAuthURL(site)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s sign-in: %w", site.Name, err)
|
||||
}
|
||||
ctx, cancel := context.WithDeadline(s.via(context.Background()), fl.deadline)
|
||||
s.mu.Lock()
|
||||
s.st.URL, s.stop = authURL, cancel
|
||||
s.mu.Unlock()
|
||||
go func() {
|
||||
defer cancel()
|
||||
user, err := QoderCompleteSignIn(ctx, fl)
|
||||
if err != nil {
|
||||
s.finish(SignInState{State: "failed", Error: site.Name + ": " + err.Error()})
|
||||
return
|
||||
}
|
||||
ls := qoderLoginsOf(site.ID)
|
||||
s.finish(SignInState{State: "done", User: user, Using: strings.EqualFold(activeOf(ls), user)})
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/qoder"
|
||||
)
|
||||
|
||||
// qoderSiteClient is qoderTestClient keeping each request's real host, so a
|
||||
// test can say which of Qoder's sites a call went to.
|
||||
func qoderSiteClient(t *testing.T, h func(host string, w http.ResponseWriter, r *http.Request)) {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h(r.Header.Get("X-Test-Host"), w, r)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
u, _ := url.Parse(srv.URL)
|
||||
old := qoderClient
|
||||
qoderClient = &http.Client{Transport: qoderTransport(func(r *http.Request) (*http.Response, error) {
|
||||
r.Header.Set("X-Test-Host", r.URL.Host)
|
||||
r.URL.Scheme, r.URL.Host = u.Scheme, u.Host
|
||||
return srv.Client().Transport.RoundTrip(r)
|
||||
})}
|
||||
t.Cleanup(func() { qoderClient = old })
|
||||
}
|
||||
|
||||
// qoderCNServer answers Qoder's endpoints as one site would, failing the test
|
||||
// for a call to any other host; jobToken says whether the site makes job
|
||||
// tokens or refuses them as Qoder CN might for its CLI's client id.
|
||||
type qoderCNServer struct {
|
||||
t *testing.T
|
||||
host string // the account host; the model host is api
|
||||
api string
|
||||
jobToken bool
|
||||
mu sync.Mutex
|
||||
seen []string
|
||||
}
|
||||
|
||||
func (s *qoderCNServer) serve(host string, w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
s.mu.Lock()
|
||||
s.seen = append(s.seen, host+path)
|
||||
s.mu.Unlock()
|
||||
want := s.host
|
||||
if strings.HasPrefix(path, "/algo/") {
|
||||
want = s.api
|
||||
}
|
||||
if host != want {
|
||||
s.t.Errorf("%s went to %s, want %s", path, host, want)
|
||||
}
|
||||
switch path {
|
||||
case qoder.DeviceTokenPollPath:
|
||||
_, _ = w.Write([]byte(`{"token":"dt-cn","refresh_token":"drt-cn","user_id":"u-cn","user_name":"CN","expires_in":7200}`))
|
||||
case qoder.JobTokenPath:
|
||||
var b map[string]string
|
||||
_ = json.NewDecoder(r.Body).Decode(&b)
|
||||
if s.host == "openapi.qoder.com.cn" && b["clientId"] != qoder.CNClientID {
|
||||
s.t.Errorf("job token clientId %q", b["clientId"])
|
||||
}
|
||||
if !s.jobToken {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(`{"message":"client not allowed"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"token":"jt-cn","refresh_token":"rt-cn","expires_in":3600000}`))
|
||||
case qoder.JobTokenRefreshPath:
|
||||
_, _ = w.Write([]byte(`{"token":"jt-cn2","refresh_token":"rt-cn2","expires_in":3600000}`))
|
||||
case qoder.DeviceTokenRefreshPath:
|
||||
_, _ = w.Write([]byte(`{"token":"dt-cn2","refresh_token":"drt-cn2","expires_in":7200}`))
|
||||
case qoder.UserInfoPath:
|
||||
_, _ = w.Write([]byte(`{"id":"u-cn","email":"cn@x","name":"CN"}`))
|
||||
case qoder.AccountUsagePath:
|
||||
_, _ = w.Write([]byte(`{"displayMode":"qoder","qoderUsage":{"userType":"pro","userQuota":{"total":100,"used":25}}}`))
|
||||
case strings.Split(qoder.ListModelsPath, "?")[0]:
|
||||
_, _ = w.Write(qoderTestCredential("cn").Models)
|
||||
default:
|
||||
s.t.Errorf("unexpected request %s%s", host, path)
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *qoderCNServer) went(hostPath string) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, x := range s.seen {
|
||||
if x == hostPath {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// TestQoderCNSignIn signs in to Qoder CN end to end against stand-ins for its
|
||||
// hosts: the page on qoder.cn with Qoder CN's CLI client id, the poll, job
|
||||
// token and user info on openapi.qoder.com.cn, the models on
|
||||
// gateway.qoder.com.cn; then usage and a refresh stay on those hosts, and the
|
||||
// account is Qoder CN's, not the global Qoder's.
|
||||
func TestQoderCNSignIn(t *testing.T) {
|
||||
signIn(t)
|
||||
srv := &qoderCNServer{t: t, host: "openapi.qoder.com.cn", api: "gateway.qoder.com.cn", jobToken: true}
|
||||
qoderSiteClient(t, srv.serve)
|
||||
authURL, flow, err := qoderAuthURL(qoderSiteOf(QoderCNID))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, _ := url.Parse(authURL)
|
||||
if u.Scheme+"://"+u.Host != "https://qoder.cn" || u.Path != qoder.DeviceSelectAccountsPath {
|
||||
t.Fatalf("auth page %s", authURL)
|
||||
}
|
||||
q := u.Query()
|
||||
if q.Get("client_id") != qoder.CNClientID || q.Has("redirect_uri") || q.Get("challenge_method") != "S256" || q.Get("nonce") == "" || q.Get("machine_id") == "" {
|
||||
t.Fatalf("auth query %v", q)
|
||||
}
|
||||
who, err := QoderCompleteSignIn(context.Background(), flow)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if who != "cn@x" || len(Logins(QoderCNID)) != 1 || len(Logins("qoder")) != 0 {
|
||||
t.Fatalf("sign-in %s: cn %+v global %+v", who, Logins(QoderCNID), Logins("qoder"))
|
||||
}
|
||||
for _, p := range []string{"openapi.qoder.com.cn" + qoder.DeviceTokenPollPath, "openapi.qoder.com.cn" + qoder.JobTokenPath,
|
||||
"openapi.qoder.com.cn" + qoder.UserInfoPath, "gateway.qoder.com.cn/algo/api/v2/model/list"} {
|
||||
if !srv.went(p) {
|
||||
t.Errorf("no call to %s: %v", p, srv.seen)
|
||||
}
|
||||
}
|
||||
cred, err := QoderCredentialOf(context.Background(), QoderCNID, who)
|
||||
if err != nil || cred.Site != QoderCNID || cred.DeviceChat || cred.Token != "jt-cn" || cred.OnSite().ChatURL() != "https://gateway.qoder.com.cn"+qoder.ChatPath {
|
||||
t.Fatalf("saved %+v %v", cred, err)
|
||||
}
|
||||
if _, err := QoderCredential(context.Background(), who); err == nil {
|
||||
t.Fatal("a Qoder CN account answers as a global one")
|
||||
}
|
||||
p, ok := qoderAccountOf(QoderCNID)
|
||||
if !ok || p.ID != QoderCNID || p.Name != "Qoder CN" || p.Website != "https://qoder.cn" || len(p.Account.models()) == 0 || p.Account.models()[0].Provider != QoderCNID {
|
||||
t.Fatalf("provider %+v", p)
|
||||
}
|
||||
if _, ok := qoderAccount(); ok {
|
||||
t.Fatal("Qoder CN account listed as the global Qoder")
|
||||
}
|
||||
|
||||
quota := qoderLoginQuota(context.Background(), Login{Agent: QoderCNID, User: who})
|
||||
if quota.Error != "" || quota.Provider != QoderCNID || quota.Name != "Qoder CN" || len(quota.Windows) != 1 || !srv.went("openapi.qoder.com.cn"+qoder.AccountUsagePath) {
|
||||
t.Fatalf("usage %+v", quota)
|
||||
}
|
||||
|
||||
// an expiring job token is refreshed on Qoder CN's account host
|
||||
c := *cred
|
||||
c.ExpiresAt = time.Now().Add(time.Minute).UnixMilli()
|
||||
if err := qoderSave(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fresh, err := QoderCredentialOf(context.Background(), QoderCNID, who)
|
||||
if err != nil || fresh.Token != "jt-cn2" || fresh.RefreshToken != "rt-cn2" || !srv.went("openapi.qoder.com.cn"+qoder.JobTokenRefreshPath) {
|
||||
t.Fatalf("refresh %+v %v", fresh, err)
|
||||
}
|
||||
if err := forgetQoderLogin(QoderCNID, who); err != nil || len(Logins(QoderCNID)) != 0 {
|
||||
t.Fatalf("forget %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestQoderCNDeviceChat: when qoder.cn won't trade the device token for a job
|
||||
// token, the account works as Qoder CN's CLI does, the device token signing
|
||||
// the model calls, and is refreshed as a device token.
|
||||
func TestQoderCNDeviceChat(t *testing.T) {
|
||||
signIn(t)
|
||||
srv := &qoderCNServer{t: t, host: "openapi.qoder.com.cn", api: "gateway.qoder.com.cn"}
|
||||
qoderSiteClient(t, srv.serve)
|
||||
_, flow, err := qoderAuthURL(qoderSiteOf(QoderCNID))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
who, err := QoderCompleteSignIn(context.Background(), flow)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cred, err := QoderCredentialOf(context.Background(), QoderCNID, who)
|
||||
if err != nil || !cred.DeviceChat || cred.Token != "dt-cn" || cred.RefreshToken != "drt-cn" || len(cred.Models) == 0 {
|
||||
t.Fatalf("saved %+v %v", cred, err)
|
||||
}
|
||||
if left := time.Until(time.UnixMilli(cred.ExpiresAt)); left < time.Hour || left > 2*time.Hour {
|
||||
t.Fatalf("device token lifetime %v", left)
|
||||
}
|
||||
c := *cred
|
||||
c.ExpiresAt = time.Now().Add(time.Minute).UnixMilli()
|
||||
if err := qoderSave(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fresh, err := QoderCredentialOf(context.Background(), QoderCNID, who)
|
||||
if err != nil || fresh.Token != "dt-cn2" || fresh.DeviceToken != "dt-cn2" || fresh.RefreshToken != "drt-cn2" || fresh.DeviceRefresh != "drt-cn2" ||
|
||||
!srv.went("openapi.qoder.com.cn"+qoder.DeviceTokenRefreshPath) || srv.went("openapi.qoder.com.cn"+qoder.JobTokenRefreshPath) {
|
||||
t.Fatalf("refresh %+v %v %v", fresh, err, srv.seen)
|
||||
}
|
||||
}
|
||||
|
||||
// TestQoderGlobalUnchanged: the global site is what it was — qoder.com with
|
||||
// the desktop client id and redirect, openapi.qoder.sh and api3.qoder.sh, no
|
||||
// fallback when a job token is refused — and a credential saved before there
|
||||
// were two sites, with no site in it, is a global one.
|
||||
func TestQoderGlobalUnchanged(t *testing.T) {
|
||||
signIn(t)
|
||||
srv := &qoderCNServer{t: t, host: "openapi.qoder.sh", api: "api3.qoder.sh", jobToken: true}
|
||||
qoderSiteClient(t, srv.serve)
|
||||
authURL, flow, err := QoderAuthURL()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, _ := url.Parse(authURL)
|
||||
if u.Host != "qoder.com" || u.Query().Get("client_id") != qoder.ClientID || u.Query().Get("redirect_uri") != qoder.RedirectURI {
|
||||
t.Fatalf("global auth page %s", authURL)
|
||||
}
|
||||
who, err := QoderCompleteSignIn(context.Background(), flow)
|
||||
if err != nil || len(Logins("qoder")) != 1 || len(Logins(QoderCNID)) != 0 {
|
||||
t.Fatalf("global sign-in %s %v", who, err)
|
||||
}
|
||||
loginsMu.Lock()
|
||||
raw := readLogins()[0].Auth
|
||||
loginsMu.Unlock()
|
||||
if strings.Contains(string(raw), `"site"`) || strings.Contains(string(raw), `"device_chat"`) {
|
||||
t.Fatalf("global credential gained fields: %s", raw)
|
||||
}
|
||||
|
||||
legacy := qoderTestCredential("old")
|
||||
legacy.ExpiresAt = time.Now().Add(time.Minute).UnixMilli()
|
||||
if legacy.Site != "" || legacy.OnSite() != qoder.Global {
|
||||
t.Fatal("a credential without a site isn't global")
|
||||
}
|
||||
if err := qoderSave(legacy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fresh, err := QoderCredential(context.Background(), "old@x")
|
||||
if err != nil || fresh.Token != "jt-cn2" || !srv.went("openapi.qoder.sh"+qoder.JobTokenRefreshPath) || fresh.OnSite().ChatURL() != qoder.ChatURL() {
|
||||
t.Fatalf("legacy refresh %+v %v", fresh, err)
|
||||
}
|
||||
|
||||
srv.jobToken = false
|
||||
_, flow, _ = QoderAuthURL()
|
||||
if _, err := QoderCompleteSignIn(context.Background(), flow); err == nil {
|
||||
t.Fatal("a refused job token signed in to the global site")
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A saved account's listing, read back without fetching again, keeps
|
||||
// Qoder's free models marked free.
|
||||
func TestQoderSavedModelsFree(t *testing.T) {
|
||||
signIn(t)
|
||||
c := qoderTestCredential("free")
|
||||
c.Models = json.RawMessage(`{"chat":[{"key":"lite","enable":true,"price_factor":0},{"key":"pro","enable":true,"price_factor":1}]}`)
|
||||
if err := qoderSave(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, ok := qoderAccount()
|
||||
if !ok {
|
||||
t.Fatal("no Qoder account")
|
||||
}
|
||||
free := map[string]bool{}
|
||||
for _, m := range p.Account.models() {
|
||||
free[m.ID] = m.Free
|
||||
}
|
||||
if len(free) != 2 || !free["lite"] || free["pro"] {
|
||||
t.Fatalf("saved models free = %v", free)
|
||||
}
|
||||
}
|
||||
@@ -1,447 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/qoder"
|
||||
)
|
||||
|
||||
type qoderTransport func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f qoderTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
func qoderTestClient(t *testing.T, h http.Handler) *http.Client {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(h)
|
||||
t.Cleanup(srv.Close)
|
||||
u, _ := url.Parse(srv.URL)
|
||||
client := &http.Client{Transport: qoderTransport(func(r *http.Request) (*http.Response, error) {
|
||||
r.URL.Scheme, r.URL.Host = u.Scheme, u.Host
|
||||
return srv.Client().Transport.RoundTrip(r)
|
||||
})}
|
||||
old := qoderClient
|
||||
qoderClient = client
|
||||
t.Cleanup(func() { qoderClient = old })
|
||||
return client
|
||||
}
|
||||
|
||||
func qoderTestCredential(user string) qoder.Credential {
|
||||
return qoder.Credential{UID: user, Email: user + "@x", Token: "jt-" + user, RefreshToken: "rt-" + user,
|
||||
DeviceToken: "dt-" + user, MachineID: "machine-" + user, ExpiresAt: time.Now().Add(time.Hour).UnixMilli(),
|
||||
Models: json.RawMessage(`{"chat":[{"key":"other-model","enable":true,"display_name":"Other","source":"system","format":"openai","is_reasoning":false,"max_input_tokens":64000,"custom_field":17}]}`)}
|
||||
}
|
||||
|
||||
func TestQoderConcurrentRefresh(t *testing.T) {
|
||||
signIn(t)
|
||||
var hits atomic.Int32
|
||||
client := qoderTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != qoder.JobTokenRefreshPath {
|
||||
t.Errorf("path %q", r.URL.Path)
|
||||
}
|
||||
var b map[string]string
|
||||
_ = json.NewDecoder(r.Body).Decode(&b)
|
||||
if b["refresh_token"] != "rt-one" || hits.Add(1) != 1 {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"token": "jt-new", "refresh_token": "rt-new", "expires_in": 3600000})
|
||||
}))
|
||||
c := qoderTestCredential("one")
|
||||
c.ExpiresAt = time.Now().Add(time.Minute).UnixMilli()
|
||||
if err := qoderSave(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
results := make(chan *qoder.Credential, 8)
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
fresh, err := QoderCredential(context.Background(), "one@x")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
results <- fresh
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
if hits.Load() != 1 || len(results) != 8 {
|
||||
t.Fatalf("refresh hits %d results %d", hits.Load(), len(results))
|
||||
}
|
||||
for got := range results {
|
||||
if got.Token != "jt-new" || got.RefreshToken != "rt-new" || got.MachineID != c.MachineID {
|
||||
t.Fatalf("fresh %+v", got)
|
||||
}
|
||||
got.Token = "caller-mutated"
|
||||
got.Models[0] = 'x'
|
||||
}
|
||||
fresh, err := QoderCredential(context.Background(), "one@x")
|
||||
if err != nil || fresh.Token != "jt-new" || !json.Valid(fresh.Models) {
|
||||
t.Fatalf("shared mutable credential: %+v %v", fresh, err)
|
||||
}
|
||||
// Refresh is also a value operation when called directly.
|
||||
client.Transport = qoderTransport(func(*http.Request) (*http.Response, error) { return nil, errors.New("offline") })
|
||||
_, _ = c.Refresh(context.Background(), client)
|
||||
if c.Token != "jt-one" || c.RefreshToken != "rt-one" {
|
||||
t.Fatal("original credential changed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQoderRefreshSaveFailureKeepsRotatedPair(t *testing.T) {
|
||||
signIn(t)
|
||||
c := qoderTestCredential("one")
|
||||
c.ExpiresAt = time.Now().Add(time.Minute).UnixMilli()
|
||||
if err := qoderSave(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := loginsPath()
|
||||
var hits atomic.Int32
|
||||
qoderTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if hits.Add(1) != 1 {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
// Make the atomic replacement fail after the upstream rotates the pair.
|
||||
if err := os.Rename(path, path+".saved"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if err := os.Mkdir(path, 0o700); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"token":"jt-new","refresh_token":"rt-new","expires_in":3600000}`))
|
||||
}))
|
||||
if _, err := QoderCredential(context.Background(), "one@x"); err == nil {
|
||||
t.Fatal("failed write reported success")
|
||||
}
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Rename(path+".saved", path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fresh, err := QoderCredential(context.Background(), "one@x")
|
||||
if err != nil || fresh.Token != "jt-new" || fresh.RefreshToken != "rt-new" || hits.Load() != 1 {
|
||||
t.Fatalf("spent token reused: %+v %v hits %d", fresh, err, hits.Load())
|
||||
}
|
||||
if len(qoderPending) != 0 {
|
||||
t.Fatal("pending write was not cleared")
|
||||
}
|
||||
}
|
||||
|
||||
// An aborted request must not drop a pair Qoder has already rotated.
|
||||
func TestQoderRefreshOutlivesAbortedRequest(t *testing.T) {
|
||||
signIn(t)
|
||||
var current atomic.Value
|
||||
current.Store("rt-one")
|
||||
var hits atomic.Int32
|
||||
qoderTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var b map[string]string
|
||||
_ = json.NewDecoder(r.Body).Decode(&b)
|
||||
hits.Add(1)
|
||||
if b["refresh_token"] != current.Load().(string) {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
current.Store("rt-new")
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
_, _ = w.Write([]byte(`{"token":"jt-new","refresh_token":"rt-new","expires_in":3600000}`))
|
||||
}))
|
||||
c := qoderTestCredential("one")
|
||||
c.ExpiresAt = time.Now().Add(time.Minute).UnixMilli()
|
||||
if err := qoderSave(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
if fresh, err := QoderCredential(ctx, "one@x"); err != nil || fresh.RefreshToken != "rt-new" {
|
||||
t.Fatalf("aborted refresh: %+v %v", fresh, err)
|
||||
}
|
||||
fresh, err := QoderCredential(context.Background(), "one@x")
|
||||
if err != nil || fresh.Token != "jt-new" || hits.Load() != 1 {
|
||||
t.Fatalf("rotated pair lost: %+v %v hits %d", fresh, err, hits.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestQoderRefusedRefreshLapses(t *testing.T) {
|
||||
signIn(t)
|
||||
qoderTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(401) }))
|
||||
c := qoderTestCredential("one")
|
||||
c.ExpiresAt = time.Now().Add(time.Minute).UnixMilli()
|
||||
c.DeviceRefresh = "drt"
|
||||
if err := qoderSave(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lapsed := func() string {
|
||||
for _, l := range Logins("qoder") {
|
||||
return l.Lapsed
|
||||
}
|
||||
return ""
|
||||
}
|
||||
// the device token serves only usage: chat still works, so the
|
||||
// account isn't lapsed and usage says why it is missing
|
||||
if _, err := qoderRefreshDevice(context.Background(), "qoder", "one@x", c.DeviceToken); err == nil || lapsed() != "" ||
|
||||
!strings.Contains(err.Error(), "usage is unavailable") || errors.Is(err, ErrQoderSignIn) {
|
||||
t.Fatalf("device refresh refused: %v lapsed %q", err, lapsed())
|
||||
}
|
||||
if _, err := QoderCredential(context.Background(), "one@x"); err == nil || lapsed() == "" || !errors.Is(err, ErrQoderSignIn) {
|
||||
t.Fatalf("job refresh refused: %v lapsed %q", err, lapsed())
|
||||
}
|
||||
if err := qoderSave(c); err != nil || lapsed() != "" {
|
||||
t.Fatalf("sign-in again keeps lapsed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A job refresh that never got an answer is no refused sign-in.
|
||||
func TestQoderRefreshNetworkErrorNotSignIn(t *testing.T) {
|
||||
signIn(t)
|
||||
qoderTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
panic(http.ErrAbortHandler)
|
||||
}))
|
||||
c := qoderTestCredential("one")
|
||||
c.ExpiresAt = time.Now().Add(time.Minute).UnixMilli()
|
||||
if err := qoderSave(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := QoderCredential(context.Background(), "one@x")
|
||||
if err == nil || errors.Is(err, ErrQoderSignIn) {
|
||||
t.Fatalf("network failure read as a lapsed sign-in: %v", err)
|
||||
}
|
||||
for _, l := range Logins("qoder") {
|
||||
if l.Lapsed != "" {
|
||||
t.Fatalf("lapsed on a network failure: %q", l.Lapsed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A Qoder refresh in flight must not hold the logins every provider shares.
|
||||
func TestQoderRefreshDoesNotBlockLogins(t *testing.T) {
|
||||
signIn(t)
|
||||
release := make(chan struct{})
|
||||
started := make(chan struct{})
|
||||
var once sync.Once
|
||||
qoderTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
once.Do(func() { close(started) })
|
||||
<-release
|
||||
_, _ = w.Write([]byte(`{"token":"jt-new","refresh_token":"rt-new","expires_in":3600000}`))
|
||||
}))
|
||||
var releaseOnce sync.Once
|
||||
unblock := func() { releaseOnce.Do(func() { close(release) }) }
|
||||
t.Cleanup(unblock)
|
||||
c := qoderTestCredential("one")
|
||||
c.ExpiresAt = time.Now().Add(time.Minute).UnixMilli()
|
||||
if err := qoderSave(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := qoderSave(qoderTestCredential("two")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := QoderCredential(context.Background(), "one@x"); done <- err }()
|
||||
<-started
|
||||
begin := time.Now()
|
||||
_ = Logins("workbuddy")
|
||||
_ = Logins("qoder")
|
||||
if err := SetLoginOn("qoder", "two@x", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d := time.Since(begin); d > 500*time.Millisecond {
|
||||
t.Fatalf("logins blocked %v behind a Qoder refresh", d)
|
||||
}
|
||||
unblock()
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the refresh wrote back into the file as it is now, keeping the change made meanwhile
|
||||
for _, l := range Logins("qoder") {
|
||||
if l.User == "two@x" && l.On {
|
||||
t.Fatal("write-back undid a change made during the refresh")
|
||||
}
|
||||
}
|
||||
if fresh, err := QoderCredential(context.Background(), "one@x"); err != nil || fresh.Token != "jt-new" {
|
||||
t.Fatalf("refreshed pair not saved: %+v %v", fresh, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQoderAccountsAndMigration(t *testing.T) {
|
||||
signIn(t)
|
||||
legacy := filepath.Join(filepath.Dir(Path()), "qoder.json")
|
||||
one := qoderTestCredential("one")
|
||||
one.MachineID = ""
|
||||
writeFile(t, legacy, one)
|
||||
ls := Logins("qoder")
|
||||
if len(ls) != 1 || ls[0].User != "one@x" || !ls[0].Active {
|
||||
t.Fatalf("migration %+v", ls)
|
||||
}
|
||||
if _, err := os.Stat(legacy); !os.IsNotExist(err) {
|
||||
t.Fatalf("legacy file remains: %v", err)
|
||||
}
|
||||
oneRead, err := QoderCredential(context.Background(), "one@x")
|
||||
if err != nil || oneRead.MachineID == "" {
|
||||
t.Fatalf("migrated identity %+v %v", oneRead, err)
|
||||
}
|
||||
if err := qoderSave(qoderTestCredential("two")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, ok := qoderAccount()
|
||||
if !ok || p.Account.User != "one@x" || len(p.AlsoOn()) != 1 || p.AlsoOn()[0].Account.User != "two@x" {
|
||||
t.Fatalf("accounts %+v", p)
|
||||
}
|
||||
if err := SetLoginOn("qoder", "two@x", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(p.AlsoOn()) != 0 {
|
||||
t.Fatal("disabled account is routed")
|
||||
}
|
||||
if err := SwitchLogin("qoder", "two@x"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, _ = qoderAccount()
|
||||
if p.Account.User != "two@x" {
|
||||
t.Fatalf("switch %+v", p.Account)
|
||||
}
|
||||
cred, err := QoderCredential(context.Background(), p.Account.User)
|
||||
if err != nil || cred.UID != "two" {
|
||||
t.Fatalf("selected credential %+v %v", cred, err)
|
||||
}
|
||||
mi, err := QoderModel(context.Background(), "two@x", "other-model")
|
||||
if err != nil || mi.MaxInputTokens != 64000 || mi.IsReasoning {
|
||||
t.Fatalf("model %+v %v", mi, err)
|
||||
}
|
||||
if _, err := QoderModel(context.Background(), "two@x", "unknown"); err == nil {
|
||||
t.Fatal("unknown model accepted")
|
||||
}
|
||||
if err := ForgetLogin("qoder", "one@x"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ForgetLogin("qoder", "two@x"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(Logins("qoder")) != 0 || QoderSignedIn() {
|
||||
t.Fatal("removed accounts remain")
|
||||
}
|
||||
if _, err := QoderCredential(context.Background(), "two@x"); err == nil {
|
||||
t.Fatal("removed token is usable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQoderSignInDeadline(t *testing.T) {
|
||||
signIn(t)
|
||||
_, flow, err := QoderAuthURL()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if left := time.Until(flow.deadline); left <= 14*time.Minute || left > 15*time.Minute {
|
||||
t.Fatalf("deadline %v", left)
|
||||
}
|
||||
flow.deadline = time.Now().Add(-time.Second)
|
||||
_, err = QoderCompleteSignIn(context.Background(), flow)
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("expired flow: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQoderCompleteSignIn(t *testing.T) {
|
||||
signIn(t)
|
||||
var machine string
|
||||
var named bool
|
||||
qoderTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case qoder.DeviceTokenPollPath:
|
||||
_, _ = w.Write([]byte(`{"token":"dt-one","refresh_token":"drt","user_id":"u1"}`))
|
||||
case qoder.JobTokenPath:
|
||||
if r.Header.Get("Authorization") != "Bearer dt-one" {
|
||||
t.Error("wrong device token")
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"token":"jt-one","refresh_token":"rt-one","expires_in":3600000}`))
|
||||
case qoder.UserInfoPath:
|
||||
if named {
|
||||
_, _ = w.Write([]byte(`{"id":"u1","email":"one@x","name":"One"}`))
|
||||
} else {
|
||||
_, _ = w.Write([]byte(`{"id":"u1"}`))
|
||||
}
|
||||
case strings.Split(qoder.ListModelsPath, "?")[0]:
|
||||
if r.Header.Get("Cosy-MachineId") != machine || r.Header.Get("Cosy-MachineOS") != qoder.MachineOS() {
|
||||
t.Error("model fetch uses wrong fingerprint")
|
||||
}
|
||||
_, _ = w.Write(qoderTestCredential("one").Models)
|
||||
default:
|
||||
t.Errorf("unexpected request %s", r.URL.Path)
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
for i := 0; i < 2; i++ {
|
||||
authURL, flow, err := QoderAuthURL()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, _ := url.Parse(authURL)
|
||||
machine = u.Query().Get("machine_id")
|
||||
who, err := QoderCompleteSignIn(context.Background(), flow)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "u1"
|
||||
if named {
|
||||
want = "one@x"
|
||||
}
|
||||
if who != want || len(Logins("qoder")) != 1 {
|
||||
t.Fatalf("sign-in %s %+v", who, Logins("qoder"))
|
||||
}
|
||||
cred, err := QoderCredential(context.Background(), who)
|
||||
if err != nil || cred.MachineID != machine || len(cred.Models) == 0 {
|
||||
t.Fatalf("saved flow: %+v %v", cred, err)
|
||||
}
|
||||
named = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestQoderLoginUsage(t *testing.T) {
|
||||
signIn(t)
|
||||
c := qoderTestCredential("one")
|
||||
c.DeviceRefresh = "drt-old"
|
||||
if err := qoderSave(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var refreshes atomic.Int32
|
||||
qoderTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case qoder.DeviceTokenRefreshPath:
|
||||
refreshes.Add(1)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"device_token": "dt-new", "refresh_token": "drt-new"})
|
||||
case qoder.AccountUsagePath:
|
||||
if r.Header.Get("Authorization") != "Bearer dt-new" {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"displayMode":"qoder","qoderUsage":{"userType":"pro","userQuota":{"total":100,"used":25},"addOnQuota":{"cap":50,"remaining":40},"orgResourcePackage":{"total":20,"used":10},"dedicatedResourcePackages":[{"name":"Team","total":10,"used":2}]}}`))
|
||||
default:
|
||||
t.Errorf("unexpected path %s", r.URL.Path)
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
q := qoderLoginQuota(context.Background(), Login{Agent: "qoder", User: "one@x"})
|
||||
if q.Error != "" || q.Plan != "pro" || len(q.Windows) != 4 || q.Windows[0].Used != 25 || q.Windows[1].Used != 20 {
|
||||
t.Fatalf("quota %+v", q)
|
||||
}
|
||||
fresh, err := QoderCredential(context.Background(), "one@x")
|
||||
if err != nil || fresh.DeviceToken != "dt-new" || fresh.DeviceRefresh != "drt-new" || fresh.Token != c.Token || fresh.MachineID != c.MachineID || refreshes.Load() != 1 {
|
||||
t.Fatalf("device refresh %+v %v", fresh, err)
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
package provider
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/yetone/magpie/internal/qoder"
|
||||
)
|
||||
|
||||
// Account endpoints use the device token, independently of the chat job token.
|
||||
func qoderLoginQuota(ctx context.Context, l Login) SubscriptionQuota {
|
||||
site := qoder.SiteOf(l.Agent)
|
||||
q := SubscriptionQuota{Provider: site.ID, User: l.User, Name: site.Name, Icon: "qoder", Plan: l.Plan, Windows: []QuotaWindow{}}
|
||||
c, err := QoderCredentialOf(ctx, site.ID, l.User)
|
||||
if err != nil {
|
||||
q.Error = err.Error()
|
||||
return q
|
||||
}
|
||||
raw, err := qoder.FetchUsage(ctx, qoderClient, site.OpenAPI, c.DeviceToken)
|
||||
var status *qoder.UsageHTTPError
|
||||
if errors.As(err, &status) && (status.StatusCode == 401 || status.StatusCode == 403) {
|
||||
var token string
|
||||
token, err = qoderRefreshDevice(ctx, site.ID, l.User, c.DeviceToken)
|
||||
if err == nil {
|
||||
raw, err = qoder.FetchUsage(ctx, qoderClient, site.OpenAPI, token)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
q.Error = err.Error()
|
||||
return q
|
||||
}
|
||||
q, err = parseQoderQuota(raw, q)
|
||||
if err != nil {
|
||||
q.Error = err.Error()
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func qoderRefreshDevice(ctx context.Context, agent, user, attempted string) (string, error) {
|
||||
site := qoder.SiteOf(agent)
|
||||
qoderMu.Lock()
|
||||
defer qoderMu.Unlock()
|
||||
l, found := qoderLookup(agent, user)
|
||||
if !found {
|
||||
return "", fmt.Errorf("no %s account %q", site.Name, user)
|
||||
}
|
||||
c, ok, pending := qoderCurrent(l)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("%s: unreadable sign-in", site.Name)
|
||||
}
|
||||
if c.DeviceToken != attempted {
|
||||
if pending {
|
||||
if err := qoderPersist(l, c, false); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return c.DeviceToken, nil
|
||||
}
|
||||
// the device refresh token rotates too: keep its reply past the caller
|
||||
rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), qoderRefreshTimeout)
|
||||
dt, err := qoder.RefreshDeviceToken(rctx, qoderClient, site.OpenAPI+qoder.DeviceTokenRefreshPath, c.DeviceRefresh)
|
||||
cancel()
|
||||
if err != nil && c.DeviceChat {
|
||||
// the device token is the chat token too: a refused one is the sign-in gone
|
||||
var refused *qoder.DeviceTokenRefreshHTTPError
|
||||
if errors.As(err, &refused) {
|
||||
err = &qoder.JobTokenRefreshHTTPError{StatusCode: refused.StatusCode}
|
||||
}
|
||||
return "", qoderRefreshFailed(agent, user, err)
|
||||
}
|
||||
if err != nil {
|
||||
// The device token serves only the account pages (usage); chat
|
||||
// runs on the job token, so a refused one doesn't lapse the account.
|
||||
var refused *qoder.DeviceTokenRefreshHTTPError
|
||||
if errors.As(err, &refused) && (refused.StatusCode == http.StatusUnauthorized || refused.StatusCode == http.StatusForbidden) {
|
||||
return "", fmt.Errorf("%[1]s usage is unavailable: %[1]s refused the account-page sign-in (chat still works) — sign in again to see usage (%[2]w)", site.Name, err)
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
c.DeviceToken, c.DeviceRefresh = dt.Token, dt.RefreshToken
|
||||
if c.DeviceChat { // the pair it spent was the chat pair too
|
||||
c.Token, c.RefreshToken, c.ExpiresAt = dt.Token, dt.RefreshToken, qoder.DeviceExpiry(*dt).UnixMilli()
|
||||
}
|
||||
if err := qoderPersist(l, c, c.DeviceChat); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.DeviceToken, nil
|
||||
}
|
||||
|
||||
func parseQoderQuota(raw []byte, q SubscriptionQuota) (SubscriptionQuota, error) {
|
||||
var env struct {
|
||||
DisplayMode string `json:"displayMode"`
|
||||
Usage map[string]json.RawMessage `json:"qoderUsage"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
return q, err
|
||||
}
|
||||
if env.DisplayMode == "enterprise" {
|
||||
q.Plan = "Enterprise"
|
||||
return q, nil
|
||||
}
|
||||
if env.DisplayMode != "qoder" || env.Usage == nil {
|
||||
return q, fmt.Errorf("Qoder: missing quota data")
|
||||
}
|
||||
field := func(a, b string) json.RawMessage {
|
||||
if v := env.Usage[a]; len(v) > 0 {
|
||||
return v
|
||||
}
|
||||
return env.Usage[b]
|
||||
}
|
||||
_ = json.Unmarshal(field("userType", "user_type"), &q.Plan)
|
||||
var expiry any
|
||||
if json.Unmarshal(field("expiresAt", "expires_at"), &expiry) == nil {
|
||||
q.Until = cmdTime(expiry)
|
||||
}
|
||||
add := func(raw json.RawMessage, name string) {
|
||||
var b struct {
|
||||
Total *float64 `json:"total"`
|
||||
Cap *float64 `json:"cap"`
|
||||
Used *float64 `json:"used"`
|
||||
Remaining *float64 `json:"remaining"`
|
||||
Name string `json:"name"`
|
||||
Unit string `json:"unit"`
|
||||
}
|
||||
if json.Unmarshal(raw, &b) != nil {
|
||||
return
|
||||
}
|
||||
if b.Total == nil {
|
||||
b.Total = b.Cap
|
||||
}
|
||||
if b.Total == nil || *b.Total <= 0 || b.Used == nil && b.Remaining == nil {
|
||||
return
|
||||
}
|
||||
used := *b.Total
|
||||
if b.Used != nil {
|
||||
used = *b.Used
|
||||
} else {
|
||||
used -= *b.Remaining
|
||||
}
|
||||
if used < 0 {
|
||||
return
|
||||
}
|
||||
if b.Name != "" {
|
||||
name = b.Name
|
||||
}
|
||||
if b.Unit == "" {
|
||||
b.Unit = "credits"
|
||||
}
|
||||
q.Windows = append(q.Windows, QuotaWindow{Name: name, Used: min(100, 100*used / *b.Total), Display: fmt.Sprintf("%g / %g %s", used, *b.Total, b.Unit)})
|
||||
}
|
||||
add(field("userQuota", "user_quota"), "Credits")
|
||||
add(field("addOnQuota", "add_on_quota"), "Add-on credits")
|
||||
add(field("orgResourcePackage", "org_resource_package"), "Shared credits")
|
||||
var dedicated []json.RawMessage
|
||||
_ = json.Unmarshal(field("dedicatedResourcePackages", "dedicated_resource_packages"), &dedicated)
|
||||
for _, b := range dedicated {
|
||||
add(b, "Dedicated credits")
|
||||
}
|
||||
return q, nil
|
||||
}
|
||||
@@ -412,12 +412,6 @@ func (s *signInFlow) begin() error {
|
||||
if err := startCommandCodeSignIn(s); err != nil {
|
||||
return err
|
||||
}
|
||||
case "qoder", QoderCNID:
|
||||
// Qoder's device flow on the account's site (qoder.com or qoder.cn),
|
||||
// run by magpie and kept in its own store
|
||||
if err := startQoderSignIn(s, qoderSiteOf(agent)); err != nil {
|
||||
return err
|
||||
}
|
||||
case "factory":
|
||||
// WorkOS's device code, as droid signs in to Factory
|
||||
if err := startFactorySignIn(s); err != nil {
|
||||
|
||||
@@ -11,8 +11,6 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/qoder"
|
||||
)
|
||||
|
||||
// An account signed in again is read afresh: the usage reading kept from
|
||||
@@ -110,8 +108,8 @@ func TestFactoryKeyAgainReadsUsageAfresh(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// WorkBuddy and Qoder keep a sign-in their own way (wbKeepSignIn,
|
||||
// qoderSave): the account's kept reading goes there too.
|
||||
// WorkBuddy keeps a sign-in its own way (wbKeepSignIn): the account's kept
|
||||
// reading goes there too.
|
||||
func TestOwnStoreSignInAgainDropsTheReading(t *testing.T) {
|
||||
signIn(t)
|
||||
for _, c := range []struct {
|
||||
@@ -122,9 +120,6 @@ func TestOwnStoreSignInAgainDropsTheReading(t *testing.T) {
|
||||
_, _, _, err := wbKeepSignIn(wbSiteOf("workbuddy"), wbCreds{UID: "u-1", Access: "a", Refresh: "r"}, "wb")
|
||||
return err
|
||||
}},
|
||||
{"qoder", "q@example.com", func() error {
|
||||
return qoderSave(qoder.Credential{UID: "q-1", Token: "t", Email: "q@example.com"})
|
||||
}},
|
||||
} {
|
||||
t.Run(c.agent, func(t *testing.T) {
|
||||
resetLoginUsage(t)
|
||||
|
||||
@@ -483,12 +483,6 @@ func fetchSubscriptionUsage(ctx context.Context) []SubscriptionQuota {
|
||||
if !moved(CommandCodePlanID) && !hidden[CommandCodePlanID] {
|
||||
fetches = append(fetches, perLogin(via(CommandCodePlanID), cmdLoginList(), accountCard(CommandCodePlanID))...)
|
||||
}
|
||||
if !moved("qoder") && !hidden["qoder"] {
|
||||
fetches = append(fetches, perLogin(via("qoder"), loginsOf(qoderLogins()), accountCard("qoder"))...)
|
||||
}
|
||||
if !moved(QoderCNID) && !hidden[QoderCNID] {
|
||||
fetches = append(fetches, perLogin(via(QoderCNID), loginsOf(qoderLoginsOf(QoderCNID)), accountCard(QoderCNID))...)
|
||||
}
|
||||
if !moved("devin") && !hidden["devin"] {
|
||||
fetches = append(fetches, perLogin(via("devin"), devinLoginList(), accountCard("devin"))...)
|
||||
}
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
package qoder
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestAuthorizationURL checks the device-flow page carries PKCE S256 and the
|
||||
// client id, and returns the verifier+nonce the later poll needs.
|
||||
func TestAuthorizationURL(t *testing.T) {
|
||||
f := NewDeviceFlow(nil, nil)
|
||||
authURL, verifier, nonce, err := f.Authorization()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(authURL, DeviceFlowHost+DeviceSelectAccountsPath) {
|
||||
t.Fatalf("url %q", authURL)
|
||||
}
|
||||
for _, q := range []string{"challenge=", "challenge_method=S256", "client_id=" + ClientID, "nonce=", "redirect_uri="} {
|
||||
if !strings.Contains(authURL, strings.TrimSuffix(q, "=")) {
|
||||
t.Fatalf("url missing %q: %s", q, authURL)
|
||||
}
|
||||
}
|
||||
if verifier == "" || nonce == "" {
|
||||
t.Fatal("no verifier/nonce")
|
||||
}
|
||||
u, _ := url.Parse(authURL)
|
||||
if u.Query().Get("machine_id") != f.MachineID() {
|
||||
t.Fatal("login machine id differs from flow")
|
||||
}
|
||||
second, _, _, _ := f.Authorization()
|
||||
u, _ = url.Parse(second)
|
||||
if u.Query().Get("machine_id") != f.MachineID() {
|
||||
t.Fatal("flow changed its machine id")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeviceFlowAndRefresh runs the real poll -> jobToken -> refresh rounds
|
||||
// against a stub of the OpenAPI host (repointed through Global.OpenAPI), checking
|
||||
// each round trips the right fields and headers.
|
||||
func TestDeviceFlowAndRefresh(t *testing.T) {
|
||||
var pollHits int
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case DeviceTokenPollPath:
|
||||
pollHits++
|
||||
if pollHits < 2 { // first try: not authorized yet
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"token": "dt-abc", "refresh_token": "drt", "user_id": "uid-9"})
|
||||
case JobTokenPath:
|
||||
if r.Header.Get("Authorization") != "Bearer dt-abc" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"token": "jt-xyz", "refresh_token": "jrt", "expires_in": 3600000})
|
||||
case JobTokenRefreshPath:
|
||||
var b struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&b)
|
||||
if b.RefreshToken != "jrt" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"token": "jt-new", "refresh_token": "jrt2", "expires_in": 7200000})
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// Repoint the package host at the stub so the real round-trip functions run
|
||||
// against it (they build their URLs from Global.OpenAPI + the path constants).
|
||||
host := Global.OpenAPI
|
||||
Global.OpenAPI = srv.URL
|
||||
defer func() { Global.OpenAPI = host }()
|
||||
client := srv.Client()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
f := NewDeviceFlow(client, nil)
|
||||
dt, err := f.PollDeviceToken(ctx, "nonce", "verifier", time.Millisecond)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dt.Token != "dt-abc" || dt.UserID != "uid-9" {
|
||||
t.Fatalf("poll: %+v", dt)
|
||||
}
|
||||
jt, err := f.JobToken(ctx, dt.Token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if jt.Token != "jt-xyz" || jt.Expiry() != time.Hour {
|
||||
t.Fatalf("jobToken: %+v", jt)
|
||||
}
|
||||
updated, err := RefreshJobToken(ctx, client, nil, "jrt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if updated.Token != "jt-new" || updated.RefreshToken != "jrt2" || updated.Expiry() != 2*time.Hour {
|
||||
t.Fatalf("refresh: %+v", updated)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchUserInfo checks the account endpoint is asked with the device token
|
||||
// and its email and name are decoded.
|
||||
func TestFetchUserInfo(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != UserInfoPath {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer dt-abc" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"id":"u1","name":"Ethan Xu","email":"e@x.com","source":"sso.google"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
host := Global.OpenAPI
|
||||
Global.OpenAPI = srv.URL
|
||||
defer func() { Global.OpenAPI = host }()
|
||||
|
||||
ui, err := FetchUserInfo(context.Background(), srv.Client(), nil, "dt-abc")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ui.Email != "e@x.com" || ui.Name != "Ethan Xu" || ui.ID != "u1" {
|
||||
t.Fatalf("userinfo: %+v", ui)
|
||||
}
|
||||
if _, err := FetchUserInfo(context.Background(), srv.Client(), nil, ""); err == nil {
|
||||
t.Fatal("empty device token should error")
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseModels checks enabled, routable chat models are kept with magpie's
|
||||
// fields, and aggregate "auto" and disabled entries are dropped.
|
||||
func TestParseModels(t *testing.T) {
|
||||
body := []byte(`{"chat":[
|
||||
{"key":"qfmodel","display_name":"Qwen3.8-Flash","enable":true,"is_vl":true,"max_input_tokens":200000},
|
||||
{"key":"auto","enable":true},
|
||||
{"key":"off-model","enable":false}]}`)
|
||||
ms, err := ParseModels(body, ProviderKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(ms) != 1 {
|
||||
t.Fatalf("want 1 routable model, got %d: %+v", len(ms), ms)
|
||||
}
|
||||
m := ms[0]
|
||||
if m.ID != "qfmodel" || m.Name != "Qwen3.8-Flash" || m.Provider != ProviderKey || m.Context != 200000 || !m.Images {
|
||||
t.Fatalf("model mapping wrong: %+v", m)
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
package qoder
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
|
||||
import "strings"
|
||||
|
||||
// The body codec: the worker base64-encodes the plaintext with a shuffled
|
||||
// alphabet, then swaps the first and last thirds of the result. Ported
|
||||
// verbatim from CLIProxyAPI, whose alphabet and grouping were dumped from a
|
||||
// live Qoder client and verified end-to-end against captured traffic.
|
||||
//
|
||||
// Alphabet (64 chars, dumped from live Qoder.exe memory):
|
||||
//
|
||||
// _doRTgHZBKcGVjlvpC,@aFSx#DPuNJme&i*MzLOEn)sUrthbf%Y^w.(kIQyXqWA!
|
||||
//
|
||||
// Grouping is standard base64: four chars = 24 bits = three plaintext bytes.
|
||||
// '!' is the 64th char and encodes the 6-bit value 63; '$' is the pad, which
|
||||
// holds a slot but carries no data.
|
||||
|
||||
const (
|
||||
// BodyAlphabet is the custom base64 alphabet.
|
||||
BodyAlphabet = "_doRTgHZBKcGVjlvpC,@aFSx#DPuNJme&i*MzLOEn)sUrthbf%Y^w.(kIQyXqWA!"
|
||||
)
|
||||
|
||||
var bodyAlphabetIndex = func() [256]int8 {
|
||||
var m [256]int8
|
||||
for i := range m {
|
||||
m[i] = -1
|
||||
}
|
||||
for i, c := range BodyAlphabet {
|
||||
m[c] = int8(i)
|
||||
}
|
||||
return m
|
||||
}()
|
||||
|
||||
// groupBytes decodes one 4-char group to its N bytes, N = floor(6*k/8) where
|
||||
// k is the number of non-pad chars. '$' is skipped; '!' maps to 63.
|
||||
func groupBytes(grp string) []byte {
|
||||
var vals []int
|
||||
for _, c := range grp {
|
||||
if c == '$' {
|
||||
continue
|
||||
}
|
||||
vals = append(vals, int(bodyAlphabetIndex[c]))
|
||||
}
|
||||
nv := len(vals)
|
||||
if nv == 0 {
|
||||
return nil
|
||||
}
|
||||
x := 0
|
||||
for _, v := range vals {
|
||||
x = (x << 6) | v
|
||||
}
|
||||
nb := (6 * nv) / 8
|
||||
out := make([]byte, nb)
|
||||
for k := 0; k < nb; k++ {
|
||||
sh := 6*nv - 8*(k+1)
|
||||
out[k] = byte((x >> sh) & 255)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// segmentEncode encodes bytes through the alphabet as one continuous base64
|
||||
// bitstream (MSB first): each byte adds 8 bits, every 6 emitted as a char; a
|
||||
// final partial group is zero-padded into one char; the char count is padded
|
||||
// out to a multiple of 4 with '$'. The 6-bit value 63 is emitted as '!'.
|
||||
func segmentEncode(data []byte) string {
|
||||
var sb strings.Builder
|
||||
acc, nb := 0, 0
|
||||
emit := func(v int) { sb.WriteByte(BodyAlphabet[v]) }
|
||||
for _, b := range data {
|
||||
acc = (acc << 8) | int(b)
|
||||
nb += 8
|
||||
for nb >= 6 {
|
||||
nb -= 6
|
||||
emit((acc >> nb) & 0x3F)
|
||||
}
|
||||
}
|
||||
if nb > 0 {
|
||||
emit((acc << (6 - nb)) & 0x3F)
|
||||
}
|
||||
for sb.Len()%4 != 0 {
|
||||
sb.WriteByte('$')
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// BodyEncode encodes one plaintext into custom base64 (no third swap).
|
||||
func BodyEncode(data []byte) string { return segmentEncode(data) }
|
||||
|
||||
// BodyDecode decodes custom base64 (no third swap).
|
||||
func BodyDecode(s string) []byte {
|
||||
var out []byte
|
||||
for gi := 0; gi+4 <= len(s); gi += 4 {
|
||||
if b := groupBytes(s[gi : gi+4]); b != nil {
|
||||
out = append(out, b...)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// swapBodyOuterThirds exchanges the first and last thirds of an encoded
|
||||
// string; the middle third stays put.
|
||||
func swapBodyOuterThirds(encoded string) string {
|
||||
third := len(encoded) / 3
|
||||
if third == 0 {
|
||||
return encoded
|
||||
}
|
||||
return encoded[len(encoded)-third:] + encoded[third:len(encoded)-third] + encoded[:third]
|
||||
}
|
||||
|
||||
// EncodeRequestBody is the wire body for an agent_chat_generation request:
|
||||
// custom base64, then the outer-third swap.
|
||||
func EncodeRequestBody(plaintext []byte) string {
|
||||
return swapBodyOuterThirds(BodyEncode(plaintext))
|
||||
}
|
||||
|
||||
// DecodeRequestBody reverses the swap, then decodes.
|
||||
func DecodeRequestBody(wire string) []byte {
|
||||
return BodyDecode(swapBodyOuterThirds(wire))
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package qoder
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Fixed vectors use RFC 4648 base64 with the client's alphabet substituted,
|
||||
// then its outer-third swap. The JSON vector is CLIProxyAPI's worker fixture.
|
||||
func TestCodecKnownAnswers(t *testing.T) {
|
||||
for _, tt := range []struct{ hex, encoded, wire string }{
|
||||
{"", "", ""},
|
||||
{"66", "D&$$", "$&$D"},
|
||||
{"666f", "DOq$", "$OqD"},
|
||||
{"666f6f", "DOWb", "bOWD"},
|
||||
{"666f6f626172", "DOWb#OgY", "gYWb#ODO"},
|
||||
{"00ff3f7f", "_vq!ef$$", "$$q!ef_v"},
|
||||
{"e4b8ade69687", "QG*tQ)PZ", "PZ*tQ)QG"},
|
||||
{"7b226d65737361676573223a5b5d7d", "mYKtDxj^#SJLNYByS..W", "ByS..Wj^#SJLNYmYKtDx"},
|
||||
} {
|
||||
t.Run(tt.hex, func(t *testing.T) {
|
||||
plain, _ := hex.DecodeString(tt.hex)
|
||||
if got := BodyEncode(plain); got != tt.encoded {
|
||||
t.Fatalf("encode %q, want %q", got, tt.encoded)
|
||||
}
|
||||
if got := BodyDecode(tt.encoded); !bytes.Equal(got, plain) {
|
||||
t.Fatalf("decode %x, want %x", got, plain)
|
||||
}
|
||||
if got := EncodeRequestBody(plain); got != tt.wire {
|
||||
t.Fatalf("wire %q, want %q", got, tt.wire)
|
||||
}
|
||||
if got := DecodeRequestBody(tt.wire); !bytes.Equal(got, plain) {
|
||||
t.Fatalf("wire decode %x, want %x", got, plain)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCosySignatureKnownAnswer(t *testing.T) {
|
||||
// Independently calculated MD5 of the five newline-separated fields.
|
||||
const path = "/api/v2/service/pro/sse/agent_chat_generation"
|
||||
if got := cosySignature("cGF5bG9hZA==", "c2VjcmV0", 1700000000, "ByS..Wj^#SJLNYmYKtDx", path); got != "da9dbed272847ea4664dd7ae8bf82575" {
|
||||
t.Fatalf("signature = %q", got)
|
||||
}
|
||||
if got := urlPathname(APIHost + ChatPath); got != path {
|
||||
t.Fatalf("signed path %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCosyMachineIdentity(t *testing.T) {
|
||||
u := &User{UID: "uid", Token: "jt", MachineID: "fixed-machine"}
|
||||
for i := 0; i < 2; i++ {
|
||||
h, err := BuildCosyHeaders(APIHost+ChatPath, u, "", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range []string{"Cosy-MachineId", "Cosy-MachineToken", "Cosy-ClientIp"} {
|
||||
if h[key] != "fixed-machine" {
|
||||
t.Fatalf("%s = %q", key, h[key])
|
||||
}
|
||||
}
|
||||
arch := map[string]string{"amd64": "x86_64", "386": "x86", "arm64": "aarch64"}[runtime.GOARCH]
|
||||
if arch == "" {
|
||||
arch = runtime.GOARCH
|
||||
}
|
||||
os := runtime.GOOS
|
||||
if os == "windows" {
|
||||
os = "win32"
|
||||
}
|
||||
if h["Cosy-MachineOS"] != arch+"_"+os {
|
||||
t.Fatalf("OS %q", h["Cosy-MachineOS"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestCodecRoundTrip checks the fiddliest reverse-engineered piece: a request
|
||||
// body survives encode-to-wire then decode-from-wire unchanged, over every
|
||||
// length so the partial final 6-bit group, the "$" padding and the
|
||||
// outer-thirds swap are all exercised.
|
||||
func TestCodecRoundTrip(t *testing.T) {
|
||||
for n := 0; n < 200; n++ {
|
||||
plain := make([]byte, n)
|
||||
if _, err := rand.Read(plain); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wire := EncodeRequestBody(plain)
|
||||
if got := DecodeRequestBody(wire); !bytes.Equal(got, plain) {
|
||||
t.Fatalf("round trip failed at len %d", n)
|
||||
}
|
||||
if len(wire)%4 != 0 {
|
||||
t.Fatalf("wire length %d not a multiple of 4", len(wire))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestCosyHeadersStructure checks the request envelope is well formed: the
|
||||
// Authorization is "Bearer COSY.<payload>.<md5 hex>", the payload base64
|
||||
// decodes to the documented JSON, and the token is never in the clear.
|
||||
func TestCosyHeadersStructure(t *testing.T) {
|
||||
u := &User{UID: "uid-1", Name: "N", Email: "e@x", Token: "jt-abc", MachineID: "machine-test"}
|
||||
ts := int64(1700000000)
|
||||
h, err := BuildCosyHeaders(APIHost+ChatPath, u, `{"messages":[]}`, ts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
auth := h["Authorization"]
|
||||
if !strings.HasPrefix(auth, "Bearer COSY.") {
|
||||
t.Fatalf("bad Authorization: %q", auth)
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(auth, "Bearer COSY."), ".")
|
||||
if len(parts) != 2 || len(parts[1]) != 32 {
|
||||
t.Fatalf("expected payload.<md5hex>, got %q", auth)
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(parts[0])
|
||||
if err != nil {
|
||||
t.Fatalf("payload not base64: %v", err)
|
||||
}
|
||||
var p map[string]any
|
||||
if json.Unmarshal(decoded, &p) != nil {
|
||||
t.Fatalf("payload not JSON: %q", decoded)
|
||||
}
|
||||
if p["version"] != "v1" || p["cosyVersion"] != "1.1.49" {
|
||||
t.Fatalf("unexpected payload fields: %v", p)
|
||||
}
|
||||
if strings.Contains(string(decoded), "jt-abc") {
|
||||
t.Fatal("token leaked into the payload")
|
||||
}
|
||||
if h["Cosy-User"] != "uid-1" {
|
||||
t.Fatalf("Cosy-User wrong: %q", h["Cosy-User"])
|
||||
}
|
||||
if h["Cosy-Date"] != "1700000000" {
|
||||
t.Fatalf("Cosy-Date wrong: %q", h["Cosy-Date"])
|
||||
}
|
||||
}
|
||||
@@ -1,207 +0,0 @@
|
||||
package qoder
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RSAPublicKeyPEM is Qoder's embedded 1024-bit RSA public key (from the
|
||||
// client's cosy source), used to encrypt the per-request AES key that wraps
|
||||
// the user blob in the COSY Authorization header.
|
||||
const RSAPublicKeyPEM = `-----BEGIN PUBLIC KEY-----
|
||||
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
|
||||
4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
|
||||
6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
|
||||
XcW+ML9FoCI6AOvOzwIDAQAB
|
||||
-----END PUBLIC KEY-----`
|
||||
|
||||
// User is the signed-in Qoder account a COSY envelope is built for.
|
||||
type User struct {
|
||||
UID string // the Qoder user id (x-gw-user-id / Cosy-User value)
|
||||
Name string // display name, may be empty
|
||||
Email string // account email, may be empty
|
||||
Token string // the jt- Bearer token (security_oauth_token)
|
||||
MachineID string // generated once at sign-in, saved with the account
|
||||
}
|
||||
|
||||
var qoderRSAKey *rsa.PublicKey
|
||||
|
||||
func init() {
|
||||
block, _ := pem.Decode([]byte(RSAPublicKeyPEM))
|
||||
if block == nil {
|
||||
panic("qoder: failed to decode embedded RSA public key")
|
||||
}
|
||||
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
panic("qoder: parse RSA public key: " + err.Error())
|
||||
}
|
||||
rsaKey, ok := pub.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
panic("qoder: embedded key is not an RSA public key")
|
||||
}
|
||||
qoderRSAKey = rsaKey
|
||||
}
|
||||
|
||||
// aes128CBCEncrypt encrypts with AES-128-CBC and PKCS#7 padding.
|
||||
func aes128CBCEncrypt(key, iv, plaintext []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
padLen := aes.BlockSize - len(plaintext)%aes.BlockSize
|
||||
padded := make([]byte, len(plaintext)+padLen)
|
||||
copy(padded, plaintext)
|
||||
for i := len(plaintext); i < len(padded); i++ {
|
||||
padded[i] = byte(padLen)
|
||||
}
|
||||
out := make([]byte, len(padded))
|
||||
cipher.NewCBCEncrypter(block, iv).CryptBlocks(out, padded)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// rsaPKCS1Encrypt wraps an AES key with Qoder's embedded public key.
|
||||
func rsaPKCS1Encrypt(key []byte) ([]byte, error) {
|
||||
return rsa.EncryptPKCS1v15(rand.Reader, qoderRSAKey, key)
|
||||
}
|
||||
|
||||
// generateUserBlob builds the AES-encrypted user info the COSY payload
|
||||
// carries, returning (info, key) both base64'd. The AES key doubles as the IV.
|
||||
func generateUserBlob(user *User) (string, string, error) {
|
||||
blob := map[string]string{
|
||||
"uid": user.UID,
|
||||
"aid": "",
|
||||
"name": user.Name,
|
||||
"email": user.Email,
|
||||
"security_oauth_token": user.Token,
|
||||
}
|
||||
raw, err := json.Marshal(blob)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("qoder: marshal user blob: %w", err)
|
||||
}
|
||||
key := []byte(strings.ReplaceAll(newUUID(), "-", "")[:16])
|
||||
iv := key[:16]
|
||||
infoEnc, err := aes128CBCEncrypt(key, iv, raw)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("qoder: aes encrypt user blob: %w", err)
|
||||
}
|
||||
keyEnc, err := rsaPKCS1Encrypt(key)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("qoder: rsa encrypt key: %w", err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(infoEnc), base64.StdEncoding.EncodeToString(keyEnc), nil
|
||||
}
|
||||
|
||||
// urlPathname is the request's path without its /algo prefix or query, which
|
||||
// is what goes into the COSY signature.
|
||||
func urlPathname(rawURL string) string {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return strings.TrimSpace(rawURL)
|
||||
}
|
||||
path := u.Path
|
||||
if strings.HasPrefix(path, "/algo") {
|
||||
path = path[len("/algo"):]
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// BuildCosyHeaders builds the full set of COSY request headers for a Qoder
|
||||
// call to rawURL with body already in its wire (encoded) form.
|
||||
func BuildCosyHeaders(rawURL string, user *User, body string, timestamp int64) (map[string]string, error) {
|
||||
if user == nil || user.MachineID == "" {
|
||||
return nil, fmt.Errorf("qoder: missing account machine id")
|
||||
}
|
||||
infoB64, keyB64, err := generateUserBlob(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
requestID := strings.ReplaceAll(newUUID(), "-", "")
|
||||
if timestamp == 0 {
|
||||
timestamp = time.Now().Unix()
|
||||
}
|
||||
payloadObj := map[string]any{
|
||||
"version": "v1",
|
||||
"requestId": requestID,
|
||||
"info": infoB64,
|
||||
"cosyVersion": "1.1.49",
|
||||
"ideVersion": "",
|
||||
}
|
||||
payloadJSON, err := json.Marshal(payloadObj)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder: marshal cosy payload: %w", err)
|
||||
}
|
||||
payload := base64.StdEncoding.EncodeToString(payloadJSON)
|
||||
|
||||
path := urlPathname(rawURL)
|
||||
sig := cosySignature(payload, keyB64, timestamp, body, path)
|
||||
|
||||
auth := "Bearer COSY." + payload + "." + sig
|
||||
machineID := user.MachineID
|
||||
|
||||
return map[string]string{
|
||||
"Accept": "application/json",
|
||||
"Accept-Encoding": "identity",
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": auth,
|
||||
"Cosy-Business-Product": "app",
|
||||
"Cosy-Business-Type": "agent",
|
||||
"Cosy-ClientIp": machineID,
|
||||
"Cosy-ClientType": "10",
|
||||
"Cosy-Data-Policy": "disagree",
|
||||
"Cosy-Date": fmt.Sprintf("%d", timestamp),
|
||||
"Cosy-Key": keyB64,
|
||||
"Cosy-MachineId": machineID,
|
||||
"Cosy-MachineToken": machineID,
|
||||
"Cosy-MachineType": "5",
|
||||
"Cosy-MachineOS": MachineOS(),
|
||||
"Cosy-Scene": "app",
|
||||
"Cosy-User": user.UID,
|
||||
"Cosy-Version": "1.1.49",
|
||||
"Login-Version": "v2",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func cosySignature(payload, key string, timestamp int64, body, path string) string {
|
||||
sum := md5.Sum([]byte(payload + "\n" + key + "\n" + fmt.Sprintf("%d", timestamp) + "\n" + body + "\n" + path))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// MachineOS uses the architecture and platform names used by desktop clients.
|
||||
func MachineOS() string {
|
||||
arch := runtime.GOARCH
|
||||
switch arch {
|
||||
case "amd64":
|
||||
arch = "x86_64"
|
||||
case "386":
|
||||
arch = "x86"
|
||||
case "arm64":
|
||||
arch = "aarch64"
|
||||
}
|
||||
os := runtime.GOOS
|
||||
if os == "windows" {
|
||||
os = "win32"
|
||||
}
|
||||
return arch + "_" + os
|
||||
}
|
||||
+50
-80
@@ -1,63 +1,24 @@
|
||||
// Package qoder speaks Qoder's inference API (api3.qoder.sh
|
||||
// agent_chat_generation SSE) the way the Qoder desktop client does, so a
|
||||
// Qoder subscription can serve every agent through magpie's gateway. The
|
||||
// protocol (endpoints, the COSY request envelope, the body codec and the
|
||||
// device-flow sign-in) is ported from CLIProxyAPI's qoder support, which
|
||||
// reverse-engineered it from the client and verified it against live captures.
|
||||
// Package qoder holds what the move of Qoder's and Qoder CN's built-in
|
||||
// accounts onto their plugin reads: the sites' ids and names and the
|
||||
// credential kept in each account's auth blob. The credential's shape is
|
||||
// ported from CLIProxyAPI's qoder support.
|
||||
// Source: https://github.com/ufec/CLIProxyAPI (MIT); see LICENSE in this directory.
|
||||
// Copyright (c) 2025-2005.9 Luis Pater
|
||||
// Copyright (c) 2025.9-present Router-For.ME
|
||||
//
|
||||
// This package supports the global Qoder client (qoder.com) and Qoder CN
|
||||
// (qoder.cn), the China site whose accounts sign in with Alibaba Cloud or a
|
||||
// phone number and exist only there. A Site holds each one's hosts.
|
||||
package qoder
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
// are retired built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, moved or not. Their built-in
|
||||
// sign-in, models, requests and usage are gone; only the move, in
|
||||
// internal/provider/migrate_qoder.go, still reads their accounts. A fix
|
||||
// belongs in the plugin (github.com/magpie-community/plugins,
|
||||
// packages/qoder), with the movers' min raised in migrate_qoder.go.
|
||||
|
||||
// OAuth device-flow configuration (verified against live captures).
|
||||
const (
|
||||
// ClientID is Qoder's device-flow client id.
|
||||
ClientID = "732aef47-9cf2-46a2-95fe-4cebb5d0d1fa"
|
||||
|
||||
// DeviceFlowHost is the device-flow authorization page host.
|
||||
DeviceFlowHost = "https://qoder.com"
|
||||
|
||||
// OpenAPIHost is the API host for token polling and job-token exchange.
|
||||
OpenAPIHost = "https://openapi.qoder.sh"
|
||||
|
||||
// APIHost is the model inference API host.
|
||||
APIHost = "https://api3.qoder.sh"
|
||||
|
||||
// RedirectURI is Qoder's app scheme used by the device flow.
|
||||
RedirectURI = "qoder-app://"
|
||||
)
|
||||
|
||||
// API endpoints.
|
||||
const (
|
||||
DeviceSelectAccountsPath = "/device/selectAccounts"
|
||||
DeviceTokenPollPath = "/api/v1/deviceToken/poll"
|
||||
DeviceTokenRefreshPath = "/api/v1/deviceToken/refresh"
|
||||
JobTokenPath = "/api/v1/me/jobToken"
|
||||
JobTokenRefreshPath = "/api/v1/jobToken/refresh"
|
||||
|
||||
// ChatPath is the SSE chat endpoint. The query asks for the LLM result
|
||||
// to be fetched, names the common agent, and says Encode=1 to use the
|
||||
// custom base64 body codec.
|
||||
ChatPath = "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1"
|
||||
|
||||
// ListModelsPath is the live model listing endpoint.
|
||||
ListModelsPath = "/algo/api/v2/model/list?Encode=1"
|
||||
|
||||
// AccountUsagePath is the desktop client's account usage endpoint.
|
||||
AccountUsagePath = "/sash/api/v2/me/usage"
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// ProviderKey is how magpie names this subscription.
|
||||
@@ -67,33 +28,17 @@ const ProviderKey = "qoder"
|
||||
// id of Qoder CN's CLI agent.
|
||||
const CNProviderKey = "qoder-cn"
|
||||
|
||||
// CNClientID is the device-flow client id Qoder CN's own CLI
|
||||
// (@qodercn-ai/qoderclicn) sends to qoder.cn in production. The global CLI
|
||||
// carries the same id; the desktop id magpie uses on qoder.com is not known to
|
||||
// be registered on qoder.cn, so Qoder CN signs in as its CLI does.
|
||||
const CNClientID = "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb"
|
||||
|
||||
// Site is one Qoder deployment: the sign-in page, the account API and the
|
||||
// inference gateway, and the client id the sign-in names.
|
||||
// Site is one Qoder deployment.
|
||||
type Site struct {
|
||||
ID string // the provider id magpie keeps its accounts under
|
||||
Name string
|
||||
Web string // device-flow authorization page host
|
||||
OpenAPI string // token poll, job token, refresh, user info and usage
|
||||
API string // model list and chat
|
||||
ClientID string
|
||||
// RedirectURI goes on the authorization page; Qoder CN's CLI sends none.
|
||||
RedirectURI string
|
||||
ID string // the provider id magpie keeps its accounts under
|
||||
Name string
|
||||
}
|
||||
|
||||
// Global is qoder.com, what magpie's Qoder subscription has always used.
|
||||
var Global = &Site{ID: ProviderKey, Name: "Qoder", Web: DeviceFlowHost, OpenAPI: OpenAPIHost,
|
||||
API: APIHost, ClientID: ClientID, RedirectURI: RedirectURI}
|
||||
// Global is qoder.com.
|
||||
var Global = &Site{ID: ProviderKey, Name: "Qoder"}
|
||||
|
||||
// CN is qoder.cn, with the hosts Qoder CN's CLI builds in for its "cn" build:
|
||||
// openapi.qoder.com.cn for accounts and gateway.qoder.com.cn for inference.
|
||||
var CN = &Site{ID: CNProviderKey, Name: "Qoder CN", Web: "https://qoder.cn",
|
||||
OpenAPI: "https://openapi.qoder.com.cn", API: "https://gateway.qoder.com.cn", ClientID: CNClientID}
|
||||
// CN is qoder.cn.
|
||||
var CN = &Site{ID: CNProviderKey, Name: "Qoder CN"}
|
||||
|
||||
// SiteOf is the site a provider id or a credential's Site names; anything but
|
||||
// Qoder CN, including none, is the global site.
|
||||
@@ -104,8 +49,33 @@ func SiteOf(id string) *Site {
|
||||
return Global
|
||||
}
|
||||
|
||||
// ChatURL is the full chat endpoint on the site's inference host.
|
||||
func (s *Site) ChatURL() string { return s.API + ChatPath }
|
||||
// Credential is kept in the account's auth blob in magpie's logins.json.
|
||||
type Credential struct {
|
||||
UID string `json:"uid"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Token string `json:"token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
DeviceToken string `json:"device_token"`
|
||||
DeviceRefresh string `json:"device_refresh,omitempty"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
MachineID string `json:"machine_id"`
|
||||
Models json.RawMessage `json:"models,omitempty"`
|
||||
// Site is the Qoder site the account is on: CNProviderKey for Qoder CN,
|
||||
// empty for the global site (every credential saved before there were two).
|
||||
Site string `json:"site,omitempty"`
|
||||
// DeviceChat says Token is the device token itself, as Qoder CN's CLI
|
||||
// uses it.
|
||||
DeviceChat bool `json:"device_chat,omitempty"`
|
||||
}
|
||||
|
||||
// ChatURL is the global site's chat endpoint.
|
||||
func ChatURL() string { return Global.ChatURL() }
|
||||
// NewMachineID generates the stable identity kept with one account: a
|
||||
// random v4 UUID in the dashed 8-4-4-4-12 form.
|
||||
func NewMachineID() string {
|
||||
var b [16]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
b[6] = b[6]&0x0f | 0x40 // version 4
|
||||
b[8] = b[8]&0x3f | 0x80 // variant 10
|
||||
h := hex.EncodeToString(b[:])
|
||||
return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:32]
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package qoder
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
// NewMachineID generates the stable identity kept with one account.
|
||||
func NewMachineID() string { return newUUID() }
|
||||
|
||||
// newUUID returns a random v4 UUID in the dashed 8-4-4-4-12 form Qoder's
|
||||
// machine_id and nonce carry. A UUID source is kept local so magpie's Qoder
|
||||
// support needs no new dependency.
|
||||
func newUUID() string {
|
||||
var b [16]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
b[6] = b[6]&0x0f | 0x40 // version 4
|
||||
b[8] = b[8]&0x3f | 0x80 // variant 10
|
||||
h := hex.EncodeToString(b[:])
|
||||
return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:32]
|
||||
}
|
||||
|
||||
// NewID is a UUID without dashes, the shape Qoder's request ids and tool-call
|
||||
// ids use.
|
||||
func NewID() string {
|
||||
h := hex.EncodeToString(uuidBytes())
|
||||
return h
|
||||
}
|
||||
|
||||
func uuidBytes() []byte {
|
||||
var b [16]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
b[6] = b[6]&0x0f | 0x40
|
||||
b[8] = b[8]&0x3f | 0x80
|
||||
return b[:]
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package qoder
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// The tests run in a home of their own, never the user's real files.
|
||||
func TestMain(m *testing.M) { testenv.Main(m) }
|
||||
@@ -1,276 +0,0 @@
|
||||
package qoder
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
)
|
||||
|
||||
// ModelInfo is one entry of the model-list response's "chat" array. Only the
|
||||
// fields magpie uses are kept.
|
||||
type ModelInfo struct {
|
||||
Key string `json:"key"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Enable bool `json:"enable"`
|
||||
DisplayName string `json:"display_name,omitempty"`
|
||||
IsVL bool `json:"is_vl,omitempty"`
|
||||
IsReasoning bool `json:"is_reasoning,omitempty"`
|
||||
MaxInputTokens int `json:"max_input_tokens,omitempty"`
|
||||
Efforts []string `json:"reasoning_efforts,omitempty"`
|
||||
Config json.RawMessage `json:"-"`
|
||||
// From thinking_config: whether the model can think, whether it can't
|
||||
// stop, and the effort it thinks at unless asked for another.
|
||||
Thinks bool `json:"-"`
|
||||
AlwaysThinks bool `json:"-"`
|
||||
DefaultEffort string `json:"-"`
|
||||
// Free is set on a model that costs the plan no credits, as Qoder's
|
||||
// client shows it: a price_factor of 0 (see free).
|
||||
Free bool `json:"-"`
|
||||
// Rate is the credits a request costs, as a multiple (its
|
||||
// price_factor), and RateWas the price struck through beside it while
|
||||
// a discount runs (see free); 0 when the listing says none.
|
||||
Rate float64 `json:"-"`
|
||||
RateWas float64 `json:"-"`
|
||||
}
|
||||
|
||||
// promotion is a listing entry's running discount: a price_factor of 0
|
||||
// while it is active, with a price before it, is a discount, not a free
|
||||
// model.
|
||||
type promotion struct {
|
||||
Active bool `json:"active"`
|
||||
Before *float64 `json:"before_promotion_price_factor"`
|
||||
BeforeC *float64 `json:"beforePromotionPriceFactor"`
|
||||
Discount float64 `json:"discount_factor"`
|
||||
DiscountC float64 `json:"discountFactor"`
|
||||
}
|
||||
|
||||
// free reads whether a model costs the plan no credits: a price_factor (the
|
||||
// credits a request costs, as a multiple; priceFactor in camel case) of 0,
|
||||
// the price Qoder's own client shows ("0×"). is_free is no word on that:
|
||||
// Qoder's listing has it true on Qwen3.8-Max at 0.5×, an off-peak discount
|
||||
// (错峰 4 折) on it, and Qoder's client shows the price, not it. It is taken
|
||||
// only from a listing with no price at all. A price of 0 for the while an
|
||||
// active promotion lasts, with a price before it, is a discount, not a free
|
||||
// model; a limited-time free model (Qwen3.8-Flash: 0×, its
|
||||
// original_price_factor 0.1 struck through) is free while it is. The same
|
||||
// rule as the plugin's freeOf (packages/qoder/index.mjs).
|
||||
//
|
||||
// The price is kept too (Rate), as Qoder's client shows it beside the
|
||||
// model: 0.5×, and the price before a discount struck through (RateWas):
|
||||
// an active promotion's before_promotion_price_factor, else an
|
||||
// original_price_factor above the price. A promotion's 0 that isn't free
|
||||
// is its price before times its discount_factor.
|
||||
func (m *ModelInfo) free(raw json.RawMessage) {
|
||||
var v struct {
|
||||
IsFree *bool `json:"is_free"`
|
||||
IsFreeC *bool `json:"isFree"`
|
||||
PriceFactor *float64 `json:"price_factor"`
|
||||
PriceC *float64 `json:"priceFactor"`
|
||||
Original float64 `json:"original_price_factor"`
|
||||
OriginalC float64 `json:"originalPriceFactor"`
|
||||
Promotion *promotion `json:"promotion"`
|
||||
PromotionT *promotion `json:"prommotion"`
|
||||
}
|
||||
if json.Unmarshal(raw, &v) != nil {
|
||||
return
|
||||
}
|
||||
if v.IsFree == nil {
|
||||
v.IsFree = v.IsFreeC
|
||||
}
|
||||
if v.PriceFactor == nil {
|
||||
v.PriceFactor = v.PriceC
|
||||
}
|
||||
if v.Promotion == nil {
|
||||
v.Promotion = v.PromotionT
|
||||
}
|
||||
if v.PriceFactor != nil {
|
||||
p := v.Promotion
|
||||
if p != nil && p.Before == nil {
|
||||
p.Before = p.BeforeC
|
||||
}
|
||||
if p != nil && p.Discount == 0 {
|
||||
p.Discount = p.DiscountC
|
||||
}
|
||||
discounted := p != nil && p.Active && p.Before != nil && *p.Before > 0
|
||||
m.Rate, m.RateWas = max(*v.PriceFactor, 0), max(v.Original, v.OriginalC)
|
||||
if discounted {
|
||||
m.RateWas = *p.Before
|
||||
if m.Rate == 0 {
|
||||
m.Rate = *p.Before * p.Discount
|
||||
}
|
||||
}
|
||||
if m.RateWas <= m.Rate {
|
||||
m.RateWas = 0
|
||||
}
|
||||
m.Free = *v.PriceFactor == 0 && !discounted
|
||||
return
|
||||
}
|
||||
m.Free = v.IsFree != nil && *v.IsFree
|
||||
}
|
||||
|
||||
// effortOrder ranks Qoder's effort names, lowest first.
|
||||
var effortOrder = []string{"minimal", "low", "medium", "high", "xhigh", "max"}
|
||||
|
||||
// thinking reads the listing's thinking_config, where Qoder keeps the
|
||||
// efforts a model offers and its default; is_reasoning alone stands for a
|
||||
// model listed without one.
|
||||
func (m *ModelInfo) thinking(raw json.RawMessage) {
|
||||
var v struct {
|
||||
Config *struct {
|
||||
Disabled json.RawMessage `json:"disabled"`
|
||||
Enabled *struct {
|
||||
Efforts map[string]struct {
|
||||
IsDefault bool `json:"is_default"`
|
||||
} `json:"efforts"`
|
||||
} `json:"enabled"`
|
||||
} `json:"thinking_config"`
|
||||
}
|
||||
m.Thinks = m.IsReasoning
|
||||
if json.Unmarshal(raw, &v) != nil || v.Config == nil {
|
||||
return
|
||||
}
|
||||
m.Thinks = v.Config.Enabled != nil
|
||||
m.AlwaysThinks = m.Thinks && len(v.Config.Disabled) == 0
|
||||
m.Efforts = nil
|
||||
if !m.Thinks {
|
||||
return
|
||||
}
|
||||
for name, e := range v.Config.Enabled.Efforts {
|
||||
m.Efforts = append(m.Efforts, name)
|
||||
if e.IsDefault {
|
||||
m.DefaultEffort = name
|
||||
}
|
||||
}
|
||||
rank := func(s string) int {
|
||||
for i, e := range effortOrder {
|
||||
if e == s {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return len(effortOrder)
|
||||
}
|
||||
sort.Slice(m.Efforts, func(i, j int) bool {
|
||||
if rank(m.Efforts[i]) != rank(m.Efforts[j]) {
|
||||
return rank(m.Efforts[i]) < rank(m.Efforts[j])
|
||||
}
|
||||
return m.Efforts[i] < m.Efforts[j]
|
||||
})
|
||||
}
|
||||
|
||||
// FetchModels retrieves the raw model listing for a signed-in user. The
|
||||
// request carries the same COSY envelope the client uses for every /algo
|
||||
// call; an empty body is signed for a GET.
|
||||
func FetchModels(ctx context.Context, client *http.Client, baseURL string, user *User) ([]byte, error) {
|
||||
if client == nil {
|
||||
client = &http.Client{}
|
||||
}
|
||||
if user == nil || strings.TrimSpace(user.Token) == "" || strings.TrimSpace(user.UID) == "" {
|
||||
return nil, fmt.Errorf("qoder: uid and token are required to fetch models")
|
||||
}
|
||||
url := strings.TrimRight(baseURL, "/") + ListModelsPath
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder: build models request: %w", err)
|
||||
}
|
||||
cosy, err := BuildCosyHeaders(url, user, "", 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder: build cosy headers: %w", err)
|
||||
}
|
||||
for k, v := range cosy {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder models request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder models: read response: %w", err)
|
||||
}
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return nil, fmt.Errorf("qoder models: HTTP %d: %s", resp.StatusCode, sanitize(body))
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func sanitize(body []byte) string {
|
||||
s := strings.TrimSpace(string(body))
|
||||
if len(s) > 512 {
|
||||
s = s[:512] + "..."
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ParseModels decodes the listing and returns the enabled, routable chat
|
||||
// models as magpie's catalog entries. Placeholder ids ("auto", "default")
|
||||
// are dropped: they route between models inside Qoder and aren't a single
|
||||
// model an agent can pick. provider is the magpie provider id the entries are
|
||||
// listed under (ProviderKey or CNProviderKey).
|
||||
func ParseModels(body []byte, provider string) ([]catalog.Model, error) {
|
||||
models, err := ModelConfigs(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []catalog.Model
|
||||
for _, m := range models {
|
||||
name := m.DisplayName
|
||||
if name == "" {
|
||||
name = m.Key
|
||||
}
|
||||
out = append(out, catalog.Model{ID: m.Key, Name: name, Provider: provider,
|
||||
Context: m.MaxInputTokens, Images: m.IsVL, Efforts: m.Efforts, Free: m.Free,
|
||||
Rate: m.Rate, RateWas: m.RateWas})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ModelConfigs preserves each enabled model's complete upstream configuration.
|
||||
func ModelConfigs(body []byte) ([]ModelInfo, error) {
|
||||
var resp struct {
|
||||
Chat []json.RawMessage `json:"chat"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &resp); err != nil {
|
||||
return nil, fmt.Errorf("qoder: invalid models json: %w", err)
|
||||
}
|
||||
var out []ModelInfo
|
||||
for _, raw := range resp.Chat {
|
||||
var m ModelInfo
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !m.Enable || !IsRoutableModel(m.Key) {
|
||||
continue
|
||||
}
|
||||
m.Config = raw
|
||||
m.thinking(raw)
|
||||
m.free(raw)
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// IsRoutableModel reports whether a model key names one model an agent can
|
||||
// pick. Aggregate entries ("auto", "default") route inside Qoder and aren't.
|
||||
func IsRoutableModel(key string) bool {
|
||||
switch strings.TrimSpace(key) {
|
||||
case "", "auto", "default":
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package qoder
|
||||
|
||||
import "testing"
|
||||
|
||||
// A model at a price_factor of 0 is free, in snake or camel case; is_free
|
||||
// counts only on a listing with no price.
|
||||
func TestParseModelsFree(t *testing.T) {
|
||||
body := []byte(`{"chat":[
|
||||
{"key":"flag","enable":true,"is_free":true,"price_factor":1},
|
||||
{"key":"camel-flag","enable":true,"isFree":true},
|
||||
{"key":"zero","enable":true,"price_factor":0},
|
||||
{"key":"camel-zero","enable":true,"priceFactor":0},
|
||||
{"key":"paid","enable":true,"is_free":false,"price_factor":0.5},
|
||||
{"key":"unsaid","enable":true}
|
||||
]}`)
|
||||
ms, err := ParseModels(body, ProviderKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[string]bool{"flag": false, "camel-flag": true, "zero": true, "camel-zero": true, "paid": false, "unsaid": false}
|
||||
if len(ms) != len(want) {
|
||||
t.Fatalf("models %+v", ms)
|
||||
}
|
||||
for _, m := range ms {
|
||||
if m.Free != want[m.ID] {
|
||||
t.Errorf("%s: Free = %v, want %v", m.ID, m.Free, want[m.ID])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Qoder's listing as it came on 2026-10-02: its app shows Qwen3.8-Max at
|
||||
// 0.5× with an off-peak badge (错峰 4 折), Qwen3.8-Flash at 0× with 0.1×
|
||||
// struck through — both carry is_free true. Only Flash is free.
|
||||
func TestParseModelsFreeIsThePrice(t *testing.T) {
|
||||
offPeak := `{"active":false,"badge":{"en":"Off-Peak 60% off","zh":"错峰 4 折"},"timezone":"Asia/Singapore","rule_id":"idle_time_model_credit_discount","discount_factor":0.4,"before_promotion_price_factor":0.5,"window_start":"22:00","window_end":"08:00"}`
|
||||
body := []byte(`{"chat":[
|
||||
{"key":"qmodel_38max","display_name":"Qwen3.8-Max","enable":true,"is_reasoning":true,"price_factor":0.5,"is_free":true,"promotion":` + offPeak + `},
|
||||
{"key":"qfmodel","display_name":"Qwen3.8-Flash","enable":true,"is_reasoning":true,"price_factor":0.0,"original_price_factor":0.1,"is_free":true},
|
||||
{"key":"qmodel_latest","display_name":"Qwen3.7-Max","enable":true,"price_factor":0.5,"original_price_factor":0.5},
|
||||
{"key":"kmodel_latest","display_name":"Kimi-K3","enable":true,"price_factor":1.4,"is_free":false},
|
||||
{"key":"window","enable":true,"price_factor":0,"is_free":true,"promotion":{"active":true,"discount_factor":0.0001,"before_promotion_price_factor":0.5}},
|
||||
{"key":"window-camel","enable":true,"priceFactor":0,"promotion":{"active":true,"beforePromotionPriceFactor":1}},
|
||||
{"key":"over","enable":true,"price_factor":0,"promotion":{"active":false,"before_promotion_price_factor":0.5}},
|
||||
{"key":"nothing","enable":true,"price_factor":0,"promotion":{"active":true,"before_promotion_price_factor":0}},
|
||||
{"key":"unpriced","enable":true,"is_free":true},
|
||||
{"key":"unpriced2","enable":true,"is_free":false}
|
||||
]}`)
|
||||
ms, err := ParseModels(body, ProviderKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[string]bool{"qmodel_38max": false, "qfmodel": true, "qmodel_latest": false, "kmodel_latest": false,
|
||||
"window": false, "window-camel": false, "over": true, "nothing": true, "unpriced": true, "unpriced2": false}
|
||||
if len(ms) != len(want) {
|
||||
t.Fatalf("models %+v", ms)
|
||||
}
|
||||
for _, m := range ms {
|
||||
if m.Free != want[m.ID] {
|
||||
t.Errorf("%s: Free = %v, want %v", m.ID, m.Free, want[m.ID])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Each model carries its price as Qoder's client shows it beside the
|
||||
// model (01huadalang on Discord: pick the cheap ones without opening
|
||||
// Qoder): Qwen3.8-Max 0.5×, Kimi-K3 1.4×, Qwen3.8-Flash 0× (free) with
|
||||
// 0.1× struck through; a running promotion's price before it struck
|
||||
// through, and its 0 that isn't free read as that price times its
|
||||
// discount. A listing with no price gives none.
|
||||
func TestParseModelsRate(t *testing.T) {
|
||||
body := []byte(`{"chat":[
|
||||
{"key":"qmodel_38max","enable":true,"price_factor":0.5,"is_free":true,"promotion":{"active":false,"discount_factor":0.4,"before_promotion_price_factor":0.5}},
|
||||
{"key":"qmodel_38max-offpeak","enable":true,"price_factor":0.2,"promotion":{"active":true,"discount_factor":0.4,"before_promotion_price_factor":0.5}},
|
||||
{"key":"qfmodel","enable":true,"price_factor":0.0,"original_price_factor":0.1,"is_free":true},
|
||||
{"key":"qmodel_latest","enable":true,"price_factor":0.5,"original_price_factor":0.5},
|
||||
{"key":"kmodel_latest","enable":true,"priceFactor":1.4,"originalPriceFactor":2},
|
||||
{"key":"window","enable":true,"price_factor":0,"promotion":{"active":true,"discount_factor":0.5,"before_promotion_price_factor":1}},
|
||||
{"key":"window-camel","enable":true,"priceFactor":0,"promotion":{"active":true,"discountFactor":0.25,"beforePromotionPriceFactor":2}},
|
||||
{"key":"unpriced","enable":true,"is_free":true}
|
||||
]}`)
|
||||
ms, err := ParseModels(body, ProviderKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[string][2]float64{"qmodel_38max": {0.5, 0}, "qmodel_38max-offpeak": {0.2, 0.5}, "qfmodel": {0, 0.1},
|
||||
"qmodel_latest": {0.5, 0}, "kmodel_latest": {1.4, 2}, "window": {0.5, 1}, "window-camel": {0.5, 2}, "unpriced": {0, 0}}
|
||||
if len(ms) != len(want) {
|
||||
t.Fatalf("models %+v", ms)
|
||||
}
|
||||
for _, m := range ms {
|
||||
if w := want[m.ID]; m.Rate != w[0] || m.RateWas != w[1] {
|
||||
t.Errorf("%s: Rate, RateWas = %v, %v, want %v, %v", m.ID, m.Rate, m.RateWas, w[0], w[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
package qoder
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DeviceToken is the dt- device token a finished device flow returns.
|
||||
type DeviceToken struct {
|
||||
Token string `json:"token"`
|
||||
DeviceToken string `json:"device_token,omitempty"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
UserID string `json:"user_id"`
|
||||
UserName string `json:"user_name,omitempty"`
|
||||
// ExpiresIn (seconds) or ExpiresAt (a date) is the token's lifetime, as
|
||||
// Qoder's CLI reads it; either may be missing.
|
||||
ExpiresIn int64 `json:"expires_in,omitempty"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
}
|
||||
|
||||
// Expiry is when the device token lapses; zero when Qoder said nothing.
|
||||
func (t DeviceToken) Expiry() time.Time {
|
||||
if at, err := time.Parse(time.RFC3339, strings.TrimSpace(t.ExpiresAt)); err == nil {
|
||||
return at
|
||||
}
|
||||
if t.ExpiresIn > 0 {
|
||||
return time.Now().Add(time.Duration(t.ExpiresIn) * time.Second)
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
// JobToken is the jt- task token that authorizes the model calls.
|
||||
type JobToken struct {
|
||||
Token string `json:"token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
// ExpiresIn is Qoder's lifetime for the token, in milliseconds.
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
}
|
||||
|
||||
// Expiry is the job token's lifetime as a duration; zero when Qoder said none.
|
||||
func (r JobToken) Expiry() time.Duration {
|
||||
if r.ExpiresIn <= 0 {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(r.ExpiresIn) * time.Millisecond
|
||||
}
|
||||
|
||||
// DeviceFlow runs Qoder's sign-in: an authorization page the user opens, then
|
||||
// a poll for the device token, then its exchange for the job token that serves
|
||||
// models. It is a helper, not a state machine: the caller owns the browser and
|
||||
// the waiting, and calls these one at a time.
|
||||
type DeviceFlow struct {
|
||||
client *http.Client
|
||||
site *Site
|
||||
machineID string
|
||||
}
|
||||
|
||||
// NewDeviceFlow makes a flow on site (nil is the global one); a nil client is
|
||||
// a 20-second-timeout one.
|
||||
func NewDeviceFlow(client *http.Client, site *Site) *DeviceFlow {
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 20 * time.Second}
|
||||
}
|
||||
if site == nil {
|
||||
site = Global
|
||||
}
|
||||
return &DeviceFlow{client: client, site: site, machineID: newUUID()}
|
||||
}
|
||||
|
||||
// Site is the Qoder site the flow signs in on.
|
||||
func (f *DeviceFlow) Site() *Site { return f.site }
|
||||
|
||||
// Client is the flow's HTTP client, reused for the model fetch after sign-in.
|
||||
func (f *DeviceFlow) Client() *http.Client { return f.client }
|
||||
|
||||
func (f *DeviceFlow) MachineID() string { return f.machineID }
|
||||
|
||||
// Authorization returns the page to open and the (verifier, nonce) the poll
|
||||
// needs. It is a PKCE device flow: a random verifier is kept, its S256 digest
|
||||
// is what the page sees.
|
||||
func (f *DeviceFlow) Authorization() (authURL, verifier, nonce string, err error) {
|
||||
raw := make([]byte, 64)
|
||||
if _, err = rand.Read(raw); err != nil {
|
||||
return "", "", "", fmt.Errorf("qoder auth url: random verifier: %w", err)
|
||||
}
|
||||
verifier = base64.RawURLEncoding.EncodeToString(raw)
|
||||
sum := sha256.Sum256([]byte(verifier))
|
||||
challenge := base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
nonce = newUUID()
|
||||
q := url.Values{}
|
||||
q.Set("challenge", challenge)
|
||||
q.Set("challenge_method", "S256")
|
||||
q.Set("nonce", nonce)
|
||||
q.Set("machine_id", f.machineID)
|
||||
q.Set("client_id", f.site.ClientID)
|
||||
if f.site.RedirectURI != "" {
|
||||
q.Set("redirect_uri", f.site.RedirectURI)
|
||||
}
|
||||
return f.site.Web + DeviceSelectAccountsPath + "?" + q.Encode(), verifier, nonce, nil
|
||||
}
|
||||
|
||||
// PollDeviceToken asks for the device token until the user has authorized it,
|
||||
// ctx ends the wait, or interval elapses between tries.
|
||||
func (f *DeviceFlow) PollDeviceToken(ctx context.Context, nonce, verifier string, interval time.Duration) (*DeviceToken, error) {
|
||||
if interval <= 0 {
|
||||
interval = 2 * time.Second
|
||||
}
|
||||
endpoint := f.site.OpenAPI + DeviceTokenPollPath
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("qoder device poll: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder device poll: create request: %w", err)
|
||||
}
|
||||
q := req.URL.Query()
|
||||
q.Set("nonce", nonce)
|
||||
q.Set("verifier", verifier)
|
||||
q.Set("challenge_method", "S256")
|
||||
req.URL.RawQuery = q.Encode()
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := f.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder device poll: request failed: %w", err)
|
||||
}
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
var t DeviceToken
|
||||
if json.Unmarshal(body, &t) == nil && strings.TrimSpace(t.Token) != "" {
|
||||
return &t, nil
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, fmt.Errorf("qoder device poll: %w", ctx.Err())
|
||||
case <-time.After(interval):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// JobToken trades a device token for the job token the model calls use.
|
||||
func (f *DeviceFlow) JobToken(ctx context.Context, deviceToken string) (*JobToken, error) {
|
||||
body, _ := json.Marshal(map[string]string{"clientId": f.site.ClientID})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, f.site.OpenAPI+JobTokenPath, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder job token: create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+deviceToken)
|
||||
resp, err := f.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder job token: request failed: %w", err)
|
||||
}
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, &JobTokenHTTPError{StatusCode: resp.StatusCode, Body: sanitize(raw)}
|
||||
}
|
||||
var t JobToken
|
||||
if err := json.Unmarshal(raw, &t); err != nil {
|
||||
return nil, fmt.Errorf("qoder job token: decode: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(t.Token) == "" {
|
||||
return nil, fmt.Errorf("qoder job token: empty token in response")
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
// JobTokenHTTPError is a refused device-to-job token exchange.
|
||||
type JobTokenHTTPError struct {
|
||||
StatusCode int
|
||||
Body string
|
||||
}
|
||||
|
||||
func (e *JobTokenHTTPError) Error() string {
|
||||
return fmt.Sprintf("qoder job token: status %d: %s", e.StatusCode, e.Body)
|
||||
}
|
||||
|
||||
// RefreshJobToken trades a job token's refresh token for a new pair on site
|
||||
// (nil is the global one). The old refresh token is spent, so the caller must
|
||||
// keep the new one.
|
||||
func RefreshJobToken(ctx context.Context, client *http.Client, site *Site, refreshToken string) (*JobToken, error) {
|
||||
if strings.TrimSpace(refreshToken) == "" {
|
||||
return nil, fmt.Errorf("qoder job token refresh: missing refresh token; sign in again")
|
||||
}
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 20 * time.Second}
|
||||
}
|
||||
if site == nil {
|
||||
site = Global
|
||||
}
|
||||
return postJobRefresh(ctx, client, site.OpenAPI+JobTokenRefreshPath, refreshToken)
|
||||
}
|
||||
|
||||
func postJobRefresh(ctx context.Context, client *http.Client, endpoint, refreshToken string) (*JobToken, error) {
|
||||
body, _ := json.Marshal(map[string]string{"refresh_token": refreshToken})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder job token refresh: create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder job token refresh: request failed: %w", err)
|
||||
}
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, &JobTokenRefreshHTTPError{StatusCode: resp.StatusCode}
|
||||
}
|
||||
var t JobToken
|
||||
if err := json.Unmarshal(raw, &t); err != nil {
|
||||
return nil, fmt.Errorf("qoder job token refresh: decode: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(t.Token) == "" || strings.TrimSpace(t.RefreshToken) == "" {
|
||||
return nil, fmt.Errorf("qoder job token refresh: incomplete token pair")
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
// JobTokenRefreshHTTPError preserves a rejected job-token refresh status.
|
||||
type JobTokenRefreshHTTPError struct {
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
func (e *JobTokenRefreshHTTPError) Error() string {
|
||||
return fmt.Sprintf("qoder job token refresh: status %d", e.StatusCode)
|
||||
}
|
||||
|
||||
// DeviceTokenRefreshHTTPError preserves a rejected refresh status without response data.
|
||||
type DeviceTokenRefreshHTTPError struct {
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
func (e *DeviceTokenRefreshHTTPError) Error() string {
|
||||
return fmt.Sprintf("qoder device token refresh: upstream HTTP %d", e.StatusCode)
|
||||
}
|
||||
|
||||
// RefreshDeviceToken rotates the device token used by account endpoints; an
|
||||
// empty endpoint is the global site's.
|
||||
func RefreshDeviceToken(ctx context.Context, client *http.Client, endpoint, refreshToken string) (*DeviceToken, error) {
|
||||
if strings.TrimSpace(refreshToken) == "" {
|
||||
return nil, fmt.Errorf("qoder device token refresh: missing refresh token; sign in again")
|
||||
}
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 20 * time.Second}
|
||||
}
|
||||
if endpoint == "" {
|
||||
endpoint = Global.OpenAPI + DeviceTokenRefreshPath
|
||||
}
|
||||
body, err := json.Marshal(map[string]string{"refresh_token": refreshToken})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder device token refresh: marshal: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(string(body)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder device token refresh: create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder device token refresh: request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, &DeviceTokenRefreshHTTPError{StatusCode: resp.StatusCode}
|
||||
}
|
||||
var token DeviceToken
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&token); err != nil {
|
||||
return nil, fmt.Errorf("qoder device token refresh: decode: %w", err)
|
||||
}
|
||||
if token.Token == "" {
|
||||
token.Token = token.DeviceToken
|
||||
}
|
||||
if strings.TrimSpace(token.Token) == "" || strings.TrimSpace(token.RefreshToken) == "" {
|
||||
return nil, fmt.Errorf("qoder device token refresh: incomplete token pair")
|
||||
}
|
||||
return &token, nil
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package qoder
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestSites: the global site is qoder.com as it always was, Qoder CN is
|
||||
// qoder.cn with its CLI's client id and no redirect, and anything that isn't
|
||||
// Qoder CN, a credential with no site included, is the global site.
|
||||
func TestSites(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
site *Site
|
||||
page, client, redirect string
|
||||
chat string
|
||||
}{
|
||||
{Global, "https://qoder.com", ClientID, RedirectURI, "https://api3.qoder.sh" + ChatPath},
|
||||
{CN, "https://qoder.cn", CNClientID, "", "https://gateway.qoder.com.cn" + ChatPath},
|
||||
} {
|
||||
authURL, _, _, err := NewDeviceFlow(nil, tt.site).Authorization()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, _ := url.Parse(authURL)
|
||||
if u.Scheme+"://"+u.Host != tt.page || u.Path != DeviceSelectAccountsPath || u.Query().Get("client_id") != tt.client || u.Query().Get("redirect_uri") != tt.redirect {
|
||||
t.Errorf("%s: %s", tt.site.ID, authURL)
|
||||
}
|
||||
if tt.site.ChatURL() != tt.chat {
|
||||
t.Errorf("%s chat %s", tt.site.ID, tt.site.ChatURL())
|
||||
}
|
||||
}
|
||||
if CN.OpenAPI != "https://openapi.qoder.com.cn" || SiteOf("qoder-cn") != CN || SiteOf("qoder") != Global || SiteOf("") != Global || ChatURL() != Global.ChatURL() {
|
||||
t.Fatal("site table")
|
||||
}
|
||||
var legacy Credential
|
||||
_ = json.Unmarshal([]byte(`{"uid":"u","token":"jt"}`), &legacy)
|
||||
if legacy.OnSite() != Global {
|
||||
t.Fatal("a credential without a site isn't global")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCNDeviceChatRefresh: a Qoder CN credential whose chat token is the
|
||||
// device token refreshes on Qoder CN's device refresh, not the job one.
|
||||
func TestCNDeviceChatRefresh(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != DeviceTokenRefreshPath {
|
||||
t.Errorf("path %s", r.URL.Path)
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"token":"dt-2","refresh_token":"drt-2","expires_at":"` + time.Now().Add(3*time.Hour).UTC().Format(time.RFC3339) + `"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
host := CN.OpenAPI
|
||||
CN.OpenAPI = srv.URL
|
||||
defer func() { CN.OpenAPI = host }()
|
||||
c := Credential{UID: "u", Token: "dt-1", RefreshToken: "drt-1", DeviceToken: "dt-1", DeviceRefresh: "drt-1", Site: CNProviderKey, DeviceChat: true}
|
||||
fresh, err := c.Refresh(context.Background(), srv.Client())
|
||||
if err != nil || fresh.Token != "dt-2" || fresh.DeviceToken != "dt-2" || fresh.RefreshToken != "drt-2" || fresh.DeviceRefresh != "drt-2" {
|
||||
t.Fatalf("%+v %v", fresh, err)
|
||||
}
|
||||
if left := time.Until(time.UnixMilli(fresh.ExpiresAt)); left < 2*time.Hour || left > 3*time.Hour {
|
||||
t.Fatalf("lifetime %v", left)
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package qoder
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Credential is kept in the account's auth blob in magpie's logins.json.
|
||||
type Credential struct {
|
||||
UID string `json:"uid"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Token string `json:"token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
DeviceToken string `json:"device_token"`
|
||||
DeviceRefresh string `json:"device_refresh,omitempty"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
MachineID string `json:"machine_id"`
|
||||
Models json.RawMessage `json:"models,omitempty"`
|
||||
// Site is the Qoder site the account is on: CNProviderKey for Qoder CN,
|
||||
// empty for the global site (every credential saved before there were two).
|
||||
Site string `json:"site,omitempty"`
|
||||
// DeviceChat says Token is the device token itself, as Qoder CN's CLI
|
||||
// uses it, because the site refused to trade it for a job token; it is
|
||||
// then refreshed as a device token.
|
||||
DeviceChat bool `json:"device_chat,omitempty"`
|
||||
}
|
||||
|
||||
// OnSite is the Qoder site the credential belongs to.
|
||||
func (c *Credential) OnSite() *Site { return SiteOf(c.Site) }
|
||||
|
||||
const refreshLead = 5 * time.Minute
|
||||
|
||||
func (c *Credential) Valid() bool {
|
||||
return c != nil && c.Token != "" && c.ExpiresAt-time.Now().UnixMilli() > int64(refreshLead/time.Millisecond)
|
||||
}
|
||||
|
||||
// Refresh returns a new credential value. The caller serializes the entire
|
||||
// check, refresh and save operation, since refresh tokens rotate on use.
|
||||
func (c Credential) Refresh(ctx context.Context, client *http.Client) (Credential, error) {
|
||||
if c.RefreshToken == "" {
|
||||
return Credential{}, fmt.Errorf("qoder: the sign-in lapsed; sign in again")
|
||||
}
|
||||
if c.DeviceChat {
|
||||
dt, err := RefreshDeviceToken(ctx, client, c.OnSite().OpenAPI+DeviceTokenRefreshPath, c.RefreshToken)
|
||||
if err != nil {
|
||||
// a refused refresh is as final as a refused job refresh
|
||||
var refused *DeviceTokenRefreshHTTPError
|
||||
if errors.As(err, &refused) {
|
||||
return Credential{}, &JobTokenRefreshHTTPError{StatusCode: refused.StatusCode}
|
||||
}
|
||||
return Credential{}, err
|
||||
}
|
||||
c.Token, c.RefreshToken = dt.Token, dt.RefreshToken
|
||||
c.DeviceToken, c.DeviceRefresh = dt.Token, dt.RefreshToken
|
||||
c.ExpiresAt = DeviceExpiry(*dt).UnixMilli()
|
||||
return c, nil
|
||||
}
|
||||
jt, err := RefreshJobToken(ctx, client, c.OnSite(), c.RefreshToken)
|
||||
if err != nil {
|
||||
return Credential{}, err
|
||||
}
|
||||
c.Token, c.RefreshToken = jt.Token, jt.RefreshToken
|
||||
life := jt.Expiry()
|
||||
if life <= 0 {
|
||||
life = 24 * time.Hour
|
||||
}
|
||||
c.ExpiresAt = time.Now().Add(life).UnixMilli()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// DeviceExpiry is when a device token used for chat is taken to lapse: what
|
||||
// Qoder said, else a day, as a job token without a lifetime is.
|
||||
func DeviceExpiry(t DeviceToken) time.Time {
|
||||
if at := t.Expiry(); !at.IsZero() {
|
||||
return at
|
||||
}
|
||||
return time.Now().Add(24 * time.Hour)
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package qoder
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// UsageHTTPError preserves the upstream status without exposing response data.
|
||||
type UsageHTTPError struct {
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
func (e *UsageHTTPError) Error() string {
|
||||
return fmt.Sprintf("qoder usage: upstream HTTP %d", e.StatusCode)
|
||||
}
|
||||
|
||||
// FetchUsage retrieves the account usage envelope using a device token; an
|
||||
// empty baseURL is the global site's account host.
|
||||
func FetchUsage(ctx context.Context, client *http.Client, baseURL, deviceToken string) (json.RawMessage, error) {
|
||||
if strings.TrimSpace(deviceToken) == "" {
|
||||
return nil, fmt.Errorf("qoder usage: missing device token")
|
||||
}
|
||||
if client == nil {
|
||||
client = &http.Client{}
|
||||
}
|
||||
if baseURL == "" {
|
||||
baseURL = Global.OpenAPI
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(baseURL, "/")+AccountUsagePath, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder usage: create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+deviceToken)
|
||||
req.Header.Set("Cosy-ClientType", "10")
|
||||
req.Header.Set("User-Agent", "Qoder")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder usage: request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, &UsageHTTPError{StatusCode: resp.StatusCode}
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder usage: read response: %w", err)
|
||||
}
|
||||
var envelope struct {
|
||||
DisplayMode string `json:"displayMode"`
|
||||
QoderUsage json.RawMessage `json:"qoderUsage"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &envelope); err != nil {
|
||||
return nil, fmt.Errorf("qoder usage: decode response: %w", err)
|
||||
}
|
||||
if envelope.DisplayMode != "qoder" && envelope.DisplayMode != "enterprise" {
|
||||
return nil, fmt.Errorf("qoder usage: unknown display mode")
|
||||
}
|
||||
if envelope.DisplayMode == "qoder" && (len(envelope.QoderUsage) == 0 || string(envelope.QoderUsage) == "null") {
|
||||
return nil, fmt.Errorf("qoder usage: missing quota data")
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package qoder
|
||||
|
||||
// PLUGIN-SERVED (see AGENTS.md): Qoder ("qoder") and Qoder CN ("qoder-cn")
|
||||
// are deprecated built-in subscriptions served by their plugin,
|
||||
// @magpie-community/opencode-qoder-auth, each once moved onto it
|
||||
// (provider.Moved; the default for a new sign-in). A moved one's
|
||||
// sign-ins, models, requests and usage are all the plugin's, never this
|
||||
// code's (only the move, in migrate*.go, still reads its accounts). A fix here alone doesn't reach those users; fix the plugin
|
||||
// (github.com/magpie-community/plugins, packages/qoder) and raise the
|
||||
// movers' min in internal/provider/migrate_qoder.go.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// UserInfoPath is the account endpoint, asked with the dt- device token (not
|
||||
// the jt- job token). It answers who the signed-in account is.
|
||||
const UserInfoPath = "/api/v1/userinfo"
|
||||
|
||||
// UserInfo is what the account endpoint says about a signed-in account.
|
||||
type UserInfo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Avatar string `json:"avatar"`
|
||||
Source string `json:"source"`
|
||||
OrgName string `json:"organization_name"`
|
||||
HighestTier bool `json:"is_highest_tier"`
|
||||
}
|
||||
|
||||
// FetchUserInfo asks site's account endpoint (nil is the global one) with a
|
||||
// device token. The device token is short-lived but outlasts the sign-in that
|
||||
// just made it, so this runs during the flow while it is fresh.
|
||||
func FetchUserInfo(ctx context.Context, client *http.Client, site *Site, deviceToken string) (*UserInfo, error) {
|
||||
if strings.TrimSpace(deviceToken) == "" {
|
||||
return nil, fmt.Errorf("qoder userinfo: missing device token")
|
||||
}
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 20 * time.Second}
|
||||
}
|
||||
if site == nil {
|
||||
site = Global
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, site.OpenAPI+UserInfoPath, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder userinfo: create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+deviceToken)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder userinfo: request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("qoder userinfo: read response: %w", err)
|
||||
}
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return nil, fmt.Errorf("qoder userinfo: HTTP %d: %s", resp.StatusCode, sanitize(body))
|
||||
}
|
||||
var u UserInfo
|
||||
if err := json.Unmarshal(body, &u); err != nil {
|
||||
return nil, fmt.Errorf("qoder userinfo: decode: %w", err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
Reference in New Issue
Block a user