mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
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
This commit is contained in:
1 parent
b296a61d0e
commit
14faec7654
13 files changed
+304
-94
No files matched your search
@@ -13,6 +13,7 @@ opencode/
|
||||
coverage.out
|
||||
*.test
|
||||
*.test.exe
|
||||
test/
|
||||
|
||||
*.rotation.json
|
||||
.rotation-*.tmp
|
||||
|
||||
@@ -192,6 +192,8 @@ System One pairs a free-form state with typed questions and returns typed answer
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## Routing and models
|
||||
@@ -236,10 +238,14 @@ The routing sequence is:
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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`.
|
||||
|
||||
When only anonymous access is configured, `/v1/models` exposes only models eligible for that lane.
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
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:
|
||||
|
||||
```json
|
||||
{
|
||||
"upstream": {
|
||||
"prompt_environment": {
|
||||
"working_directory": "/workspace",
|
||||
"workspace_root": "/workspace",
|
||||
"platform": "linux",
|
||||
"is_git_repo": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
### Tool shaping
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Legacy `functions` definitions pass through the same single renaming step as modern tools, keeping definitions, named choices, history references, and response restoration consistent.
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -192,6 +192,8 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
|
||||
|
||||
客户端协议与上游原生协议相同时,会保留供应商特有字段。跨协议请求经过统一中间结构转换,部分参数没有等价表达。例如,Chat 的 JSON 输出约束与 `seed` 不会被转发到 Anthropic Messages。不支持的内容块或工具类型可能被拒绝。
|
||||
|
||||
转换 Responses 历史时,相邻的 assistant reasoning、文本和函数调用项目会组成同一轮 assistant 消息,包括函数调用之间穿插文本的情况。工具结果和 user 消息会分隔轮次;转换为 Chat Completions 时,缺失或不匹配的工具结果仍会被拒绝。
|
||||
|
||||
网关仅实现上表中的接口,不提供 embeddings、文件上传、图像生成、Responses 查询或取消接口。网关不保存会话历史;客户端需要提交历史,或使用实际上游支持的相关能力。
|
||||
|
||||
## 路由与模型
|
||||
@@ -236,10 +238,14 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
|
||||
|
||||
匿名阶段不受 `retry.max_attempts` 截断,但所有阶段共享请求总超时。网络错误、认证失败、限流和服务端错误可以触发出口轮换。请求级 `400`/`413`/`422`(例如 `context_length_exceeded`)会立即结束请求:换出口或换 Tier 都无法改变请求本身。IP 级 abuse `403` 只淘汰当前出口;所有出口都被封时停止扫描,已配置的 Go Key 仍可继续服务。
|
||||
|
||||
如果后续重试在收到 HTTP 响应前发生传输错误,网关会保留最近一次上游 HTTP 错误,而不是用传输错误覆盖它。状态码和 `Retry-After` 保持不变,响应体最多在内存中保留 64 KiB,沿用现有错误消息转换。重试前会释放原响应连接或 WARP 出口;后续真实 HTTP 响应会取代旧响应,客户端取消仍优先处理。此行为不更换会话标识、不增加重试预算,也不改变上游额度。
|
||||
|
||||
配置 `models.anonymous_backoff` 后,连续 `threshold` 次匿名失败或所有出口都被 IP 封禁会暂停整条匿名通道 `base_hours`,之后每次再触发翻倍,直到 `max_hours`。单个非滥用 `403` 或 `429` 不会立即熔断,只计入连续失败。暂停期间不取代理、不发任何上游请求(包括模型目录刷新和可用性探测),路由直接落到认证通道。窗口到期后只允许一个请求做半开探测:成功关闭熔断并恢复匿名通道,失败则开启下一个更长的窗口。省略该配置块时熔断关闭。
|
||||
|
||||
每个 Tier 使用自己的原生协议编码请求。启用 `performance.first_event_timeout_seconds` 后,会先等待完整的 SSE data 事件再向客户端交付响应;注释心跳不算首事件。首事件前超时或断开会沿用现有 Key / 代理重试预算,交付后不再重放。默认 `0` 关闭,可对接受请求后无事件的上游尝试设置为 `15` 秒。它限制首事件而非首个文本 token,不适用于 System One;轮转别名使用独立的 `rotation.first_output_seconds`。识别到过期的 Responses reasoning 引用时,可执行一次修复重试;指定 Key 的诊断不会执行该重试。
|
||||
|
||||
已知 OpenCode 标题请求在提示词和消息整形前判定,避免整形改变消息数量后,误加 agent 工具或把普通 agent 请求误判为标题请求。既有标题特征和历史限制保持不变;这并不代表所有 `FreeUsageLimitError` 都已解决。
|
||||
|
||||
只有匿名通道可用时,`/v1/models` 仅展示符合匿名条件的模型。
|
||||
|
||||
免费模型不需要 Zen Key:启用 `anonymous: true` 后由匿名通道提供,已配置的 Key 只作为回退。如果想保留 Key 但只暴露免费模型,设置 `models.free_only: true`:付费模型不再出现在 `/v1/models`,直接请求会被拒绝,轮转别名只保留免费成员;免费模型仍可回退到已配置的 Key。
|
||||
@@ -258,14 +264,35 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
|
||||
|
||||
每个经过整形的免费模型请求都会携带 OpenCode CLI 自身的系统提示词——基础指令、`<env>` 环境块和内置 skill 列表——因为免费层级会校验请求是否具有 agent 形态。v1 `/zen` 使用 1.x 工具名,`/inference` 与 `/zen/go` 使用 2.x 工具名。环境块包含请求的模型、网关工作目录、平台和 UTC 日期。
|
||||
|
||||
远程客户端可通过可选的 `upstream.prompt_environment` 替换注入的环境值,不删除字段、不改变顺序,也不修改官方基础提示词:
|
||||
|
||||
```json
|
||||
{
|
||||
"upstream": {
|
||||
"prompt_environment": {
|
||||
"working_directory": "/workspace",
|
||||
"workspace_root": "/workspace",
|
||||
"platform": "linux",
|
||||
"is_git_repo": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
这是需要合并到现有 `upstream` 对象中的配置片段,不是完整配置。省略或设置为空对象时保持原有宿主机行为。非空 `working_directory` 同时作为默认 workspace root,除非另设 `workspace_root`;其他省略值保持旧默认,包括 `is_git_repo: true`。平台支持 `linux`、`darwin`、`win32`,其中 `windows` 会规范化为 `win32`;显式平台也会同步选择 shell 工具描述,但网关不会执行或转换客户端命令。路径仅作为文本使用,不解析、不访问;控制字符、行分隔符和尖括号会被拒绝。这些值由运维人员指定,不代表自动识别了客户端环境;需要不同环境的客户端应使用独立网关配置。请求模型和 UTC 日期保持不变。任意覆写值(包括 macOS 描述)是否通过上游校验仍需验证。
|
||||
|
||||
注入按协议处理:Chat 的系统与 developer 消息会合并为一条位于最前的 `system` 消息;Anthropic 写入 `system`(字符串,或调用方提供块列表时在最前插入文本块);Responses 写入 `instructions`。如果系统内容中已包含标记 `You are opencode, an interactive CLI tool`,请求会原样通过,因此已经发送官方提示词的客户端不会被重复注入。通过 Zen 或 Go Key 提供的免费模型也会接受同样的整形,只是仍然从对应 Tier 的代理出网。
|
||||
|
||||
覆写仅作用于网关注入的环境块,不修改客户端已有的官方提示词;匿名、认证、WARP 和探测请求共用该设置。通过 WebUI 保存其他设置时会保留这些值;修改请编辑 JSON 配置并重新加载,目前没有独立的 WebUI 输入字段。
|
||||
|
||||
### 工具整形
|
||||
|
||||
每个经过整形的免费模型请求中,网关会把客户端声明的每个具名工具改名为不透明的线上名称 `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 服务端工具保持不变。
|
||||
|
||||
响应(包括流式与非流式,以及拆分到多个 Chat 分块中的工具名)会恢复为客户端声明的名称。只有在客户端声明了等价工具时,官方工具名才会映射到客户端名称;否则响应中的名称保持原样。整形请求历史时,未知工具调用以及没有客户端等价工具的官方调用会连同配对的结果一起移除;若具名 `tool_choice` 指向被移除的工具,也会一并移除。
|
||||
|
||||
旧版 `functions` 定义与现代工具使用同一次重命名,确保定义、具名选择、历史引用和响应名称还原保持一致。
|
||||
|
||||
### 免费模型可用性
|
||||
|
||||
只探测 ID 含 `free`(不区分大小写),或元数据输入、输出价格均为零且未弃用的模型,按模型原生协议发送简短探测请求。先尝试已启用的匿名通道,再尝试一个配置的 Zen Key;启用 `warp.enabled` 时,每条探测通道都改走 WARP 而不是代理,无法取得出口时结果为 `warp_unavailable`,视为不确定。任一通道返回完整有效响应即视为可用,只有所有实际尝试的通道都明确返回模型不存在或已下架时才自动禁用,从模型列表与路由中移除。认证失败、429、超时、网络错误、5xx 和响应格式异常均视为结果不确定,不新增禁用,1 小时后复测。探测不修改生产 Key / 代理的冷却状态,也不计入请求统计,但仍会访问上游并可能消耗免费额度。
|
||||
|
||||
+2
-1
@@ -15,7 +15,8 @@
|
||||
"upstream": {
|
||||
"zen": "https://opencode.ai/zen",
|
||||
"go": "https://opencode.ai/zen/go",
|
||||
"anonymous": "https://opencode.ai/inference"
|
||||
"anonymous": "https://opencode.ai/inference",
|
||||
"prompt_environment": {}
|
||||
},
|
||||
"retry": {
|
||||
"max_attempts": 3,
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"opencode2api/internal/jsonutil"
|
||||
wire "opencode2api/internal/protocol"
|
||||
@@ -133,7 +134,44 @@ type UpstreamConfig struct {
|
||||
// anonymous lane uses only this origin: the v1 /zen fallback is retired for
|
||||
// free models and its call site is commented out. Empty means
|
||||
// https://opencode.ai/inference.
|
||||
Anonymous string `json:"anonymous"`
|
||||
Anonymous string `json:"anonymous"`
|
||||
PromptEnvironment *PromptEnvironmentConfig `json:"prompt_environment,omitempty"`
|
||||
}
|
||||
|
||||
type PromptEnvironmentConfig struct {
|
||||
WorkingDirectory string `json:"working_directory,omitempty"`
|
||||
WorkspaceRoot string `json:"workspace_root,omitempty"`
|
||||
Platform string `json:"platform,omitempty"`
|
||||
IsGitRepo *bool `json:"is_git_repo,omitempty"`
|
||||
}
|
||||
|
||||
func (environment *PromptEnvironmentConfig) Normalize() error {
|
||||
if environment == nil {
|
||||
return nil
|
||||
}
|
||||
for name, value := range map[string]string{
|
||||
"working_directory": environment.WorkingDirectory,
|
||||
"workspace_root": environment.WorkspaceRoot,
|
||||
} {
|
||||
for _, character := range value {
|
||||
if unicode.IsControl(character) || character == '\u2028' || character == '\u2029' || character == '<' || character == '>' {
|
||||
return fmt.Errorf("upstream.prompt_environment.%s must not contain control characters, line separators, or angle brackets", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
platform := strings.ToLower(strings.TrimSpace(environment.Platform))
|
||||
if platform == "windows" {
|
||||
platform = "win32"
|
||||
}
|
||||
switch platform {
|
||||
case "", "linux", "darwin", "win32":
|
||||
default:
|
||||
return errors.New("upstream.prompt_environment.platform must be linux, darwin, win32, windows, or empty")
|
||||
}
|
||||
environment.WorkingDirectory = strings.TrimSpace(environment.WorkingDirectory)
|
||||
environment.WorkspaceRoot = strings.TrimSpace(environment.WorkspaceRoot)
|
||||
environment.Platform = platform
|
||||
return nil
|
||||
}
|
||||
|
||||
// RetryConfig bounds the upstream retries. MaxAttempts caps the attempts of a
|
||||
@@ -345,6 +383,17 @@ func Normalize(path string, cfg Config) (Config, error) {
|
||||
if cfg.Listen == "" {
|
||||
return Config{}, errors.New("listen must not be empty")
|
||||
}
|
||||
if cfg.Upstream.PromptEnvironment != nil {
|
||||
environment := *cfg.Upstream.PromptEnvironment
|
||||
if err := environment.Normalize(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if environment.IsGitRepo != nil {
|
||||
isGitRepo := *environment.IsGitRepo
|
||||
environment.IsGitRepo = &isGitRepo
|
||||
}
|
||||
cfg.Upstream.PromptEnvironment = &environment
|
||||
}
|
||||
cfg.Upstream.Zen = strings.TrimSpace(cfg.Upstream.Zen)
|
||||
cfg.Upstream.Go = strings.TrimSpace(cfg.Upstream.Go)
|
||||
cfg.Upstream.Anonymous = strings.TrimSpace(cfg.Upstream.Anonymous)
|
||||
@@ -560,6 +609,14 @@ func Clone(cfg Config) Config {
|
||||
cfg.GoKeys = append([]string(nil), cfg.GoKeys...)
|
||||
cfg.Proxies = append([]string(nil), cfg.Proxies...)
|
||||
cfg.effectiveProxies = append([]string(nil), cfg.effectiveProxies...)
|
||||
if cfg.Upstream.PromptEnvironment != nil {
|
||||
environment := *cfg.Upstream.PromptEnvironment
|
||||
if environment.IsGitRepo != nil {
|
||||
isGitRepo := *environment.IsGitRepo
|
||||
environment.IsGitRepo = &isGitRepo
|
||||
}
|
||||
cfg.Upstream.PromptEnvironment = &environment
|
||||
}
|
||||
if cfg.Models.Protocols != nil {
|
||||
protocols := make(map[string]string, len(cfg.Models.Protocols))
|
||||
for key, value := range cfg.Models.Protocols {
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/httpx"
|
||||
)
|
||||
|
||||
// errFreeTierIPBlocked reports that OpenCode's free gateway refused the request
|
||||
@@ -92,6 +94,29 @@ func peekResponseBody(resp *http.Response) []byte {
|
||||
return prefix
|
||||
}
|
||||
|
||||
// bufferRetryResponse releases a response's transport before the next attempt,
|
||||
// retaining at most 64 KiB of its body, including any prefix read before an error.
|
||||
func bufferRetryResponse(resp *http.Response) {
|
||||
if resp == nil || resp.Body == nil {
|
||||
return
|
||||
}
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
_ = resp.Body.Close()
|
||||
resp.Body = io.NopCloser(bytes.NewReader(body))
|
||||
}
|
||||
|
||||
// replaceRetryResponse keeps the latest HTTP response across transport failures
|
||||
// and closes a superseded response before giving ownership to its replacement.
|
||||
func replaceRetryResponse(previous, current *http.Response) *http.Response {
|
||||
if current == nil {
|
||||
return previous
|
||||
}
|
||||
if previous != nil && previous != current {
|
||||
httpx.DrainAndClose(previous.Body)
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
// peekNetworkAbuseBlock classifies a response without consuming its body.
|
||||
func peekNetworkAbuseBlock(resp *http.Response) bool {
|
||||
if resp == nil || resp.StatusCode != http.StatusForbidden {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
wire "opencode2api/internal/protocol"
|
||||
)
|
||||
|
||||
@@ -46,9 +47,9 @@ var (
|
||||
)
|
||||
|
||||
// opencodeEnvironment renders the <env> block the CLI puts after its base
|
||||
// prompt. The working directory is resolved once per process; a platform
|
||||
// without one falls back to the official container path.
|
||||
func opencodeEnvironment(model string) string {
|
||||
// prompt. Configured values replace the host defaults without changing the
|
||||
// field names or order; the host directory is resolved once per process.
|
||||
func opencodeEnvironment(model string, environment *config.PromptEnvironmentConfig) string {
|
||||
opencodeEnvOnce.Do(func() {
|
||||
directory := ""
|
||||
if current, err := os.Getwd(); err == nil {
|
||||
@@ -67,13 +68,31 @@ func opencodeEnvironment(model string) string {
|
||||
if platform == "windows" {
|
||||
platform = "win32"
|
||||
}
|
||||
directory := opencodeWorkDir
|
||||
workspace := directory
|
||||
gitRepo := "yes"
|
||||
if environment != nil {
|
||||
if environment.WorkingDirectory != "" {
|
||||
directory = environment.WorkingDirectory
|
||||
workspace = directory
|
||||
}
|
||||
if environment.WorkspaceRoot != "" {
|
||||
workspace = environment.WorkspaceRoot
|
||||
}
|
||||
if environment.Platform != "" {
|
||||
platform = environment.Platform
|
||||
}
|
||||
if environment.IsGitRepo != nil && !*environment.IsGitRepo {
|
||||
gitRepo = "no"
|
||||
}
|
||||
}
|
||||
return strings.Join([]string{
|
||||
"You are powered by the model named " + apiModel + ". The exact model ID is opencode/" + apiModel,
|
||||
"Here is some useful information about the environment you are running in:",
|
||||
"<env>",
|
||||
" Working directory: " + opencodeWorkDir,
|
||||
" Workspace root folder: " + opencodeWorkDir,
|
||||
" Is directory a git repo: yes",
|
||||
" Working directory: " + directory,
|
||||
" Workspace root folder: " + workspace,
|
||||
" Is directory a git repo: " + gitRepo,
|
||||
" Platform: " + platform,
|
||||
" Today's date: " + time.Now().UTC().Format("Mon Jan 02 2006"),
|
||||
"</env>",
|
||||
@@ -82,12 +101,12 @@ func opencodeEnvironment(model string) string {
|
||||
|
||||
// opencodeSystemPrompt assembles the full CLI system prompt for model and the
|
||||
// upstream generation's tool naming.
|
||||
func opencodeSystemPrompt(model string, v1 bool) string {
|
||||
func opencodeSystemPrompt(model string, v1 bool, environment *config.PromptEnvironmentConfig) string {
|
||||
base := opencodePromptV2
|
||||
if v1 {
|
||||
base = opencodePromptV1
|
||||
}
|
||||
return base + opencodeEnvironment(model) + "\n" + opencodeSkills
|
||||
return base + opencodeEnvironment(model, environment) + "\n" + opencodeSkills
|
||||
}
|
||||
|
||||
// injectOfficialPrompt prepends the official CLI system prompt to a shaped
|
||||
@@ -95,12 +114,12 @@ func opencodeSystemPrompt(model string, v1 bool) string {
|
||||
// already carries the marker is left untouched, so repeated shaping cannot
|
||||
// duplicate the prompt. System One payloads are not chat bodies and are never
|
||||
// touched.
|
||||
func injectOfficialPrompt(payload map[string]any, protocol wire.Protocol, v1 bool) bool {
|
||||
func injectOfficialPrompt(payload map[string]any, protocol wire.Protocol, v1 bool, environment *config.PromptEnvironmentConfig) bool {
|
||||
if payload == nil || protocol == wire.SystemOne {
|
||||
return false
|
||||
}
|
||||
model, _ := payload["model"].(string)
|
||||
prompt := opencodeSystemPrompt(model, v1)
|
||||
prompt := opencodeSystemPrompt(model, v1, environment)
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
return injectChatPrompt(payload, prompt)
|
||||
|
||||
@@ -57,7 +57,7 @@ func (g *Gateway) resolvedEffort(model string, tier config.Tier, protocol wire.P
|
||||
// free tier by prepareAnonymousBody. v1 reports whether the probe targets the
|
||||
// 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) {
|
||||
func probePayload(model string, protocol wire.Protocol, effort string, v1 bool, environment *config.PromptEnvironmentConfig) ([]byte, error) {
|
||||
if protocol == wire.SystemOne {
|
||||
// TypeSafe's native boolean type is "noul", not JSON Schema boolean.
|
||||
return json.Marshal(map[string]any{"model": model, "state": "1 + 1 = 2", "questions": map[string]any{
|
||||
@@ -76,7 +76,7 @@ func probePayload(model string, protocol wire.Protocol, effort string, v1 bool)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shaped, _ := prepareAnonymousBody(b, protocol, v1)
|
||||
shaped, _ := prepareAnonymousBody(b, protocol, v1, environment)
|
||||
return shaped, nil
|
||||
}
|
||||
|
||||
@@ -224,7 +224,7 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
|
||||
// (http_<status>, model_unavailable, probe_timeout, warp_unavailable, ...) and
|
||||
// whether the upstream rejected the reasoning effort.
|
||||
func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, baseURL, key, model string, protocol wire.Protocol, ids identity.RequestIDs, effort string, overWARP bool) probeResult {
|
||||
b, err := probePayload(model, protocol, effort, models.IsV1Upstream(baseURL))
|
||||
b, err := probePayload(model, protocol, effort, models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
|
||||
if err != nil {
|
||||
return probeResult{reason: "request_conversion_error"}
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ func officialToolDefinition(name string, v1 bool) (opencodeToolDefinition, bool)
|
||||
// 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 {
|
||||
func officialTool(protocol wire.Protocol, name string, v1 bool, platform string) map[string]any {
|
||||
description := "Agent tool " + name
|
||||
parameters := map[string]any{"type": "object", "properties": map[string]any{}}
|
||||
if definition, ok := officialToolDefinition(name, v1); ok {
|
||||
@@ -146,10 +146,10 @@ func officialTool(protocol wire.Protocol, name string, v1 bool) map[string]any {
|
||||
}
|
||||
if v1 {
|
||||
if name == "bash" {
|
||||
description = v1BashDescription(description)
|
||||
description = v1BashDescription(description, platform)
|
||||
}
|
||||
} else if name == "shell" {
|
||||
description = v2ShellDescription(description)
|
||||
description = v2ShellDescription(description, platform)
|
||||
}
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
@@ -179,39 +179,58 @@ func officialTool(protocol wire.Protocol, name string, v1 bool) map[string]any {
|
||||
}
|
||||
|
||||
// officialToolset renders the full official set for a lane.
|
||||
func officialToolset(protocol wire.Protocol, v1 bool) []any {
|
||||
func officialToolset(protocol wire.Protocol, v1 bool, platform string) []any {
|
||||
names := officialToolNames(v1)
|
||||
tools := make([]any, 0, len(names))
|
||||
for _, name := range names {
|
||||
tools = append(tools, officialTool(protocol, name, v1))
|
||||
tools = append(tools, officialTool(protocol, name, v1, platform))
|
||||
}
|
||||
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" {
|
||||
// v2ShellDescription renders the configured platform's shell description,
|
||||
// retaining the host-based behavior when no platform override is supplied.
|
||||
func v2ShellDescription(base, platform string) string {
|
||||
if platform == "" {
|
||||
platform = runtime.GOOS
|
||||
if platform != "windows" {
|
||||
return base
|
||||
}
|
||||
}
|
||||
switch platform {
|
||||
case "win32", "windows":
|
||||
return strings.Replace(base, "on Linux using bash", "on Windows using powershell", 1)
|
||||
case "darwin":
|
||||
return strings.Replace(base, "on Linux using bash", "on macOS using bash", 1)
|
||||
default:
|
||||
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" {
|
||||
func v1BashDescription(base, platform string) string {
|
||||
if platform == "" {
|
||||
platform = runtime.GOOS
|
||||
if platform != "windows" {
|
||||
return base
|
||||
}
|
||||
}
|
||||
switch platform {
|
||||
case "win32", "windows":
|
||||
return strings.Replace(base, "OS: linux, Shell: bash", "OS: windows, Shell: powershell", 1)
|
||||
case "darwin":
|
||||
return strings.Replace(base, "OS: linux, Shell: bash", "OS: darwin, Shell: bash", 1)
|
||||
default:
|
||||
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 to an opaque wire name, 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) {
|
||||
func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 bool, platform string) (*wire.ToolRenames, bool) {
|
||||
switch protocol {
|
||||
case wire.Chat, wire.Responses, wire.Anthropic:
|
||||
default:
|
||||
@@ -245,7 +264,7 @@ func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 b
|
||||
}
|
||||
}
|
||||
}
|
||||
items = append(items, convertLegacyFunctions(legacy, protocol, renames, used)...)
|
||||
items = append(items, convertLegacyFunctions(legacy, protocol)...)
|
||||
delete(payload, "functions")
|
||||
}
|
||||
}
|
||||
@@ -266,7 +285,7 @@ func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 b
|
||||
}
|
||||
shaped = append(shaped, entry)
|
||||
}
|
||||
shaped = append(shaped, officialToolset(protocol, v1)...)
|
||||
shaped = append(shaped, officialToolset(protocol, v1, platform)...)
|
||||
payload["tools"] = shaped
|
||||
officialNames := officialToolNames(v1)
|
||||
bindOfficialToolAliases(renames, declaredNames, officialNames)
|
||||
@@ -558,8 +577,8 @@ func setToolName(protocol wire.Protocol, entry map[string]any, name string) {
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// the protocol's tool shape for the shared renaming pass.
|
||||
func convertLegacyFunctions(entries []any, protocol wire.Protocol) []any {
|
||||
converted := make([]any, 0, len(entries))
|
||||
for _, raw := range entries {
|
||||
entry, ok := raw.(map[string]any)
|
||||
@@ -570,12 +589,11 @@ func convertLegacyFunctions(entries []any, protocol wire.Protocol, renames *wire
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
wireName := clientWireName(renames, used, name)
|
||||
description := jsonutil.StringAt(entry, "description")
|
||||
switch protocol {
|
||||
case wire.Chat:
|
||||
function := map[string]any{
|
||||
"name": wireName,
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parameters": legacyParameters(entry),
|
||||
}
|
||||
@@ -586,7 +604,7 @@ func convertLegacyFunctions(entries []any, protocol wire.Protocol, renames *wire
|
||||
case wire.Responses:
|
||||
tool := map[string]any{
|
||||
"type": "function",
|
||||
"name": wireName,
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parameters": legacyParameters(entry),
|
||||
}
|
||||
|
||||
@@ -299,8 +299,13 @@ func stripStaleReasoningInputs(route models.Route, bodies map[config.Tier][]byte
|
||||
// 2xx. Without a success it returns the last HTTP response, whose body is still
|
||||
// open, in preference to the last error. Once ctx is done it no longer enters
|
||||
// the key tiers.
|
||||
func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, models.Route, int, error) {
|
||||
func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultRoute models.Route, resultAttempts int, resultErr error) {
|
||||
var lastResponse *http.Response
|
||||
defer func() {
|
||||
if lastResponse != nil && lastResponse != response {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
}
|
||||
}()
|
||||
var lastErr error
|
||||
effectiveRoute := route
|
||||
attempts := attemptOffset
|
||||
@@ -313,10 +318,13 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
if route.Anonymous {
|
||||
resp, err, used := g.doAnonymousUpstream(ctx, route, bodies, ids, attempts)
|
||||
attempts += used
|
||||
lastResponse, lastErr = resp, err
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return nil, effectiveRoute, attempts, ctx.Err()
|
||||
}
|
||||
if err == nil && resp != nil && resp.StatusCode/100 == 2 {
|
||||
return resp, route, attempts, nil
|
||||
}
|
||||
lastResponse, lastErr = resp, err
|
||||
if errors.Is(err, errDeterministicClientRejection) {
|
||||
// The request itself was rejected. Another lane or key gets the same
|
||||
// answer, and retrying only buries this error under the next one, so
|
||||
@@ -341,6 +349,9 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
// The anonymous phase already consumed the request budget. Entering the
|
||||
// authenticated tiers here would only fire instant attempts against a
|
||||
// dead context, cooling keys that were never really tried.
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return nil, effectiveRoute, attempts, ctx.Err()
|
||||
}
|
||||
if lastResponse != nil {
|
||||
return lastResponse, effectiveRoute, attempts, nil
|
||||
}
|
||||
@@ -363,13 +374,17 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
keyRoute.Tier = tier
|
||||
keyRoute.Anonymous = false
|
||||
keyRoute.Protocol = route.ProtocolFor(tier)
|
||||
effectiveRoute = keyRoute
|
||||
bufferRetryResponse(lastResponse)
|
||||
resp, err, used := g.doKeyUpstream(ctx, keyRoute, bodies, ids, attempts)
|
||||
attempts += used
|
||||
lastResponse = replaceRetryResponse(lastResponse, resp)
|
||||
if resp != nil {
|
||||
effectiveRoute = keyRoute
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return nil, effectiveRoute, attempts, ctx.Err()
|
||||
}
|
||||
if err == nil && resp != nil && resp.StatusCode/100 == 2 {
|
||||
if lastResponse != nil {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
}
|
||||
return resp, keyRoute, attempts, nil
|
||||
}
|
||||
if resp != nil {
|
||||
@@ -377,27 +392,20 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
// Same request-level rejection as on the anonymous lane: no
|
||||
// other tier can fix it, so return it as is.
|
||||
g.logger.Warn("upstream rejected the request; not trying other tiers", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempts", attempts, "tier", keyRoute.Tier, "status", resp.StatusCode)
|
||||
if lastResponse != nil {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
}
|
||||
return resp, keyRoute, attempts, nil
|
||||
}
|
||||
if lastResponse != nil {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
}
|
||||
lastResponse = resp
|
||||
}
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
}
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return nil, effectiveRoute, attempts, ctx.Err()
|
||||
}
|
||||
if blocked {
|
||||
// The request never left the free tier's IP block: keep the block as
|
||||
// the client-facing cause even if a Go fallback also failed, and close
|
||||
// the last free-tier response whose body the handler will not forward.
|
||||
if lastResponse != nil {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
}
|
||||
return nil, effectiveRoute, attempts, errFreeTierIPBlocked
|
||||
}
|
||||
if lastResponse != nil {
|
||||
@@ -436,7 +444,7 @@ func (g *Gateway) maxAnonymousExits() int {
|
||||
// exhausting the proxy cursor returns control to the preferred authenticated
|
||||
// tiers. It returns the last response (body still open), else the last error,
|
||||
// plus the number of attempts made.
|
||||
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
|
||||
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) {
|
||||
if g.usesWARP(route.ID, config.TierZen, true) {
|
||||
return g.doWarpAnonymousUpstream(ctx, route, bodies, ids, attemptOffset)
|
||||
}
|
||||
@@ -447,6 +455,11 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
}
|
||||
defer g.anonymous.ReleaseProbe()
|
||||
var lastResponse *http.Response
|
||||
defer func() {
|
||||
if lastResponse != nil && lastResponse != response {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
}
|
||||
}()
|
||||
var lastErr error
|
||||
// blocked records that some exit is under the free tier's IP block. The
|
||||
// result then reports errFreeTierIPBlocked even when no exit was left to
|
||||
@@ -494,7 +507,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
preparedBodies := make([][]byte, len(upstreams))
|
||||
toolRenames := make([]*wire.ToolRenames, len(upstreams))
|
||||
for i, baseURL := range upstreams {
|
||||
preparedBodies[i], toolRenames[i] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL))
|
||||
preparedBodies[i], toolRenames[i] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
|
||||
}
|
||||
for proxies < limit {
|
||||
if ctx.Err() != nil {
|
||||
@@ -531,10 +544,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
meta.Attempts = attemptOffset + attempts
|
||||
meta.Tier = string(config.TierZen)
|
||||
}
|
||||
if lastResponse != nil {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
lastResponse = nil
|
||||
}
|
||||
bufferRetryResponse(lastResponse)
|
||||
req, err := upstreamRequest(ctx, baseURL, protocol, preparedBodies[index], ids, anonymousZenKey)
|
||||
if err != nil {
|
||||
return nil, err, attempts
|
||||
@@ -546,11 +556,12 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
started := time.Now()
|
||||
resp, err := doInferenceAttempt(g.inferenceClient(node.proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
|
||||
duration := time.Since(started)
|
||||
lastResponse = replaceRetryResponse(lastResponse, resp)
|
||||
if ctx.Err() != nil {
|
||||
// The parent budget expired while this attempt was in flight. Its
|
||||
// outcome says nothing about this proxy, so record nothing and stop
|
||||
// scanning.
|
||||
lastResponse, lastErr = resp, err
|
||||
lastErr = err
|
||||
if lastErr == nil && lastResponse == nil {
|
||||
lastErr = ctx.Err()
|
||||
}
|
||||
@@ -563,7 +574,6 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
|
||||
return resp, nil, attempts
|
||||
}
|
||||
lastResponse = resp
|
||||
lastErr = asProxyUnavailable(node.proxy, err)
|
||||
if err != nil {
|
||||
g.logger.Debug("anonymous transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err)
|
||||
@@ -614,6 +624,9 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
break
|
||||
}
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return nil, ctx.Err(), attempts
|
||||
}
|
||||
// Every configured exit is under the same IP block: another request
|
||||
// cannot reach a working exit, so pause the lane instead of repeating the
|
||||
// 403 walk until the exit cool-downs expire.
|
||||
@@ -624,6 +637,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
}
|
||||
if isTitle {
|
||||
if fallback := titleFallback(g.logger, route.ID, rawBody, lastResponse, lastErr); fallback != nil {
|
||||
lastResponse = nil
|
||||
return fallback, nil, attempts
|
||||
}
|
||||
}
|
||||
@@ -696,7 +710,7 @@ func (g *Gateway) inferenceClient(proxy *proxyTransport, baseURL, model string)
|
||||
// (/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) {
|
||||
func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool, environment *config.PromptEnvironmentConfig) ([]byte, *wire.ToolRenames) {
|
||||
if protocol == wire.SystemOne {
|
||||
return body, nil
|
||||
}
|
||||
@@ -704,6 +718,7 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte,
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return body, nil
|
||||
}
|
||||
isTitle := isTitleGenerationRequest(payload)
|
||||
changed := false
|
||||
if streaming, ok := payload["stream"].(bool); !ok || !streaming {
|
||||
payload["stream"] = true
|
||||
@@ -712,13 +727,17 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte,
|
||||
if ensureAnonymousChatUsage(payload, protocol) {
|
||||
changed = true
|
||||
}
|
||||
if injectOfficialPrompt(payload, protocol, v1) {
|
||||
if injectOfficialPrompt(payload, protocol, v1, environment) {
|
||||
changed = true
|
||||
}
|
||||
var renames *wire.ToolRenames
|
||||
if !isTitleGenerationRequest(payload) {
|
||||
if !isTitle {
|
||||
platform := ""
|
||||
if environment != nil {
|
||||
platform = environment.Platform
|
||||
}
|
||||
var toolsChanged bool
|
||||
renames, toolsChanged = renameAndCompleteTools(payload, protocol, v1)
|
||||
renames, toolsChanged = renameAndCompleteTools(payload, protocol, v1, platform)
|
||||
if toolsChanged {
|
||||
changed = true
|
||||
}
|
||||
@@ -904,7 +923,7 @@ func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier
|
||||
if tier == config.TierGo {
|
||||
baseURL = g.cfg.Upstream.Go
|
||||
}
|
||||
shaped, renames := prepareAnonymousBody(body, route.ProtocolFor(tier), models.IsV1Upstream(baseURL))
|
||||
shaped, renames := prepareAnonymousBody(body, route.ProtocolFor(tier), models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
|
||||
return shaped, renames, !bytes.Equal(shaped, body)
|
||||
}
|
||||
|
||||
@@ -996,8 +1015,13 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route,
|
||||
// without being held against the key or the proxy. It returns the last
|
||||
// response (body still open), else the last error, plus the number of
|
||||
// attempts made.
|
||||
func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
|
||||
func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) {
|
||||
var lastResponse *http.Response
|
||||
defer func() {
|
||||
if lastResponse != nil && lastResponse != response {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
}
|
||||
}()
|
||||
var lastErr error
|
||||
nodes := g.zenNodes
|
||||
baseURL := g.cfg.Upstream.Zen
|
||||
@@ -1047,10 +1071,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
|
||||
meta.Attempts = attemptOffset + attempts
|
||||
meta.Tier = string(route.Tier)
|
||||
}
|
||||
if lastResponse != nil {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
lastResponse = nil
|
||||
}
|
||||
bufferRetryResponse(lastResponse)
|
||||
req, err := upstreamRequest(ctx, baseURL, route.Protocol, body, ids, node.key)
|
||||
if err != nil {
|
||||
return nil, err, attempts
|
||||
@@ -1085,12 +1106,13 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
|
||||
resp, err = doInferenceAttempt(g.inferenceClient(proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
|
||||
}
|
||||
attemptDuration := time.Since(attemptStarted)
|
||||
lastResponse = replaceRetryResponse(lastResponse, resp)
|
||||
if ctx.Err() != nil {
|
||||
// The request budget expired while this attempt was in flight. A
|
||||
// canceled context says nothing about the key or the proxy: without
|
||||
// this guard the instant DeadlineExceeded would cool a healthy key
|
||||
// and evict a healthy proxy from the pool.
|
||||
lastResponse, lastErr = resp, err
|
||||
lastErr = err
|
||||
if lastErr == nil && lastResponse == nil {
|
||||
lastErr = ctx.Err()
|
||||
}
|
||||
@@ -1119,7 +1141,6 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
|
||||
g.logger.Debug("upstream rejected a non-retryable request", "component", "upstream", "event", "attempt_rejected", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "status", resp.StatusCode, "proxy", proxyLabel, "duration_ms", attemptDuration.Milliseconds())
|
||||
return resp, nil, attempts
|
||||
}
|
||||
lastResponse = resp
|
||||
if useWARP && errors.Is(err, errWARPUnavailable) {
|
||||
// No exit at all: another key would only wait on the same pool.
|
||||
lastErr = err
|
||||
@@ -1136,6 +1157,9 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
|
||||
g.logger.Debug("upstream returned a retryable response", "component", "upstream", "event", "attempt_retryable_response", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "status", resp.StatusCode, "proxy", proxyLabel, "duration_ms", attemptDuration.Milliseconds())
|
||||
}
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return nil, ctx.Err(), attempts
|
||||
}
|
||||
if lastResponse != nil {
|
||||
return lastResponse, nil, attempts
|
||||
}
|
||||
|
||||
+20
-11
@@ -226,7 +226,7 @@ func warpProxy(label string) *proxyTransport {
|
||||
// proxy. The lane breaker still applies; per-proxy cooldowns and the block
|
||||
// cursor do not, because a block is a property of the WARP exit and rotation
|
||||
// replaces it.
|
||||
func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
|
||||
func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) {
|
||||
if !g.anonymous.AllowAttempt() {
|
||||
return nil, errAnonymousLanePaused, 0
|
||||
}
|
||||
@@ -240,7 +240,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
|
||||
prepared := make([][]byte, len(upstreams))
|
||||
renames := make([]*wire.ToolRenames, len(upstreams))
|
||||
for index, baseURL := range upstreams {
|
||||
prepared[index], renames[index] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL))
|
||||
prepared[index], renames[index] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
|
||||
}
|
||||
// A 429 is scoped to the exit that carried it, so the request keeps
|
||||
// rotating exits until the configured attempt budget is spent; only then
|
||||
@@ -253,6 +253,11 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
|
||||
}
|
||||
firstEventTimeout := time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds) * time.Second
|
||||
var lastResponse *http.Response
|
||||
defer func() {
|
||||
if lastResponse != nil && lastResponse != response {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
}
|
||||
}()
|
||||
var lastErr error
|
||||
blocked, halted := false, false
|
||||
attempts := 0
|
||||
@@ -265,6 +270,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
|
||||
break
|
||||
}
|
||||
leaseBlocked := false
|
||||
lastStatus := 0
|
||||
for index, baseURL := range upstreams {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
@@ -275,10 +281,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
|
||||
meta.Attempts = attemptOffset + attempts
|
||||
meta.Tier = string(config.TierZen)
|
||||
}
|
||||
if lastResponse != nil {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
lastResponse = nil
|
||||
}
|
||||
bufferRetryResponse(lastResponse)
|
||||
req, err := upstreamRequest(ctx, baseURL, protocol, prepared[index], ids, anonymousZenKey)
|
||||
if err != nil {
|
||||
return nil, err, attempts
|
||||
@@ -287,21 +290,23 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
|
||||
started := time.Now()
|
||||
resp, egress, err := g.doWARPAttempt(ctx, req, baseURL, route.ID, firstEventTimeout)
|
||||
duration := time.Since(started)
|
||||
lastResponse = replaceRetryResponse(lastResponse, resp)
|
||||
if ctx.Err() != nil {
|
||||
lastResponse, lastErr = resp, err
|
||||
lastErr = err
|
||||
if lastErr == nil && lastResponse == nil {
|
||||
lastErr = ctx.Err()
|
||||
}
|
||||
break
|
||||
}
|
||||
status := upstreamStatus(resp)
|
||||
lastStatus = status
|
||||
g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, warpProxy(egress), resp, err, duration)
|
||||
if err == nil && status/100 == 2 {
|
||||
g.anonymous.NoteSuccess()
|
||||
g.logger.Debug("anonymous WARP upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", egress, "status", status, "duration_ms", duration.Milliseconds())
|
||||
return resp, nil, attempts
|
||||
}
|
||||
lastResponse, lastErr = resp, err
|
||||
lastErr = err
|
||||
if err != nil {
|
||||
g.logger.Debug("anonymous WARP transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", egress, "duration_ms", duration.Milliseconds(), "error", err)
|
||||
// A broken tunnel affects both upstream gates; rotate the exit
|
||||
@@ -335,23 +340,27 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
|
||||
if halted || ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
if status := upstreamStatus(lastResponse); status == http.StatusTooManyRequests {
|
||||
if lastStatus == http.StatusTooManyRequests {
|
||||
if !g.warp.HasUntriedActive(triedEgresses) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !leaseBlocked && upstreamStatus(lastResponse) != http.StatusTooManyRequests {
|
||||
if !leaseBlocked && lastStatus != http.StatusTooManyRequests {
|
||||
if pause, tripped := g.anonymous.NoteFailure(); tripped {
|
||||
g.logger.Warn("anonymous lane circuit breaker opened", "component", "upstream", "event", "anonymous_breaker_open", "status", upstreamStatus(lastResponse), "paused_for", pause.String())
|
||||
g.logger.Warn("anonymous lane circuit breaker opened", "component", "upstream", "event", "anonymous_breaker_open", "status", lastStatus, "paused_for", pause.String())
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return nil, ctx.Err(), attempts
|
||||
}
|
||||
if halted {
|
||||
return lastResponse, errDeterministicClientRejection, attempts
|
||||
}
|
||||
if isTitle {
|
||||
if fallback := titleFallback(g.logger, route.ID, rawBody, lastResponse, lastErr); fallback != nil {
|
||||
lastResponse = nil
|
||||
return fallback, nil, attempts
|
||||
}
|
||||
}
|
||||
|
||||
@@ -540,7 +540,9 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest
|
||||
request.System = append(request.System, blocks...)
|
||||
} else if role == "developer" {
|
||||
request.Developer = append(request.Developer, blocks...)
|
||||
} else if role == "user" || role == "assistant" {
|
||||
} else if role == "assistant" {
|
||||
appendBridgeBlock(&request.Messages, role, blocks...)
|
||||
} else if role == "user" {
|
||||
request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks})
|
||||
}
|
||||
default:
|
||||
@@ -659,19 +661,19 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest
|
||||
return request, nil
|
||||
}
|
||||
|
||||
// appendBridgeBlock adds a block decoded from a standalone Responses item. It
|
||||
// joins the previous message when that has the same role and holds only tool
|
||||
// calls or results, so consecutive function_call (or function_call_output)
|
||||
// items form one turn; otherwise the block starts a new message.
|
||||
func appendBridgeBlock(messages *[]bridgeMessage, role string, block bridgeBlock) {
|
||||
// appendBridgeBlock adds blocks decoded from a standalone Responses item. It
|
||||
// joins adjacent assistant items into one turn, including interleaved text,
|
||||
// reasoning and tool calls. Tool results join only a preceding tool-only user
|
||||
// message, so results and user input keep assistant turns separate.
|
||||
func appendBridgeBlock(messages *[]bridgeMessage, role string, blocks ...bridgeBlock) {
|
||||
if len(*messages) > 0 {
|
||||
last := &(*messages)[len(*messages)-1]
|
||||
if last.Role == role && bridgeBlocksOnlyTools(last.Blocks) {
|
||||
last.Blocks = append(last.Blocks, block)
|
||||
if last.Role == role && (role == "assistant" || bridgeBlocksOnlyTools(last.Blocks)) {
|
||||
last.Blocks = append(last.Blocks, blocks...)
|
||||
return
|
||||
}
|
||||
}
|
||||
*messages = append(*messages, bridgeMessage{Role: role, Blocks: []bridgeBlock{block}})
|
||||
*messages = append(*messages, bridgeMessage{Role: role, Blocks: blocks})
|
||||
}
|
||||
|
||||
// bridgeBlocksOnlyTools reports whether blocks is non-empty and holds only
|
||||
|
||||
@@ -134,7 +134,7 @@ async function save(event) {
|
||||
proxies: secretInputs("proxies"),
|
||||
proxyfile: $("#c-proxyfile").value,
|
||||
prefer: $("#c-prefer").value,
|
||||
upstream: { zen: $("#c-up-zen").value, go: $("#c-up-go").value },
|
||||
upstream: { ...current.upstream, zen: $("#c-up-zen").value, go: $("#c-up-go").value },
|
||||
retry: { max_attempts: numberValue("#c-attempts"), timeout_seconds: numberValue("#c-timeout") },
|
||||
models: {
|
||||
refresh_seconds: numberValue("#c-refresh"),
|
||||
|
||||
Reference in new issue
Block a user