diff --git a/internal/gateway/opencode_client_test.go b/internal/gateway/opencode_client_test.go index 090eeb4c8..a8a10a634 100644 --- a/internal/gateway/opencode_client_test.go +++ b/internal/gateway/opencode_client_test.go @@ -57,7 +57,7 @@ func TestOpenCodeClientHeaders(t *testing.T) { } send("zen/kimi-k2.6", "") send("zen/kimi-k2.6", "") - send("zen/kimi-k2.6", "ses_0f9e921e8001MExXod3RWVP3aU") // OpenCode's own goes as it is + send("zen/kimi-k2.6", "ses_ecc5d8f28ffe9Cy14V8Em7lI2u") // OpenCode 1.19.0's own goes as it is send("other/kimi-k2.6", "") zen, other := got["opencode.ai"], got["other.test"] @@ -66,13 +66,18 @@ func TestOpenCodeClientHeaders(t *testing.T) { } id := regexp.MustCompile(`^(ses|msg)_[0-9a-f]{12}[0-9A-Za-z]{14}$`) for i, r := range zen { - if ua := r.h.Get("User-Agent"); ua != "opencode/"+provider.OpenCodeVersion { + if ua := r.h.Get("User-Agent"); ua != provider.OpenCodeUserAgent { t.Errorf("zen %d: User-Agent %q", i, ua) } if !id.MatchString(r.h.Get("x-opencode-session")) || !id.MatchString(r.h.Get("x-opencode-request")) || !strings.HasPrefix(r.h.Get("x-opencode-session"), "ses_") || !strings.HasPrefix(r.h.Get("x-opencode-request"), "msg_") { t.Errorf("zen %d: session %q request %q", i, r.h.Get("x-opencode-session"), r.h.Get("x-opencode-request")) } + for _, h := range []string{"x-opencode-session-id", "x-session-affinity", "X-Session-Id"} { + if v := r.h.Get(h); v != r.h.Get("x-opencode-session") { + t.Errorf("zen %d: %s %q, x-opencode-session %q", i, h, v, r.h.Get("x-opencode-session")) + } + } if r.h.Get("x-opencode-client") != "cli" || r.h.Get("x-opencode-project") != "global" { t.Errorf("zen %d: client %q project %q", i, r.h.Get("x-opencode-client"), r.h.Get("x-opencode-project")) } @@ -88,7 +93,7 @@ func TestOpenCodeClientHeaders(t *testing.T) { t.Errorf("session %q %q, request %q %q", zen[0].h.Get("x-opencode-session"), zen[1].h.Get("x-opencode-session"), zen[0].h.Get("x-opencode-request"), zen[1].h.Get("x-opencode-request")) } - if s := zen[2].h.Get("x-opencode-session"); s != "ses_0f9e921e8001MExXod3RWVP3aU" { + if s := zen[2].h.Get("x-opencode-session"); s != "ses_ecc5d8f28ffe9Cy14V8Em7lI2u" { t.Errorf("OpenCode's own session became %q", s) } for k := range other[0].h { diff --git a/internal/provider/kilo.go b/internal/provider/kilo.go index 4ee900e37..209030d69 100644 --- a/internal/provider/kilo.go +++ b/internal/provider/kilo.go @@ -36,7 +36,7 @@ func KiloClient(h http.Header, key, session string) { h.Set("User-Agent", "Kilo-Code/"+KiloVersion) h.Set("X-KILOCODE-EDITORNAME", "Kilo CLI "+KiloVersion) if session != "" { - id := openCodeID("ses", session) + id := openCodeSession(session) h.Set("x-kilocode-mode", "code") h.Set("X-KILOCODE-TASKID", id) h.Set("x-session-affinity", id) diff --git a/internal/provider/opencode_client.go b/internal/provider/opencode_client.go index d38145bdc..974dea669 100644 --- a/internal/provider/opencode_client.go +++ b/internal/provider/opencode_client.go @@ -1,13 +1,16 @@ package provider import ( + "container/list" "crypto/rand" - "crypto/sha256" - "encoding/hex" "encoding/json" + "fmt" "net/http" "regexp" + "strconv" "strings" + "sync" + "time" "github.com/yetone/magpie/internal/catalog" ) @@ -15,25 +18,33 @@ import ( // OpenCodeVersion is the OpenCode release magpie says it is to OpenCode's // gateway. Zen's free tier turns away anything older than 1.18.0 (426 // "OpenCode 1.18.0 or newer is required to use the free tier"). -const OpenCodeVersion = "1.18.34" +const OpenCodeVersion = "1.19.0" + +// OpenCodeUserAgent is the User-Agent OpenCode 1.19.0 sends, its ai-sdk +// and Bun included, as captured from the real client. +const OpenCodeUserAgent = "opencode/" + OpenCodeVersion + " ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14" // OpenCodeAnonymousKey is the key OpenCode asks Zen with when no one is // signed in to it, which Zen's free models answer. const OpenCodeAnonymousKey = "public" // OpenCodeClient makes a request to OpenCode's gateway (Zen or Go) carry -// what OpenCode itself sends there (packages/opencode/src/session/llm/ -// request.ts, for a provider whose id starts with "opencode"): its -// User-Agent, the session in x-opencode-session, the turn in +// what OpenCode itself sends there (packages/core/src/session/ +// model-request.ts): its User-Agent, the session in x-opencode-session, +// x-opencode-session-id, x-session-affinity and X-Session-Id, the turn in // x-opencode-request, and x-opencode-client and x-opencode-project. Zen's // free models are served to no one else ("OpenCode's free tier can only be -// used from within OpenCode"). session names the conversation; one already -// in OpenCode's form (ses_…) goes as it is, any other becomes one, the same -// for the same conversation, which Zen routes and caches by. +// used from within OpenCode"), and Zen reads the session id as OpenCode +// lays one out (openCodeSession). session names the conversation, whose +// turns keep one session id, which Zen routes and caches by. func OpenCodeClient(h http.Header, session string) { - h.Set("User-Agent", "opencode/"+OpenCodeVersion) - h.Set("x-opencode-session", openCodeID("ses", session)) - h.Set("x-opencode-request", openCodeID("msg", "")) + id := openCodeSession(session) + h.Set("User-Agent", OpenCodeUserAgent) + h.Set("x-opencode-session", id) + h.Set("x-opencode-session-id", id) + h.Set("x-session-affinity", id) + h.Set("X-Session-Id", id) + h.Set("x-opencode-request", openCodeNewID("msg", false, time.Now())) h.Set("x-opencode-client", "cli") // OpenCode's project outside a git repository h.Set("x-opencode-project", "global") @@ -102,22 +113,83 @@ var openCodeIDRe = regexp.MustCompile(`^[a-z]{3}_[0-9a-f]{12}[0-9A-Za-z]{14}$`) const base62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" -// openCodeID is an id as OpenCode makes them (prefix_, 12 hex digits and 14 -// base62 ones): seed's own when it is one with this prefix, else made from -// seed, or at random when there is none. -func openCodeID(prefix, seed string) string { - if strings.HasPrefix(seed, prefix+"_") && openCodeIDRe.MatchString(seed) { - return seed +// openCodeIDs is the clock and counter ids are made with, and the session +// id made for each conversation. +var openCodeIDs = struct { + sync.Mutex + last, counter int64 + sessions map[string]*list.Element // seed → its element in order + order *list.List // of openCodeKept, the least recently used first +}{sessions: map[string]*list.Element{}, order: list.New()} + +type openCodeKept struct{ seed, id string } + +// openCodeKeep is how many conversations' session ids are kept. +const openCodeKeep = 1000 + +// openCodeNewID is an id as OpenCode makes one (packages/schema/src/ +// identifier.ts): prefix_, 12 hex digits of the time in milliseconds times +// 0x1000 plus a count of the ids made in that millisecond (bit-inverted +// for a session, so the newest sorts first), then 14 random base62 ones. +func openCodeNewID(prefix string, descending bool, now time.Time) string { + ms := now.UnixMilli() + openCodeIDs.Lock() + if ms != openCodeIDs.last { + openCodeIDs.last, openCodeIDs.counter = ms, 0 } - var b [32]byte - if seed != "" { - b = sha256.Sum256([]byte(seed)) - } else if _, err := rand.Read(b[:]); err != nil { - b = sha256.Sum256([]byte(randomUUID())) + openCodeIDs.counter++ + current := uint64(ms)*0x1000 + uint64(openCodeIDs.counter) + openCodeIDs.Unlock() + if descending { + current = ^current } - id := []byte(prefix + "_" + hex.EncodeToString(b[:6])) - for _, c := range b[6:20] { + var b [14]byte + if _, err := rand.Read(b[:]); err != nil { + copy(b[:], randomUUID()) + } + id := []byte(fmt.Sprintf("%s_%012x", prefix, current&0xffffffffffff)) + for _, c := range b { id = append(id, base62[int(c)%len(base62)]) } return string(id) } + +// openCodeRealSession says whether id is a session id OpenCode could have +// made: of its shape, with a small count in its low 12 bits (inverted). +// Zen's free tier answers 403 FreeTierError to one that isn't, a hash cut +// to the same shape among them (c9cu on Discord). +func openCodeRealSession(id string) bool { + if !strings.HasPrefix(id, "ses_") || !openCodeIDRe.MatchString(id) { + return false + } + low, err := strconv.ParseUint(id[13:16], 16, 16) + return err == nil && 0xfff-low < 16 +} + +// openCodeSession is the session id sent for the conversation seed names: +// seed itself when it is one OpenCode could have made, else one made the +// first time seed is seen and kept for its next turns (the last +// openCodeKeep conversations' are kept), or a new one when there is no +// seed. +func openCodeSession(seed string) string { + if openCodeRealSession(seed) { + return seed + } + if seed == "" { + return openCodeNewID("ses", true, time.Now()) + } + id := openCodeNewID("ses", true, time.Now()) // made first: it takes the lock + openCodeIDs.Lock() + defer openCodeIDs.Unlock() + if e, ok := openCodeIDs.sessions[seed]; ok { + openCodeIDs.order.MoveToBack(e) + return e.Value.(openCodeKept).id + } + if openCodeIDs.order.Len() >= openCodeKeep { + oldest := openCodeIDs.order.Front() + openCodeIDs.order.Remove(oldest) + delete(openCodeIDs.sessions, oldest.Value.(openCodeKept).seed) + } + openCodeIDs.sessions[seed] = openCodeIDs.order.PushBack(openCodeKept{seed, id}) + return id +} diff --git a/internal/provider/opencode_client_test.go b/internal/provider/opencode_client_test.go new file mode 100644 index 000000000..46aad3e90 --- /dev/null +++ b/internal/provider/opencode_client_test.go @@ -0,0 +1,98 @@ +package provider + +import ( + "net/http" + "strconv" + "testing" + "time" +) + +// openCodeDecode reads an id as OpenCode's identifier.ts lays it out: the +// time in milliseconds (kept to 36 bits) and the count of ids made in it. +func openCodeDecode(t *testing.T, id string, descending bool) (ms, counter uint64) { + t.Helper() + v, err := strconv.ParseUint(id[4:16], 16, 64) + if err != nil { + t.Fatalf("%q: %v", id, err) + } + if descending { + v = ^v & 0xffffffffffff + } + return v / 0x1000, v % 0x1000 +} + +// Zen's free tier answers 403 FreeTierError ("can only be used from within +// OpenCode") to a session id OpenCode couldn't have made (c9cu on Discord: +// muse-spark-1.3-contributor-free from Pi worked one day and not the +// next). Checked against opencode.ai with the same request: +// ses_e9283da055b15JwOAra76bwUx4, a sha256 cut to the shape that magpie +// sent, got 403; ses_ecc5d8f28ffe9Cy14V8Em7lI2u, from a real OpenCode +// 1.19.0 run, got 200. The session made is OpenCode's: descending, the +// time it was made, a small count. +func TestOpenCodeSessionIsOpenCodes(t *testing.T) { + before := uint64(time.Now().UnixMilli()) % (1 << 36) + id := openCodeSession("conversation-a") + after := uint64(time.Now().UnixMilli()) % (1 << 36) + if !openCodeIDRe.MatchString(id) || id[:4] != "ses_" || !openCodeRealSession(id) { + t.Fatalf("session %q", id) + } + if ms, n := openCodeDecode(t, id, true); ms < before || ms > after || n < 1 || n >= 16 { + t.Fatalf("session %q: time %d (want %d..%d), count %d", id, ms, before, after, n) + } + // one conversation keeps one session, another gets its own + if again, other := openCodeSession("conversation-a"), openCodeSession("conversation-b"); again != id || other == id { + t.Fatalf("sessions %q %q %q", id, again, other) + } + if a, b := openCodeSession(""), openCodeSession(""); a == b || !openCodeRealSession(a) { + t.Fatalf("no conversation: %q %q", a, b) + } + // OpenCode's own goes as it is; a hash cut to its shape doesn't + const real, hashed = "ses_ecc5d8f28ffe9Cy14V8Em7lI2u", "ses_e9283da055b15JwOAra76bwUx4" + if got := openCodeSession(real); got != real { + t.Fatalf("OpenCode's own session became %q", got) + } + if openCodeRealSession(hashed) { + t.Fatal("a hash passes for OpenCode's session") + } + if got := openCodeSession(hashed); got == hashed || !openCodeRealSession(got) { + t.Fatalf("a hashed session went on as %q", got) + } + h := http.Header{} + OpenCodeClient(h, "conversation-a") + if h.Get("x-opencode-session") != id || h.Get("x-opencode-session-id") != id || h.Get("User-Agent") != OpenCodeUserAgent { + t.Fatalf("headers %v", h) + } + if req := h.Get("x-opencode-request"); req[:4] != "msg_" || !openCodeIDRe.MatchString(req) { + t.Fatalf("request %q", req) + } +} + +// Ids made in one millisecond count up, as OpenCode's do; a request's is +// ascending. +func TestOpenCodeIDsCountUp(t *testing.T) { + now := time.UnixMilli(1_790_000_000_000) + first, second := openCodeNewID("msg", false, now), openCodeNewID("msg", false, now) + if ms, n := openCodeDecode(t, first, false); ms != 1_790_000_000_000%(1<<36) || n != 1 { + t.Fatalf("%q: time %d count %d", first, ms, n) + } + if _, n := openCodeDecode(t, second, false); n != 2 || second <= first { + t.Fatalf("%q after %q: count %d", second, first, n) + } +} + +// Only the last openCodeKeep conversations' sessions are kept. +func TestOpenCodeSessionsKeptBounded(t *testing.T) { + first := openCodeSession("bounded-0") + for i := 1; i <= openCodeKeep; i++ { + openCodeSession("bounded-" + strconv.Itoa(i)) + } + openCodeIDs.Lock() + n := openCodeIDs.order.Len() + openCodeIDs.Unlock() + if n > openCodeKeep { + t.Fatalf("%d kept", n) + } + if openCodeSession("bounded-0") == first { + t.Fatal("the oldest conversation's session was still kept") + } +}