mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
feat(free-tier): prefix client tools with clint_ and complete the official set
Shaped free-model requests now look like an official CLI session on every lane. Each client tool is renamed to a sanitized, collision-free clint_ name and the full official tool set for the lane is appended (11 tools on the 1.x /zen lane, 13 on 2.x /inference and /zen/go). Requests without tools, with an empty array, or with a legacy functions array receive the official set too, and tool_choice, function_call and the tool-call history are rewritten to match. Responses, streaming and not, are restored to the names the client declared, including a Chat in a stream split across chunks. Unmapped names pass through, so an official tool the client never declared is never hidden or replayed.
This commit is contained in:
1 parent
97cdb29713
commit
fd4c1c6d40
15 files changed
+1088
-507
No files matched your search
@@ -240,6 +240,12 @@ Ogni richiesta di un modello gratuito già normalizzata porta il system prompt d
|
||||
|
||||
L'iniezione dipende dal protocollo: i messaggi system e developer di Chat vengono fusi in un unico messaggio `system` iniziale; Anthropic riceve un valore `system` (stringa, oppure un blocco di testo iniziale quando il chiamante invia blocchi); Responses riceve `instructions`. Se il contenuto system contiene già il marcatore `You are opencode, an interactive CLI tool`, la richiesta passa invariata, quindi un client che invia già il prompt ufficiale non ne riceve una seconda copia. I modelli gratuiti serviti da una chiave Zen o Go ricevono la stessa normalizzazione, ma escono comunque dal proxy di quel tier.
|
||||
|
||||
### Normalizzazione degli strumenti
|
||||
|
||||
Su ogni richiesta di un modello gratuito già normalizzata il gateway rinomina ogni strumento nominato del client in `clint_<name>` — i caratteri fuori da `A-Za-z0-9_-` diventano `_`, i nomi sono limitati a 64 byte e le collisioni ricevono il suffisso `_2`, `_3`, … — e aggiunge l'intero set ufficiale del canale: le definizioni 1.x (`bash`, `edit`, `glob`, `grep`, `read`, `skill`, `task`, `todowrite`, `webfetch`, `websearch`, `write`) su `/zen` e il set di 13 strumenti 2.x su `/inference` e `/zen/go`. Le richieste senza `tools`, con un array vuoto o con il vecchio array `functions` ricevono lo stesso set; `tool_choice`, il vecchio `function_call` e la cronologia delle tool call vengono riscritti di conseguenza. Gli strumenti integrati di Responses e quelli server di Anthropic restano invariati.
|
||||
|
||||
Le risposte vengono riportate ai nomi dichiarati dal client, sia in streaming sia non, incluso un nome Chat suddiviso su più chunk. Se l'upstream chiama uno strumento ufficiale che il client non ha dichiarato, il nome passa invariato: il gateway non riproduce né nasconde le chiamate ufficiali.
|
||||
|
||||
### Disponibilità dei modelli gratuiti
|
||||
|
||||
Il gateway verifica con una breve richiesta e il protocollo nativo i modelli il cui ID contiene `free` (senza distinzione tra maiuscole e minuscole) oppure i cui metadati indicano un costo input/output pari a zero e che non sono deprecati. Prova prima il canale anonimo abilitato, poi una chiave Zen configurata. Con `warp.enabled`, ogni canale di probe esce tramite WARP invece che da un proxy; se non è possibile acquisire un'uscita il risultato è `warp_unavailable` e resta inconcludente. Una risposta valida e completa su uno dei canali mantiene il modello abilitato. Il modello viene disabilitato nel rilevamento e nell'instradamento solo quando tutti i canali provati indicano esplicitamente che non esiste o è stato ritirato. Errori di autenticazione, limiti di frequenza, timeout, errori di trasporto, risposte 5xx e risposte malformate non sono conclusivi: non disabilitano nuovi modelli e vengono verificati di nuovo dopo un'ora. I controlli non alterano cooldown, stato dei proxy o statistiche delle richieste di produzione, ma raggiungono comunque l'upstream e possono consumare la quota gratuita.
|
||||
|
||||
@@ -242,6 +242,12 @@ Every shaped free-model request carries the OpenCode CLI's own system prompt —
|
||||
|
||||
Injection is protocol-aware: Chat system and developer messages are folded into one leading `system` message, Anthropic receives a `system` value (a string, or a leading text block when the caller sent blocks), and Responses receives `instructions`. A body whose system content already contains the marker `You are opencode, an interactive CLI tool` is passed through, so a client that sends the official prompt never gets a second copy. Free models served by a Zen or Go key receive the same shaping even though they still leave through that tier's proxy.
|
||||
|
||||
### Tool shaping
|
||||
|
||||
On every shaped free-model request the gateway renames each named client tool to `clint_<name>` — characters outside `A-Za-z0-9_-` become `_`, names are capped at 64 bytes, and collisions get a `_2`, `_3`, … suffix — and appends the complete official tool set for the lane: the 1.x definitions (`bash`, `edit`, `glob`, `grep`, `read`, `skill`, `task`, `todowrite`, `webfetch`, `websearch`, `write`) on `/zen`, and the 13-tool 2.x set on `/inference` and `/zen/go`. Requests without a `tools` array, with an empty one, or with a legacy `functions` array get the same official set; `tool_choice`, legacy `function_call`, and the tool-call history are rewritten to match. Responses built-in tools and Anthropic server tools are left untouched.
|
||||
|
||||
Responses are restored to the names the client declared, for streaming and non-streaming replies, including a Chat tool name split across chunks. If the upstream calls an official tool the client never declared, that name passes through unchanged: the gateway does not replay or hide official tool calls.
|
||||
|
||||
### Free model availability
|
||||
|
||||
The gateway probes models whose IDs contain `free` (case-insensitive), or whose metadata reports zero input/output cost without deprecation, with a short request using its native protocol. It tries the enabled anonymous lane first and then one configured Zen Key. With `warp.enabled`, every probe lane leaves through WARP instead of a proxy; when no exit can be acquired the probe reports `warp_unavailable` and stays inconclusive. A valid completed response on either lane keeps the model enabled; the model is disabled in discovery and routing only when every attempted lane explicitly reports that the model does not exist or has been retired. Authentication errors, rate limits, timeouts, transport errors, 5xx responses, and malformed replies are inconclusive: they do not create a new disable, and are checked again in one hour. Probe traffic does not alter production key/proxy cooldowns or request statistics. It still reaches the upstream and may consume its free allowance.
|
||||
|
||||
@@ -246,6 +246,12 @@ Mỗi request mô hình miễn phí đã được định hình đều mang syst
|
||||
|
||||
Việc chèn phụ thuộc giao thức: các message system và developer của Chat được gộp thành một message `system` duy nhất ở đầu; Anthropic nhận giá trị `system` (chuỗi, hoặc một text block ở đầu khi bên gọi gửi danh sách block); Responses nhận `instructions`. Nếu nội dung system đã chứa dấu hiệu `You are opencode, an interactive CLI tool`, request được giữ nguyên, nên client đã gửi prompt chính thức sẽ không bị chèn lần hai. Mô hình miễn phí phục vụ qua Zen hoặc Go Key cũng được định hình như vậy nhưng vẫn ra ngoài qua proxy của tier đó.
|
||||
|
||||
### Định hình công cụ
|
||||
|
||||
Trên mỗi request mô hình miễn phí đã được định hình, gateway đổi tên từng công cụ có tên của client thành `clint_<name>` — ký tự ngoài `A-Za-z0-9_-` thành `_`, tên tối đa 64 byte, trùng tên thì thêm hậu tố `_2`, `_3`, … — rồi thêm toàn bộ bộ công cụ chính thức của làn: định nghĩa 1.x (`bash`, `edit`, `glob`, `grep`, `read`, `skill`, `task`, `todowrite`, `webfetch`, `websearch`, `write`) trên `/zen`, và bộ 13 công cụ 2.x trên `/inference` và `/zen/go`. Request không có `tools`, có mảng rỗng, hoặc dùng mảng `functions` kiểu cũ cũng nhận bộ chính thức; `tool_choice`, `function_call` kiểu cũ và lịch sử tool call được viết lại tương ứng. Công cụ tích hợp của Responses và công cụ máy chủ của Anthropic được giữ nguyên.
|
||||
|
||||
Phản hồi được khôi phục về tên client đã khai báo, cho cả luồng và không luồng, kể cả tên công cụ Chat bị chia qua nhiều chunk. Nếu upstream gọi một công cụ chính thức mà client chưa khai báo, tên đó được truyền nguyên: gateway không phát lại hay che các lời gọi công cụ chính thức.
|
||||
|
||||
### Tính khả dụng của mô hình miễn phí
|
||||
|
||||
Gateway dò các mô hình có ID chứa `free` (không phân biệt hoa thường), hoặc có metadata báo chi phí input/output bằng 0 mà không bị ngừng cấp, bằng một request ngắn dùng giao thức gốc của mô hình. Nó thử làn ẩn danh đang bật trước, rồi tới một Zen Key đã cấu hình. Khi bật `warp.enabled`, mọi làn dò đi qua WARP thay vì proxy; nếu không lấy được đầu ra, kết quả là `warp_unavailable` và được coi là không kết luận. Một phản hồi hợp lệ và hoàn tất trên bất kỳ làn nào sẽ giữ mô hình ở trạng thái bật; mô hình chỉ bị tắt trong phát hiện và định tuyến khi mọi làn được thử đều báo rõ ràng rằng mô hình không tồn tại hoặc đã bị thu hồi. Lỗi xác thực, giới hạn tần suất, timeout, lỗi truyền tải, phản hồi 5xx và câu trả lời sai định dạng đều không kết luận: chúng không tạo ra lần tắt mới và sẽ được kiểm tra lại sau một giờ. Lưu lượng dò không làm thay đổi cooldown key/proxy sản xuất hay thống kê request. Nó vẫn đi tới upstream và có thể tiêu tốn hạn mức miễn phí của họ.
|
||||
|
||||
@@ -242,6 +242,12 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
|
||||
|
||||
注入按协议处理:Chat 的系统与 developer 消息会合并为一条位于最前的 `system` 消息;Anthropic 写入 `system`(字符串,或调用方提供块列表时在最前插入文本块);Responses 写入 `instructions`。如果系统内容中已包含标记 `You are opencode, an interactive CLI tool`,请求会原样通过,因此已经发送官方提示词的客户端不会被重复注入。通过 Zen 或 Go Key 提供的免费模型也会接受同样的整形,只是仍然从对应 Tier 的代理出网。
|
||||
|
||||
### 工具整形
|
||||
|
||||
每个经过整形的免费模型请求中,网关会把客户端声明的每个具名工具改名为 `clint_<name>`——`A-Za-z0-9_-` 之外的字符替换为 `_`,名称最长 64 字节,冲突时追加 `_2`、`_3` 等后缀——并追加该通道的完整官方工具集:`/zen` 使用 1.x 定义(`bash`、`edit`、`glob`、`grep`、`read`、`skill`、`task`、`todowrite`、`webfetch`、`websearch`、`write`),`/inference` 与 `/zen/go` 使用 13 个工具的 2.x 定义。没有 `tools`、`tools` 为空数组或使用旧版 `functions` 数组的请求同样会补全官方工具集;`tool_choice`、旧版 `function_call` 和工具调用历史会同步改写。Responses 内置工具和 Anthropic 服务端工具保持不变。
|
||||
|
||||
响应会恢复为客户端声明的名称,流式与非流式均适用,包括被拆分到多个 Chat 分块中的工具名。如果上游调用了客户端从未声明的官方工具,该名称会原样透传:网关不会重放或隐藏官方工具调用。
|
||||
|
||||
### 免费模型可用性
|
||||
|
||||
只探测 ID 含 `free`(不区分大小写),或元数据输入、输出价格均为零且未弃用的模型,按模型原生协议发送简短探测请求。先尝试已启用的匿名通道,再尝试一个配置的 Zen Key;启用 `warp.enabled` 时,每条探测通道都改走 WARP 而不是代理,无法取得出口时结果为 `warp_unavailable`,视为不确定。任一通道返回完整有效响应即视为可用,只有所有实际尝试的通道都明确返回模型不存在或已下架时才自动禁用,从模型列表与路由中移除。认证失败、429、超时、网络错误、5xx 和响应格式异常均视为结果不确定,不新增禁用,1 小时后复测。探测不修改生产 Key / 代理的冷却状态,也不计入请求统计,但仍会访问上游并可能消耗免费额度。
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// origin (models.V1Base, also the default upstream.zen), which
|
||||
// models.IsV1Upstream detects. It expects the OpenCode 1.x client shape: the
|
||||
// 1.x User-Agent, the x-opencode-request header, a git-commit-shaped project
|
||||
// and, on the free tier, the single "read" tool. The v2 lane is the /inference
|
||||
// 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.
|
||||
@@ -222,16 +222,17 @@ func callerScope(ctx context.Context) string {
|
||||
type requestShapeContextKey struct{}
|
||||
|
||||
type requestShape struct {
|
||||
shaped bool
|
||||
toolAlias string
|
||||
shaped bool
|
||||
renames *wire.ToolRenames
|
||||
}
|
||||
|
||||
func setRequestShape(ctx context.Context, shaped bool, toolAlias string) {
|
||||
func setRequestShape(ctx context.Context, shaped bool, renames *wire.ToolRenames) {
|
||||
if state, ok := ctx.Value(requestShapeContextKey{}).(*requestShape); ok {
|
||||
state.shaped, state.toolAlias = shaped, toolAlias
|
||||
state.shaped, state.renames = shaped, renames
|
||||
}
|
||||
if meta := telemetry.MetaFromContext(ctx); meta != nil {
|
||||
meta.Shaped, meta.ToolAlias = shaped, toolAlias
|
||||
meta.Shaped = shaped
|
||||
meta.ToolRenames = renames.Count()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,7 +383,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
shape := requestShapeFrom(r.Context())
|
||||
toolAlias := shape.toolAlias
|
||||
toolRenames := shape.renames
|
||||
if stream {
|
||||
if meta != nil {
|
||||
meta.Stream = true
|
||||
@@ -395,7 +396,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
streamBody := wire.RenameStreamReader(resp.Body, upstreamRoute.Protocol, v1ReadTool, toolAlias)
|
||||
streamBody := wire.RenameStreamReader(resp.Body, upstreamRoute.Protocol, toolRenames)
|
||||
var usage wire.Usage
|
||||
var usageReported bool
|
||||
if external == upstreamRoute.Protocol {
|
||||
@@ -435,7 +436,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
}
|
||||
responseBody = collapsed
|
||||
}
|
||||
responseBody = wire.RenameResponseTool(responseBody, upstreamRoute.Protocol, v1ReadTool, toolAlias)
|
||||
responseBody = wire.RenameResponseTool(responseBody, upstreamRoute.Protocol, toolRenames)
|
||||
if usage, reported := wire.ResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil {
|
||||
meta.Usage, meta.UsageReported = usage, reported
|
||||
}
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
[
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "bash",
|
||||
"description": "Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.\n\nBe aware: OS: linux, Shell: bash\n\nAll commands run in the current working directory by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID using `cd <directory> && <command>` patterns - use `workdir` instead.\n\nUse `/tmp/opencode` for temporary work outside the workspace. This directory has already been created, already exists, and is pre-approved for external directory access.\n\nIMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.\n\nBefore executing the command, please follow these steps:\n\n1. Directory Verification:\n - If the command will create new directories or files, first use `ls` to verify the parent directory exists and is the correct location\n - For example, before running \"mkdir foo/bar\", first use `ls foo` to check that \"foo\" exists and is the intended parent directory\n\n2. Command Execution:\n - Always quote file paths that contain spaces with double quotes (e.g., rm \"path with spaces/file.txt\")\n - Examples of proper quoting:\n - mkdir \"/Users/name/My Documents\" (correct)\n - mkdir /Users/name/My Documents (incorrect - will fail)\n - python \"/path/with spaces/script.py\" (correct)\n - python /path/with spaces/script.py (incorrect - will fail)\n - After ensuring proper quoting, execute the command.\n - Capture the output of the command.\n\nUsage notes:\n - The command argument is required.\n - You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms.\n - If the output exceeds 2000 lines or 51200 bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Do NOT use `head`, `tail`, or other truncation commands to limit output; the full output will already be captured to a file for more precise searching.\n\n - Avoid using Bash with the `find`, `grep`, `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:\n - File search: Use Glob (NOT find or ls)\n - Content search: Use Grep (NOT grep or rg)\n - Read files: Use Read (NOT cat/head/tail)\n - Edit files: Use Edit (NOT sed/awk)\n - Write files: Use Write (NOT echo >/cat <<EOF)\n - Communication: Output text directly (NOT echo/printf)\n - When issuing multiple commands:\n - If the commands are independent and can run in parallel, make multiple bash tool calls in a single message. For example, if you need to run \"git status\" and \"git diff\", send a single message with two bash tool calls in parallel.\n - If the commands depend on each other and must run sequentially, use a single Bash call with '&&' to chain them together (e.g., `git add . && git commit -m \"message\" && git push`). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead.\n - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail\n - DO NOT use newlines to separate commands (newlines are ok in quoted strings)\n - AVOID using `cd <directory> && <command>`. Use the `workdir` parameter to change directories instead.\n <good-example>\n Use workdir=\"/foo/bar\" with command: pytest tests\n </good-example>\n <bad-example>\n cd /foo/bar && pytest tests\n </bad-example>\n\n# Git and GitHub\n- Only commit, amend, push, or create PRs when explicitly requested.\n- Before committing, inspect `git status`, `git diff`, and `git log --oneline -10`; stage only intended files and never commit secrets.\n- Write a concise commit message that matches the repo style.\n- Do not update git config, skip hooks, use interactive `-i`, force-push, or create empty commits unless explicitly requested.\n- If a commit fails or hooks reject it, fix the issue and create a new commit; do not amend the failed commit.\n- Before creating a PR, inspect status, diff, remote tracking, recent commits, and the diff from the base branch.\n- Review all commits included in the PR, not just the latest commit.\n- Use `gh` for GitHub tasks, including PRs, issues, checks, and releases; return the PR URL when done.\n",
|
||||
"parameters": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "The command to execute"
|
||||
},
|
||||
"timeout": {
|
||||
"minimum": -9007199254740991,
|
||||
"exclusiveMinimum": 0,
|
||||
"type": "integer",
|
||||
"maximum": 9007199254740991,
|
||||
"description": "Optional timeout in milliseconds"
|
||||
},
|
||||
"workdir": {
|
||||
"type": "string",
|
||||
"description": "The working directory to run the command in. Defaults to the current directory. Use this instead of 'cd' commands."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "edit",
|
||||
"description": "Performs exact string replacements in files. \n\nUsage:\n- You must use your `Read` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file. \n- When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: line number + colon + space (e.g., `1: `). Everything after that space is the actual file content to match. Never include any part of the line number prefix in the oldString or newString.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\n- The edit will FAIL if `oldString` is not found in the file with an error \"oldString not found in content\".\n- The edit will FAIL if `oldString` is found multiple times in the file with an error \"Found multiple matches for oldString. Provide more surrounding lines in oldString to identify the correct match.\" Either provide a larger string with more surrounding context to make it unique or use `replaceAll` to change every instance of `oldString`. \n- Use `replaceAll` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.\n",
|
||||
"parameters": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filePath": {
|
||||
"type": "string",
|
||||
"description": "The absolute path to the file to modify"
|
||||
},
|
||||
"oldString": {
|
||||
"type": "string",
|
||||
"description": "The text to replace"
|
||||
},
|
||||
"newString": {
|
||||
"type": "string",
|
||||
"description": "The text to replace it with (must be different from oldString)"
|
||||
},
|
||||
"replaceAll": {
|
||||
"type": "boolean",
|
||||
"description": "Replace all occurrences of oldString (default false)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"filePath",
|
||||
"oldString",
|
||||
"newString"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "glob",
|
||||
"description": "- Fast file pattern matching tool that works with any codebase size\n- Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n- Returns matching file paths\n- Use this tool when you need to find files by name patterns\n- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the Task tool instead\n- You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.\n",
|
||||
"parameters": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"pattern": {
|
||||
"type": "string",
|
||||
"description": "The glob pattern to match files against"
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter \"undefined\" or \"null\" - simply omit it for the default behavior. Must be a valid directory path if provided."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"pattern"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "grep",
|
||||
"description": "- Fast content search tool that works with any codebase size\n- Searches file contents using regular expressions\n- Supports full regex syntax (eg. \"log.*Error\", \"function\\s+\\w+\", etc.)\n- Filter files by pattern with the include parameter (eg. \"*.js\", \"*.{ts,tsx}\")\n- Returns file paths and line numbers with matching lines\n- Use this tool when you need to find files containing specific patterns\n- If you need to identify/count the number of matches within files, use the Bash tool with `rg` (ripgrep) directly. Do NOT use `grep`.\n- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the Task tool instead\n",
|
||||
"parameters": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"pattern": {
|
||||
"type": "string",
|
||||
"description": "The regex pattern to search for in file contents"
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "The directory to search in. Defaults to the current working directory."
|
||||
},
|
||||
"include": {
|
||||
"type": "string",
|
||||
"description": "File pattern to include in the search (e.g. \"*.js\", \"*.{ts,tsx}\")"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"pattern"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "read",
|
||||
"description": "Read a file or directory from the local filesystem. If the path does not exist, an error is returned.\n\nUsage:\n- The filePath parameter should be an absolute path.\n- By default, this tool returns up to 2000 lines from the start of the file.\n- The offset parameter is the line number to start from (1-indexed).\n- To read later sections, call this tool again with a larger offset.\n- Use the grep tool to find specific content in large files or files with long lines.\n- If you are unsure of the correct file path, use the glob tool to look up filenames by glob pattern.\n- Contents are returned with each line prefixed by its line number as `<line>: <content>`. For example, if a file has contents \"foo\\n\", you will receive \"1: foo\\n\". For directories, entries are returned one per line (without line numbers) with a trailing `/` for subdirectories.\n- Any line longer than 2000 characters is truncated.\n- Call this tool in parallel when you know there are multiple files you want to read.\n- Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.\n- This tool can read image files and PDFs and return them as file attachments.\n",
|
||||
"parameters": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filePath": {
|
||||
"type": "string",
|
||||
"description": "The absolute path to the file or directory to read"
|
||||
},
|
||||
"offset": {
|
||||
"minimum": 0,
|
||||
"type": "integer",
|
||||
"maximum": 9007199254740991,
|
||||
"description": "The line number to start reading from (1-indexed)"
|
||||
},
|
||||
"limit": {
|
||||
"minimum": 0,
|
||||
"type": "integer",
|
||||
"maximum": 9007199254740991,
|
||||
"description": "The maximum number of lines to read (defaults to 2000)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"filePath"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "skill",
|
||||
"description": "Load a specialized skill when the task at hand matches one of the skills listed in the system prompt.\n\nUse this tool to inject the skill's instructions and resources into current conversation. The output may contain detailed workflow guidance as well as references to scripts, files, etc in the same directory as the skill.\n\nThe skill name must match one of the skills listed in your system prompt.\n",
|
||||
"parameters": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "The name of the skill from available_skills"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "task",
|
||||
"description": "Launch a new agent to handle complex, multistep tasks autonomously.\n\nWhen using the Task tool, you must specify a subagent_type parameter to select which agent type to use.\n\nWhen NOT to use the Task tool:\n- If you want to read a specific file path, use the Read or Glob tool instead of the Task tool, to find the match more quickly\n- If you are searching for a specific class definition like \"class Foo\", use the Grep tool instead, to find the match more quickly\n- If you are searching for code within a specific file or set of 2-3 files, use the Read tool instead of the Task tool, to find the match more quickly\n- If no available agent is a good fit for the task, use other tools directly\n\n\nUsage notes:\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n2. Once you have delegated work to an agent, do not duplicate that work yourself. Continue with non-overlapping tasks, or wait for the result. For background tasks, you will be notified automatically when the result is ready.\n3. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result. The output includes a task_id you can reuse later to continue the same subagent session.\n4. Each agent invocation starts with a fresh context unless you provide task_id to resume the same subagent session (which continues with its previous messages and tool outputs). When starting fresh, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n5. The agent's outputs should generally be trusted\n6. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands).\n7. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n\nAvailable agent types and the tools they have access to:\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": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "A short (3-5 words) description of the task"
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string",
|
||||
"description": "The task for the agent to perform"
|
||||
},
|
||||
"subagent_type": {
|
||||
"type": "string",
|
||||
"description": "The type of specialized agent to use for this task"
|
||||
},
|
||||
"task_id": {
|
||||
"type": "string",
|
||||
"description": "This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)"
|
||||
},
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "The command that triggered this task"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"description",
|
||||
"prompt",
|
||||
"subagent_type"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "todowrite",
|
||||
"description": "Create and maintain a structured task list for the current coding session. Tracks progress, organizes multi-step work, and surfaces status to the user.\n\n## When to use\nUse proactively when:\n- The task requires 3+ distinct steps or actions (not just 3 tool calls for a single conceptual step)\n- The work is non-trivial and benefits from planning\n- The user provides multiple tasks (numbered or comma-separated) or explicitly asks for a todo list\n- New instructions arrive - capture them as todos\n- You start a task - mark it `in_progress` (only one at a time) before working\n- You finish a task - mark it `completed` and add any follow-ups discovered during the work\n\n## When NOT to use\nSkip when:\n- The work is a single, straightforward task (or <3 trivial steps)\n- The request is purely informational or conversational\n- Tracking adds no organizational value\n\n## States\n- `pending` - not started\n- `in_progress` - actively working (exactly ONE at a time)\n- `completed` - finished successfully\n- `cancelled` - no longer needed\n\n## Rules\n- Update status in real time; don't batch completions\n- Mark `completed` only after the required work is actually done, including any required verification. Never based on intent.\n- Keep exactly one `in_progress` while work remains\n- If blocked or partial, keep it `in_progress` and add a follow-up todo describing the blocker\n- Preserve user-provided commands verbatim (flags, args, order)\n- Items should be specific and actionable; break large work into smaller steps\n\n## Examples\n\nUse it:\n- \"Add a dark mode toggle and run the tests\" -> multi-step feature + explicit verification\n- \"Rename getCwd -> getCurrentWorkingDirectory across the repo\" -> grep reveals 15 occurrences in 8 files\n- \"Implement registration, catalog, cart, checkout\" -> multiple complex features\n\nSkip it:\n- \"How do I print Hello World in Python?\" -> informational\n- \"Add a comment to calculateTotal\" -> single edit\n- \"Run npm install and tell me what happened\" -> one command\n\nWhen in doubt, use it.\n",
|
||||
"parameters": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"todos": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {
|
||||
"type": "string",
|
||||
"description": "Brief description of the task"
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"description": "Current status of the task: pending, in_progress, completed, cancelled"
|
||||
},
|
||||
"priority": {
|
||||
"type": "string",
|
||||
"description": "Priority level of the task: high, medium, low"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"content",
|
||||
"status",
|
||||
"priority"
|
||||
]
|
||||
},
|
||||
"description": "The updated todo list"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"todos"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "webfetch",
|
||||
"description": "- Fetches content from a specified URL\n- Takes a URL and optional format as input\n- Fetches the URL content, converts to requested format (markdown by default)\n- Returns the content in the specified format\n- Use this tool when you need to retrieve and analyze web content\n\nUsage notes:\n - IMPORTANT: if another tool is present that offers better web fetching capabilities, is more targeted to the task, or has fewer restrictions, prefer using that tool instead of this one.\n - The URL must be a fully-formed valid URL\n - HTTP URLs will be automatically upgraded to HTTPS\n - Format options: \"markdown\" (default), \"text\", or \"html\"\n - This tool is read-only and does not modify any files\n - Results may be summarized if the content is very large\n",
|
||||
"parameters": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"url": {
|
||||
"type": "string",
|
||||
"description": "The URL to fetch content from"
|
||||
},
|
||||
"format": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"text",
|
||||
"markdown",
|
||||
"html"
|
||||
],
|
||||
"description": "The format to return the content in (text, markdown, or html). Defaults to markdown.",
|
||||
"default": "markdown"
|
||||
},
|
||||
"timeout": {
|
||||
"type": "number",
|
||||
"description": "Optional timeout in seconds (max 120)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"url"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "websearch",
|
||||
"description": "- Search the web using the session's web search provider - performs real-time web searches and can scrape content from specific URLs\n- Provides up-to-date information for current events and recent data\n- Supports configurable result counts and returns the content from the most relevant websites\n- Use this tool for accessing information beyond knowledge cutoff\n- Searches are performed automatically within a single API call\n\nUsage notes:\n - Supports live crawling modes when available: 'fallback' (backup if cached unavailable) or 'preferred' (prioritize live crawling)\n - Search types when available: 'auto' (balanced), 'fast' (quick results), 'deep' (comprehensive search)\n - Configurable context length for optimal LLM integration\n - Domain filtering and advanced search options available\n\nThe current year is 2026. You MUST use this year when searching for recent information or current events\n- Example: If the current year is 2026 and the user asks for \"latest AI news\", search for \"AI news 2026\", NOT \"AI news 2025\"\n",
|
||||
"parameters": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"description": "Websearch query"
|
||||
},
|
||||
"numResults": {
|
||||
"type": "number",
|
||||
"description": "Number of search results to return (default: 8)"
|
||||
},
|
||||
"livecrawl": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"fallback",
|
||||
"preferred"
|
||||
],
|
||||
"description": "Live crawl mode - 'fallback': use live crawling as backup if cached content unavailable, 'preferred': prioritize live crawling (default: 'fallback')"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"auto",
|
||||
"fast",
|
||||
"deep"
|
||||
],
|
||||
"description": "Search type - 'auto': balanced search (default), 'fast': quick results, 'deep': comprehensive search"
|
||||
},
|
||||
"contextMaxCharacters": {
|
||||
"type": "number",
|
||||
"description": "Maximum characters for context string optimized for LLMs (default: 10000)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"query"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "write",
|
||||
"description": "Writes a file to the local filesystem.\n\nUsage:\n- This tool will overwrite the existing file if there is one at the provided path.\n- If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.\n- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.\n",
|
||||
"parameters": {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {
|
||||
"type": "string",
|
||||
"description": "The content to write to the file"
|
||||
},
|
||||
"filePath": {
|
||||
"type": "string",
|
||||
"description": "The absolute path to the file to write (must be absolute, not relative)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"content",
|
||||
"filePath"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -55,8 +55,8 @@ func (g *Gateway) resolvedEffort(model string, tier config.Tier, protocol wire.P
|
||||
// question, or a minimal streaming "Reply with OK." Chat prompt converted to
|
||||
// protocol, with effort forced when non-empty and the result shaped for the
|
||||
// free tier by prepareAnonymousBody. v1 reports whether the probe targets the
|
||||
// v1 lane (models.IsV1Upstream), which selects the single "read" tool shaping
|
||||
// instead of the v2 toolset.
|
||||
// v1 lane (models.IsV1Upstream), which selects the 1.x toolset instead of the
|
||||
// 2.x one.
|
||||
func probePayload(model string, protocol wire.Protocol, effort string, v1 bool) ([]byte, error) {
|
||||
if protocol == wire.SystemOne {
|
||||
// TypeSafe's native boolean type is "noul", not JSON Schema boolean.
|
||||
|
||||
@@ -214,8 +214,8 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter,
|
||||
result.reason = "request_conversion_error"
|
||||
return result
|
||||
}
|
||||
body, toolAlias, shaped := g.shapeKeyBody(bodies[config.TierGo], route, config.TierGo)
|
||||
setRequestShape(parent, shaped, toolAlias)
|
||||
body, toolRenames, shaped := g.shapeKeyBody(bodies[config.TierGo], route, config.TierGo)
|
||||
setRequestShape(parent, shaped, toolRenames)
|
||||
cursor := g.goNodes.CursorFor(ids.Session)
|
||||
var node *upstreamNode
|
||||
// Each group attempt is exactly one HTTP call. Key selection may change,
|
||||
@@ -305,7 +305,7 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter,
|
||||
g.monitor.BeginStream()
|
||||
defer g.monitor.EndStream()
|
||||
}
|
||||
streamBody := wire.RenameStreamReader(resp.Body, route.Protocol, v1ReadTool, toolAlias)
|
||||
streamBody := wire.RenameStreamReader(resp.Body, route.Protocol, toolRenames)
|
||||
usage, reported, committed, err := wire.RotationStream(original.Context(), w, streamBody, route.Protocol, external, alias, ready)
|
||||
if meta != nil {
|
||||
meta.Usage = usage
|
||||
@@ -343,7 +343,7 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter,
|
||||
b, err = wire.CollapseStream(bytes.NewReader(b), route.Protocol, route.ID)
|
||||
}
|
||||
if err == nil {
|
||||
b = wire.RenameResponseTool(b, route.Protocol, v1ReadTool, toolAlias)
|
||||
b = wire.RenameResponseTool(b, route.Protocol, toolRenames)
|
||||
}
|
||||
var document map[string]any
|
||||
if err == nil {
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"opencode2api/internal/jsonutil"
|
||||
wire "opencode2api/internal/protocol"
|
||||
)
|
||||
|
||||
// The free tier only accepts agent-shaped traffic, and each lane validates the
|
||||
// tool definitions against its own CLI generation. These assets are the
|
||||
// genuine definitions captured from the official clients: opencode_tools.json
|
||||
// for the 2.x lanes (/inference and /zen/go) and opencode_tools_v1.json for the
|
||||
// 1.x lane (/zen).
|
||||
//
|
||||
//go:embed opencode_tools.json
|
||||
var opencodeToolsV2JSON []byte
|
||||
|
||||
//go:embed opencode_tools_v1.json
|
||||
var opencodeToolsV1JSON []byte
|
||||
|
||||
// opencodeToolDefinition is the description and schema of one official tool.
|
||||
type opencodeToolDefinition struct {
|
||||
Description string `json:"description"`
|
||||
Parameters map[string]any `json:"parameters"`
|
||||
}
|
||||
|
||||
// v2OfficialToolOrder is the key order of opencode_tools.json, made explicit
|
||||
// because Go maps do not preserve it. Tool order is not validated upstream, but
|
||||
// keeping the captured order makes the wire body stable.
|
||||
var v2OfficialToolOrder = []string{
|
||||
"edit", "execute", "glob", "grep", "question", "read", "shell",
|
||||
"skill", "subagent", "webfetch", "websearch", "write", "patch",
|
||||
}
|
||||
|
||||
var (
|
||||
opencodeToolsOnce sync.Once
|
||||
opencodeToolsV2 map[string]opencodeToolDefinition
|
||||
opencodeToolsV1 map[string]opencodeToolDefinition
|
||||
opencodeToolsV1Order []string
|
||||
)
|
||||
|
||||
// loadOfficialTools decodes both embedded tool sets once. A file that fails to
|
||||
// decode leaves that generation with no known definitions, which only degrades
|
||||
// the definition back to a placeholder; the tool names are still appended.
|
||||
func loadOfficialTools() {
|
||||
opencodeToolsOnce.Do(func() {
|
||||
opencodeToolsV2 = map[string]opencodeToolDefinition{}
|
||||
if err := json.Unmarshal(opencodeToolsV2JSON, &opencodeToolsV2); err != nil {
|
||||
opencodeToolsV2 = map[string]opencodeToolDefinition{}
|
||||
}
|
||||
opencodeToolsV1 = map[string]opencodeToolDefinition{}
|
||||
opencodeToolsV1Order = nil
|
||||
var entries []struct {
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters map[string]any `json:"parameters"`
|
||||
} `json:"function"`
|
||||
}
|
||||
if err := json.Unmarshal(opencodeToolsV1JSON, &entries); err == nil {
|
||||
for _, entry := range entries {
|
||||
name := entry.Function.Name
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
opencodeToolsV1[name] = opencodeToolDefinition{
|
||||
Description: entry.Function.Description,
|
||||
Parameters: entry.Function.Parameters,
|
||||
}
|
||||
opencodeToolsV1Order = append(opencodeToolsV1Order, name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// officialToolNames returns the names of the official set for the lane.
|
||||
func officialToolNames(v1 bool) []string {
|
||||
loadOfficialTools()
|
||||
if v1 {
|
||||
return opencodeToolsV1Order
|
||||
}
|
||||
return v2OfficialToolOrder
|
||||
}
|
||||
|
||||
// officialToolDefinition returns the captured definition for an official name.
|
||||
func officialToolDefinition(name string, v1 bool) (opencodeToolDefinition, bool) {
|
||||
loadOfficialTools()
|
||||
if v1 {
|
||||
definition, ok := opencodeToolsV1[name]
|
||||
return definition, ok
|
||||
}
|
||||
definition, ok := opencodeToolsV2[name]
|
||||
return definition, ok
|
||||
}
|
||||
|
||||
// officialTool renders one official definition in the wire shape the protocol
|
||||
// expects. The 2.x Chat shape marks every tool strict:false, as the client does;
|
||||
// the captured 1.x entries carry no strict field and are rendered verbatim.
|
||||
func officialTool(protocol wire.Protocol, name string, v1 bool) map[string]any {
|
||||
description := "Agent tool " + name
|
||||
parameters := map[string]any{"type": "object", "properties": map[string]any{}}
|
||||
if definition, ok := officialToolDefinition(name, v1); ok {
|
||||
description = definition.Description
|
||||
if definition.Parameters != nil {
|
||||
parameters = definition.Parameters
|
||||
}
|
||||
}
|
||||
if v1 {
|
||||
if name == "bash" {
|
||||
description = v1BashDescription(description)
|
||||
}
|
||||
} else if name == "shell" {
|
||||
description = v2ShellDescription(description)
|
||||
}
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
function := map[string]any{
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parameters": parameters,
|
||||
}
|
||||
if !v1 {
|
||||
function["strict"] = false
|
||||
}
|
||||
return map[string]any{"type": "function", "function": function}
|
||||
case wire.Anthropic:
|
||||
return map[string]any{
|
||||
"name": name,
|
||||
"description": description,
|
||||
"input_schema": parameters,
|
||||
}
|
||||
default:
|
||||
return map[string]any{
|
||||
"type": "function",
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parameters": parameters,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// officialToolset renders the full official set for a lane.
|
||||
func officialToolset(protocol wire.Protocol, v1 bool) []any {
|
||||
names := officialToolNames(v1)
|
||||
tools := make([]any, 0, len(names))
|
||||
for _, name := range names {
|
||||
tools = append(tools, officialTool(protocol, name, v1))
|
||||
}
|
||||
return tools
|
||||
}
|
||||
|
||||
// v2ShellDescription renders the shell tool description for the host platform.
|
||||
// The 2.x client describes the shell it actually has, so a Windows host says
|
||||
// powershell where a Unix host says bash.
|
||||
func v2ShellDescription(base string) string {
|
||||
if runtime.GOOS != "windows" {
|
||||
return base
|
||||
}
|
||||
return strings.Replace(base, "on Linux using bash", "on Windows using powershell", 1)
|
||||
}
|
||||
|
||||
// v1BashDescription applies the same platform rewrite to the 1.x bash
|
||||
// definition, which states its OS and shell inline.
|
||||
func v1BashDescription(base string) string {
|
||||
if runtime.GOOS != "windows" {
|
||||
return base
|
||||
}
|
||||
return strings.Replace(base, "OS: linux, Shell: bash", "OS: windows, Shell: powershell", 1)
|
||||
}
|
||||
|
||||
// renameAndCompleteTools makes the tool list read as an official CLI session:
|
||||
// every named client tool is renamed with the clint_ prefix, legacy functions
|
||||
// arrays are converted, and the full official set for the lane is appended.
|
||||
// The returned map restores the client names in the upstream response.
|
||||
func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 bool) (*wire.ToolRenames, bool) {
|
||||
switch protocol {
|
||||
case wire.Chat, wire.Responses, wire.Anthropic:
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
renames := wire.NewToolRenames()
|
||||
used := map[string]bool{}
|
||||
var items []any
|
||||
if raw, exists := payload["tools"]; exists {
|
||||
if list, ok := raw.([]any); ok {
|
||||
items = list
|
||||
}
|
||||
}
|
||||
if protocol == wire.Chat || protocol == wire.Responses {
|
||||
if legacy, ok := payload["functions"].([]any); ok {
|
||||
items = append(items, convertLegacyFunctions(legacy, protocol, renames, used)...)
|
||||
delete(payload, "functions")
|
||||
}
|
||||
}
|
||||
shaped := make([]any, 0, len(items)+len(officialToolNames(v1)))
|
||||
for _, item := range items {
|
||||
entry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
shaped = append(shaped, item)
|
||||
continue
|
||||
}
|
||||
name, ok := renamableToolName(protocol, entry)
|
||||
if !ok {
|
||||
shaped = append(shaped, item)
|
||||
continue
|
||||
}
|
||||
if wireName := clientWireName(renames, used, name); wireName != name {
|
||||
setToolName(protocol, entry, wireName)
|
||||
}
|
||||
shaped = append(shaped, entry)
|
||||
}
|
||||
shaped = append(shaped, officialToolset(protocol, v1)...)
|
||||
payload["tools"] = shaped
|
||||
rewriteToolReferences(payload, protocol, renames)
|
||||
return renames, true
|
||||
}
|
||||
|
||||
// renamableToolName returns the client tool name of one definition. Responses
|
||||
// built-in tools (web search and similar) have no client name and are left
|
||||
// untouched.
|
||||
func renamableToolName(protocol wire.Protocol, entry map[string]any) (string, bool) {
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
name := jsonutil.StringAt(entry, "function", "name")
|
||||
return name, name != ""
|
||||
case wire.Responses:
|
||||
switch jsonutil.StringAt(entry, "type") {
|
||||
case "", "function", "custom":
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
name := jsonutil.StringAt(entry, "name")
|
||||
return name, name != ""
|
||||
default:
|
||||
// Anthropic server tools (web search and similar) carry a type; a
|
||||
// plain client tool has only name/description/input_schema.
|
||||
switch jsonutil.StringAt(entry, "type") {
|
||||
case "", "custom":
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
name := jsonutil.StringAt(entry, "name")
|
||||
return name, name != ""
|
||||
}
|
||||
}
|
||||
|
||||
// clientWireName returns the existing wire name for a client tool, or allocates
|
||||
// a new one. A duplicate client definition reuses the first allocation so every
|
||||
// reference keeps pointing at one name.
|
||||
func clientWireName(renames *wire.ToolRenames, used map[string]bool, client string) string {
|
||||
if wireName, ok := renames.Wire(client); ok {
|
||||
return wireName
|
||||
}
|
||||
wireName := wire.ClientToolWireName(client, used)
|
||||
renames.Add(client, wireName)
|
||||
return wireName
|
||||
}
|
||||
|
||||
// setToolName writes the wire name into one tool definition in place.
|
||||
func setToolName(protocol wire.Protocol, entry map[string]any, name string) {
|
||||
if protocol == wire.Chat {
|
||||
if function, ok := entry["function"].(map[string]any); ok {
|
||||
function["name"] = name
|
||||
}
|
||||
return
|
||||
}
|
||||
entry["name"] = name
|
||||
}
|
||||
|
||||
// convertLegacyFunctions turns the pre-tools "functions" array into entries of
|
||||
// the protocol's tool shape and renames their names.
|
||||
func convertLegacyFunctions(entries []any, protocol wire.Protocol, renames *wire.ToolRenames, used map[string]bool) []any {
|
||||
converted := make([]any, 0, len(entries))
|
||||
for _, raw := range entries {
|
||||
entry, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
name := jsonutil.StringAt(entry, "name")
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
wireName := clientWireName(renames, used, name)
|
||||
description := jsonutil.StringAt(entry, "description")
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
function := map[string]any{
|
||||
"name": wireName,
|
||||
"description": description,
|
||||
"parameters": legacyParameters(entry),
|
||||
}
|
||||
if strict, ok := entry["strict"]; ok {
|
||||
function["strict"] = strict
|
||||
}
|
||||
converted = append(converted, map[string]any{"type": "function", "function": function})
|
||||
case wire.Responses:
|
||||
tool := map[string]any{
|
||||
"type": "function",
|
||||
"name": wireName,
|
||||
"description": description,
|
||||
"parameters": legacyParameters(entry),
|
||||
}
|
||||
if strict, ok := entry["strict"]; ok {
|
||||
tool["strict"] = strict
|
||||
}
|
||||
converted = append(converted, tool)
|
||||
}
|
||||
}
|
||||
return converted
|
||||
}
|
||||
|
||||
// legacyParameters returns a legacy function's parameters, defaulting to an
|
||||
// empty object schema.
|
||||
func legacyParameters(entry map[string]any) any {
|
||||
if parameters, ok := entry["parameters"]; ok && parameters != nil {
|
||||
return parameters
|
||||
}
|
||||
return map[string]any{"type": "object", "properties": map[string]any{}}
|
||||
}
|
||||
|
||||
// rewriteToolReferences renames every outbound reference to a client tool so
|
||||
// the request stays self-consistent: named tool_choice (including legacy Chat
|
||||
// and Responses allowed_tools forms), legacy function_call, and the tool-call
|
||||
// history each protocol keeps. String choices pass through untouched.
|
||||
func rewriteToolReferences(payload map[string]any, protocol wire.Protocol, renames *wire.ToolRenames) {
|
||||
if renames.Empty() {
|
||||
return
|
||||
}
|
||||
rename := func(container map[string]any) {
|
||||
name, ok := container["name"].(string)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if wireName, ok := renames.Wire(name); ok {
|
||||
container["name"] = wireName
|
||||
}
|
||||
}
|
||||
renameAllowedTools := func(choice map[string]any) {
|
||||
for _, rawEntry := range jsonutil.SliceAt(choice, "allowed_tools") {
|
||||
if entry, ok := rawEntry.(map[string]any); ok {
|
||||
rename(entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
if choice, ok := payload["tool_choice"].(map[string]any); ok {
|
||||
if function, ok := choice["function"].(map[string]any); ok {
|
||||
rename(function)
|
||||
} else {
|
||||
rename(choice)
|
||||
}
|
||||
}
|
||||
if call, ok := payload["function_call"].(map[string]any); ok {
|
||||
rename(call)
|
||||
}
|
||||
for _, rawMessage := range jsonutil.SliceAt(payload, "messages") {
|
||||
message, _ := rawMessage.(map[string]any)
|
||||
if call, ok := message["function_call"].(map[string]any); ok {
|
||||
rename(call)
|
||||
}
|
||||
for _, rawCall := range jsonutil.SliceAt(message, "tool_calls") {
|
||||
call, _ := rawCall.(map[string]any)
|
||||
if function, ok := call["function"].(map[string]any); ok {
|
||||
rename(function)
|
||||
}
|
||||
}
|
||||
}
|
||||
case wire.Responses:
|
||||
if choice, ok := payload["tool_choice"].(map[string]any); ok {
|
||||
rename(choice)
|
||||
renameAllowedTools(choice)
|
||||
}
|
||||
for _, rawItem := range jsonutil.SliceAt(payload, "input") {
|
||||
item, _ := rawItem.(map[string]any)
|
||||
switch jsonutil.StringAt(item, "type") {
|
||||
case "function_call", "custom_tool_call":
|
||||
rename(item)
|
||||
}
|
||||
}
|
||||
case wire.Anthropic:
|
||||
if choice, ok := payload["tool_choice"].(map[string]any); ok {
|
||||
rename(choice)
|
||||
}
|
||||
for _, rawMessage := range jsonutil.SliceAt(payload, "messages") {
|
||||
message, _ := rawMessage.(map[string]any)
|
||||
for _, rawBlock := range jsonutil.SliceAt(message, "content") {
|
||||
block, _ := rawBlock.(map[string]any)
|
||||
if jsonutil.StringAt(block, "type") == "tool_use" {
|
||||
rename(block)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-422
@@ -4,7 +4,6 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
_ "embed"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -13,12 +12,10 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
@@ -397,9 +394,9 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
protocol := route.ProtocolFor(config.TierZen)
|
||||
upstreams := g.anonymousUpstreams()
|
||||
preparedBodies := make([][]byte, len(upstreams))
|
||||
toolAliases := make([]string, len(upstreams))
|
||||
toolRenames := make([]*wire.ToolRenames, len(upstreams))
|
||||
for i, baseURL := range upstreams {
|
||||
preparedBodies[i], toolAliases[i] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL))
|
||||
preparedBodies[i], toolRenames[i] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL))
|
||||
}
|
||||
for proxies < limit {
|
||||
if ctx.Err() != nil {
|
||||
@@ -430,7 +427,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
}
|
||||
break
|
||||
}
|
||||
setRequestShape(ctx, false, toolAliases[index])
|
||||
setRequestShape(ctx, false, toolRenames[index])
|
||||
attempts++
|
||||
if meta := telemetry.MetaFromContext(ctx); meta != nil {
|
||||
meta.Attempts = attemptOffset + attempts
|
||||
@@ -579,91 +576,24 @@ func (g *Gateway) inferenceClient(proxy *proxyTransport, baseURL, model string)
|
||||
return proxy.client
|
||||
}
|
||||
|
||||
// v1ReadTool is the single tool name required by the v1 free-tier gate
|
||||
// (/zen). Unlike the v2 /inference gate, it does not require a
|
||||
// shell/edit/glob/grep toolset and does not validate tool descriptions or
|
||||
// parameter schemas: a single tool named "read" is sufficient.
|
||||
const v1ReadTool = "read"
|
||||
|
||||
// v1DeprecatedReadDescription is attached when the gateway must inject a
|
||||
// placeholder "read" tool on the v1 lane (/zen) because the client request
|
||||
// declared no read-related tool of its own. It explicitly tells the model that
|
||||
// the tool is deprecated and must never be invoked.
|
||||
const v1DeprecatedReadDescription = "DEPRECATED: This tool is deprecated and disabled. Do NOT call or reference this tool under any circumstances; ignore it completely."
|
||||
|
||||
// v2CoreTools are the tool names the v2 /inference free-tier gate expects on
|
||||
// an agent-shaped request. Requests without a shell tool and a read tool are
|
||||
// rejected with 403 FreeTierError.
|
||||
// prepareAnonymousBody returns body normalized for the free tier alongside the
|
||||
// tool renames the response must restore. The body is forced to stream (keeping
|
||||
// Chat usage reporting on), carries the official CLI system prompt, and its
|
||||
// tools are renamed and completed for the lane v1 selects; an unchanged body is
|
||||
// returned as is.
|
||||
//
|
||||
// "shell" is the name OpenCode 2.x ships; the v1 client's "bash" spelling is
|
||||
// deliberately not injected on /inference because that gate validates the
|
||||
// definition of every tool it recognises, and a "bash" definition the gateway
|
||||
// synthesises does not match the one upstream expects. Since 2026-10-14 name
|
||||
// presence is not enough on /inference either: the upstream compares each
|
||||
// recognised tool's description and parameter schema against the official CLI's
|
||||
// definitions byte-for-byte (minimal stand-ins 403), which is why the genuine
|
||||
// definitions below are embedded. Tool order is irrelevant and extra client
|
||||
// tools are allowed.
|
||||
var v2CoreTools = []string{"shell", "edit", "glob", "grep", "read"}
|
||||
|
||||
// opencodeToolsJSON holds the genuine OpenCode tool definitions (description
|
||||
// and JSON schema) captured from the official client. The /inference free-tier
|
||||
// gate 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 for the v2
|
||||
// lane 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
|
||||
|
||||
// opencodeToolDefinition is one entry of opencode_tools.json.
|
||||
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.
|
||||
// The embedded JSON is decoded once; if it fails to decode, no tool is known.
|
||||
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 body normalized for the free tier alongside any
|
||||
// original client tool name that was aliased to "read" for the v1 gate. The
|
||||
// body is forced to stream (keeping Chat usage reporting on) and its tools are
|
||||
// shaped for the lane v1 selects; an unchanged body is returned as is.
|
||||
//
|
||||
// On the v1 gate (v1 == true), none of the v2 core tools are injected: if the
|
||||
// client declared a read-related tool (case-insensitive, e.g. "reAd",
|
||||
// "Read_file", "readFile"), it is renamed in-place to "read" while keeping its
|
||||
// original description and parameters, and its original name is returned so
|
||||
// the gateway can restore it in the downstream response; if no read-related
|
||||
// tool is present, a single deprecated "read" stub is injected.
|
||||
//
|
||||
// On a v2 gate (v1 == false), v2CoreTools with genuine CLI 2.x definitions are
|
||||
// ensured. System One payloads are decision requests, not agent traffic, so
|
||||
// they are forwarded verbatim, as is a body that is not a JSON object.
|
||||
func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte, string) {
|
||||
// Every named client tool becomes clint_<name> (sanitized and collision-safe)
|
||||
// and the full official set for the lane is appended, so the request looks like
|
||||
// an official CLI session on both the v1 (/zen) and v2 lanes. System One
|
||||
// payloads are decision requests, not agent traffic, so they are forwarded
|
||||
// verbatim, as is a body that is not a JSON object.
|
||||
func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte, *wire.ToolRenames) {
|
||||
if protocol == wire.SystemOne {
|
||||
return body, ""
|
||||
return body, nil
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return body, ""
|
||||
return body, nil
|
||||
}
|
||||
changed := false
|
||||
if streaming, ok := payload["stream"].(bool); !ok || !streaming {
|
||||
@@ -676,29 +606,23 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte,
|
||||
if injectOfficialPrompt(payload, protocol, v1) {
|
||||
changed = true
|
||||
}
|
||||
var alias string
|
||||
if v1 {
|
||||
var toolChanged bool
|
||||
alias, toolChanged = ensureV1ReadTool(payload, protocol)
|
||||
if toolChanged {
|
||||
changed = true
|
||||
}
|
||||
} else if ensureV2Tools(payload, protocol) {
|
||||
renames, toolsChanged := renameAndCompleteTools(payload, protocol, v1)
|
||||
if toolsChanged {
|
||||
changed = true
|
||||
}
|
||||
if !v1 && protocol == wire.Chat && ensureV2CompletionLimit(payload) {
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return body, alias
|
||||
return body, renames
|
||||
}
|
||||
encoded, err := encodeAnonymousBody(payload, protocol, v1)
|
||||
if err != nil {
|
||||
// The alias is dropped with the failed re-encode: the body never left
|
||||
// the gateway, so there is nothing downstream to restore.
|
||||
return body, ""
|
||||
// The renames are dropped with the failed re-encode: the body never
|
||||
// left the gateway, so there is nothing downstream to restore.
|
||||
return body, nil
|
||||
}
|
||||
return encoded, alias
|
||||
return encoded, renames
|
||||
}
|
||||
|
||||
// v2CompletionLimit is the max_completion_tokens a 2.x client puts on every
|
||||
@@ -810,315 +734,6 @@ func ensureAnonymousChatUsage(payload map[string]any, protocol wire.Protocol) bo
|
||||
return true
|
||||
}
|
||||
|
||||
// ensureV1ReadTool satisfies the v1 free-tier gate (/zen) using only the
|
||||
// single "read" tool requirement:
|
||||
// 1. If the client already has an exact "read" tool, nothing is injected or
|
||||
// renamed.
|
||||
// 2. If the client has a read-related tool (case-insensitive match such as
|
||||
// "reAd", "read_file", "ReadFile", etc.), that tool is renamed to "read"
|
||||
// (preserving its client description and schema), any matching tool_choice
|
||||
// or historical tool call in the request is rewritten to "read", and the
|
||||
// client's original tool name is returned so responses can be restored.
|
||||
// A case-insensitive "read" is preferred over other read-related names.
|
||||
// 3. If the client has no read-related tool at all, a single "read" stub tool
|
||||
// is appended with a deprecated/ignore description so the model never
|
||||
// invokes it.
|
||||
//
|
||||
// It also reports whether the payload changed. A "tools" value that is not an
|
||||
// array is left untouched.
|
||||
func ensureV1ReadTool(payload map[string]any, protocol wire.Protocol) (string, bool) {
|
||||
raw, exists := payload["tools"]
|
||||
if !exists {
|
||||
payload["tools"] = []any{v1DeprecatedReadTool(protocol)}
|
||||
return "", true
|
||||
}
|
||||
items, ok := raw.([]any)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
candidateIndex := -1
|
||||
candidateName := ""
|
||||
caseFoldCandidate := false
|
||||
for index, item := range items {
|
||||
name := anonymousToolName(protocol, item)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
if name == v1ReadTool {
|
||||
return "", false
|
||||
}
|
||||
if strings.EqualFold(name, v1ReadTool) {
|
||||
if !caseFoldCandidate {
|
||||
candidateIndex = index
|
||||
candidateName = name
|
||||
caseFoldCandidate = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if candidateIndex < 0 && isV1ReadToolCandidate(name) {
|
||||
candidateIndex = index
|
||||
candidateName = name
|
||||
}
|
||||
}
|
||||
if candidateIndex >= 0 {
|
||||
setAnonymousToolName(protocol, items[candidateIndex], v1ReadTool)
|
||||
rewriteV1ToolReferences(payload, protocol, candidateName, v1ReadTool)
|
||||
payload["tools"] = items
|
||||
return candidateName, true
|
||||
}
|
||||
items = append(items, v1DeprecatedReadTool(protocol))
|
||||
payload["tools"] = items
|
||||
return "", true
|
||||
}
|
||||
|
||||
// isV1ReadToolCandidate reports whether a client tool name represents a
|
||||
// read-related tool (case-insensitive), such as "reAd", "read_file",
|
||||
// "ReadFile", "file_read", or "view_file".
|
||||
func isV1ReadToolCandidate(name string) bool {
|
||||
lower := strings.ToLower(strings.TrimSpace(name))
|
||||
if lower == "" {
|
||||
return false
|
||||
}
|
||||
if lower == "read" {
|
||||
return true
|
||||
}
|
||||
normalized := strings.NewReplacer("_", "", "-", "", ".", "").Replace(lower)
|
||||
switch normalized {
|
||||
case "readfile", "fileread", "readfiles", "readtext", "readtextfile", "readcontent", "viewfile":
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(lower, "read_") || strings.HasPrefix(lower, "read-") || strings.HasSuffix(lower, "_read") || strings.HasSuffix(lower, "-read")
|
||||
}
|
||||
|
||||
// setAnonymousToolName updates the function name of a tool definition in-place
|
||||
// while keeping all other client fields (description, parameters/input_schema,
|
||||
// strict, etc.) intact.
|
||||
func setAnonymousToolName(protocol wire.Protocol, item any, name string) {
|
||||
entry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if protocol == wire.Chat {
|
||||
if function, ok := entry["function"].(map[string]any); ok {
|
||||
function["name"] = name
|
||||
}
|
||||
return
|
||||
}
|
||||
entry["name"] = name
|
||||
}
|
||||
|
||||
// rewriteV1ToolReferences renames any named tool_choice and
|
||||
// assistant tool-call history entries from fromName to toName so the outbound
|
||||
// request stays self-consistent after a client read tool is aliased to "read".
|
||||
func rewriteV1ToolReferences(payload map[string]any, protocol wire.Protocol, fromName, toName string) {
|
||||
if fromName == "" || fromName == toName {
|
||||
return
|
||||
}
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
if choice, ok := payload["tool_choice"].(map[string]any); ok {
|
||||
if function, ok := choice["function"].(map[string]any); ok && jsonutil.StringAt(function, "name") == fromName {
|
||||
function["name"] = toName
|
||||
}
|
||||
}
|
||||
for _, rawMsg := range jsonutil.SliceAt(payload, "messages") {
|
||||
msg, _ := rawMsg.(map[string]any)
|
||||
for _, rawCall := range jsonutil.SliceAt(msg, "tool_calls") {
|
||||
call, _ := rawCall.(map[string]any)
|
||||
if function, ok := call["function"].(map[string]any); ok && jsonutil.StringAt(function, "name") == fromName {
|
||||
function["name"] = toName
|
||||
}
|
||||
}
|
||||
}
|
||||
case wire.Responses:
|
||||
if choice, ok := payload["tool_choice"].(map[string]any); ok && jsonutil.StringAt(choice, "name") == fromName {
|
||||
choice["name"] = toName
|
||||
}
|
||||
for _, rawItem := range jsonutil.SliceAt(payload, "input") {
|
||||
item, _ := rawItem.(map[string]any)
|
||||
if jsonutil.StringAt(item, "type") == "function_call" && jsonutil.StringAt(item, "name") == fromName {
|
||||
item["name"] = toName
|
||||
}
|
||||
}
|
||||
case wire.Anthropic:
|
||||
if choice, ok := payload["tool_choice"].(map[string]any); ok && jsonutil.StringAt(choice, "name") == fromName {
|
||||
choice["name"] = toName
|
||||
}
|
||||
for _, rawMsg := range jsonutil.SliceAt(payload, "messages") {
|
||||
msg, _ := rawMsg.(map[string]any)
|
||||
for _, rawBlock := range jsonutil.SliceAt(msg, "content") {
|
||||
block, _ := rawBlock.(map[string]any)
|
||||
if jsonutil.StringAt(block, "type") == "tool_use" && jsonutil.StringAt(block, "name") == fromName {
|
||||
block["name"] = toName
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// v1DeprecatedReadTool builds the single placeholder "read" tool injected on
|
||||
// the v1 lane (/zen) when the client request has no read-related tool of its
|
||||
// own, in the wire shape of protocol. Its description marks the tool as
|
||||
// deprecated and instructs the model to ignore it completely.
|
||||
func v1DeprecatedReadTool(protocol wire.Protocol) map[string]any {
|
||||
parameters := map[string]any{"type": "object", "properties": map[string]any{}}
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
return map[string]any{
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": v1ReadTool,
|
||||
"description": v1DeprecatedReadDescription,
|
||||
"parameters": parameters,
|
||||
},
|
||||
}
|
||||
case wire.Anthropic:
|
||||
return map[string]any{
|
||||
"name": v1ReadTool,
|
||||
"description": v1DeprecatedReadDescription,
|
||||
"input_schema": parameters,
|
||||
}
|
||||
default:
|
||||
return map[string]any{
|
||||
"type": "function",
|
||||
"name": v1ReadTool,
|
||||
"description": v1DeprecatedReadDescription,
|
||||
"parameters": parameters,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ensureV2Tools makes the tool list read as an OpenCode 2.x agent session on
|
||||
// a v2 gate: every recognised OpenCode tool carries its genuine CLI 2.x
|
||||
// definition and missing core tools are appended with genuine schemas;
|
||||
// unrecognised client tools are left untouched. It reports whether the payload
|
||||
// changed; a "tools" value that is not an array is left untouched.
|
||||
func ensureV2Tools(payload map[string]any, protocol wire.Protocol) bool {
|
||||
raw, exists := payload["tools"]
|
||||
if !exists {
|
||||
payload["tools"] = v2Toolset(protocol, v2CoreTools)
|
||||
return true
|
||||
}
|
||||
items, ok := raw.([]any)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
changed := false
|
||||
present := make(map[string]bool, len(items))
|
||||
for index, item := range items {
|
||||
name := anonymousToolName(protocol, item)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
present[name] = true
|
||||
if _, known := knownOpencodeTool(name); known {
|
||||
items[index] = v2Tool(protocol, name)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
missing := make([]string, 0, len(v2CoreTools))
|
||||
for _, name := range v2CoreTools {
|
||||
if !present[name] {
|
||||
missing = append(missing, name)
|
||||
}
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
items = append(items, v2Toolset(protocol, missing)...)
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return false
|
||||
}
|
||||
payload["tools"] = items
|
||||
return true
|
||||
}
|
||||
|
||||
// anonymousToolName returns the name of a tool definition in the wire shape
|
||||
// of protocol (function.name on Chat, name elsewhere), or "" when it has none.
|
||||
func anonymousToolName(protocol wire.Protocol, item any) string {
|
||||
entry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
if protocol == wire.Chat {
|
||||
return jsonutil.StringAt(entry, "function", "name")
|
||||
}
|
||||
return jsonutil.StringAt(entry, "name")
|
||||
}
|
||||
|
||||
// v2ShellDescription renders the shell tool description for the host platform.
|
||||
// The 2.x client describes the shell it actually has, so a Windows host says
|
||||
// powershell where a Unix host says bash. The captured definition ships the
|
||||
// Unix wording, which would advertise a shell a Windows gateway does not have.
|
||||
func v2ShellDescription(base string) string {
|
||||
if runtime.GOOS != "windows" {
|
||||
return base
|
||||
}
|
||||
return strings.Replace(base, "on Linux using bash", "on Windows using powershell", 1)
|
||||
}
|
||||
|
||||
// v2Toolset returns the wire-shaped genuine CLI 2.x definitions for the given
|
||||
// tool names on a v2 gate. A nil names selects every v2CoreTools entry.
|
||||
func v2Toolset(protocol wire.Protocol, names []string) []any {
|
||||
if names == nil {
|
||||
names = v2CoreTools
|
||||
}
|
||||
tools := make([]any, 0, len(names))
|
||||
for _, name := range names {
|
||||
if tool := v2Tool(protocol, name); tool != nil {
|
||||
tools = append(tools, tool)
|
||||
}
|
||||
}
|
||||
return tools
|
||||
}
|
||||
|
||||
// v2Tool renders one tool in the shape the given protocol expects, using the
|
||||
// genuine OpenCode CLI 2.x definition whenever one is known and an "Agent tool
|
||||
// <name>" placeholder with an empty object schema otherwise. SystemOne
|
||||
// payloads never reach this path (prepareAnonymousBody forwards them
|
||||
// verbatim), so it falls back to the Responses/default shape.
|
||||
func v2Tool(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
|
||||
}
|
||||
}
|
||||
if name == "shell" {
|
||||
description = v2ShellDescription(description)
|
||||
}
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
return map[string]any{
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parameters": parameters,
|
||||
// The 2.x client marks every tool strict:false, so a tool that
|
||||
// omits the field is byte-different from the client's on every
|
||||
// request that carries tools.
|
||||
"strict": false,
|
||||
},
|
||||
}
|
||||
case wire.Anthropic:
|
||||
return map[string]any{
|
||||
"name": name,
|
||||
"description": description,
|
||||
"input_schema": parameters,
|
||||
}
|
||||
default:
|
||||
return map[string]any{
|
||||
"type": "function",
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parameters": parameters,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// requestBodyDumpLimit caps how much of an outbound body is written to the log.
|
||||
const requestBodyDumpLimit = 64 << 10
|
||||
|
||||
@@ -1161,22 +776,23 @@ func (g *Gateway) dumpOutboundBodies(route models.Route, bodies map[config.Tier]
|
||||
}
|
||||
|
||||
// shapeKeyBody normalizes key-tier free-model wire bodies to agent shape
|
||||
// (stream + required tools), mirroring the anonymous lane; the tier's base URL
|
||||
// decides between v1 and v2 shaping. Upstream now rejects non-agent-shaped
|
||||
// free-tier requests on every lane with 403 FreeTierError; paid models keep
|
||||
// their original bodies. It reports the shaped body, any v1 "read" tool alias
|
||||
// that must be restored in the response, and whether the body changed so the
|
||||
// gateway can collapse the SSE stream a non-streaming client receives back.
|
||||
func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier) ([]byte, string, bool) {
|
||||
// (stream + official prompt + renamed and completed tools), mirroring the
|
||||
// anonymous lane; the tier's base URL decides between v1 and v2 shaping.
|
||||
// Upstream now rejects non-agent-shaped free-tier requests on every lane with
|
||||
// 403 FreeTierError; paid models keep their original bodies. It reports the
|
||||
// shaped body, the tool renames to restore in the response, and whether the
|
||||
// body changed so the gateway can collapse the SSE stream a non-streaming
|
||||
// client receives back.
|
||||
func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier) ([]byte, *wire.ToolRenames, bool) {
|
||||
if !g.catalog.IsFreeModel(route.ID) {
|
||||
return body, "", false
|
||||
return body, nil, false
|
||||
}
|
||||
baseURL := g.cfg.Upstream.Zen
|
||||
if tier == config.TierGo {
|
||||
baseURL = g.cfg.Upstream.Go
|
||||
}
|
||||
shaped, alias := prepareAnonymousBody(body, route.ProtocolFor(tier), models.IsV1Upstream(baseURL))
|
||||
return shaped, alias, !bytes.Equal(shaped, body)
|
||||
shaped, renames := prepareAnonymousBody(body, route.ProtocolFor(tier), models.IsV1Upstream(baseURL))
|
||||
return shaped, renames, !bytes.Equal(shaped, body)
|
||||
}
|
||||
|
||||
// doSelectedKeyUpstream sends exactly one attempt through the operator-selected
|
||||
@@ -1201,11 +817,11 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route,
|
||||
if len(body) == 0 {
|
||||
return nil, fmt.Errorf("no prepared %s request body", override.Tier), 0
|
||||
}
|
||||
shaped, alias, changed := g.shapeKeyBody(body, route, override.Tier)
|
||||
shaped, toolRenames, changed := g.shapeKeyBody(body, route, override.Tier)
|
||||
if changed {
|
||||
body = shaped
|
||||
}
|
||||
setRequestShape(ctx, changed, alias)
|
||||
setRequestShape(ctx, changed, toolRenames)
|
||||
useWARP := g.usesWARP(route.ID, override.Tier, false)
|
||||
proxy := nodes.Proxy(node)
|
||||
if !useWARP {
|
||||
@@ -1282,11 +898,11 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
|
||||
if len(body) == 0 {
|
||||
return nil, fmt.Errorf("no prepared %s request body", route.Tier), 0
|
||||
}
|
||||
shaped, alias, changed := g.shapeKeyBody(body, route, route.Tier)
|
||||
shaped, toolRenames, changed := g.shapeKeyBody(body, route, route.Tier)
|
||||
if changed {
|
||||
body = shaped
|
||||
}
|
||||
setRequestShape(ctx, changed, alias)
|
||||
setRequestShape(ctx, changed, toolRenames)
|
||||
useWARP := g.usesWARP(route.ID, route.Tier, false)
|
||||
for attempts < g.cfg.Retry.MaxAttempts {
|
||||
if ctx.Err() != nil {
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"opencode2api/internal/httpx"
|
||||
"opencode2api/internal/identity"
|
||||
"opencode2api/internal/models"
|
||||
wire "opencode2api/internal/protocol"
|
||||
"opencode2api/internal/telemetry"
|
||||
"opencode2api/internal/warp"
|
||||
)
|
||||
@@ -219,9 +220,9 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
|
||||
protocol := route.ProtocolFor(config.TierZen)
|
||||
upstreams := g.anonymousUpstreams()
|
||||
prepared := make([][]byte, len(upstreams))
|
||||
aliases := make([]string, len(upstreams))
|
||||
renames := make([]*wire.ToolRenames, len(upstreams))
|
||||
for index, baseURL := range upstreams {
|
||||
prepared[index], aliases[index] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL))
|
||||
prepared[index], renames[index] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL))
|
||||
}
|
||||
limit := max(g.cfg.Retry.MaxAttempts, g.warp.Size()+1)
|
||||
firstEventTimeout := time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds) * time.Second
|
||||
@@ -241,7 +242,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
setRequestShape(ctx, false, aliases[index])
|
||||
setRequestShape(ctx, false, renames[index])
|
||||
attempts++
|
||||
if meta := telemetry.MetaFromContext(ctx); meta != nil {
|
||||
meta.Attempts = attemptOffset + attempts
|
||||
|
||||
@@ -503,29 +503,26 @@ func ResponseUsage(protocol Protocol, body []byte) (Usage, bool) {
|
||||
return decodeOpenAIUsage(usage), true
|
||||
}
|
||||
|
||||
// RenameResponseTool rewrites tool call names matching fromName to toName inside
|
||||
// a serialized JSON response or SSE event data object for the given protocol.
|
||||
// It is used to restore a client's original read-related tool name (e.g.
|
||||
// "reAd" or "read_file") after the v1 lane's shaper aliased it to "read" on the
|
||||
// outbound wire.
|
||||
// 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 the name; correctness does not depend on it,
|
||||
// because every name that is rewritten is compared exactly after decoding.
|
||||
// Names that do not match fromName, including ones already equal to toName,
|
||||
// are left alone.
|
||||
func RenameResponseTool(body []byte, protocol Protocol, fromName, toName string) []byte {
|
||||
if fromName == "" || toName == "" || fromName == toName || len(body) == 0 {
|
||||
// frames that cannot contain an alias; every rewrite is an exact map lookup
|
||||
// after decoding. Names without a mapping 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(fromName)) {
|
||||
if !bytes.Contains(body, []byte(ClientToolPrefix)) {
|
||||
return body
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return body
|
||||
}
|
||||
if !renameToolInMap(payload, protocol, fromName, toName) {
|
||||
if !renameToolInMap(payload, protocol, renames) {
|
||||
return body
|
||||
}
|
||||
encoded, err := json.Marshal(payload)
|
||||
@@ -535,12 +532,33 @@ func RenameResponseTool(body []byte, protocol Protocol, fromName, toName string)
|
||||
return encoded
|
||||
}
|
||||
|
||||
// renameToolInMap rewrites matching tool names in a decoded response or stream
|
||||
// renameToolInMap rewrites aliased tool names in a decoded response or stream
|
||||
// event and reports whether anything changed. Every place a protocol reports a
|
||||
// tool call is visited: Chat message and delta tool_calls, Responses
|
||||
// function_call items under "item", "output" and a "response" envelope, and
|
||||
// Anthropic tool_use blocks under "content_block" or "content".
|
||||
func renameToolInMap(payload map[string]any, protocol Protocol, fromName, toName string) bool {
|
||||
// tool call is visited: Chat message, delta and legacy function_call tool
|
||||
// calls, Responses function_call and custom_tool_call items under "item",
|
||||
// "output" and a "response" envelope, and Anthropic tool_use blocks under
|
||||
// "content_block" or "content".
|
||||
func renameToolInMap(payload map[string]any, protocol Protocol, renames *ToolRenames) bool {
|
||||
rename := func(container map[string]any) bool {
|
||||
name, ok := container["name"].(string)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
client, ok := renames.Client(name)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
container["name"] = client
|
||||
return true
|
||||
}
|
||||
renameItem := func(item map[string]any) bool {
|
||||
switch jsonutil.StringAt(item, "type") {
|
||||
case "function_call", "custom_tool_call":
|
||||
return rename(item)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
changed := false
|
||||
switch protocol {
|
||||
case Chat:
|
||||
@@ -550,47 +568,42 @@ func renameToolInMap(payload map[string]any, protocol Protocol, fromName, toName
|
||||
container := jsonutil.MapAt(choice, key)
|
||||
for _, rawCall := range jsonutil.SliceAt(container, "tool_calls") {
|
||||
call, _ := rawCall.(map[string]any)
|
||||
if function, ok := call["function"].(map[string]any); ok && jsonutil.StringAt(function, "name") == fromName {
|
||||
function["name"] = toName
|
||||
if function, ok := call["function"].(map[string]any); ok && rename(function) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if function, ok := container["function_call"].(map[string]any); ok && rename(function) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
case Responses:
|
||||
if item, ok := payload["item"].(map[string]any); ok {
|
||||
if jsonutil.StringAt(item, "type") == "function_call" && jsonutil.StringAt(item, "name") == fromName {
|
||||
item["name"] = toName
|
||||
changed = true
|
||||
}
|
||||
if item, ok := payload["item"].(map[string]any); ok && renameItem(item) {
|
||||
changed = true
|
||||
}
|
||||
for _, rawItem := range jsonutil.SliceAt(payload, "output") {
|
||||
item, _ := rawItem.(map[string]any)
|
||||
if jsonutil.StringAt(item, "type") == "function_call" && jsonutil.StringAt(item, "name") == fromName {
|
||||
item["name"] = toName
|
||||
if renameItem(item) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if resp, ok := payload["response"].(map[string]any); ok {
|
||||
for _, rawItem := range jsonutil.SliceAt(resp, "output") {
|
||||
item, _ := rawItem.(map[string]any)
|
||||
if jsonutil.StringAt(item, "type") == "function_call" && jsonutil.StringAt(item, "name") == fromName {
|
||||
item["name"] = toName
|
||||
if renameItem(item) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
case Anthropic:
|
||||
if block, ok := payload["content_block"].(map[string]any); ok {
|
||||
if jsonutil.StringAt(block, "type") == "tool_use" && jsonutil.StringAt(block, "name") == fromName {
|
||||
block["name"] = toName
|
||||
if jsonutil.StringAt(block, "type") == "tool_use" && rename(block) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
for _, rawBlock := range jsonutil.SliceAt(payload, "content") {
|
||||
block, _ := rawBlock.(map[string]any)
|
||||
if jsonutil.StringAt(block, "type") == "tool_use" && jsonutil.StringAt(block, "name") == fromName {
|
||||
block["name"] = toName
|
||||
if jsonutil.StringAt(block, "type") == "tool_use" && rename(block) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
|
||||
+26
-29
@@ -227,22 +227,21 @@ func ForwardStream(ctx context.Context, w http.ResponseWriter, reader io.Reader,
|
||||
return usage, observer.Reported(), cause
|
||||
}
|
||||
|
||||
// RenameStreamReader wraps an SSE stream reader and rewrites tool call names
|
||||
// matching fromName back to toName before downstream parsers or writers consume
|
||||
// the stream. When fromName or toName is empty (or identical), reader is
|
||||
// returned unchanged.
|
||||
// RenameStreamReader wraps an SSE stream reader and rewrites aliased tool call
|
||||
// names back to the names the client declared before downstream parsers or
|
||||
// writers consume the stream. An empty rename set returns reader unchanged.
|
||||
//
|
||||
// It is a pull-based transform instead of a goroutine plus io.Pipe so a client
|
||||
// that disconnects mid-stream cannot strand a blocked writer. Chat frames go
|
||||
// through the fragment-aware rewriter, while the other protocols use the
|
||||
// stateless RenameResponseTool rewrite on each frame.
|
||||
func RenameStreamReader(reader io.Reader, protocol Protocol, fromName, toName string) io.Reader {
|
||||
if fromName == "" || toName == "" || fromName == toName {
|
||||
func RenameStreamReader(reader io.Reader, protocol Protocol, renames *ToolRenames) io.Reader {
|
||||
if renames.Empty() {
|
||||
return reader
|
||||
}
|
||||
return &renameStreamReader{
|
||||
buffer: bufio.NewReaderSize(reader, 64<<10),
|
||||
renamer: &streamToolRenamer{protocol: protocol, fromName: fromName, toName: toName, tools: map[string]*streamToolRenameState{}},
|
||||
renamer: &streamToolRenamer{protocol: protocol, renames: renames, tools: map[string]*streamToolRenameState{}},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,8 +311,8 @@ func (reader *renameStreamReader) rewriteLine(line string) []byte {
|
||||
|
||||
// streamToolRenameState tracks how one tool call's name was resolved while a
|
||||
// stream is rewritten. Chat deltas may repeat a growing name prefix or append
|
||||
// fragments, so a value that is still a prefix of fromName is held back until
|
||||
// it either completes the match or diverges.
|
||||
// fragments, so a value that is still a prefix of a known wire name is held
|
||||
// back until it either completes the match or diverges.
|
||||
type streamToolRenameState struct {
|
||||
decided bool
|
||||
renamed bool
|
||||
@@ -325,23 +324,22 @@ type streamToolRenameState struct {
|
||||
// chunks is reassembled before it is matched.
|
||||
type streamToolRenamer struct {
|
||||
protocol Protocol
|
||||
fromName string
|
||||
toName string
|
||||
renames *ToolRenames
|
||||
tools map[string]*streamToolRenameState
|
||||
}
|
||||
|
||||
// rewriteFrame rewrites one SSE data payload, which is raw JSON text. Frames
|
||||
// that cannot carry a tool name are returned untouched, so only a payload that
|
||||
// mentions the source name (Anthropic and Responses) or "tool_calls" (Chat) is
|
||||
// mentions a client alias (Anthropic and Responses) or "tool_calls" (Chat) is
|
||||
// decoded.
|
||||
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, renamer.fromName) {
|
||||
if !strings.Contains(raw, ClientToolPrefix) {
|
||||
return []byte(raw)
|
||||
}
|
||||
return RenameResponseTool([]byte(raw), renamer.protocol, renamer.fromName, renamer.toName)
|
||||
return RenameResponseTool([]byte(raw), renamer.protocol, renamer.renames)
|
||||
}
|
||||
if !strings.Contains(raw, `"tool_calls"`) {
|
||||
return []byte(raw)
|
||||
@@ -401,11 +399,11 @@ func (renamer *streamToolRenamer) rewriteChatFrame(raw string) []byte {
|
||||
}
|
||||
|
||||
// applyNameFragment folds one name fragment into a tool's rename state and
|
||||
// reports whether the frame changed. Once the accumulated name completes
|
||||
// fromName, it is replaced by toName; while it is still a prefix of fromName
|
||||
// the name is held back; on divergence the accumulated name is written out as
|
||||
// is. After a resolved rename, any further fragment is dropped, because it
|
||||
// belongs to a longer name the client never declared.
|
||||
// reports whether the frame changed. Once the accumulated name matches a wire
|
||||
// name exactly, it is replaced by the client name; while it is still a proper
|
||||
// prefix of one the name is held back; on divergence the accumulated name is
|
||||
// written out as is. After a resolved rename, any further fragment is dropped,
|
||||
// because it belongs to a longer name the client never declared.
|
||||
func (renamer *streamToolRenamer) applyNameFragment(state *streamToolRenameState, function map[string]any, fragment string) bool {
|
||||
if state.decided {
|
||||
if !state.renamed {
|
||||
@@ -420,21 +418,20 @@ func (renamer *streamToolRenamer) applyNameFragment(state *streamToolRenameState
|
||||
return false
|
||||
}
|
||||
state.pending = mergeToolName(state.pending, fragment)
|
||||
switch {
|
||||
case state.pending == renamer.fromName:
|
||||
function["name"] = renamer.toName
|
||||
if client, ok := renamer.renames.Client(state.pending); ok {
|
||||
function["name"] = client
|
||||
state.decided, state.renamed = true, true
|
||||
return true
|
||||
case strings.HasPrefix(renamer.fromName, state.pending):
|
||||
// Still a prefix of the alias: hold the fragment until a later frame
|
||||
// either completes the match or diverges.
|
||||
}
|
||||
if renamer.renames.HasLongerPrefix(state.pending) {
|
||||
// Still a prefix of a known wire name: hold the fragment until a later
|
||||
// frame either completes the match or diverges.
|
||||
delete(function, "name")
|
||||
return true
|
||||
default:
|
||||
function["name"] = state.pending
|
||||
state.decided = true
|
||||
return true
|
||||
}
|
||||
function["name"] = state.pending
|
||||
state.decided = true
|
||||
return true
|
||||
}
|
||||
|
||||
// toolState returns the rename state for a tool key, creating it on first
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ClientToolPrefix marks every client tool the gateway renames on a shaped
|
||||
// free-tier request. The prefix keeps client tools distinct from the official
|
||||
// OpenCode set the gateway appends, and lets responses be restored to the names
|
||||
// the client declared.
|
||||
const ClientToolPrefix = "clint_"
|
||||
|
||||
// toolWireNameLimit is the longest tool name the upstreams accept.
|
||||
const toolWireNameLimit = 64
|
||||
|
||||
// ToolRenames records the client-to-wire tool names of one shaped request. The
|
||||
// zero value and a nil pointer are both empty and safe to use.
|
||||
type ToolRenames struct {
|
||||
toWire map[string]string
|
||||
toClient map[string]string
|
||||
}
|
||||
|
||||
// NewToolRenames returns an empty rename set.
|
||||
func NewToolRenames() *ToolRenames {
|
||||
return &ToolRenames{toWire: map[string]string{}, toClient: map[string]string{}}
|
||||
}
|
||||
|
||||
// Empty reports whether no tool was renamed.
|
||||
func (r *ToolRenames) Empty() bool {
|
||||
return r == nil || len(r.toWire) == 0
|
||||
}
|
||||
|
||||
// Count reports how many client tools were renamed.
|
||||
func (r *ToolRenames) Count() int {
|
||||
if r == nil {
|
||||
return 0
|
||||
}
|
||||
return len(r.toWire)
|
||||
}
|
||||
|
||||
// Wire returns the wire name registered for an exact client name.
|
||||
func (r *ToolRenames) Wire(client string) (string, bool) {
|
||||
if r == nil || client == "" {
|
||||
return "", false
|
||||
}
|
||||
wire, ok := r.toWire[client]
|
||||
return wire, ok
|
||||
}
|
||||
|
||||
// Client returns the client name registered for an exact wire name.
|
||||
func (r *ToolRenames) Client(wire string) (string, bool) {
|
||||
if r == nil || wire == "" {
|
||||
return "", false
|
||||
}
|
||||
client, ok := r.toClient[wire]
|
||||
return client, ok
|
||||
}
|
||||
|
||||
// Add records one client-to-wire mapping. Adding the same pair twice is a
|
||||
// no-op; a conflicting pair keeps the first wire name so the map stays
|
||||
// invertible.
|
||||
func (r *ToolRenames) Add(client, wire string) {
|
||||
if r == nil || client == "" || wire == "" || client == wire {
|
||||
return
|
||||
}
|
||||
if existing, ok := r.toWire[client]; ok {
|
||||
if existing != wire {
|
||||
return
|
||||
}
|
||||
}
|
||||
if _, taken := r.toClient[wire]; taken {
|
||||
return
|
||||
}
|
||||
r.toWire[client] = wire
|
||||
r.toClient[wire] = client
|
||||
}
|
||||
|
||||
// HasPrefix reports whether any wire name starts with prefix.
|
||||
func (r *ToolRenames) HasPrefix(prefix string) bool {
|
||||
if r == nil || prefix == "" {
|
||||
return false
|
||||
}
|
||||
for wire := range r.toClient {
|
||||
if strings.HasPrefix(wire, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HasLongerPrefix reports whether any wire name is longer than prefix and
|
||||
// starts with it. A stream fragment builder uses this to hold a partial name
|
||||
// back until the next chunk resolves it.
|
||||
func (r *ToolRenames) HasLongerPrefix(prefix string) bool {
|
||||
if r == nil || prefix == "" {
|
||||
return false
|
||||
}
|
||||
for wire := range r.toClient {
|
||||
if len(wire) > len(prefix) && strings.HasPrefix(wire, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
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 {
|
||||
if client, ok := r.Client(wire); ok {
|
||||
return client
|
||||
}
|
||||
if strings.HasPrefix(wire, ClientToolPrefix) {
|
||||
if rest := strings.TrimPrefix(wire, ClientToolPrefix); rest != "" {
|
||||
return rest
|
||||
}
|
||||
}
|
||||
return wire
|
||||
}
|
||||
|
||||
// ClientToolWireName builds the wire name for one client tool. The name keeps
|
||||
// only [A-Za-z0-9_-], collapses every other run to a single underscore, and is
|
||||
// trimmed; an empty result becomes "tool". It is truncated to fit alongside the
|
||||
// prefix and the 64-byte limit, and collisions with used names get a _2, _3, …
|
||||
// suffix. The chosen name is recorded in used.
|
||||
func ClientToolWireName(name string, used map[string]bool) string {
|
||||
if used == nil {
|
||||
used = map[string]bool{}
|
||||
}
|
||||
clean := sanitizeToolName(name)
|
||||
if clean == "" {
|
||||
clean = "tool"
|
||||
}
|
||||
if max := toolWireNameLimit - len(ClientToolPrefix); len(clean) > max {
|
||||
clean = clean[:max]
|
||||
}
|
||||
base := ClientToolPrefix + clean
|
||||
if !used[base] {
|
||||
used[base] = true
|
||||
return base
|
||||
}
|
||||
for suffix := 2; ; suffix++ {
|
||||
tag := "_" + strconv.Itoa(suffix)
|
||||
cut := toolWireNameLimit - len(tag)
|
||||
if cut > len(base) {
|
||||
cut = len(base)
|
||||
}
|
||||
candidate := base[:cut] + tag
|
||||
if !used[candidate] {
|
||||
used[candidate] = true
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sanitizeToolName reduces a client tool name to the character set upstreams
|
||||
// accept, collapsing invalid runs into one underscore.
|
||||
func sanitizeToolName(name string) string {
|
||||
var builder strings.Builder
|
||||
underscored := false
|
||||
for _, char := range name {
|
||||
switch {
|
||||
case char >= 'a' && char <= 'z', char >= 'A' && char <= 'Z', char >= '0' && char <= '9', char == '-', char == '_':
|
||||
builder.WriteRune(char)
|
||||
underscored = char == '_'
|
||||
default:
|
||||
if !underscored {
|
||||
builder.WriteByte('_')
|
||||
underscored = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Trim(builder.String(), "_-")
|
||||
}
|
||||
@@ -43,11 +43,10 @@ type RequestMeta struct {
|
||||
// lane. Non-streaming responses for shaped requests arrive as SSE
|
||||
// and must be collapsed like anonymous ones.
|
||||
Shaped bool
|
||||
// ToolAlias holds the client's original read-related tool name (e.g.
|
||||
// "reAd" or "read_file") when the v1 lane's shaper renamed it to "read"
|
||||
// on the outbound wire. When non-empty, "read" tool calls in the
|
||||
// upstream response are rewritten back to ToolAlias before returning.
|
||||
ToolAlias string
|
||||
// ToolRenames counts the client tools the free-tier shaper renamed with
|
||||
// the clint_ prefix. The upstream response is rewritten back to the
|
||||
// client's names before it is returned.
|
||||
ToolRenames int
|
||||
Usage protocol.Usage
|
||||
UsageReported bool
|
||||
AttemptOutcome string
|
||||
|
||||
Reference in new issue
Block a user