Skip to content

Commit 9f59241

Browse files
committed
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.
1 parent 5187184 commit 9f59241

9 files changed

Lines changed: 158 additions & 49 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ Eligibility is a routing decision; the upstream can still reject or rate-limit t
214214

215215
The routing sequence is:
216216

217-
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.
217+
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.
218218
2. Try authenticated tiers in `prefer` order, using only tiers with a configured key and a route for that model.
219219
3. Apply `retry.max_attempts` separately to each authenticated tier.
220220

@@ -293,7 +293,7 @@ See [config.example.json](config.example.json) for a complete starting configura
293293
| `prefer` | `go`; accepts `go` or `zen`. |
294294
| `upstream.zen` | `https://opencode.ai/zen`. |
295295
| `upstream.go` | `https://opencode.ai/zen/go`. |
296-
| `upstream.anonymous` | `https://opencode.ai/inference`; tried first by the anonymous lane, which falls back to `/zen`. |
296+
| `upstream.anonymous` | `https://opencode.ai/inference`; the only anonymous lane (the retired `/zen` fallback is commented out in `anonymousUpstreams`). |
297297
| `proxies` | Falls back to `["direct"]` when both proxy sources are empty. |
298298
| `proxyfile` | Optional; relative paths resolve beside the configuration file. |
299299
| `models.refresh_seconds` | `300`; minimum 1. |

‎internal/config/config.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,9 @@ type UpstreamConfig struct {
129129
// CLI shape. The WebUI also reads the plan's quota from its /v1/usage.
130130
Go string `json:"go"`
131131
// Anonymous is the v2 /inference origin of the keyless free tier. The
132-
// anonymous lane tries this origin first and falls back to the v1 /zen
133-
// origin (models.V1Base, not Zen), which is the only upstream used when
134-
// this one equals the v1 origin. Empty means https://opencode.ai/inference.
132+
// anonymous lane uses only this origin: the v1 /zen fallback is retired for
133+
// free models and its call site is commented out. Empty means
134+
// https://opencode.ai/inference.
135135
Anonymous string `json:"anonymous"`
136136
}
137137

‎internal/gateway/gateway.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@
88
// 1.x User-Agent, the x-opencode-request header, a git-commit-shaped project
99
// and, on the free tier, the 1.x toolset. The v2 lane is the /inference
1010
// origin (upstream.anonymous) and the Go plan's /zen/go origin, which expect
11-
// the OpenCode 2.x CLI shape. The anonymous free tier tries the configured v2
12-
// /inference origin first and falls back to the v1 origin.
11+
// the OpenCode 2.x CLI shape. The anonymous free tier uses the configured v2
12+
// /inference origin only; the retired v1 fallback is kept in
13+
// anonymousUpstreams but commented out.
1314
package gateway
1415

1516
import (

‎internal/gateway/refresh.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,8 +276,8 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin
276276
var models []string
277277
var status int
278278
var err error
279-
// List models on the configured v2 /inference origin first, then fall
280-
// back to the v1 origin (see anonymousUpstreams).
279+
// List models on the configured v2 /inference origin; the v1 fallback
280+
// is retired (see anonymousUpstreams).
281281
for _, upstream := range g.anonymousUpstreams() {
282282
models, status, err = modelcatalog.FetchModels(refreshCtx, node.proxy.client, upstream, anonymousZenKey)
283283
if err == nil || isProxyFailure(err) {

‎internal/gateway/upstream.go‎

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -347,13 +347,14 @@ func (g *Gateway) maxAnonymousExits() int {
347347
// proxy is tried at most once, up to performance.max_anonymous_exits proxies;
348348
// rotating #pool proxies may be drawn again until Retry.MaxAttempts proxies
349349
// were used. For each proxy it tries the upstreams in anonymousUpstreams
350-
// order: the configured v2 /inference upstream (Upstream.Anonymous) before the
351-
// v1 lane (models.V1Base). Any failure, including an HTTP error response,
352-
// advances to the next upstream or proxy; a proxy-route failure, or a proxy
353-
// marked unhealthy, skips that proxy's remaining upstreams. Only a successful
354-
// response ends the anonymous phase; exhausting the proxy cursor returns
355-
// control to the preferred authenticated tiers. It returns the last response
356-
// (body still open), else the last error, plus the number of attempts made.
350+
// order: the configured v2 /inference upstream (Upstream.Anonymous) only, since
351+
// the v1 lane fallback is retired and commented out there. Any failure,
352+
// including an HTTP error response, advances to the next upstream or proxy; a
353+
// proxy-route failure, or a proxy marked unhealthy, skips that proxy's
354+
// remaining upstreams. Only a successful response ends the anonymous phase;
355+
// exhausting the proxy cursor returns control to the preferred authenticated
356+
// tiers. It returns the last response (body still open), else the last error,
357+
// plus the number of attempts made.
357358
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
358359
if g.usesWARP(route.ID, config.TierZen, true) {
359360
return g.doWarpAnonymousUpstream(ctx, route, bodies, ids, attemptOffset)
@@ -550,17 +551,21 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
550551
return nil, lastErr, attempts
551552
}
552553

553-
// anonymousUpstreams returns the ordered base URLs for the keyless free tier:
554-
// the configured v2 /inference origin (Upstream.Anonymous) is tried first, and
555-
// the v1 origin (models.V1Base) is kept as a fallback. Only the v1 origin is
556-
// returned when Upstream.Anonymous is empty or names that same origin.
554+
// anonymousUpstreams returns the ordered base URLs for the keyless free tier.
555+
// Only the v2 /inference origin is used: the 1.x /zen lane was retired for free
556+
// models, so the v1 fallback is commented out rather than called. The code is
557+
// kept for a revert; uncommenting the two lines marked below restores the old
558+
// order (v2 first, v1 as fallback).
557559
func (g *Gateway) anonymousUpstreams() []string {
558-
v1 := strings.TrimRight(models.V1Base, "/")
560+
// v1 := strings.TrimRight(models.V1Base, "/")
559561
primary := strings.TrimRight(g.cfg.Upstream.Anonymous, "/")
560-
if primary == "" || strings.EqualFold(v1, primary) {
561-
return []string{models.V1Base}
562+
if primary == "" {
563+
// Config normalization fills this; keep the v2 default for a zero-value
564+
// config so this never falls through to the retired v1 lane.
565+
primary = "https://opencode.ai/inference"
562566
}
563-
return []string{g.cfg.Upstream.Anonymous, models.V1Base}
567+
return []string{primary}
568+
// return []string{g.cfg.Upstream.Anonymous, models.V1Base}
564569
}
565570

566571
// inferenceClient picks the client of proxy for a request for model to

‎internal/identity/request.go‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,11 @@ func DeriveRequestIDs(r *http.Request, body map[string]any, scope string) Reques
7979
}
8080
projectSignal := jsonutil.FirstString(r.Header.Get("x-opencode-project"), jsonutil.StringAt(body, "metadata", "project_id"))
8181
if projectSignal == "" {
82-
// Without a client project every caller would otherwise share one
83-
// constant upstream project.
84-
projectSignal = "opencode2api:default-project"
85-
if scope != "" {
86-
projectSignal += ":" + scope
87-
}
82+
// A fresh project id per request. The free tier ledges its quota per
83+
// project id and egress, so one shared id is one shared bucket: the old
84+
// per-caller default arrived pre-burned on popular exits. A client that
85+
// names its project keeps that name.
86+
projectSignal = RandomProjectID()
8887
}
8988
parentSession := jsonutil.FirstString(
9089
r.Header.Get("x-parent-session-id"),
@@ -284,3 +283,15 @@ func RandomID(prefix string, size int) string {
284283
}
285284
return prefix + "_" + hex.EncodeToString(buf)
286285
}
286+
287+
// RandomProjectID returns a project id in the shape the official CLI sends: the
288+
// 40-character hex of a git root commit. It is minted per request when the
289+
// client names no project, because the free tier ledges quota per project id
290+
// and egress together. It panics when the system random source fails.
291+
func RandomProjectID() string {
292+
buf := make([]byte, 20)
293+
if _, err := rand.Read(buf); err != nil {
294+
panic(fmt.Sprintf("crypto/rand failed: %v", err))
295+
}
296+
return hex.EncodeToString(buf)
297+
}

‎internal/protocol/response.go‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -503,19 +503,33 @@ func ResponseUsage(protocol Protocol, body []byte) (Usage, bool) {
503503
return decodeOpenAIUsage(usage), true
504504
}
505505

506+
// mayCarryToolName is the fast path for a response body or SSE frame: a body
507+
// that mentions neither a client alias nor a tool-call marker cannot name a
508+
// tool, so it is handed on without decoding. The markers are the protocol's
509+
// own spellings; folding an unprefixed official name (todowrite) needs the
510+
// frame decoded even when no clint_ alias is present.
511+
func mayCarryToolName(body []byte) bool {
512+
return bytes.Contains(body, []byte(ClientToolPrefix)) ||
513+
bytes.Contains(body, []byte(`"tool_calls"`)) ||
514+
bytes.Contains(body, []byte(`"function_call"`)) ||
515+
bytes.Contains(body, []byte(`"custom_tool_call"`)) ||
516+
bytes.Contains(body, []byte(`"tool_use"`)) ||
517+
bytes.Contains(body, []byte(`"server_tool_use"`))
518+
}
519+
506520
// RenameResponseTool rewrites tool call names that carry a client alias back to
507521
// the name the client declared, inside a serialized JSON response or SSE event
508522
// data object for the given protocol. It is the counterpart of the outbound
509523
// clint_ renaming applied to shaped free-tier requests.
510524
//
511-
// The bytes.Contains check is only a fast path that skips the unmarshal for
512-
// frames that cannot contain an alias; every rewrite is an exact map lookup
513-
// after decoding. Names without a mapping are left alone.
525+
// mayCarryToolName is only a fast path that skips the unmarshal for frames that
526+
// cannot contain a tool name; every rewrite is a map lookup after decoding.
527+
// Names that map to nothing are left alone.
514528
func RenameResponseTool(body []byte, protocol Protocol, renames *ToolRenames) []byte {
515529
if renames.Empty() || len(body) == 0 {
516530
return body
517531
}
518-
if !bytes.Contains(body, []byte(ClientToolPrefix)) {
532+
if !mayCarryToolName(body) {
519533
return body
520534
}
521535
var payload map[string]any
@@ -544,8 +558,8 @@ func renameToolInMap(payload map[string]any, protocol Protocol, renames *ToolRen
544558
if !ok {
545559
return false
546560
}
547-
client, ok := renames.Client(name)
548-
if !ok {
561+
client, changed := renames.Resolve(name)
562+
if !changed {
549563
return false
550564
}
551565
container["name"] = client

‎internal/protocol/stream.go‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ func (renamer *streamToolRenamer) rewriteFrame(raw string) []byte {
336336
if renamer.protocol != Chat {
337337
// Anthropic and Responses streams always carry a complete tool name in
338338
// a single event, so the stateless object rewrite is exact.
339-
if !strings.Contains(raw, ClientToolPrefix) {
339+
if !mayCarryToolName([]byte(raw)) {
340340
return []byte(raw)
341341
}
342342
return RenameResponseTool([]byte(raw), renamer.protocol, renamer.renames)
@@ -429,8 +429,12 @@ func (renamer *streamToolRenamer) applyNameFragment(state *streamToolRenameState
429429
delete(function, "name")
430430
return true
431431
}
432-
function["name"] = state.pending
433-
state.decided = true
432+
// The name is complete. Resolve folds a spelling that differs from exactly
433+
// one declared client tool only in case or separators; a name nothing
434+
// declared is written out as the model sent it.
435+
client, renamed := renamer.renames.Resolve(state.pending)
436+
function["name"] = client
437+
state.decided, state.renamed = true, renamed
434438
return true
435439
}
436440

‎internal/protocol/tools.go‎

Lines changed: 84 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,21 @@ const toolWireNameLimit = 64
1919
type ToolRenames struct {
2020
toWire map[string]string
2121
toClient map[string]string
22+
// byCase and byShape map a folded client name back to the one declared
23+
// client tool it names. A value of "" marks a fold two tools share: that
24+
// name is never guessed between.
25+
byCase map[string]string
26+
byShape map[string]string
2227
}
2328

2429
// NewToolRenames returns an empty rename set.
2530
func NewToolRenames() *ToolRenames {
26-
return &ToolRenames{toWire: map[string]string{}, toClient: map[string]string{}}
31+
return &ToolRenames{
32+
toWire: map[string]string{},
33+
toClient: map[string]string{},
34+
byCase: map[string]string{},
35+
byShape: map[string]string{},
36+
}
2737
}
2838

2939
// Empty reports whether no tool was renamed.
@@ -74,6 +84,41 @@ func (r *ToolRenames) Add(client, wire string) {
7484
}
7585
r.toWire[client] = wire
7686
r.toClient[wire] = client
87+
r.bindFolded(r.byCase, strings.ToLower(client), client)
88+
r.bindFolded(r.byShape, foldToolName(client), client)
89+
}
90+
91+
// bindFolded records client under key in a folded map. An empty key names
92+
// nothing (a client tool spelled only with separators must not be handed every
93+
// other such name), and a key two clients share is marked ambiguous.
94+
func (r *ToolRenames) bindFolded(folded map[string]string, key, client string) {
95+
if folded == nil || key == "" {
96+
return
97+
}
98+
if existing, ok := folded[key]; ok {
99+
if existing != client {
100+
folded[key] = ""
101+
}
102+
return
103+
}
104+
folded[key] = client
105+
}
106+
107+
// toolNameSeparators are the characters ignored when matching a tool name by
108+
// shape, after case: "todo_write", "todo-write", "todo.write" and "todowrite"
109+
// all fold to one key.
110+
const toolNameSeparators = "_.- \t\r\n"
111+
112+
// foldToolName lowercases name and removes the separators agents spell tool
113+
// names with, so two spellings of one tool fold together.
114+
func foldToolName(name string) string {
115+
var builder strings.Builder
116+
for _, char := range strings.ToLower(name) {
117+
if !strings.ContainsRune(toolNameSeparators, char) {
118+
builder.WriteRune(char)
119+
}
120+
}
121+
return builder.String()
77122
}
78123

79124
// HasPrefix reports whether any wire name starts with prefix.
@@ -104,19 +149,48 @@ func (r *ToolRenames) HasLongerPrefix(prefix string) bool {
104149
return false
105150
}
106151

107-
// Restore maps a wire name back to the client name. When the exact mapping is
108-
// gone (for example after a configuration reload mid-stream), stripping the
109-
// prefix is the best available recovery; a name without it is returned as is.
110-
func (r *ToolRenames) Restore(wire string) string {
152+
// Resolve maps a tool name the upstream reported back to the name the client
153+
// declared. It is the response-side counterpart of the wire rename: an exact
154+
// wire name restores, a clint_ prefix is stripped as a best-effort recovery
155+
// (for example after a configuration reload mid-stream), and a name that
156+
// differs from exactly one declared client tool only in case, or else only in
157+
// case and separators (todowrite → todo_write), is folded onto that tool. A
158+
// name two tools fold to is never guessed between. It reports whether the
159+
// result differs from the name given.
160+
func (r *ToolRenames) Resolve(wire string) (string, bool) {
161+
if r == nil || wire == "" {
162+
return wire, false
163+
}
111164
if client, ok := r.Client(wire); ok {
112-
return client
165+
return client, client != wire
113166
}
114-
if strings.HasPrefix(wire, ClientToolPrefix) {
115-
if rest := strings.TrimPrefix(wire, ClientToolPrefix); rest != "" {
116-
return rest
167+
client := wire
168+
if rest, ok := strings.CutPrefix(wire, ClientToolPrefix); ok && rest != "" {
169+
client = rest
170+
}
171+
if _, declared := r.toWire[client]; declared {
172+
return client, client != wire
173+
}
174+
lower := strings.ToLower(client)
175+
if match, ok := r.byCase[lower]; ok {
176+
// A key present with an empty value is two client tools folded
177+
// together; the name as written is the only safe answer.
178+
if match != "" {
179+
return match, match != wire
117180
}
181+
return client, client != wire
182+
}
183+
if match, ok := r.byShape[foldToolName(client)]; ok && match != "" {
184+
return match, match != wire
118185
}
119-
return wire
186+
return client, client != wire
187+
}
188+
189+
// Restore maps a wire name back to the client name. See Resolve for the rules;
190+
// a name it cannot map is returned as is.
191+
func (r *ToolRenames) Restore(wire string) string {
192+
client, _ := r.Resolve(wire)
193+
return client
120194
}
121195

122196
// ClientToolWireName builds the wire name for one client tool. The name keeps

0 commit comments

Comments
 (0)