feat: serve System One decision models on /v1/systemone

OpenCode Zen publishes System One models (jev-1.13, jev-1.13-free) on a
/v1/systemone endpoint. A request pairs a free-form state with typed
questions and the reply carries typed answers, so the payload shares no
shape with the chat/responses bridge and cannot be translated.

- protocol: add SystemOne with its endpoint path.
- discovery: read "systemone" rows from the upstream endpoint tables so
  those models stop being bucketed as unsupported.
- gateway: add POST /v1/systemone, which relays the body verbatim
  through the existing tier and anonymous machinery and returns the
  answer document unchanged. Models on another protocol are rejected
  with a clear error instead of being forwarded to a message API.
- anonymous lane: keep System One bodies verbatim. Forcing streaming or
  injecting the core agent tools, which the free tier requires for chat
  traffic, would invalidate a decision request.

Verified end-to-end against the live upstream: jev-1.13-free answers
through the gateway with cost 0, chat and responses models keep working,
and the endpoint rejects mismatched payloads.
This commit is contained in:
asas6661 committed 2026-09-23 12:11:45 +08:00
1 parent 8e776c43b5
commit 4fed6e4d31
4 files changed
+128 -4

No files matched your search

+109
View File
@@ -71,6 +71,7 @@ func (g *Gateway) Handler() http.Handler {
mux.HandleFunc("POST /v1/chat/completions", g.authenticate(g.handleInference(wire.Chat)))
mux.HandleFunc("POST /v1/responses", g.authenticate(g.handleInference(wire.Responses)))
mux.HandleFunc("POST /v1/messages", g.authenticate(g.handleInference(wire.Anthropic)))
mux.HandleFunc("POST /v1/systemone", g.authenticate(g.handleSystemOne))
mux.HandleFunc("GET /healthz", g.handleHealth)
return telemetry.Recover(g.logger, mux)
}
@@ -248,6 +249,114 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
}
}
// handleSystemOne forwards System One decision requests verbatim. The payload
// pairs a free-form state with typed questions, which no message-shaped
// upstream protocol accepts, so it is never translated: the body is relayed to
// the upstream systemone endpoint and the typed answer document is returned
// unchanged. System One answers are non-streaming today; a streaming upstream
// reply is still relayed verbatim should that change.
func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBody))
if err != nil {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "request body is too large or unreadable", "invalid_request_error", "")
return
}
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "request body must be a JSON object", "invalid_request_error", "")
return
}
model := jsonutil.StringAt(payload, "model")
meta := telemetry.MetaFromRequest(r)
if meta != nil {
meta.Model = model
}
if model == "" {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "model is required", "invalid_request_error", "model")
return
}
if !g.catalog.Supported(model) {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model")
return
}
route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous)
if err != nil {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, err.Error(), "invalid_request_error", "model")
return
}
// System One has no translation layer, so only models whose upstream
// protocol is systemone can be served from this endpoint. A chat or
// responses model belongs on its own endpoint, where the bridge can convert
// it; forwarding it here would send a decision payload to a message API.
if route.Protocol != wire.SystemOne {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, fmt.Sprintf("the model does not use the %s protocol", wire.SystemOne), "invalid_request_error", "model")
return
}
if meta != nil {
meta.Tier = string(route.Tier)
meta.Protocol = route.Protocol
}
// One verbatim body serves every tier: a decision payload has no per-tier
// encoding, so no protocol conversion is attempted.
bodies := make(map[config.Tier][]byte, len(route.KeyTiers)+1)
bodies[route.Tier] = body
for _, tier := range route.KeyTiers {
bodies[tier] = body
}
ids := identity.DeriveRequestIDs(r, payload)
if meta != nil {
meta.Request = ids.Request
}
requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second)
defer cancel()
resp, upstreamRoute, err := g.doUpstream(requestCtx, route, bodies, ids)
if err != nil {
finalTier := route.Tier
if meta != nil && meta.Tier != "" {
finalTier = config.Tier(meta.Tier)
}
keyID, channel, anonymous := requestCredential(requestCtx)
g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "tier", finalTier, "key_id", keyID, "channel", channel, "anonymous", anonymous, "error", err)
if errors.Is(err, context.DeadlineExceeded) {
wire.WriteError(w, wire.SystemOne, http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout", ids.Request)
return
}
wire.WriteError(w, wire.SystemOne, http.StatusBadGateway, "all upstream attempts failed", "upstream_error", ids.Request)
return
}
defer resp.Body.Close()
if meta != nil {
meta.Tier = string(upstreamRoute.Tier)
meta.Protocol = upstreamRoute.Protocol
}
w.Header().Set("x-request-id", ids.Request)
if resp.StatusCode/100 != 2 {
copyErrorResponse(w, wire.SystemOne, resp, ids.Request)
return
}
if contentType := resp.Header.Get("Content-Type"); strings.HasPrefix(contentType, "text/event-stream") {
if meta != nil {
meta.Stream = true
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
return
}
responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20))
if err != nil {
wire.WriteError(w, wire.SystemOne, http.StatusBadGateway, "failed to read upstream response", "upstream_error", ids.Request)
return
}
if usage, reported := wire.ResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil {
meta.Usage, meta.UsageReported = usage, reported
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(resp.StatusCode)
_, _ = w.Write(responseBody)
}
func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, input map[string]any) (map[config.Tier][]byte, error) {
tiers := make([]config.Tier, 0, len(route.KeyTiers)+1)
seen := make(map[config.Tier]bool, len(route.KeyTiers)+1)
+6 -1
View File
@@ -333,8 +333,13 @@ var anonymousCoreTools = []string{"bash", "edit", "glob", "grep", "read"}
// prepareAnonymousBody returns a copy of body normalized for the anonymous
// free tier: streaming enabled plus the core agent tools present. Bodies
// that already satisfy both (or are not JSON objects) are returned
// unchanged.
// unchanged. System One payloads are decision requests, not agent traffic, so
// they are forwarded verbatim; injecting streaming or tool definitions would
// make the upstream reject them.
func prepareAnonymousBody(body []byte, protocol wire.Protocol) []byte {
if protocol == wire.SystemOne {
return body
}
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
return body
+3 -1
View File
@@ -21,7 +21,7 @@ const (
GoDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/go.mdx"
)
var protocolDocEndpointPattern = regexp.MustCompile("\\|[^|]+\\|\\s*`?([^|`\\s]+)`?\\s*\\|\\s*`[^`]+/v1/(chat/completions|responses|messages)`")
var protocolDocEndpointPattern = regexp.MustCompile("\\|[^|]+\\|\\s*`?([^|`\\s]+)`?\\s*\\|\\s*`[^`]+/v1/(chat/completions|responses|messages|systemone)`")
type Capabilities struct {
Protocols map[config.Tier]map[string]wire.Protocol
@@ -210,6 +210,8 @@ func FetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string
protocol = wire.Responses
case "messages":
protocol = wire.Anthropic
case "systemone":
protocol = wire.SystemOne
}
if protocol != "" {
result[modelID] = protocol
+10 -2
View File
@@ -1,4 +1,5 @@
// Package protocol translates Chat, Responses, and Anthropic payloads and streams.
// Package protocol translates Chat, Responses, and Anthropic payloads and
// streams, and carries the opaque System One decision payloads.
package protocol
type Protocol string
@@ -7,10 +8,15 @@ const (
Chat Protocol = "chat"
Responses Protocol = "responses"
Anthropic Protocol = "anthropic"
// SystemOne is OpenCode Zen's structured decision endpoint. A request pairs
// a free-form state with typed questions and the reply carries typed
// answers, so the payload shares no shape with the chat/responses bridge and
// is forwarded as-is.
SystemOne Protocol = "systemone"
)
func Valid(p Protocol) bool {
return p == Chat || p == Responses || p == Anthropic
return p == Chat || p == Responses || p == Anthropic || p == SystemOne
}
func Path(protocol Protocol) string {
@@ -19,6 +25,8 @@ func Path(protocol Protocol) string {
return "/v1/responses"
case Anthropic:
return "/v1/messages"
case SystemOne:
return "/v1/systemone"
default:
return "/v1/chat/completions"
}