From 4fed6e4d31c45ec218eb5dd50f0e3e6fd9c4460f Mon Sep 17 00:00:00 2001 From: asas6661 Date: Wed, 23 Sep 2026 12:11:45 +0800 Subject: [PATCH] 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. --- internal/gateway/gateway.go | 109 ++++++++++++++++++++++++++++++++++ internal/gateway/upstream.go | 7 ++- internal/models/discovery.go | 4 +- internal/protocol/protocol.go | 12 +++- 4 files changed, 128 insertions(+), 4 deletions(-) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 310573e..9bf6b49 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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) diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 57563ef..e2ba172 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -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 diff --git a/internal/models/discovery.go b/internal/models/discovery.go index 7dfc967..05ac4ff 100644 --- a/internal/models/discovery.go +++ b/internal/models/discovery.go @@ -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 diff --git a/internal/protocol/protocol.go b/internal/protocol/protocol.go index 4f35ad3..5adad72 100644 --- a/internal/protocol/protocol.go +++ b/internal/protocol/protocol.go @@ -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" }