Files
magpie/internal/provider/kilo.go
T
yetone bb136e1b70 providers: a Kilo Gateway preset serves Kilo Code's free models with no key (lml on Discord: the community plugin's free models come from OpenCode Zen, KiloCode Gateway and Cline) — Kilo's gateway is OpenRouter's API at https://api.kilo.ai/api/openrouter (KILO_OPENROUTER_BASE in Kilo-Org/kilocode packages/kilo-gateway; /api/gateway is the same), its list GET {base}/models in OpenRouter's shape with an isFree flag, readable with no key, and its docs (kilo-docs gateway/authentication.md) and backend (Kilo-Org/cloud web-shared ai-gateway/handlers/llm-proxy.ts, is-free-model.ts: kilo-auto/free, ":free", openrouter/free, stealth/*-alpha, Kilo's own free models) serve a free model to a caller with no credential, by IP, 200 requests an hour. The new "kilo" preset (Kilo Gateway, NoKey) is Ready with no key: its list is the gateway's own, asked as the Kilo CLI asks it, the free models alone without a key and every model with one, the free ones (isFree, or free by id) marked Free and priced at nothing in ListPrice; a model that says it takes no tools, or that makes no text (Lyria), is left out. Requests to Kilo's host (the gateway's and the Test button's) carry the Kilo CLI 7.8.3's headers (packages/opencode session/llm/request.ts, kilocode/const.ts, kilo-gateway headers.ts): HTTP-Referer https://kilocode.ai, X-Title Kilo Code, User-Agent Kilo-Code/7.8.3, X-KILOCODE-EDITORNAME "Kilo CLI 7.8.3", and on a chat x-kilocode-mode code with the conversation as its task (X-KILOCODE-TASKID, x-session-affinity, X-Session-Id, a ses_ id as for OpenCode), which the gateway keys its prompt cache on; no other provider gets them. Without a key no Authorization is sent: Kilo's clients send "Bearer anonymous", which the gateway reads as no credential only until no released client sends it (tokens.ts ANONYMOUS_BEARER_SENTINEL, "Delete this constant once no released client sends it"), and any other bearer it can't verify is refused with 401 rather than served as anonymous; pi-freeflow measured that a placeholder bearer gets 401 INVALID_TOKEN and no Authorization gets 200 on every free model. A key, when given, goes as a Bearer and reaches the paid models. The key field can now say more than "optional for local servers" (PresetDef.KeyHint: "optional: free models need no key", 可不填:免费模型无需密钥); Kilo's icon is its own (kilocode packages/ui provider/kilo.svg, MIT). Only Chat is set; Kilo's Responses and Anthropic routes are not used. One GET of the public /models was made while looking (399 models, 18 free); no chat request was made to Kilo. TestKiloModels (a fake gateway: asked as the CLI with no Authorization, the free models alone without a key and all with one, a model free by its flag priced at nothing), TestKiloClient and TestKiloClientHeaders (the CLI's headers and no Authorization on a keyless request through the gateway, the key on a keyed one, none of them on another provider) fail without the change. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./internal/... pass (TestClaudeRunEndsWhenTheClientLeaves, TestUserPath and TestClaudeSignedOut failed once under the full run's load, pass on the rerun; none touches Kilo).
2026-10-02 14:03:31 +08:00

176 lines
5.4 KiB
Go

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)
}