diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 45305bb33..b021c16b3 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1642,6 +1642,11 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid // ("only available via Cline product surfaces") without provider.ClineClient(req.Header) } + if p.IsKilo() { + // as the Kilo CLI sends it, signed out when the provider has no + // key: the gateway serves its free models to anyone + provider.KiloClient(req.Header, p.Key, conversationID(in, body)) + } if p.Account != nil && p.Account.Agent == "codex" { // what Codex says about the request goes on as codexUpstream // relays it — a subagent's kind, the turn's metadata, a turn on diff --git a/internal/gateway/kilo_client_test.go b/internal/gateway/kilo_client_test.go new file mode 100644 index 000000000..462704f83 --- /dev/null +++ b/internal/gateway/kilo_client_test.go @@ -0,0 +1,84 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// The Kilo Gateway's free models are served with no key: a Kilo provider +// saved without one is asked as the Kilo CLI asks (its attribution and +// editor, the conversation as its task) with no Authorization, one with +// a key sends that key, and no other provider gets Kilo's headers. +func TestKiloClientHeaders(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + free, err := provider.FromPreset("kilo") + if err != nil { + t.Fatal(err) + } + free.ID, free.Models = "kilo", []string{"qwen/qwen3.8-27b:free"} + keyed := free + keyed.ID, keyed.Key, keyed.Chat = "kilo-keyed", "kilo_jwt", "https://api.kilocode.ai/api/openrouter" + for _, p := range []provider.Provider{free, keyed, + {ID: "other", Name: "Other", Key: "k", Chat: "https://other.test/v1", Models: []string{"qwen/qwen3.8-27b:free"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + got := map[string]*http.Request{} + s := New() + s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) { + got[r.URL.Host] = r.Clone(r.Context()) + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"c","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"pong"},"finish_reason":"stop"}]}`))}, nil + })} + for _, id := range []string{"kilo", "kilo-keyed", "other"} { + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+id+`/qwen/qwen3.8-27b:free","messages":[{"role":"user","content":"Say pong"}]}`)) + req.Header.Set("User-Agent", "some-agent/1.0") + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", id, rec.Code, rec.Body) + } + } + k, kk, o := got["api.kilo.ai"], got["api.kilocode.ai"], got["other.test"] + if k == nil || kk == nil || o == nil { + t.Fatalf("requests: %v", got) + } + if k.URL.Path != "/api/openrouter/chat/completions" { + t.Errorf("path %s", k.URL.Path) + } + want := map[string]string{ + "HTTP-Referer": "https://kilocode.ai", "X-Title": "Kilo Code", + "User-Agent": "Kilo-Code/" + provider.KiloVersion, "X-KILOCODE-EDITORNAME": "Kilo CLI " + provider.KiloVersion, + "x-kilocode-mode": "code", + } + if a := k.Header.Values("Authorization"); len(a) != 0 { + t.Errorf("keyless kilo sent Authorization %q", a) + } + for k2, v := range want { + if k.Header.Get(k2) != v { + t.Errorf("kilo: %s %q, want %q", k2, k.Header.Get(k2), v) + } + } + if id := k.Header.Get("X-KILOCODE-TASKID"); !strings.HasPrefix(id, "ses_") || k.Header.Get("X-Session-Id") != id { + t.Errorf("kilo task %q", id) + } + if got := kk.Header.Get("Authorization"); got != "Bearer kilo_jwt" { + t.Errorf("keyed kilo: Authorization %q", got) + } + for _, h := range []string{"X-KILOCODE-EDITORNAME", "X-KILOCODE-TASKID", "X-Title"} { + if o.Header.Get(h) != "" { + t.Errorf("other provider got %s", h) + } + } + if o.Header.Get("Authorization") != "Bearer k" { + t.Errorf("other: %q", o.Header.Get("Authorization")) + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 3c6bba5fe..53fa86611 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -5042,7 +5042,7 @@ function drawEditor(p, presetID) { // provider with no key read .set of it (willz: a local Ollama without a // key opened no editor, its row just toggling) const copied = (!p && draft.copyOf && providers.providers.find((x) => x.id === draft.copyOf)) || null; - const key = input(draft.key || "", p?.key.set ? t("{masked} · paste a new key to replace it", { masked: p.key.masked }) : copied?.key.set ? t("{masked} · {name}'s key, or paste another", { masked: copied.key.masked, name: copied.name }) : t(pr?.noKey || p?.key.optional ? "optional for local servers" : "paste an API key"), "password"); + const key = input(draft.key || "", p?.key.set ? t("{masked} · paste a new key to replace it", { masked: p.key.masked }) : copied?.key.set ? t("{masked} · {name}'s key, or paste another", { masked: copied.key.masked, name: copied.name }) : t(pr?.keyHint || (pr?.noKey || p?.key.optional ? "optional for local servers" : "paste an API key")), "password"); key.oninput = () => { draft.key = key.value; }; key.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter" && isNew) save(); else if (e.key === "Escape") cancelEdit(); }; const side = el("div", "side"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 9017ca8ad..2c0d185fa 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -636,6 +636,8 @@ const I18N = { "{name} saved": "已保存 {name}", "{masked} · paste a new key to replace it": "{masked} · 粘贴新密钥以替换", "optional for local servers": "本地服务可不填", + "optional: free models need no key": "可不填:免费模型无需密钥", + "free models with no key": "免费模型,无需密钥", "paste an API key": "粘贴 API 密钥", "Show": "显示", "Hide": "隐藏", diff --git a/internal/gui/assets/icons/kilo.svg b/internal/gui/assets/icons/kilo.svg new file mode 100644 index 000000000..b2fcadc42 --- /dev/null +++ b/internal/gui/assets/icons/kilo.svg @@ -0,0 +1 @@ +Kilo Code diff --git a/internal/provider/kilo.go b/internal/provider/kilo.go new file mode 100644 index 000000000..52b3d7abd --- /dev/null +++ b/internal/provider/kilo.go @@ -0,0 +1,175 @@ +package provider + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "slices" + "strings" + "time" + + "github.com/yetone/magpie/internal/catalog" +) + +// KiloVersion is the Kilo CLI release magpie says it is to the Kilo +// Gateway. +const KiloVersion = "7.8.3" + +// KiloClient makes a request to the Kilo Gateway carry what the Kilo CLI +// sends it (Kilo-Org/kilocode packages/opencode/src/session/llm/request.ts +// and kilocode/const.ts, packages/kilo-gateway/src/headers.ts): Kilo +// Code's attribution and User-Agent, the editor it runs in, its mode, and +// the session as the task, which the gateway keys its prompt cache on. +// session names the conversation, made into one of the CLI's ids (ses_…) +// as for OpenCode; none leaves the session headers out. A provider with no +// key sends no Authorization at all: the gateway answers a free model to a +// caller with no credential as anonymous (by IP, 200 requests an hour), and +// refuses a bearer it can't verify with 401 (Kilo-Org/cloud +// web-shared/src/lib/tokens.ts, ai-gateway/handlers/llm-proxy.ts). Kilo's +// clients still send "Bearer anonymous", which the gateway reads as none +// only until no released client sends it, so it is not copied here. +func KiloClient(h http.Header, key, session string) { + h.Set("HTTP-Referer", "https://kilocode.ai") + h.Set("X-Title", "Kilo Code") + h.Set("User-Agent", "Kilo-Code/"+KiloVersion) + h.Set("X-KILOCODE-EDITORNAME", "Kilo CLI "+KiloVersion) + if session != "" { + id := openCodeID("ses", session) + h.Set("x-kilocode-mode", "code") + h.Set("X-KILOCODE-TASKID", id) + h.Set("x-session-affinity", id) + h.Set("X-Session-Id", id) + } + if key == "" { + h.Del("Authorization") + } +} + +// IsKilo reports whether the provider is the Kilo Gateway: made from its +// preset, or at Kilo's API host. +func (p Provider) IsKilo() bool { + if p.Preset == "kilo" { + return true + } + h := p.Host() + return h == "api.kilo.ai" || h == "api.kilocode.ai" +} + +// kiloModels is the gateway's list as Kilo's clients ask it (GET +// {base}/models, kilo-gateway src/api/models.ts): OpenRouter's shape, with +// isFree on the models it serves at no cost. Without a key only those are +// listed, the rest wanting a Kilo account; with one, all of them, the free +// ones marked. A model that says it takes no tools is left out, as Kilo +// leaves it out. +func (p Provider) kiloModels(ctx context.Context) ([]catalog.Model, string, error) { + base := strings.TrimRight(strings.TrimSpace(p.Chat), "/") + u := base + "/models" + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + if err != nil { + return nil, base, err + } + req.Header.Set("Accept", "application/json") + KiloClient(req.Header, p.Key, "") + if p.Key != "" { + req.Header.Set("Authorization", "Bearer "+p.Key) + } + for k, v := range p.Headers { + req.Header[k] = []string{v} + } + res, err := http.DefaultClient.Do(req) + if err != nil { + return nil, base, err + } + defer res.Body.Close() + b, _ := io.ReadAll(io.LimitReader(res.Body, 8<<20)) + if res.StatusCode != http.StatusOK { + return nil, base, errorf("%s: HTTP %d", u, res.StatusCode) + } + var list struct { + Data []struct { + ID string `json:"id"` + Name string `json:"name"` + ContextLength any `json:"context_length"` + MaxOutput any `json:"max_completion_tokens"` + Params []string `json:"supported_parameters"` + IsFree bool `json:"isFree"` + TopProvider struct { + MaxOutput any `json:"max_completion_tokens"` + } `json:"top_provider"` + Architecture struct { + Input []string `json:"input_modalities"` + Output []string `json:"output_modalities"` + } `json:"architecture"` + } `json:"data"` + } + if err := json.Unmarshal(b, &list); err != nil { + return nil, base, errorf("%s: not a model list", u) + } + num := func(v any) int { + if n, ok := v.(float64); ok && n > 0 { + return int(n) + } + return 0 + } + var ms []catalog.Model + for _, r := range list.Data { + if r.ID == "" || len(r.Params) > 0 && !slices.Contains(r.Params, "tools") { + continue + } + if out := r.Architecture.Output; len(out) > 0 && !slices.Contains(out, "text") { + continue // one that only draws or makes sound + } + free := r.IsFree || isKiloFree(r.ID) + if p.Key == "" && !free { + continue + } + name := r.Name + if name == "" { + name = r.ID + } + m := catalog.Model{ID: r.ID, Name: name, Free: free, Context: num(r.ContextLength), + Reasoning: slices.Contains(r.Params, "reasoning")} + if m.Output = num(r.TopProvider.MaxOutput); m.Output == 0 { + m.Output = num(r.MaxOutput) + } + if in := r.Architecture.Input; in != nil { + yes := slices.Contains(in, "image") + m.ImageInput, m.Images = &yes, yes + } + if free { + m.Price = &catalog.Price{} + } + ms = append(ms, m) + } + if len(ms) == 0 { + return nil, base, errors.New(u + ": no models listed") + } + return ms, base, nil +} + +// isKiloFree reports whether id is one of the gateway's free models by its +// id alone: a ":free" one, which its docs say anyone may ask, or Kilo's +// own free router. +func isKiloFree(id string) bool { + return strings.HasSuffix(id, ":free") || id == "kilo-auto/free" +} + +// kiloFreeModel reports whether model is one of the Kilo Gateway's free +// models on p: one the fetched list marks free, else one free by its id. +func (p Provider) kiloFreeModel(model string) bool { + if !p.IsKilo() { + return false + } + if ms, _, ok := p.live(); ok { + for _, m := range ms { + if m.ID == model { + return m.Free + } + } + } + return isKiloFree(model) +} diff --git a/internal/provider/kilo_test.go b/internal/provider/kilo_test.go new file mode 100644 index 000000000..1dd0bcc0d --- /dev/null +++ b/internal/provider/kilo_test.go @@ -0,0 +1,123 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "slices" + "testing" + + "github.com/yetone/magpie/internal/catalog" +) + +// kiloList is the Kilo Gateway's /models as it answers (October 2026): +// OpenRouter's shape with isFree, an auto router priced at -1, a free +// model by its flag alone, ":free" ones, one that takes no tools and one +// that only draws. +const kiloList = `{"data":[ + {"id":"kilo-auto/efficient","name":"Auto Efficient","context_length":1000000,"pricing":{"prompt":"-1","completion":"-1"},"supported_parameters":["tools","reasoning"],"isFree":false}, + {"id":"kilo-auto/free","name":"Auto Free","context_length":256000,"pricing":{"prompt":"0","completion":"0"},"supported_parameters":["tools"],"isFree":true}, + {"id":"stealth/space-bunny-alpha","name":"Space Bunny Alpha","context_length":1000000,"top_provider":{"max_completion_tokens":65536},"architecture":{"input_modalities":["text","image"],"output_modalities":["text"]},"pricing":{"prompt":"0","completion":"0"},"supported_parameters":["tools","reasoning"],"isFree":true}, + {"id":"qwen/qwen3.8-27b:free","name":"Qwen: Qwen3.8 27B (free)","context_length":262144,"supported_parameters":["tools"],"isFree":true}, + {"id":"nvidia/nemotron-3.5-content-safety:free","name":"NVIDIA: Nemotron 3.5 Content Safety (free)","context_length":128000,"supported_parameters":["max_tokens"],"isFree":true}, + {"id":"google/lyria-3-pro-preview","name":"Lyria","context_length":1048576,"architecture":{"output_modalities":["audio"]},"pricing":{"prompt":"0","completion":"0"},"isFree":false}, + {"id":"anthropic/claude-sonnet-5","name":"Anthropic: Claude Sonnet 5","context_length":1000000,"pricing":{"prompt":"0.000003","completion":"0.000015"},"supported_parameters":["tools"],"isFree":false} +]}` + +// The Kilo Gateway serves its free models to anyone (by IP), and Kilo's +// clients list them from its /models, asked as the Kilo CLI: with no key +// the provider lists the free ones alone, asked with no Authorization; +// with a key every model, the free ones marked Free and priced at nothing +// (lml on Discord: the community plugin's free models from KiloCode). +func TestKiloModels(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + var asked []*http.Request + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/openrouter/models" { + http.NotFound(w, r) + return + } + asked = append(asked, r) + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(kiloList)) + })) + defer srv.Close() + p, err := FromPreset("kilo") + if err != nil { + t.Fatal(err) + } + if !p.Ready() { + t.Fatal("a Kilo provider with no key isn't ready") + } + p.ID, p.Chat = "kilo-test", srv.URL+"/api/openrouter" + ids := func(ms []catalog.Model) (all, free []string) { + for _, m := range ms { + all = append(all, m.ID) + if m.Free { + free = append(free, m.ID) + } + } + return + } + + ms, err := p.Fetch(context.Background()) + if err != nil { + t.Fatal(err) + } + h := asked[0].Header + for k, v := range map[string]string{"Authorization": "", "User-Agent": "Kilo-Code/" + KiloVersion, + "X-KILOCODE-EDITORNAME": "Kilo CLI " + KiloVersion, "HTTP-Referer": "https://kilocode.ai", "X-Title": "Kilo Code"} { + if h.Get(k) != v { + t.Errorf("list asked with %s %q, want %q", k, h.Get(k), v) + } + } + all, free := ids(ms) + want := []string{"kilo-auto/free", "stealth/space-bunny-alpha", "qwen/qwen3.8-27b:free"} + if !slices.Equal(all, want) || !slices.Equal(free, want) { + t.Fatalf("no key: %v (free %v)", all, free) + } + if m := ms[1]; m.Context != 1000000 || m.Output != 65536 || !m.Images || !m.Reasoning || m.Name != "Space Bunny Alpha" { + t.Fatalf("model: %+v", m) + } + // a free model by its flag alone costs nothing, not its maker's price + if pr, ok := p.ListPrice("stealth/space-bunny-alpha"); !ok || pr != (catalog.Price{}) { + t.Fatalf("free price: %+v %v", pr, ok) + } + + p.Key = "kilo_jwt" + ms, err = p.Fetch(context.Background()) + if err != nil { + t.Fatal(err) + } + if got := asked[1].Header.Get("Authorization"); got != "Bearer kilo_jwt" { + t.Fatalf("with a key, asked with %q", got) + } + all, free = ids(ms) + if !slices.Equal(all, []string{"kilo-auto/efficient", "kilo-auto/free", "stealth/space-bunny-alpha", "qwen/qwen3.8-27b:free", "anthropic/claude-sonnet-5"}) || !slices.Equal(free, want) { + t.Fatalf("with a key: %v (free %v)", all, free) + } + + // another provider's ":free" model isn't Kilo's to price + o, _ := FromPreset("together") + if o.kiloFreeModel("qwen/qwen3.8-27b:free") { + t.Fatal("kiloFreeModel on another provider") + } +} + +// The CLI's headers: the session as its task, and no Authorization at all +// when there is no key (a placeholder bearer is refused). +func TestKiloClient(t *testing.T) { + h := http.Header{"Authorization": {"Bearer "}} + KiloClient(h, "", "conversation-1") + id := h.Get("X-KILOCODE-TASKID") + if !openCodeIDRe.MatchString(id) || id[:4] != "ses_" || h.Get("x-session-affinity") != id || h.Get("X-Session-Id") != id || + h.Get("x-kilocode-mode") != "code" || len(h.Values("Authorization")) != 0 { + t.Fatalf("headers: %v", h) + } + h2 := http.Header{} + KiloClient(h2, "k", "conversation-1") + if h2.Get("X-KILOCODE-TASKID") != id || h2.Get("Authorization") != "" { + t.Fatalf("with a key: %v", h2) + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index 9b8afb935..d39f8d70f 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -147,6 +147,15 @@ func (p Provider) Fetch(ctx context.Context) ([]catalog.Model, error) { return catalog.Chat(ms), catalog.SaveLive(p.ID, base, ms) } } + // the Kilo Gateway's list as Kilo's clients ask it, which marks its + // free models; with no key, those alone + if p.IsKilo() && strings.TrimSpace(p.ModelsURL) == "" { + ms, base, err := p.kiloModels(ctx) + if err != nil { + return nil, err + } + return catalog.Chat(ms), catalog.SaveLive(p.ID, base, ms) + } // Only keys in use. An off key is not asked, and its list does not // join the catalog or take capabilities off a key that is on. if keys := p.KeysOn(); len(keys) > 1 { @@ -622,7 +631,7 @@ var makerCatalogs = sync.OnceValue(func() []string { // at gpt-6-astra's or gemini-3.8-flash's maker's price, as a Claude // account is at Anthropic's. func (p Provider) ListPrice(model string) (catalog.Price, bool) { - if p.clineFreeModel(model) { + if p.clineFreeModel(model) || p.kiloFreeModel(model) { // served at no cost: not at the price of the model it is free of return catalog.Price{}, true } diff --git a/internal/provider/presets.go b/internal/provider/presets.go index 5e6883123..de91ba69a 100644 --- a/internal/provider/presets.go +++ b/internal/provider/presets.go @@ -25,6 +25,7 @@ type PresetDef struct { Website string `json:"website,omitempty"` KeysURL string `json:"keysUrl,omitempty"` NoKey bool `json:"noKey,omitempty"` // local servers: a key is optional + KeyHint string `json:"keyHint,omitempty"` // the key field's placeholder, when it says more than NoKey's Sponsored bool `json:"sponsored,omitempty"` // shown first, with a tag Note string `json:"note,omitempty"` // one line under the name Short string `json:"short,omitempty"` // the add sheet's name for it, when Name is long @@ -301,6 +302,14 @@ var presets = []PresetDef{ // its free models (-free) are served to OpenCode alone, which // magpie asks them as (OpenCodeFree) Website: "https://opencode.ai/docs/zen", KeysURL: "https://opencode.ai/auth"}, + // Kilo Code's gateway, at the OpenRouter-style API its own clients use + // (kilo.go): its free models (isFree, ":free") are served with no key, + // as Kilo serves them signed out; a Kilo key reaches the rest + {ID: "kilo", Name: "Kilo Gateway", Icon: "kilo", Kind: KindRelay, NoKey: true, + Chat: "https://api.kilo.ai/api/openrouter", + Note: "free models with no key", + KeyHint: "optional: free models need no key", + Website: "https://kilo.ai/docs/gateway", KeysURL: "https://app.kilo.ai"}, // Command Code's Provider API: its Claude models on /messages alone, the // rest on chat and Responses, as its model list says (#93) {ID: "commandcode", Name: "Command Code", Icon: "commandcode", Kind: KindRelay, diff --git a/internal/provider/test.go b/internal/provider/test.go index 8e6b9ec20..be0ea37da 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -299,6 +299,9 @@ func probe(ctx context.Context, p Provider, proto Protocol, url string, body []b if p.IsCline() { ClineClient(req.Header) } + if p.IsKilo() { + KiloClient(req.Header, p.Key, "") + } if err := p.Sign(ctx, req, proto, body); err != nil { r.Error = err.Error() return r