Files
magpie/internal/provider/opencode_endpoints.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

97 lines
4.0 KiB
Go

package provider
import (
"cmp"
"net/url"
"strings"
)
// openCodeRoot is the root of OpenCode's gateway a base URL is at — Zen's
// (https://opencode.ai/zen) or Go's (…/zen/go), or the inference API's
// that serves the same paths (…/inference, …/inference/go: models.dev's
// URL for both since October 2026), given with /v1 or without — and the
// models.dev provider that lists its models: opencode or opencode-go.
// Both are "" for any other URL.
func openCodeRoot(base string) (root, catalogID string) {
u, err := url.Parse(strings.TrimRight(strings.TrimSpace(base), "/"))
if err != nil || u.Scheme == "" {
return "", ""
}
if !openCodeHost(u.Hostname()) {
return "", ""
}
switch path := strings.TrimSuffix(strings.TrimRight(u.Path, "/"), "/v1"); path {
case "/zen/go", "/inference/go":
return u.Scheme + "://" + u.Host + path, "opencode-go"
case "/zen", "/inference":
return u.Scheme + "://" + u.Host + path, "opencode"
}
return "", ""
}
// openCodeGemini is the base of Gemini's generateContent at the gateway
// root is: models/{model}:streamGenerateContent is asked under it. Zen's
// /zen/v1 relays it to the inference API's Google route, reading the key
// from x-goog-api-key; Go's /zen/go/v1 has no such route (404), so Go's
// Gemini models are asked at the inference API's /inference/go/v1, where
// Go's docs give their endpoint (opencode.ai/v2/docs/console/go, #2168).
func openCodeGemini(root string) string {
if r, ok := strings.CutSuffix(root, "/zen/go"); ok {
return r + "/inference/go/v1"
}
return root + "/v1"
}
// openCodeEndpoints fills in the APIs of OpenCode's gateway a provider at
// it was saved without. Zen and Go serve each model on one API of three,
// all under one root — chat completions and Responses at /v1, Anthropic's
// Messages at the root — and turn it away on the other two. OpenCode asks
// a model through the AI SDK package models.dev's per-model provider.npm
// names: @ai-sdk/openai (Responses) for GPT, Grok and Muse Spark,
// @ai-sdk/anthropic (Messages) for Claude, MiniMax and some Qwen,
// @ai-sdk/google (Gemini's generateContent) for Gemini, and
// @ai-sdk/openai-compatible (chat) for the rest. A provider at Go added by
// hand or brought from another app with its chat URL alone had nowhere
// but chat to send GPT, Grok, MiniMax or Muse Spark, which Go answers
// with "Model does not support this protocol" (#1215), and none had
// anywhere but those three to send a Gemini model (#2168). A URL the user
// gave an API keeps it, and so does a catalog they named.
func (p *Provider) openCodeEndpoints() {
root, catalogID := "", ""
for _, u := range []string{p.Chat, p.Responses, p.Anthropic, p.Gemini} {
if root, catalogID = openCodeRoot(u); root != "" {
break
}
}
if root == "" {
return
}
p.Chat = cmp.Or(p.Chat, root+"/v1")
p.Responses = cmp.Or(p.Responses, root+"/v1")
p.Anthropic = cmp.Or(p.Anthropic, root)
p.Gemini = cmp.Or(p.Gemini, openCodeGemini(root))
p.Catalog = cmp.Or(p.Catalog, catalogID)
}
// openCodeCatalogs are the models.dev providers that say which API a model
// of OpenCode's gateway is served on: the list of the gateway its URL is
// at (Go's for Go, Zen's for Zen) alone, whatever catalog the provider was
// saved with — the two serve one model on different APIs (MiniMax M2.7 on
// Messages at Go, on chat at Zen) — or, at another path, its own.
func (p Provider) openCodeCatalogs() []string {
for _, u := range []string{p.Chat, p.Responses, p.Anthropic, p.Gemini} {
if _, id := openCodeRoot(u); id != "" {
return []string{id}
}
}
return p.Catalogs()
}
// NamedOnlyOn is whether p serves on proto only the models its list names
// that API for, so that one it names none for isn't asked there:
// OpenCode's Gemini API, which serves the Gemini models alone (each of
// OpenCode's models is served on one API family, its inference docs say).
// The rest are asked on chat, Responses or Messages, as before it had a
// Gemini URL (#2168).
func (p Provider) NamedOnlyOn(proto Protocol) bool { return proto == Gemini && p.IsOpenCode() }