From bb136e1b709ecf3004764ccb948af34bdcc68909 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 14:02:47 +0800 Subject: [PATCH] =?UTF-8?q?providers:=20a=20Kilo=20Gateway=20preset=20serv?= =?UTF-8?q?es=20Kilo=20Code's=20free=20models=20with=20no=20key=20(lml=20o?= =?UTF-8?q?n=20Discord:=20the=20community=20plugin's=20free=20models=20com?= =?UTF-8?q?e=20from=20OpenCode=20Zen,=20KiloCode=20Gateway=20and=20Cline)?= =?UTF-8?q?=20=E2=80=94=20Kilo's=20gateway=20is=20OpenRouter's=20API=20at?= =?UTF-8?q?=20https://api.kilo.ai/api/openrouter=20(KILO=5FOPENROUTER=5FBA?= =?UTF-8?q?SE=20in=20Kilo-Org/kilocode=20packages/kilo-gateway;=20/api/gat?= =?UTF-8?q?eway=20is=20the=20same),=20its=20list=20GET=20{base}/models=20i?= =?UTF-8?q?n=20OpenRouter's=20shape=20with=20an=20isFree=20flag,=20readabl?= =?UTF-8?q?e=20with=20no=20key,=20and=20its=20docs=20(kilo-docs=20gateway/?= =?UTF-8?q?authentication.md)=20and=20backend=20(Kilo-Org/cloud=20web-shar?= =?UTF-8?q?ed=20ai-gateway/handlers/llm-proxy.ts,=20is-free-model.ts:=20ki?= =?UTF-8?q?lo-auto/free,=20":free",=20openrouter/free,=20stealth/*-alpha,?= =?UTF-8?q?=20Kilo's=20own=20free=20models)=20serve=20a=20free=20model=20t?= =?UTF-8?q?o=20a=20caller=20with=20no=20credential,=20by=20IP,=20200=20req?= =?UTF-8?q?uests=20an=20hour.=20The=20new=20"kilo"=20preset=20(Kilo=20Gate?= =?UTF-8?q?way,=20NoKey)=20is=20Ready=20with=20no=20key:=20its=20list=20is?= =?UTF-8?q?=20the=20gateway's=20own,=20asked=20as=20the=20Kilo=20CLI=20ask?= =?UTF-8?q?s=20it,=20the=20free=20models=20alone=20without=20a=20key=20and?= =?UTF-8?q?=20every=20model=20with=20one,=20the=20free=20ones=20(isFree,?= =?UTF-8?q?=20or=20free=20by=20id)=20marked=20Free=20and=20priced=20at=20n?= =?UTF-8?q?othing=20in=20ListPrice;=20a=20model=20that=20says=20it=20takes?= =?UTF-8?q?=20no=20tools,=20or=20that=20makes=20no=20text=20(Lyria),=20is?= =?UTF-8?q?=20left=20out.=20Requests=20to=20Kilo's=20host=20(the=20gateway?= =?UTF-8?q?'s=20and=20the=20Test=20button's)=20carry=20the=20Kilo=20CLI=20?= =?UTF-8?q?7.8.3's=20headers=20(packages/opencode=20session/llm/request.ts?= =?UTF-8?q?,=20kilocode/const.ts,=20kilo-gateway=20headers.ts):=20HTTP-Ref?= =?UTF-8?q?erer=20https://kilocode.ai,=20X-Title=20Kilo=20Code,=20User-Age?= =?UTF-8?q?nt=20Kilo-Code/7.8.3,=20X-KILOCODE-EDITORNAME=20"Kilo=20CLI=207?= =?UTF-8?q?.8.3",=20and=20on=20a=20chat=20x-kilocode-mode=20code=20with=20?= =?UTF-8?q?the=20conversation=20as=20its=20task=20(X-KILOCODE-TASKID,=20x-?= =?UTF-8?q?session-affinity,=20X-Session-Id,=20a=20ses=5F=20id=20as=20for?= =?UTF-8?q?=20OpenCode),=20which=20the=20gateway=20keys=20its=20prompt=20c?= =?UTF-8?q?ache=20on;=20no=20other=20provider=20gets=20them.=20Without=20a?= =?UTF-8?q?=20key=20no=20Authorization=20is=20sent:=20Kilo's=20clients=20s?= =?UTF-8?q?end=20"Bearer=20anonymous",=20which=20the=20gateway=20reads=20a?= =?UTF-8?q?s=20no=20credential=20only=20until=20no=20released=20client=20s?= =?UTF-8?q?ends=20it=20(tokens.ts=20ANONYMOUS=5FBEARER=5FSENTINEL,=20"Dele?= =?UTF-8?q?te=20this=20constant=20once=20no=20released=20client=20sends=20?= =?UTF-8?q?it"),=20and=20any=20other=20bearer=20it=20can't=20verify=20is?= =?UTF-8?q?=20refused=20with=20401=20rather=20than=20served=20as=20anonymo?= =?UTF-8?q?us;=20pi-freeflow=20measured=20that=20a=20placeholder=20bearer?= =?UTF-8?q?=20gets=20401=20INVALID=5FTOKEN=20and=20no=20Authorization=20ge?= =?UTF-8?q?ts=20200=20on=20every=20free=20model.=20A=20key,=20when=20given?= =?UTF-8?q?,=20goes=20as=20a=20Bearer=20and=20reaches=20the=20paid=20model?= =?UTF-8?q?s.=20The=20key=20field=20can=20now=20say=20more=20than=20"optio?= =?UTF-8?q?nal=20for=20local=20servers"=20(PresetDef.KeyHint:=20"optional:?= =?UTF-8?q?=20free=20models=20need=20no=20key",=20=E5=8F=AF=E4=B8=8D?= =?UTF-8?q?=E5=A1=AB=EF=BC=9A=E5=85=8D=E8=B4=B9=E6=A8=A1=E5=9E=8B=E6=97=A0?= =?UTF-8?q?=E9=9C=80=E5=AF=86=E9=92=A5);=20Kilo's=20icon=20is=20its=20own?= =?UTF-8?q?=20(kilocode=20packages/ui=20provider/kilo.svg,=20MIT).=20Only?= =?UTF-8?q?=20Chat=20is=20set;=20Kilo's=20Responses=20and=20Anthropic=20ro?= =?UTF-8?q?utes=20are=20not=20used.=20One=20GET=20of=20the=20public=20/mod?= =?UTF-8?q?els=20was=20made=20while=20looking=20(399=20models,=2018=20free?= =?UTF-8?q?);=20no=20chat=20request=20was=20made=20to=20Kilo.=20TestKiloMo?= =?UTF-8?q?dels=20(a=20fake=20gateway:=20asked=20as=20the=20CLI=20with=20n?= =?UTF-8?q?o=20Authorization,=20the=20free=20models=20alone=20without=20a?= =?UTF-8?q?=20key=20and=20all=20with=20one,=20a=20model=20free=20by=20its?= =?UTF-8?q?=20flag=20priced=20at=20nothing),=20TestKiloClient=20and=20Test?= =?UTF-8?q?KiloClientHeaders=20(the=20CLI's=20headers=20and=20no=20Authori?= =?UTF-8?q?zation=20on=20a=20keyless=20request=20through=20the=20gateway,?= =?UTF-8?q?=20the=20key=20on=20a=20keyed=20one,=20none=20of=20them=20on=20?= =?UTF-8?q?another=20provider)=20fail=20without=20the=20change.=20go=20vet?= =?UTF-8?q?=20./internal/...,=20go=20build=20-tags=20nogui=20(darwin,=20GO?= =?UTF-8?q?OS=3Dlinux),=20GOOS=3Dwindows=20go=20build,=20go=20test=20-tags?= =?UTF-8?q?=20nogui=20./internal/...=20pass=20(TestClaudeRunEndsWhenTheCli?= =?UTF-8?q?entLeaves,=20TestUserPath=20and=20TestClaudeSignedOut=20failed?= =?UTF-8?q?=20once=20under=20the=20full=20run's=20load,=20pass=20on=20the?= =?UTF-8?q?=20rerun;=20none=20touches=20Kilo).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/gateway.go | 5 + internal/gateway/kilo_client_test.go | 84 +++++++++++++ internal/gui/assets/app.js | 2 +- internal/gui/assets/i18n.js | 2 + internal/gui/assets/icons/kilo.svg | 1 + internal/provider/kilo.go | 175 +++++++++++++++++++++++++++ internal/provider/kilo_test.go | 123 +++++++++++++++++++ internal/provider/models.go | 11 +- internal/provider/presets.go | 9 ++ internal/provider/test.go | 3 + 10 files changed, 413 insertions(+), 2 deletions(-) create mode 100644 internal/gateway/kilo_client_test.go create mode 100644 internal/gui/assets/icons/kilo.svg create mode 100644 internal/provider/kilo.go create mode 100644 internal/provider/kilo_test.go 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