Files
magpie/internal/gateway/opencode_session.go
T
yetone d1f57b70ee provider: every request to OpenCode's gateway names its conversation's session, at any port, lists, decisions, usage and the probe too, Codex's thread by its prompt_cache_key (luci on Discord)
OpenCode Go, added as a custom provider and asked from Codex, answered some
users 400 "Request is missing x-opencode-session and cannot be routed
efficiently", the Test button's probe too; a static header on the provider
stopped the 400 but put every conversation on one backend.

OpenCode's own client (packages/core, 4397ee4) sends x-opencode-session =
SessionAffinity (parentID ?? fork ?? id) on every model request, and a
fresh session for stateless calls; the console's inference proxy routes
every /zen and /zen/go path, models and usage included, by it.

- OpenCodeURL/openCodeHost: opencode.ai or a subdomain, by hostname, so a
  base URL naming a port (https://opencode.ai:443/zen/go/v1) is OpenCode's;
  IsOpenCode, OpenCodeFreeURL and openCodeRoot share it. Before, the turn's
  session was set only when p.Host() matched without a port.
- gateway: the turn's seed is the client's own x-opencode-session, else
  sessionOf (X-Magpie-Session, Codex's session_id, …), else the body's
  prompt_cache_key, else conversationID. Without the cache key two Codex
  conversations opened in one folder (same environment message) were one
  session.
- Sign: a request to OpenCode's gateway that names no session gets a fresh
  one (OpenCodeSession), so System One decisions and anything else signed
  are never refused; the user's own header still wins.
- Model lists (FetchURL, FetchAtListed, FetchGemini) get a fresh session
  via listHeadersAt, Go's usage windows via planWindows, the probe a
  session of its own.
- A 4xx/5xx from OpenCode's gateway logs host, path, the sent headers'
  names (never values), x-opencode-session's first 8 chars or "missing",
  and whether the provider's own header pinned it.

Run (worktree, -tags nogui -p 1):
- go test ./internal/gateway -run TestOpenCodeGoSessionPerConversation and
  -run 'OpenCode|Zen|Session|Conversation|Decide|SystemOne|UserHeader|Kilo|Cline|Gemini': ok
- go test ./internal/provider -run TestOpenCodeSessionOnEveryCall and
  -run 'OpenCode|Zen|Sign|Header|Fetch|Model|Probe|PlanQuota|Quota|Decide|Detect|Kilo|Cline|UserAgent': ok
- gofmt -l clean; go vet -tags nogui GOOS=darwin/linux/windows on both
  packages: ok
Broken by hand: seed back to conversationID -> red (threads c and d one
session); old IsOpenCode -> red (port provider's turns two sessions);
Sign's backstop removed -> red; list session removed -> red. The probe's
own OpenCodeClient removed stays green: Sign's backstop gives it a fresh
session anyway.
Not run: the full suite; no request to the real OpenCode gateway; why
luci's users miss the header (port, proxy/mirror host, a client header) is
not confirmed, the new log line will tell.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00

63 lines
2.4 KiB
Go

package gateway
import (
"log"
"net/http"
"slices"
"strings"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// openCodeSeed names the conversation a request to OpenCode's gateway is a
// turn of, for its x-opencode-session (provider.OpenCodeClient): the
// client's own x-opencode-session when it sent one, else the session the
// client names (X-Magpie-Session, Codex's session_id, Claude Code's
// session, Pi's affinity: sessionOf), else the body's prompt_cache_key
// (Codex's thread), else the conversation's first user message
// (conversationID). OpenCode itself sends one session id for every turn of
// a session (packages/core/src/session/affinity.ts), and Zen and Go route
// a session to the backend that has its prompt cached: every turn of one
// conversation names the same, and two conversations never one. Without
// the cache key, two of Codex's conversations in one folder, which open on
// the same environment message, were one session.
func openCodeSeed(in http.Header, body []byte) string {
if v := strings.TrimSpace(in.Get("x-opencode-session")); v != "" {
return v
}
if v := sessionOf(in); v != "" {
return v
}
if k := strings.TrimSpace(gjson.GetBytes(body, "prompt_cache_key").String()); k != "" {
return "prompt_cache_key\x00" + k
}
return conversationID(in, body)
}
// logOpenCodeRefusal writes to magpie's log what went to OpenCode's
// gateway with a request it refused: where, the names of the headers sent
// (never a value), and whether x-opencode-session was among them, by its
// first 8 characters. OpenCode answers a request without one 400
// "Request is missing x-opencode-session and cannot be routed
// efficiently" (luci on Discord), and this tells that apart from a
// session the user's own header pins every conversation to.
func logOpenCodeRefusal(p provider.Provider, req *http.Request, status int) {
var names []string
for k := range req.Header {
names = append(names, strings.ToLower(k))
}
slices.Sort(names)
session := "missing"
if v := req.Header.Get("x-opencode-session"); v != "" {
session = v[:min(len(v), 8)] + "…"
for k := range p.Headers {
if strings.EqualFold(k, "x-opencode-session") {
session += " (the provider's own header: one session for every conversation)"
}
}
}
log.Printf("opencode: %s answered %d to %s %s%s; x-opencode-session %s; headers sent: %s",
p.ID, status, req.Method, req.URL.Host, req.URL.Path, session, strings.Join(names, ", "))
}