From be91f8697a781ec0c0b41c9a7b1f8ac3fa8e30c1 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Thu, 15 Oct 2026 00:06:24 +0800 Subject: [PATCH] fix: restore free-tier requests and route anonymous probes correctly --- config.example.json | 3 +- internal/config/config.go | 12 +- internal/config/secrets.go | 2 +- internal/gateway/opencode_tools.json | 353 +++++++++++++++++++++++++++ internal/gateway/probe.go | 14 +- internal/gateway/refresh.go | 2 +- internal/gateway/upstream.go | 121 +++++++-- internal/httpx/client.go | 14 +- 8 files changed, 480 insertions(+), 41 deletions(-) create mode 100644 internal/gateway/opencode_tools.json diff --git a/config.example.json b/config.example.json index a76d2a6..083d85c 100644 --- a/config.example.json +++ b/config.example.json @@ -8,7 +8,8 @@ "proxyfile": "", "upstream": { "zen": "https://opencode.ai/zen", - "go": "https://opencode.ai/zen/go" + "go": "https://opencode.ai/zen/go", + "anonymous": "https://opencode.ai/inference" }, "retry": { "max_attempts": 3, diff --git a/internal/config/config.go b/internal/config/config.go index d44250d..ebdc935 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -54,6 +54,10 @@ type ReasoningConfig struct { type UpstreamConfig struct { Zen string `json:"zen"` Go string `json:"go"` + // Anonymous is the base URL used by the keyless free-tier lane. Upstream + // moved keyless inference off /zen onto its own host, so the anonymous lane + // no longer shares the Zen base with the keyed lanes. + Anonymous string `json:"anonymous"` } type RetryConfig struct { @@ -128,7 +132,7 @@ func Load(path string) (Config, error) { } cfg := Config{ Listen: "127.0.0.1:8080", - Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go"}, + Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go", Anonymous: "https://opencode.ai/inference"}, Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300}, Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}}, Performance: PerformanceConfig{MaxIdleConns: 2048, MaxIdleConnsPerHost: 256, MaxConnsPerHost: 0, IdleConnTimeoutSeconds: 120, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 15}, @@ -169,7 +173,11 @@ func Normalize(path string, cfg Config) (Config, error) { } cfg.Upstream.Zen = strings.TrimSpace(cfg.Upstream.Zen) cfg.Upstream.Go = strings.TrimSpace(cfg.Upstream.Go) - for name, raw := range map[string]string{"upstream.zen": cfg.Upstream.Zen, "upstream.go": cfg.Upstream.Go} { + cfg.Upstream.Anonymous = strings.TrimSpace(cfg.Upstream.Anonymous) + if cfg.Upstream.Anonymous == "" { + cfg.Upstream.Anonymous = "https://opencode.ai/inference" + } + for name, raw := range map[string]string{"upstream.zen": cfg.Upstream.Zen, "upstream.go": cfg.Upstream.Go, "upstream.anonymous": cfg.Upstream.Anonymous} { u, err := url.Parse(strings.TrimSpace(raw)) if err != nil || u.Host == "" || (strings.ToLower(u.Scheme) != "http" && strings.ToLower(u.Scheme) != "https") { return Config{}, fmt.Errorf("%s must be an http or https URL", name) diff --git a/internal/config/secrets.go b/internal/config/secrets.go index 5ed4592..d81fa83 100644 --- a/internal/config/secrets.go +++ b/internal/config/secrets.go @@ -46,7 +46,7 @@ func (r *SecretRedactor) Replace(cfg Config) { if cfg.WebUI.Password != "" { values = append(values, cfg.WebUI.Password) } - for _, value := range []string{cfg.Upstream.Zen, cfg.Upstream.Go} { + for _, value := range []string{cfg.Upstream.Zen, cfg.Upstream.Go, cfg.Upstream.Anonymous} { if parsed, err := url.Parse(value); err == nil && parsed.User != nil { values = append(values, value, parsed.User.Username()) if password, ok := parsed.User.Password(); ok { diff --git a/internal/gateway/opencode_tools.json b/internal/gateway/opencode_tools.json new file mode 100644 index 0000000..d3e25b1 --- /dev/null +++ b/internal/gateway/opencode_tools.json @@ -0,0 +1,353 @@ +{ + "edit": { + "description": "Edit the contents of a file by finding and replacing exact text. When editing text from Read output, preserve the exact indentation (tabs or spaces) and omit the line-number prefix, such as `1: `. Never include the prefix in oldString or newString. Write line breaks as \\n; the file's existing CRLF or LF line endings are matched and preserved. To change line endings themselves, make oldString and newString differ only in \\r; that edit applies to the exact bytes. If there is no exact match, the edit retries while ignoring typographic quote, dash, and space variants, then trailing whitespace on each line. The edit fails if oldString is not found. By default, oldString must identify a UNIQUE location. Multiple matches FAIL unless replaceAll is true. Add more surrounding context to disambiguate, or set replaceAll to true to replace every occurrence. Use replaceAll when the change should apply to every occurrence, such as renaming a variable.", + "parameters": { + "additionalProperties": false, + "properties": { + "newString": { + "description": "Text to replace oldString with (must differ from oldString)", + "type": "string" + }, + "oldString": { + "description": "Exact text to find and replace", + "type": "string" + }, + "path": { + "description": "File to edit", + "type": "string" + }, + "replaceAll": { + "description": "Whether to replace every occurrence of oldString. When false, oldString must match exactly once. Defaults to false.", + "type": "boolean" + } + }, + "required": [ + "path", + "oldString", + "newString" + ], + "type": "object" + } + }, + "execute": { + "description": "Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.\n`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable; all other external access goes through `tools`.\nWithin `{ code }`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Inside `{ code }`, ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.\nCall tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.[\"tool-name\"](input)`.\nPrefer an explicit `return`; if omitted, the final top-level expression becomes the result.\nAwait every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.", + "parameters": { + "additionalProperties": false, + "properties": { + "code": { + "type": "string" + } + }, + "required": [ + "code" + ], + "type": "object" + } + }, + "glob": { + "description": "Search file paths using a glob pattern (examples: \"**/*.ts\", \"src/**/*.tsx\").", + "parameters": { + "additionalProperties": false, + "properties": { + "hidden": { + "description": "Include hidden files and directories (default: false).", + "type": "boolean" + }, + "limit": { + "description": "Maximum number of matching files to return (default: 100)", + "exclusiveMinimum": 0, + "type": "integer" + }, + "path": { + "description": "Directory to search. Defaults to the current working directory.", + "type": "string" + }, + "pattern": { + "description": "Glob pattern to match files against", + "type": "string" + } + }, + "required": [ + "pattern" + ], + "type": "object" + } + }, + "grep": { + "description": "Search file contents using ripgrep's regular expression syntax or literal text matching. Use it to locate specific code, symbols, or text patterns, and narrow searches with `path` or `include`. Returns matching file paths, line numbers, and line previews.", + "parameters": { + "additionalProperties": false, + "properties": { + "caseSensitive": { + "description": "Use case-sensitive matching (default: true).", + "type": "boolean" + }, + "include": { + "description": "Glob pattern to filter files (for example, \"*.js\" or \"*.{ts,tsx}\")", + "type": "string" + }, + "limit": { + "description": "Maximum number of matching lines to return (default: 100)", + "exclusiveMinimum": 0, + "type": "integer" + }, + "literal": { + "description": "Treat `pattern` as exact text instead of a regular expression (default: false).", + "type": "boolean" + }, + "path": { + "description": "File or directory to search. Defaults to the current working directory.", + "type": "string" + }, + "pattern": { + "description": "Regular expression or literal text to match in file contents.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "pattern" + ], + "type": "object" + } + }, + "question": { + "description": "Use this tool when you need to ask the user questions during execution. This allows you to:\n1. Gather user preferences or requirements\n2. Clarify ambiguous instructions\n3. Get decisions on implementation choices as you work\n4. Offer choices to the user about what direction to take.\n\nUsage notes:\n- A \"Type your own answer\" option is added automatically; don't include a separate option for free form answers\n- Set `multiple: true` to allow selecting more than one option\n- If you recommend a specific option, make that the first option in the list and add \"(Recommended)\" at the end of the label", + "parameters": { + "additionalProperties": false, + "properties": { + "questions": { + "description": "Questions to ask", + "items": { + "additionalProperties": false, + "properties": { + "header": { + "description": "Very short label (max 30 chars)", + "type": "string" + }, + "multiple": { + "type": "boolean" + }, + "options": { + "description": "Available choices", + "items": { + "additionalProperties": false, + "properties": { + "description": { + "description": "Explanation of choice", + "type": "string" + }, + "label": { + "description": "Display text (1-5 words, concise)", + "type": "string" + } + }, + "required": [ + "label", + "description" + ], + "type": "object" + }, + "type": "array" + }, + "question": { + "description": "Complete question", + "type": "string" + } + }, + "required": [ + "question", + "header", + "options" + ], + "type": "object" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "questions" + ], + "type": "object" + } + }, + "read": { + "description": "Read the contents of a file or directory. Supports text files, images, and PDFs. Images and PDFs are presented directly to the model. Each text line is prefixed by its 1-based line number as : . The prefix is for reference and is not part of the file content. Directory entries are returned one per line. Use offset and limit to read large files or directories in sections. Prefer one larger read over many small slices, and use grep to find specific content in large files.", + "parameters": { + "additionalProperties": false, + "properties": { + "limit": { + "description": "The maximum number of lines or directory entries to read (defaults to and capped at 2000)", + "minimum": 0, + "type": "integer" + }, + "offset": { + "description": "The line or directory entry to start reading from (1-based)", + "minimum": 0, + "type": "integer" + }, + "path": { + "description": "File or directory to read", + "type": "string" + } + }, + "required": [ + "path" + ], + "type": "object" + } + }, + "shell": { + "description": "Execute a shell command and return its output. Commands run on Windows using powershell. Quote file paths containing spaces or special characters. Prefer dedicated tools over shell commands when possible. When output is large, the full result is saved to a file and a truncated preview is returned. Rely on automatic truncation unless filtering the output is more useful. Commands accept an optional timeout, background commands have no timeout by default. Background commands return immediately, and you will be notified when they complete.", + "parameters": { + "additionalProperties": false, + "properties": { + "background": { + "description": "Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion.", + "type": "boolean" + }, + "command": { + "description": "Shell command string to execute", + "type": "string" + }, + "timeout": { + "description": "Timeout in milliseconds. Set to 0 to disable the timeout. Defaults to 120000 for foreground commands. Background commands have no timeout by default.", + "minimum": 0, + "type": "integer" + }, + "workdir": { + "description": "Working directory to execute the command in. Defaults to the current working directory. When possible, avoid changing directories in the command and set the working directory here instead.", + "type": "string" + } + }, + "required": [ + "command" + ], + "type": "object" + } + }, + "skill": { + "description": "Load a specialized skill's instructions and resources into the current conversation when the task at hand matches its description.\n\nThe skill ID must match an available skill or a skill explicitly referenced by the user.", + "parameters": { + "additionalProperties": false, + "properties": { + "id": { + "description": "The ID of an available skill or a skill explicitly referenced by the user", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + } + }, + "subagent": { + "description": "Spawns an agent in a child session to work on the specified task.\nThe output includes a sessionID you can pass back later to continue that specific conversation with the subagent.\nNew child sessions start with fresh context, so include all relevant context and instructions when you don't pass a sessionID.\nForeground (default) runs the subagent to completion and returns its final response.\nBackground mode (background=true) launches it asynchronously and returns immediately; you are notified when it finishes.\nUse background only for independent work that can run while you continue elsewhere.\n\nAvailable subagents:\n- explore: Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. \"src/components/**/*.tsx\"), search code for keywords (eg. \"API endpoints\"), or answer questions about the codebase (eg. \"how do API endpoints work?\"). When calling this agent, specify the desired thoroughness level: \"quick\" for basic searches, \"medium\" for moderate exploration, or \"very thorough\" for comprehensive analysis across multiple locations and naming conventions.\n- general: General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel.", + "parameters": { + "additionalProperties": false, + "properties": { + "agent": { + "description": "The type of specialized agent to use for this task. If the user asks for a subagent by a name that is not one of the available subagents, they most likely mean a model: pick a suitable agent and pass the name through the model parameter instead.", + "type": "string" + }, + "background": { + "description": "Run the subagent in the background and return immediately. You will be notified when it completes. DO NOT sleep, poll, or proactively check on its progress.", + "type": "boolean" + }, + "description": { + "description": "A short 3-5 word label for the task, displayed to the user", + "type": "string" + }, + "model": { + "description": "NEVER set this unless the user explicitly asks for a particular model or variant. The value is written as \"providerID/modelID\", or \"providerID/modelID#variant\" to include a variant. Do not guess the ID: look the model up with the models tool, filtering to your own provider first.", + "type": "string" + }, + "prompt": { + "description": "The task for the subagent to perform", + "type": "string" + }, + "sessionID": { + "description": "Continue a specific previous subagent conversation by passing its sessionID. Calls without a sessionID start a new conversation.", + "pattern": "^ses", + "type": "string" + } + }, + "required": [ + "agent", + "description", + "prompt" + ], + "type": "object" + } + }, + "webfetch": { + "description": "Fetch content from an HTTP or HTTPS URL and return it as text, markdown, or HTML. Markdown is the default.\n\nUse a more targeted tool when one is available. This tool is read-only. Large text results may be replaced with a preview while the complete output is retained in managed storage.", + "parameters": { + "additionalProperties": false, + "properties": { + "format": { + "description": "The format to return the content in. Defaults to markdown.", + "enum": [ + "text", + "markdown", + "html" + ], + "type": "string" + }, + "timeout": { + "description": "Optional timeout in seconds (maximum: 120)", + "exclusiveMinimum": 0, + "maximum": 120, + "type": "number" + }, + "url": { + "description": "The HTTP or HTTPS URL to fetch content from", + "type": "string" + } + }, + "required": [ + "url" + ], + "type": "object" + } + }, + "websearch": { + "description": "Search the web using the user's selected search integration. Use this for current information beyond knowledge cutoff.\n\nThe current year is 2026. Use this year when searching for recent information or current events.", + "parameters": { + "additionalProperties": false, + "properties": { + "query": { + "description": "Websearch query", + "type": "string" + } + }, + "required": [ + "query" + ], + "type": "object" + } + }, + "write": { + "description": "Writes a file to the local filesystem, overwriting if one exists.\n\nMissing parent directories are created automatically.\n\nUse this tool to create new files or overwrite existing files. For partial changes, use the edit tool instead.", + "parameters": { + "additionalProperties": false, + "properties": { + "content": { + "description": "Content to write to the file", + "type": "string" + }, + "path": { + "description": "Path to the file to write to", + "type": "string" + } + }, + "required": [ + "path", + "content" + ], + "type": "object" + } + } +} diff --git a/internal/gateway/probe.go b/internal/gateway/probe.go index 539180f..9dccfdb 100644 --- a/internal/gateway/probe.go +++ b/internal/gateway/probe.go @@ -75,20 +75,20 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult } ids := identity.RequestIDs{Session: identity.CanonicalSessionID("availability:" + model), Project: identity.StableID("prj", "opencode2api:default-project")} type lane struct { - key, name string - client *http.Client + key, name, baseURL string + client *http.Client } var lanes []lane if g.cfg.Anonymous { cursor := g.anonymous.CursorFor(ids.Session) if node := cursor.Next(); node != nil { - lanes = append(lanes, lane{anonymousZenKey, "anonymous", node.proxy.client}) + lanes = append(lanes, lane{anonymousZenKey, "anonymous", g.cfg.Upstream.Anonymous, node.proxy.client}) } } cursor := g.zenNodes.CursorFor(ids.Session) if node := cursor.Next(); node != nil { if proxy := g.zenNodes.Proxy(node); proxy != nil { - lanes = append(lanes, lane{node.key, "zen", proxy.client}) + lanes = append(lanes, lane{node.key, "zen", g.cfg.Upstream.Zen, proxy.client}) } } result := probeResult{reason: "no_probe_channel"} @@ -98,7 +98,7 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult return probeResult{reason: "canceled"} } run := func(effort string) probeResult { - return g.probeAttempt(ctx, lane.client, lane.key, model, protocol, ids, effort) + return g.probeAttempt(ctx, lane.client, lane.baseURL, lane.key, model, protocol, ids, effort) } result = run("") result.channel = lane.name @@ -142,7 +142,7 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult return result } -func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, key, model string, protocol wire.Protocol, ids identity.RequestIDs, effort string) probeResult { +func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, baseURL, key, model string, protocol wire.Protocol, ids identity.RequestIDs, effort string) probeResult { b, err := probePayload(model, protocol, effort) if err != nil { return probeResult{reason: "request_conversion_error"} @@ -150,7 +150,7 @@ func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, key, ctx, cancel := context.WithTimeout(parent, 60*time.Second) defer cancel() ids.Request = identity.RandomID("req", 16) - req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Zen, protocol, b, ids, key) + req, err := newUpstreamRequest(ctx, baseURL, protocol, b, ids, key) if err != nil { return probeResult{reason: "request_creation_error"} } diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index deb6f28..0a404a7 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -207,7 +207,7 @@ func (g *Gateway) refreshZen(ctx context.Context) []string { if !g.cfg.Anonymous { return nil } - return g.refreshAnonymousTier(ctx, g.cfg.Upstream.Zen) + return g.refreshAnonymousTier(ctx, g.cfg.Upstream.Anonymous) } func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []string { diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 2e15124..8c68b8b 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "crypto/sha256" + _ "embed" "encoding/hex" "encoding/json" "errors" @@ -13,6 +14,7 @@ import ( "sort" "strconv" "strings" + "sync" "time" "opencode2api/internal/config" @@ -296,7 +298,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b httpx.DrainAndClose(lastResponse.Body) lastResponse = nil } - req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Zen, route.Protocol, body, ids, anonymousZenKey) + req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Anonymous, route.Protocol, body, ids, anonymousZenKey) if err != nil { return nil, err, attempts } @@ -338,17 +340,54 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b } // anonymousCoreTools are the tool names the anonymous free tier expects on -// an agent-shaped request. Requests without them are rejected with 403 -// FreeTierError. Only the names matter; the gateway synthesizes minimal -// definitions for whichever ones the downstream client did not declare. -var anonymousCoreTools = []string{"bash", "edit", "glob", "grep", "read"} +// an agent-shaped request. Requests without a shell tool and a read tool are +// rejected with 403 FreeTierError. +// +// "shell" is the name OpenCode 2.x ships; the pre-2.x "bash" spelling is +// deliberately not injected because the free tier validates the definition of +// every tool it recognises, and a "bash" definition the gateway synthesises +// does not match the one upstream expects. +var anonymousCoreTools = []string{"shell", "edit", "glob", "grep", "read"} + +// opencodeToolsJSON holds the genuine OpenCode tool definitions (description +// and JSON schema) captured from the official client. The free tier checks the +// definition of every tool whose name it recognises, so a synthesised stub — +// even one carrying the right name — is rejected with 403 FreeTierError. The +// gateway therefore ships the real definitions and uses them both for the tools +// it injects and for any same-named tool the downstream client declared. +// +//go:embed opencode_tools.json +var opencodeToolsJSON []byte + +type opencodeToolDefinition struct { + Description string `json:"description"` + Parameters map[string]any `json:"parameters"` +} + +var ( + opencodeToolsOnce sync.Once + opencodeTools map[string]opencodeToolDefinition +) + +// knownOpencodeTool returns the genuine definition for an OpenCode tool name. +func knownOpencodeTool(name string) (opencodeToolDefinition, bool) { + opencodeToolsOnce.Do(func() { + definitions := map[string]opencodeToolDefinition{} + if err := json.Unmarshal(opencodeToolsJSON, &definitions); err != nil { + definitions = map[string]opencodeToolDefinition{} + } + opencodeTools = definitions + }) + definition, ok := opencodeTools[name] + return definition, ok +} // 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. 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. +// free tier: streaming enabled plus the core agent tools present with genuine +// definitions. Bodies that already satisfy all of that (or are not JSON +// objects) are returned 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 @@ -398,10 +437,11 @@ func ensureAnonymousChatUsage(payload map[string]any, protocol wire.Protocol) bo return true } -// ensureAnonymousTools appends minimal definitions for any missing core -// tool so the request reads as an agent session upstream. It reports -// whether the payload changed. Tools the client already declared are left -// untouched. +// ensureAnonymousTools makes the tool list read as an agent session: every +// recognised OpenCode tool carries its genuine definition, and the missing +// core tools are appended. It reports whether the payload changed. Tools whose +// names upstream does not recognise are left exactly as the client declared +// them, so downstream function calling keeps working. func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol) bool { raw, exists := payload["tools"] if !exists { @@ -412,10 +452,20 @@ func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol) bool { if !ok { return false } + changed := false present := make(map[string]bool, len(items)) - for _, item := range items { - if name := anonymousToolName(protocol, item); name != "" { - present[name] = true + for index, item := range items { + name := anonymousToolName(protocol, item) + if name == "" { + continue + } + present[name] = true + // A declared definition for a recognised tool name is replaced with the + // genuine one: the free tier rejects a stub, and a client that happens to + // use the same name with its own schema would otherwise fail the request. + if _, known := knownOpencodeTool(name); known { + items[index] = anonymousTool(protocol, name) + changed = true } } missing := make([]string, 0, len(anonymousCoreTools)) @@ -424,10 +474,14 @@ func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol) bool { missing = append(missing, name) } } - if len(missing) == 0 { + if len(missing) > 0 { + items = append(items, anonymousToolset(protocol, missing)...) + changed = true + } + if !changed { return false } - payload["tools"] = append(items, anonymousToolset(protocol, missing)...) + payload["tools"] = items return true } @@ -453,9 +507,17 @@ func anonymousToolset(protocol wire.Protocol, names []string) []any { return tools } +// anonymousTool renders one core tool in the shape the given protocol expects, +// using the genuine OpenCode definition whenever one is known. func anonymousTool(protocol wire.Protocol, name string) map[string]any { description := "Agent tool " + name parameters := map[string]any{"type": "object", "properties": map[string]any{}} + if definition, ok := knownOpencodeTool(name); ok { + description = definition.Description + if definition.Parameters != nil { + parameters = definition.Parameters + } + } switch protocol { case wire.Chat: return map[string]any{ @@ -804,16 +866,18 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Proto } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json, text/event-stream") + // Upstream fingerprints the client on every tier: it wants the OpenCode + // User-Agent shape, x-opencode-session-id, and a bare 40-character hex + // x-opencode-project, and it rejects the gateway's own x-opencode-request + // header. Dropping or changing any one of them turns the request into a 403 + // FreeTierError, so the client's header set is mirrored exactly. req.Header.Set("User-Agent", httpx.UserAgent()) req.Header.Set("x-opencode-client", "cli") req.Header.Set("x-opencode-session", ids.Session) - // OpenCode 1.18.x sends these correlation headers to preserve provider-side - // prompt/session affinity. Keep the legacy x-opencode-session header too so - // older Zen deployments continue to recognize the request. + req.Header.Set("x-opencode-session-id", ids.Session) req.Header.Set("x-session-affinity", ids.Session) req.Header.Set("X-Session-Id", ids.Session) - req.Header.Set("x-opencode-request", ids.Request) - req.Header.Set("x-opencode-project", ids.Project) + req.Header.Set("x-opencode-project", clientProjectID(ids.Project)) if ids.ParentSession != "" { req.Header.Set("x-parent-session-id", ids.ParentSession) } @@ -827,6 +891,15 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Proto return req, nil } +// clientProjectID renders the project header the way the client does: a bare +// 40-character lowercase hex id rather than the gateway's "prj_" prefixed +// stable id. The value itself is not checked upstream, only its shape, but +// hashing keeps one conversation pinned to one project. +func clientProjectID(project string) string { + sum := sha256.Sum256([]byte("opencode-project\x00" + project)) + return hex.EncodeToString(sum[:20]) +} + func isNonRetryableClientResponse(resp *http.Response, err error) bool { return err == nil && resp != nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests } diff --git a/internal/httpx/client.go b/internal/httpx/client.go index 34fb9f2..804f2ee 100644 --- a/internal/httpx/client.go +++ b/internal/httpx/client.go @@ -1,10 +1,14 @@ package httpx -import ( - "fmt" - "runtime" -) +// clientVersion is the OpenCode release the gateway claims to be. Upstream +// accepts a range of releases, so this only needs bumping when it starts +// rejecting older ones. +const clientVersion = "2.0.29" +// UserAgent reports the gateway as an OpenCode client using the shape upstream +// expects: "opencode///". The previous +// "opencode/ ( ; )" form is rejected with 403 +// FreeTierError even when the rest of the request is identical. func UserAgent() string { - return fmt.Sprintf("opencode/1.18.31 (%s %s; %s)", runtime.GOOS, runtime.GOARCH, runtime.Version()) + return "opencode/latest/" + clientVersion + "/cli" }