Merge pull request #41 from asas6661/feat/systemone-protocol

feat: serve System One decision models on /v1/systemone
This commit is contained in:
Jason Xu authored and GitHub committed 2026-09-23 14:05:01 +08:00
commit 79a208a467
4 files changed
+141 -4

No files matched your search

+122
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)
}
@@ -140,6 +141,15 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
meta.Tier = string(route.Tier)
meta.Protocol = route.Protocol
}
// A System One model has no message-shaped equivalent, so a decision
// payload submitted on a message endpoint is relayed verbatim instead of
// being converted. This keeps the model reachable for clients that can
// only address /v1/chat/completions or /v1/responses — for example a
// gateway whose OpenAI platform pins every request to Responses.
if route.Protocol == wire.SystemOne {
g.forwardSystemOne(w, r, body, payload, model, route)
return
}
bodies, err := g.prepareRouteBodies(external, route, payload)
if err != nil {
wire.WriteError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "")
@@ -248,6 +258,118 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
}
}
// handleSystemOne serves System One decision requests on their own endpoint.
// Only models whose upstream protocol is System One can be served here; a chat
// or responses model belongs on its own endpoint, where the bridge can convert
// it.
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")
if meta := telemetry.MetaFromRequest(r); 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
}
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
}
g.forwardSystemOne(w, r, body, payload, model, route)
}
// forwardSystemOne relays a System One decision payload verbatim to the
// upstream systemone endpoint and returns the typed answer document unchanged.
// The payload pairs a free-form state with typed questions, which no
// message-shaped upstream protocol accepts, so it is never translated. Answers
// are non-streaming today; a streaming upstream reply is still relayed.
func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body []byte, payload map[string]any, model string, route models.Route) {
meta := telemetry.MetaFromRequest(r)
if meta != nil {
meta.Model = model
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"
}