Skip to content

Commit 14faec7

Browse files
committed
fix(gateway): harden free-tier retries and client compatibility
Preserve upstream HTTP failures across transport retries, classify title requests before shaping, and rename legacy functions exactly once. Keep adjacent Responses assistant items together, including interleaved text and calls. Add opt-in prompt environment overrides with matching shell descriptions, strict validation, and WebUI round-trip preservation. Document compatibility boundaries and retain existing defaults. Include the requested test/ ignore rule. Offline zz_ regressions passed and were removed after validation as requested; vet and Windows/Linux builds passed. Refs #173, #175, #176, #178, #179, #181
1 parent b296a61 commit 14faec7

13 files changed

Lines changed: 304 additions & 94 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ opencode/
1313
coverage.out
1414
*.test
1515
*.test.exe
16+
test/
1617

1718
*.rotation.json
1819
.rotation-*.tmp

‎README.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ System One pairs a free-form state with typed questions and returns typed answer
192192

193193
Requests using the upstream's native protocol retain provider-specific fields. Requests crossing protocols pass through a common representation; not every option has an equivalent. For example, Chat JSON output constraints and `seed` are not forwarded to Anthropic Messages. Unsupported content or tool types may be rejected.
194194

195+
When converting Responses history, adjacent assistant reasoning, text, and function-call items form one assistant turn, including text interleaved between function calls. Tool results and user messages separate turns; missing or unmatched tool results remain validation errors when converting to Chat Completions.
196+
195197
The gateway exposes the routes listed above. It does not implement embeddings, file uploads, image generation, or Responses retrieval and cancellation. It does not store conversation history; clients must supply the history or use features supported by the actual upstream.
196198

197199
## Routing and models
@@ -236,10 +238,14 @@ The routing sequence is:
236238

237239
Anonymous attempts are not cut short by `retry.max_attempts`, but all attempts share the request timeout. Network errors, authentication failures, rate limits, and server errors can rotate exits. A request-level `400`/`413`/`422` (for example `context_length_exceeded`) ends the request immediately: another exit or tier cannot change the request. An IP-level abuse `403` blocks only that exit; if every exit is blocked, the gateway stops walking them, and an authenticated Go key can still serve the request.
238240

241+
If a retry fails before producing an HTTP response, the gateway retains the latest upstream HTTP error instead of replacing it with a transport error. Its status and `Retry-After` are preserved, and up to 64 KiB of its body is retained for the existing error-message conversion. The previous response connection or WARP lease is released before another attempt. A later HTTP response replaces the earlier one, and a client cancellation still takes precedence. This does not change session IDs, retry budgets, or upstream quotas.
242+
239243
When the free tier is blocked for the whole deployment (an IP-level `403` abuse response), retrying only extends the penalty, so an optional lane-level circuit breaker can stop the probing. With `models.anonymous_backoff` configured, `threshold` consecutive failed anonymous attempts or an all-exits IP block pause the whole anonymous lane for `base_hours`, doubling on every further trip up to `max_hours`. A single non-abuse `403` or `429` does not open the breaker; it counts toward the threshold. While paused, requests skip the lane entirely: no proxy is drawn, no upstream request is made, and routing goes straight to the authenticated tiers. Catalog refreshes and availability probes honour the pause as well. When the window expires one request wins the half-open probe; success closes the breaker and restores the free lane, failure opens the next, longer window. The block is absent, and so the breaker stays off, by default.
240244

241245
Requests are encoded for each tier's own protocol. With `performance.first_event_timeout_seconds` enabled, a successful SSE response is held until the first complete data event. A timeout or disconnect before that event uses the existing key/proxy retry budget; comments do not satisfy the timeout. Once released downstream, the stream is never replayed. The default is `0` (disabled); try `15` seconds for upstreams that accept requests but send no events. This bounds the first event, not the first text token, and does not apply to System One. Rotation aliases use their separate `rotation.first_output_seconds` timeout. A recognized stale Responses reasoning reference can trigger one repair pass; selected-key diagnostics never use that replay.
242246

247+
Known OpenCode title requests are identified before prompt and message shaping, so those mutations cannot accidentally add agent tools to a title request or classify an ordinary agent request as a title request. The existing title-pattern and history restrictions still apply; this is not a general fix for every `FreeUsageLimitError`.
248+
243249
When only anonymous access is configured, `/v1/models` exposes only models eligible for that lane.
244250

245251
Free models never need a Zen key: with `anonymous: true` they are served by the public lane, and a configured key is only their fallback. To keep keys but expose free models only, set `models.free_only: true`. Paid models then disappear from `/v1/models`, direct requests for them are rejected, and rotation aliases keep only free members; free models may still fall back to the configured keys.
@@ -258,14 +264,35 @@ The upstream free quota is scoped to the egress block, so rotation only helps wh
258264

259265
Every shaped free-model request carries the OpenCode CLI's own system prompt — its base instructions, the `<env>` block, and the built-in skill listing — because the free tier validates agent-shaped traffic. The v1 `/zen` lane uses the 1.x tool names; `/inference` and `/zen/go` use the 2.x names. The environment block names the requested model, the gateway's working directory, the platform, and a UTC date.
260266

267+
For remote clients, optionally set `upstream.prompt_environment` to replace the injected environment values without removing fields, changing their order, or modifying the official base prompt:
268+
269+
```json
270+
{
271+
"upstream": {
272+
"prompt_environment": {
273+
"working_directory": "/workspace",
274+
"workspace_root": "/workspace",
275+
"platform": "linux",
276+
"is_git_repo": true
277+
}
278+
}
279+
}
280+
```
281+
282+
This is a configuration fragment to merge into the existing `upstream` object, not a complete configuration. An absent or empty object preserves the previous host-based behavior. A nonempty `working_directory` also supplies the workspace root unless `workspace_root` is set separately; omitted values otherwise keep their existing defaults, including `is_git_repo: true`. Supported platforms are `linux`, `darwin`, and `win32` (`windows` is normalized to `win32`). An explicit platform also selects the corresponding shell-tool description; the gateway does not execute or translate client commands. Paths are used as text, not resolved or accessed, and control characters, line separators, and angle brackets are rejected. These are operator-supplied compatibility values, not automatically detected client facts: use separate gateway configurations when clients require different environments. The requested model and UTC date remain unchanged. Arbitrary overrides, including the macOS description, have not been verified against upstream validation.
283+
261284
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.
262285

286+
The override applies only to the gateway-injected block; a client's existing official prompt is left untouched. It is shared by anonymous, keyed, WARP, and probe shaping, and is preserved when saving other settings through the WebUI. Edit the JSON configuration and reload it to change these advanced values; no dedicated WebUI fields are provided.
287+
263288
### Tool shaping
264289

265290
On every shaped free-model request the gateway replaces each named client tool with an opaque wire name, `clint_` plus the first 12 hex characters of the client name's SHA-256 (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`. The digest is not cosmetic: the free tier refuses a shaped body that still carries another client's vocabulary — a Claude Code request that declares both `ReportFindings` and `ScheduleWakeup` is answered with `FreeUsageLimitError`, and removing either name lifts the refusal — so no client tool name reaches the wire. 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.
266291

267292
Responses are restored to client-declared names in streaming and non-streaming replies, including Chat tool names split across chunks. An official name is mapped when the client declared an equivalent tool; otherwise it remains unchanged in the response. In request history, unknown tool calls and official calls without a declared equivalent are removed with their paired results, and a named `tool_choice` targeting one of those dropped calls is removed too.
268293

294+
Legacy `functions` definitions pass through the same single renaming step as modern tools, keeping definitions, named choices, history references, and response restoration consistent.
295+
269296
### Free model availability
270297

271298
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.

‎README.zh-CN.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
192192

193193
客户端协议与上游原生协议相同时,会保留供应商特有字段。跨协议请求经过统一中间结构转换,部分参数没有等价表达。例如,Chat 的 JSON 输出约束与 `seed` 不会被转发到 Anthropic Messages。不支持的内容块或工具类型可能被拒绝。
194194

195+
转换 Responses 历史时,相邻的 assistant reasoning、文本和函数调用项目会组成同一轮 assistant 消息,包括函数调用之间穿插文本的情况。工具结果和 user 消息会分隔轮次;转换为 Chat Completions 时,缺失或不匹配的工具结果仍会被拒绝。
196+
195197
网关仅实现上表中的接口,不提供 embeddings、文件上传、图像生成、Responses 查询或取消接口。网关不保存会话历史;客户端需要提交历史,或使用实际上游支持的相关能力。
196198

197199
## 路由与模型
@@ -236,10 +238,14 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
236238

237239
匿名阶段不受 `retry.max_attempts` 截断,但所有阶段共享请求总超时。网络错误、认证失败、限流和服务端错误可以触发出口轮换。请求级 `400`/`413`/`422`(例如 `context_length_exceeded`)会立即结束请求:换出口或换 Tier 都无法改变请求本身。IP 级 abuse `403` 只淘汰当前出口;所有出口都被封时停止扫描,已配置的 Go Key 仍可继续服务。
238240

241+
如果后续重试在收到 HTTP 响应前发生传输错误,网关会保留最近一次上游 HTTP 错误,而不是用传输错误覆盖它。状态码和 `Retry-After` 保持不变,响应体最多在内存中保留 64 KiB,沿用现有错误消息转换。重试前会释放原响应连接或 WARP 出口;后续真实 HTTP 响应会取代旧响应,客户端取消仍优先处理。此行为不更换会话标识、不增加重试预算,也不改变上游额度。
242+
239243
配置 `models.anonymous_backoff` 后,连续 `threshold` 次匿名失败或所有出口都被 IP 封禁会暂停整条匿名通道 `base_hours`,之后每次再触发翻倍,直到 `max_hours`。单个非滥用 `403` 或 `429` 不会立即熔断,只计入连续失败。暂停期间不取代理、不发任何上游请求(包括模型目录刷新和可用性探测),路由直接落到认证通道。窗口到期后只允许一个请求做半开探测:成功关闭熔断并恢复匿名通道,失败则开启下一个更长的窗口。省略该配置块时熔断关闭。
240244

241245
每个 Tier 使用自己的原生协议编码请求。启用 `performance.first_event_timeout_seconds` 后,会先等待完整的 SSE data 事件再向客户端交付响应;注释心跳不算首事件。首事件前超时或断开会沿用现有 Key / 代理重试预算,交付后不再重放。默认 `0` 关闭,可对接受请求后无事件的上游尝试设置为 `15` 秒。它限制首事件而非首个文本 token,不适用于 System One;轮转别名使用独立的 `rotation.first_output_seconds`。识别到过期的 Responses reasoning 引用时,可执行一次修复重试;指定 Key 的诊断不会执行该重试。
242246

247+
已知 OpenCode 标题请求在提示词和消息整形前判定,避免整形改变消息数量后,误加 agent 工具或把普通 agent 请求误判为标题请求。既有标题特征和历史限制保持不变;这并不代表所有 `FreeUsageLimitError` 都已解决。
248+
243249
只有匿名通道可用时,`/v1/models` 仅展示符合匿名条件的模型。
244250

245251
免费模型不需要 Zen Key:启用 `anonymous: true` 后由匿名通道提供,已配置的 Key 只作为回退。如果想保留 Key 但只暴露免费模型,设置 `models.free_only: true`:付费模型不再出现在 `/v1/models`,直接请求会被拒绝,轮转别名只保留免费成员;免费模型仍可回退到已配置的 Key。
@@ -258,14 +264,35 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
258264

259265
每个经过整形的免费模型请求都会携带 OpenCode CLI 自身的系统提示词——基础指令、`<env>` 环境块和内置 skill 列表——因为免费层级会校验请求是否具有 agent 形态。v1 `/zen` 使用 1.x 工具名,`/inference` 与 `/zen/go` 使用 2.x 工具名。环境块包含请求的模型、网关工作目录、平台和 UTC 日期。
260266

267+
远程客户端可通过可选的 `upstream.prompt_environment` 替换注入的环境值,不删除字段、不改变顺序,也不修改官方基础提示词:
268+
269+
```json
270+
{
271+
"upstream": {
272+
"prompt_environment": {
273+
"working_directory": "/workspace",
274+
"workspace_root": "/workspace",
275+
"platform": "linux",
276+
"is_git_repo": true
277+
}
278+
}
279+
}
280+
```
281+
282+
这是需要合并到现有 `upstream` 对象中的配置片段,不是完整配置。省略或设置为空对象时保持原有宿主机行为。非空 `working_directory` 同时作为默认 workspace root,除非另设 `workspace_root`;其他省略值保持旧默认,包括 `is_git_repo: true`。平台支持 `linux`、`darwin`、`win32`,其中 `windows` 会规范化为 `win32`;显式平台也会同步选择 shell 工具描述,但网关不会执行或转换客户端命令。路径仅作为文本使用,不解析、不访问;控制字符、行分隔符和尖括号会被拒绝。这些值由运维人员指定,不代表自动识别了客户端环境;需要不同环境的客户端应使用独立网关配置。请求模型和 UTC 日期保持不变。任意覆写值(包括 macOS 描述)是否通过上游校验仍需验证。
283+
261284
注入按协议处理:Chat 的系统与 developer 消息会合并为一条位于最前的 `system` 消息;Anthropic 写入 `system`(字符串,或调用方提供块列表时在最前插入文本块);Responses 写入 `instructions`。如果系统内容中已包含标记 `You are opencode, an interactive CLI tool`,请求会原样通过,因此已经发送官方提示词的客户端不会被重复注入。通过 Zen 或 Go Key 提供的免费模型也会接受同样的整形,只是仍然从对应 Tier 的代理出网。
262285

286+
覆写仅作用于网关注入的环境块,不修改客户端已有的官方提示词;匿名、认证、WARP 和探测请求共用该设置。通过 WebUI 保存其他设置时会保留这些值;修改请编辑 JSON 配置并重新加载,目前没有独立的 WebUI 输入字段。
287+
263288
### 工具整形
264289

265290
每个经过整形的免费模型请求中,网关会把客户端声明的每个具名工具改名为不透明的线上名称 `clint_` 加上客户端名称 SHA-256 的前 12 个十六进制字符(冲突时追加 `_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 服务端工具保持不变。
266291

267292
响应(包括流式与非流式,以及拆分到多个 Chat 分块中的工具名)会恢复为客户端声明的名称。只有在客户端声明了等价工具时,官方工具名才会映射到客户端名称;否则响应中的名称保持原样。整形请求历史时,未知工具调用以及没有客户端等价工具的官方调用会连同配对的结果一起移除;若具名 `tool_choice` 指向被移除的工具,也会一并移除。
268293

294+
旧版 `functions` 定义与现代工具使用同一次重命名,确保定义、具名选择、历史引用和响应名称还原保持一致。
295+
269296
### 免费模型可用性
270297

271298
只探测 ID 含 `free`(不区分大小写),或元数据输入、输出价格均为零且未弃用的模型,按模型原生协议发送简短探测请求。先尝试已启用的匿名通道,再尝试一个配置的 Zen Key;启用 `warp.enabled` 时,每条探测通道都改走 WARP 而不是代理,无法取得出口时结果为 `warp_unavailable`,视为不确定。任一通道返回完整有效响应即视为可用,只有所有实际尝试的通道都明确返回模型不存在或已下架时才自动禁用,从模型列表与路由中移除。认证失败、429、超时、网络错误、5xx 和响应格式异常均视为结果不确定,不新增禁用,1 小时后复测。探测不修改生产 Key / 代理的冷却状态,也不计入请求统计,但仍会访问上游并可能消耗免费额度。

‎config.example.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
"upstream": {
1616
"zen": "https://opencode.ai/zen",
1717
"go": "https://opencode.ai/zen/go",
18-
"anonymous": "https://opencode.ai/inference"
18+
"anonymous": "https://opencode.ai/inference",
19+
"prompt_environment": {}
1920
},
2021
"retry": {
2122
"max_attempts": 3,

0 commit comments

Comments
 (0)