mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
feat(free-tier): use only the v2 lane and fold response tool names
The anonymous free tier now calls the configured v2 /inference origin only; the retired v1 /zen fallback is commented out rather than deleted, so the lane order can be restored in one edit. Catalog refresh and probes follow anonymousUpstreams, so they stop trying /zen too. A request whose client names no project now gets a fresh 40-hex project id. The free tier ledges quota per project id and egress, and the old per-caller default was one shared bucket that popular exits had already burned. Response tool names now resolve in the order exact wire name, clint_ prefix, case fold, separator fold. A fold two declared tools share is never guessed between. The stream and JSON rewriters share the resolver, and their fast path now recognizes unprefixed tool-call frames.
This commit is contained in:
1 parent
1de0f3fa47
commit
54fe16ebb7
9 files changed
+158
-49
No files matched your search
@@ -222,7 +222,7 @@ Eligibility is a routing decision; the upstream can still reject or rate-limit t
|
||||
|
||||
The routing sequence is:
|
||||
|
||||
1. For an eligible model, try up to `performance.max_anonymous_exits` available anonymous proxies once each. Every proxy tries the v2 `/inference` lane first, then the v1 `/zen` lane.
|
||||
1. For an eligible model, try up to `performance.max_anonymous_exits` available anonymous proxies once each. Every proxy uses the v2 `/inference` lane; the v1 `/zen` fallback is retired for free models and its call site is commented out.
|
||||
2. Try authenticated tiers in `prefer` order, using only tiers with a configured key and a route for that model.
|
||||
3. Apply `retry.max_attempts` separately to each authenticated tier.
|
||||
|
||||
@@ -301,7 +301,7 @@ See [config.example.json](config.example.json) for a complete starting configura
|
||||
| `prefer` | `go`; accepts `go` or `zen`. |
|
||||
| `upstream.zen` | `https://opencode.ai/zen`. |
|
||||
| `upstream.go` | `https://opencode.ai/zen/go`. |
|
||||
| `upstream.anonymous` | `https://opencode.ai/inference`; tried first by the anonymous lane, which falls back to `/zen`. |
|
||||
| `upstream.anonymous` | `https://opencode.ai/inference`; the only anonymous lane (the retired `/zen` fallback is commented out in `anonymousUpstreams`). |
|
||||
| `proxies` | Falls back to `["direct"]` when both proxy sources are empty. |
|
||||
| `proxyfile` | Optional; relative paths resolve beside the configuration file. |
|
||||
| `models.refresh_seconds` | `300`; minimum 1. |
|
||||
|
||||
@@ -129,9 +129,9 @@ type UpstreamConfig struct {
|
||||
// CLI shape. The WebUI also reads the plan's quota from its /v1/usage.
|
||||
Go string `json:"go"`
|
||||
// Anonymous is the v2 /inference origin of the keyless free tier. The
|
||||
// anonymous lane tries this origin first and falls back to the v1 /zen
|
||||
// origin (models.V1Base, not Zen), which is the only upstream used when
|
||||
// this one equals the v1 origin. Empty means https://opencode.ai/inference.
|
||||
// anonymous lane uses only this origin: the v1 /zen fallback is retired for
|
||||
// free models and its call site is commented out. Empty means
|
||||
// https://opencode.ai/inference.
|
||||
Anonymous string `json:"anonymous"`
|
||||
}
|
||||
|
||||
|
||||
@@ -8,8 +8,9 @@
|
||||
// 1.x User-Agent, the x-opencode-request header, a git-commit-shaped project
|
||||
// and, on the free tier, the 1.x toolset. The v2 lane is the /inference
|
||||
// origin (upstream.anonymous) and the Go plan's /zen/go origin, which expect
|
||||
// the OpenCode 2.x CLI shape. The anonymous free tier tries the configured v2
|
||||
// /inference origin first and falls back to the v1 origin.
|
||||
// the OpenCode 2.x CLI shape. The anonymous free tier uses the configured v2
|
||||
// /inference origin only; the retired v1 fallback is kept in
|
||||
// anonymousUpstreams but commented out.
|
||||
package gateway
|
||||
|
||||
import (
|
||||
|
||||
@@ -276,8 +276,8 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin
|
||||
var models []string
|
||||
var status int
|
||||
var err error
|
||||
// List models on the configured v2 /inference origin first, then fall
|
||||
// back to the v1 origin (see anonymousUpstreams).
|
||||
// List models on the configured v2 /inference origin; the v1 fallback
|
||||
// is retired (see anonymousUpstreams).
|
||||
for _, upstream := range g.anonymousUpstreams() {
|
||||
models, status, err = modelcatalog.FetchModels(refreshCtx, node.proxy.client, upstream, anonymousZenKey)
|
||||
if err == nil || isProxyFailure(err) {
|
||||
|
||||
@@ -347,13 +347,14 @@ func (g *Gateway) maxAnonymousExits() int {
|
||||
// proxy is tried at most once, up to performance.max_anonymous_exits proxies;
|
||||
// rotating #pool proxies may be drawn again until Retry.MaxAttempts proxies
|
||||
// were used. For each proxy it tries the upstreams in anonymousUpstreams
|
||||
// order: the configured v2 /inference upstream (Upstream.Anonymous) before the
|
||||
// v1 lane (models.V1Base). Any failure, including an HTTP error response,
|
||||
// advances to the next upstream or proxy; a proxy-route failure, or a proxy
|
||||
// marked unhealthy, skips that proxy's remaining upstreams. Only a successful
|
||||
// response ends the anonymous phase; exhausting the proxy cursor returns
|
||||
// control to the preferred authenticated tiers. It returns the last response
|
||||
// (body still open), else the last error, plus the number of attempts made.
|
||||
// order: the configured v2 /inference upstream (Upstream.Anonymous) only, since
|
||||
// the v1 lane fallback is retired and commented out there. Any failure,
|
||||
// including an HTTP error response, advances to the next upstream or proxy; a
|
||||
// proxy-route failure, or a proxy marked unhealthy, skips that proxy's
|
||||
// remaining upstreams. Only a successful response ends the anonymous phase;
|
||||
// exhausting the proxy cursor returns control to the preferred authenticated
|
||||
// tiers. It returns the last response (body still open), else the last error,
|
||||
// plus the number of attempts made.
|
||||
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
|
||||
if g.usesWARP(route.ID, config.TierZen, true) {
|
||||
return g.doWarpAnonymousUpstream(ctx, route, bodies, ids, attemptOffset)
|
||||
@@ -550,17 +551,21 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
return nil, lastErr, attempts
|
||||
}
|
||||
|
||||
// anonymousUpstreams returns the ordered base URLs for the keyless free tier:
|
||||
// the configured v2 /inference origin (Upstream.Anonymous) is tried first, and
|
||||
// the v1 origin (models.V1Base) is kept as a fallback. Only the v1 origin is
|
||||
// returned when Upstream.Anonymous is empty or names that same origin.
|
||||
// anonymousUpstreams returns the ordered base URLs for the keyless free tier.
|
||||
// Only the v2 /inference origin is used: the 1.x /zen lane was retired for free
|
||||
// models, so the v1 fallback is commented out rather than called. The code is
|
||||
// kept for a revert; uncommenting the two lines marked below restores the old
|
||||
// order (v2 first, v1 as fallback).
|
||||
func (g *Gateway) anonymousUpstreams() []string {
|
||||
v1 := strings.TrimRight(models.V1Base, "/")
|
||||
// v1 := strings.TrimRight(models.V1Base, "/")
|
||||
primary := strings.TrimRight(g.cfg.Upstream.Anonymous, "/")
|
||||
if primary == "" || strings.EqualFold(v1, primary) {
|
||||
return []string{models.V1Base}
|
||||
if primary == "" {
|
||||
// Config normalization fills this; keep the v2 default for a zero-value
|
||||
// config so this never falls through to the retired v1 lane.
|
||||
primary = "https://opencode.ai/inference"
|
||||
}
|
||||
return []string{g.cfg.Upstream.Anonymous, models.V1Base}
|
||||
return []string{primary}
|
||||
// return []string{g.cfg.Upstream.Anonymous, models.V1Base}
|
||||
}
|
||||
|
||||
// inferenceClient picks the client of proxy for a request for model to
|
||||
|
||||
@@ -79,12 +79,11 @@ func DeriveRequestIDs(r *http.Request, body map[string]any, scope string) Reques
|
||||
}
|
||||
projectSignal := jsonutil.FirstString(r.Header.Get("x-opencode-project"), jsonutil.StringAt(body, "metadata", "project_id"))
|
||||
if projectSignal == "" {
|
||||
// Without a client project every caller would otherwise share one
|
||||
// constant upstream project.
|
||||
projectSignal = "opencode2api:default-project"
|
||||
if scope != "" {
|
||||
projectSignal += ":" + scope
|
||||
}
|
||||
// A fresh project id per request. The free tier ledges its quota per
|
||||
// project id and egress, so one shared id is one shared bucket: the old
|
||||
// per-caller default arrived pre-burned on popular exits. A client that
|
||||
// names its project keeps that name.
|
||||
projectSignal = RandomProjectID()
|
||||
}
|
||||
parentSession := jsonutil.FirstString(
|
||||
r.Header.Get("x-parent-session-id"),
|
||||
@@ -284,3 +283,15 @@ func RandomID(prefix string, size int) string {
|
||||
}
|
||||
return prefix + "_" + hex.EncodeToString(buf)
|
||||
}
|
||||
|
||||
// RandomProjectID returns a project id in the shape the official CLI sends: the
|
||||
// 40-character hex of a git root commit. It is minted per request when the
|
||||
// client names no project, because the free tier ledges quota per project id
|
||||
// and egress together. It panics when the system random source fails.
|
||||
func RandomProjectID() string {
|
||||
buf := make([]byte, 20)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
return hex.EncodeToString(buf)
|
||||
}
|
||||
@@ -503,19 +503,33 @@ func ResponseUsage(protocol Protocol, body []byte) (Usage, bool) {
|
||||
return decodeOpenAIUsage(usage), true
|
||||
}
|
||||
|
||||
// mayCarryToolName is the fast path for a response body or SSE frame: a body
|
||||
// that mentions neither a client alias nor a tool-call marker cannot name a
|
||||
// tool, so it is handed on without decoding. The markers are the protocol's
|
||||
// own spellings; folding an unprefixed official name (todowrite) needs the
|
||||
// frame decoded even when no clint_ alias is present.
|
||||
func mayCarryToolName(body []byte) bool {
|
||||
return bytes.Contains(body, []byte(ClientToolPrefix)) ||
|
||||
bytes.Contains(body, []byte(`"tool_calls"`)) ||
|
||||
bytes.Contains(body, []byte(`"function_call"`)) ||
|
||||
bytes.Contains(body, []byte(`"custom_tool_call"`)) ||
|
||||
bytes.Contains(body, []byte(`"tool_use"`)) ||
|
||||
bytes.Contains(body, []byte(`"server_tool_use"`))
|
||||
}
|
||||
|
||||
// RenameResponseTool rewrites tool call names that carry a client alias back to
|
||||
// the name the client declared, inside a serialized JSON response or SSE event
|
||||
// data object for the given protocol. It is the counterpart of the outbound
|
||||
// clint_ renaming applied to shaped free-tier requests.
|
||||
//
|
||||
// The bytes.Contains check is only a fast path that skips the unmarshal for
|
||||
// frames that cannot contain an alias; every rewrite is an exact map lookup
|
||||
// after decoding. Names without a mapping are left alone.
|
||||
// mayCarryToolName is only a fast path that skips the unmarshal for frames that
|
||||
// cannot contain a tool name; every rewrite is a map lookup after decoding.
|
||||
// Names that map to nothing are left alone.
|
||||
func RenameResponseTool(body []byte, protocol Protocol, renames *ToolRenames) []byte {
|
||||
if renames.Empty() || len(body) == 0 {
|
||||
return body
|
||||
}
|
||||
if !bytes.Contains(body, []byte(ClientToolPrefix)) {
|
||||
if !mayCarryToolName(body) {
|
||||
return body
|
||||
}
|
||||
var payload map[string]any
|
||||
@@ -544,8 +558,8 @@ func renameToolInMap(payload map[string]any, protocol Protocol, renames *ToolRen
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
client, ok := renames.Client(name)
|
||||
if !ok {
|
||||
client, changed := renames.Resolve(name)
|
||||
if !changed {
|
||||
return false
|
||||
}
|
||||
container["name"] = client
|
||||
|
||||
@@ -336,7 +336,7 @@ func (renamer *streamToolRenamer) rewriteFrame(raw string) []byte {
|
||||
if renamer.protocol != Chat {
|
||||
// Anthropic and Responses streams always carry a complete tool name in
|
||||
// a single event, so the stateless object rewrite is exact.
|
||||
if !strings.Contains(raw, ClientToolPrefix) {
|
||||
if !mayCarryToolName([]byte(raw)) {
|
||||
return []byte(raw)
|
||||
}
|
||||
return RenameResponseTool([]byte(raw), renamer.protocol, renamer.renames)
|
||||
@@ -429,8 +429,12 @@ func (renamer *streamToolRenamer) applyNameFragment(state *streamToolRenameState
|
||||
delete(function, "name")
|
||||
return true
|
||||
}
|
||||
function["name"] = state.pending
|
||||
state.decided = true
|
||||
// The name is complete. Resolve folds a spelling that differs from exactly
|
||||
// one declared client tool only in case or separators; a name nothing
|
||||
// declared is written out as the model sent it.
|
||||
client, renamed := renamer.renames.Resolve(state.pending)
|
||||
function["name"] = client
|
||||
state.decided, state.renamed = true, renamed
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
+84
-10
@@ -19,11 +19,21 @@ const toolWireNameLimit = 64
|
||||
type ToolRenames struct {
|
||||
toWire map[string]string
|
||||
toClient map[string]string
|
||||
// byCase and byShape map a folded client name back to the one declared
|
||||
// client tool it names. A value of "" marks a fold two tools share: that
|
||||
// name is never guessed between.
|
||||
byCase map[string]string
|
||||
byShape map[string]string
|
||||
}
|
||||
|
||||
// NewToolRenames returns an empty rename set.
|
||||
func NewToolRenames() *ToolRenames {
|
||||
return &ToolRenames{toWire: map[string]string{}, toClient: map[string]string{}}
|
||||
return &ToolRenames{
|
||||
toWire: map[string]string{},
|
||||
toClient: map[string]string{},
|
||||
byCase: map[string]string{},
|
||||
byShape: map[string]string{},
|
||||
}
|
||||
}
|
||||
|
||||
// Empty reports whether no tool was renamed.
|
||||
@@ -74,6 +84,41 @@ func (r *ToolRenames) Add(client, wire string) {
|
||||
}
|
||||
r.toWire[client] = wire
|
||||
r.toClient[wire] = client
|
||||
r.bindFolded(r.byCase, strings.ToLower(client), client)
|
||||
r.bindFolded(r.byShape, foldToolName(client), client)
|
||||
}
|
||||
|
||||
// bindFolded records client under key in a folded map. An empty key names
|
||||
// nothing (a client tool spelled only with separators must not be handed every
|
||||
// other such name), and a key two clients share is marked ambiguous.
|
||||
func (r *ToolRenames) bindFolded(folded map[string]string, key, client string) {
|
||||
if folded == nil || key == "" {
|
||||
return
|
||||
}
|
||||
if existing, ok := folded[key]; ok {
|
||||
if existing != client {
|
||||
folded[key] = ""
|
||||
}
|
||||
return
|
||||
}
|
||||
folded[key] = client
|
||||
}
|
||||
|
||||
// toolNameSeparators are the characters ignored when matching a tool name by
|
||||
// shape, after case: "todo_write", "todo-write", "todo.write" and "todowrite"
|
||||
// all fold to one key.
|
||||
const toolNameSeparators = "_.- \t\r\n"
|
||||
|
||||
// foldToolName lowercases name and removes the separators agents spell tool
|
||||
// names with, so two spellings of one tool fold together.
|
||||
func foldToolName(name string) string {
|
||||
var builder strings.Builder
|
||||
for _, char := range strings.ToLower(name) {
|
||||
if !strings.ContainsRune(toolNameSeparators, char) {
|
||||
builder.WriteRune(char)
|
||||
}
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// HasPrefix reports whether any wire name starts with prefix.
|
||||
@@ -104,19 +149,48 @@ func (r *ToolRenames) HasLongerPrefix(prefix string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Restore maps a wire name back to the client name. When the exact mapping is
|
||||
// gone (for example after a configuration reload mid-stream), stripping the
|
||||
// prefix is the best available recovery; a name without it is returned as is.
|
||||
func (r *ToolRenames) Restore(wire string) string {
|
||||
// Resolve maps a tool name the upstream reported back to the name the client
|
||||
// declared. It is the response-side counterpart of the wire rename: an exact
|
||||
// wire name restores, a clint_ prefix is stripped as a best-effort recovery
|
||||
// (for example after a configuration reload mid-stream), and a name that
|
||||
// differs from exactly one declared client tool only in case, or else only in
|
||||
// case and separators (todowrite → todo_write), is folded onto that tool. A
|
||||
// name two tools fold to is never guessed between. It reports whether the
|
||||
// result differs from the name given.
|
||||
func (r *ToolRenames) Resolve(wire string) (string, bool) {
|
||||
if r == nil || wire == "" {
|
||||
return wire, false
|
||||
}
|
||||
if client, ok := r.Client(wire); ok {
|
||||
return client
|
||||
return client, client != wire
|
||||
}
|
||||
if strings.HasPrefix(wire, ClientToolPrefix) {
|
||||
if rest := strings.TrimPrefix(wire, ClientToolPrefix); rest != "" {
|
||||
return rest
|
||||
client := wire
|
||||
if rest, ok := strings.CutPrefix(wire, ClientToolPrefix); ok && rest != "" {
|
||||
client = rest
|
||||
}
|
||||
if _, declared := r.toWire[client]; declared {
|
||||
return client, client != wire
|
||||
}
|
||||
lower := strings.ToLower(client)
|
||||
if match, ok := r.byCase[lower]; ok {
|
||||
// A key present with an empty value is two client tools folded
|
||||
// together; the name as written is the only safe answer.
|
||||
if match != "" {
|
||||
return match, match != wire
|
||||
}
|
||||
return client, client != wire
|
||||
}
|
||||
return wire
|
||||
if match, ok := r.byShape[foldToolName(client)]; ok && match != "" {
|
||||
return match, match != wire
|
||||
}
|
||||
return client, client != wire
|
||||
}
|
||||
|
||||
// Restore maps a wire name back to the client name. See Resolve for the rules;
|
||||
// a name it cannot map is returned as is.
|
||||
func (r *ToolRenames) Restore(wire string) string {
|
||||
client, _ := r.Resolve(wire)
|
||||
return client
|
||||
}
|
||||
|
||||
// ClientToolWireName builds the wire name for one client tool. The name keeps
|
||||
|
||||
Reference in new issue
Block a user