From f32c4a0e61387ced9a1aa42076ad700591b5cf0d Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Fri, 14 Aug 2026 08:33:22 +0800 Subject: [PATCH] feat: add OpenCode Zen API compatibility proxy --- .gitignore | 8 + README.md | 179 ++++++++++ config.example.json | 30 ++ config.go | 141 ++++++++ convert.go | 774 ++++++++++++++++++++++++++++++++++++++++++++ gateway.go | 357 ++++++++++++++++++++ go.mod | 3 + ids.go | 94 ++++++ main.go | 60 ++++ models.go | 177 ++++++++++ pool.go | 168 ++++++++++ stream.go | 508 +++++++++++++++++++++++++++++ 12 files changed, 2499 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 config.example.json create mode 100644 config.go create mode 100644 convert.go create mode 100644 gateway.go create mode 100644 go.mod create mode 100644 ids.go create mode 100644 main.go create mode 100644 models.go create mode 100644 pool.go create mode 100644 stream.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4824121 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.key +config.json +opencode/ +opencode2api +opencode2api.exe +*.log +.tmp/ +.gocache/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..c99acfb --- /dev/null +++ b/README.md @@ -0,0 +1,179 @@ +# opencode2api + +`opencode2api` 是一个使用 Go 编写的 OpenCode Zen / Zen Go 协议代理。它对外提供标准 OpenAI 与 Anthropic API,并自动添加 OpenCode 客户端请求头。 + +主要功能: + +- 支持 OpenAI Chat Completions、Responses 和 Models API +- 支持 Anthropic Messages API +- 支持普通响应和 SSE 流式响应 +- 支持文本、图片、工具定义、工具调用和工具结果转换 +- 分离配置 Zen key 池与 Zen Go key 池 +- 模型同时存在于两个上游时优先使用 Zen +- 支持直连、HTTP、HTTPS、SOCKS5 和 SOCKS5H 代理 +- 将 key 平均固定分配给代理,保持连接亲和性 +- 使用无锁轮询分配并发请求 +- 节点失败后立即切换,并对故障节点进行短时冷却 +- 为不同会话生成不同的 OpenCode 会话 ID + +## API 路径 + +| 方法 | 路径 | 协议 | +| --- | --- | --- | +| `GET` | `/v1/models` | OpenAI 模型列表 | +| `POST` | `/v1/chat/completions` | OpenAI Chat Completions | +| `POST` | `/v1/responses` | OpenAI Responses | +| `POST` | `/v1/messages` | Anthropic Messages | +| `GET` | `/healthz` | 健康检查 | + +## 编译 + +需要 Go 1.24 或更高版本。 + +```bash +go build -o opencode2api ./ +``` + +## 配置 + +复制示例配置: + +```bash +cp config.example.json config.json +``` + +然后编辑 `config.json`: + +```json +{ + "listen": "127.0.0.1:8080", + "server_keys": ["change-this-local-key"], + "zen_keys": ["sk-your-zen-key"], + "go_keys": [], + "proxies": ["direct"], + "upstream": { + "zen": "https://opencode.ai/zen", + "go": "https://opencode.ai/zen/go" + }, + "retry": { + "max_attempts": 3, + "timeout_seconds": 300 + }, + "models": { + "refresh_seconds": 300, + "protocols": {} + }, + "performance": { + "max_idle_conns": 2048, + "max_idle_conns_per_host": 256, + "max_conns_per_host": 0, + "idle_conn_timeout_seconds": 120, + "connect_timeout_seconds": 5, + "failure_cooldown_seconds": 15 + }, + "logging": { + "level": "info" + } +} +``` + +### 基础字段 + +| 字段 | 含义 | +| --- | --- | +| `listen` | 本地监听地址。默认建议使用 `127.0.0.1:8080`,避免服务直接暴露到公网。 | +| `server_keys` | 调用本代理时使用的本地 API key 列表。它们只用于本地鉴权,不会发送给 OpenCode。 | +| `zen_keys` | OpenCode Zen API key 池。允许配置多个 key。 | +| `go_keys` | OpenCode Zen Go API key 池。没有 Go key 时可以使用空数组。 | +| `proxies` | 上游代理列表。支持 `direct`、`http://`、`https://`、`socks5://` 和 `socks5h://`。URL 可以包含代理用户名和密码。 | + +`server_keys` 至少需要一个值;`zen_keys` 和 `go_keys` 至少有一个池不能为空。 + +### key 与代理分配规则 + +只需要直连时使用: + +```json +"proxies": ["direct"] +``` + +SOCKS5 代理示例: + +```json +"proxies": ["socks5://127.0.0.1:1080"] +``` + +多个代理示例: + +```json +"proxies": [ + "http://user:password@127.0.0.1:7890", + "socks5://127.0.0.1:1080" +] +``` + +### `upstream` + +| 字段 | 含义 | +| --- | --- | +| `upstream.zen` | Zen 上游根地址,通常保持为 `https://opencode.ai/zen`。 | +| `upstream.go` | Zen Go 上游根地址,通常保持为 `https://opencode.ai/zen/go`。 | + +### `retry` + +| 字段 | 含义 | +| --- | --- | +| `retry.max_attempts` | 单个请求的最大尝试次数,包含第一次请求。非 2xx 响应或网络错误会切换节点。 | +| `retry.timeout_seconds` | 单个客户端请求的总超时时间,同时用于限制上游响应头等待时间。 | + +流式响应一旦已经向客户端输出数据,就不会切换节点重新生成,避免拼接两个不同的响应。 + +### `models` + +| 字段 | 含义 | +| --- | --- | +| `models.refresh_seconds` | 重新读取 Zen 和 Go 模型列表的间隔秒数。两个列表会并发刷新。 | +| `models.protocols` | 手动指定模型的原生协议。值只能是 `chat`、`responses` 或 `anthropic`。通常保持为空。 | + +模型协议覆盖示例: + +```json +"protocols": { + "custom-model": "chat" +} +``` + +模型同时存在于 Zen 与 Go 时优先选择 Zen;仅存在于 Go 时才使用 Go key 池。 + +### `performance` + +| 字段 | 含义 | +| --- | --- | +| `performance.max_idle_conns` | 所有上游连接池允许保留的最大空闲连接数。 | +| `performance.max_idle_conns_per_host` | 每个上游主机允许保留的最大空闲连接数。 | +| `performance.max_conns_per_host` | 每个主机的最大并发连接数。`0` 表示不设置上限。 | +| `performance.idle_conn_timeout_seconds` | 空闲连接在连接池中保留的时间。 | +| `performance.connect_timeout_seconds` | 与上游或代理建立 TCP 连接的超时时间。 | +| `performance.failure_cooldown_seconds` | 连接失败、认证失败、限流或 5xx 后节点的基础冷却时间。连续失败会指数增加冷却时间。 | + +### `logging` + +| 字段 | 含义 | +| --- | --- | +| `logging.level` | 日志级别,支持 `info` 和 `debug`。生产环境建议使用 `info`。 | + +日志不会输出完整上游 key、本地 key、Authorization、`x-api-key` 或请求消息正文。 + + +## 会话 ID + +代理会为上游添加 OpenCode 使用的 `User-Agent`、`x-opencode-client`、`x-opencode-session`、`x-opencode-request` 和 `x-opencode-project` 请求头。 + +- 每个请求使用不同的 `x-opencode-request`,同一次请求的重试保持不变。 +- 优先使用客户端提供的 `x-opencode-session`、`x-session-id`、`conversation-id`、`conversation_id` 或 `metadata.session_id` 生成会话 ID。 +- 没有显式会话标识时,使用第一条用户消息生成稳定会话 ID,使同一段多轮对话保持一致。 +- 如果两个独立会话的第一条消息完全相同,建议由客户端发送不同的 `x-session-id`,以确保两个会话严格分离。 + +## 致谢 + +感谢 [LINUX DO](https://linux.do) 社区一直以来的支持。 diff --git a/config.example.json b/config.example.json new file mode 100644 index 0000000..c7c1ad0 --- /dev/null +++ b/config.example.json @@ -0,0 +1,30 @@ +{ + "listen": "127.0.0.1:8080", + "server_keys": ["change-this-local-key"], + "zen_keys": ["sk-your-zen-key"], + "go_keys": [], + "proxies": ["direct"], + "upstream": { + "zen": "https://opencode.ai/zen", + "go": "https://opencode.ai/zen/go" + }, + "retry": { + "max_attempts": 3, + "timeout_seconds": 300 + }, + "models": { + "refresh_seconds": 300, + "protocols": {} + }, + "performance": { + "max_idle_conns": 2048, + "max_idle_conns_per_host": 256, + "max_conns_per_host": 0, + "idle_conn_timeout_seconds": 120, + "connect_timeout_seconds": 5, + "failure_cooldown_seconds": 15 + }, + "logging": { + "level": "info" + } +} diff --git a/config.go b/config.go new file mode 100644 index 0000000..3778d8c --- /dev/null +++ b/config.go @@ -0,0 +1,141 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "net/url" + "os" + "strings" +) + +type Config struct { + Listen string `json:"listen"` + ServerKeys []string `json:"server_keys"` + ZenKeys []string `json:"zen_keys"` + GoKeys []string `json:"go_keys"` + Proxies []string `json:"proxies"` + Upstream UpstreamConfig `json:"upstream"` + Retry RetryConfig `json:"retry"` + Models ModelsConfig `json:"models"` + Performance PerformanceConfig `json:"performance"` + Logging LoggingConfig `json:"logging"` +} + +type UpstreamConfig struct { + Zen string `json:"zen"` + Go string `json:"go"` +} + +type RetryConfig struct { + MaxAttempts int `json:"max_attempts"` + TimeoutSeconds int `json:"timeout_seconds"` +} + +type ModelsConfig struct { + RefreshSeconds int `json:"refresh_seconds"` + Protocols map[string]string `json:"protocols"` +} + +type LoggingConfig struct { + Level string `json:"level"` +} + +type PerformanceConfig struct { + MaxIdleConns int `json:"max_idle_conns"` + MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"` + MaxConnsPerHost int `json:"max_conns_per_host"` + IdleConnTimeoutSeconds int `json:"idle_conn_timeout_seconds"` + ConnectTimeoutSeconds int `json:"connect_timeout_seconds"` + FailureCooldownSeconds int `json:"failure_cooldown_seconds"` +} + +func LoadConfig(path string) (Config, error) { + data, err := os.ReadFile(path) + if err != nil { + return Config{}, fmt.Errorf("read %s: %w", path, err) + } + cfg := Config{ + Listen: "127.0.0.1:8080", + Proxies: []string{"direct"}, + Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go"}, + Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300}, + Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}}, + Performance: PerformanceConfig{MaxIdleConns: 2048, MaxIdleConnsPerHost: 256, MaxConnsPerHost: 0, IdleConnTimeoutSeconds: 120, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 15}, + Logging: LoggingConfig{Level: "info"}, + } + dec := json.NewDecoder(strings.NewReader(string(data))) + dec.DisallowUnknownFields() + if err := dec.Decode(&cfg); err != nil { + return Config{}, fmt.Errorf("parse %s: %w", path, err) + } + trimList(&cfg.ServerKeys) + trimList(&cfg.ZenKeys) + trimList(&cfg.GoKeys) + trimList(&cfg.Proxies) + if cfg.Listen == "" { + return Config{}, errors.New("listen must not be empty") + } + if len(cfg.ServerKeys) == 0 { + return Config{}, errors.New("server_keys must contain at least one local key") + } + if len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 { + return Config{}, errors.New("zen_keys or go_keys must contain at least one upstream key") + } + if len(cfg.Proxies) == 0 { + cfg.Proxies = []string{"direct"} + } + if cfg.Retry.MaxAttempts < 1 { + return Config{}, errors.New("retry.max_attempts must be at least 1") + } + if cfg.Retry.TimeoutSeconds < 1 { + return Config{}, errors.New("retry.timeout_seconds must be at least 1") + } + if cfg.Models.RefreshSeconds < 1 { + return Config{}, errors.New("models.refresh_seconds must be at least 1") + } + if cfg.Performance.MaxIdleConns < 1 || cfg.Performance.MaxIdleConnsPerHost < 1 || cfg.Performance.MaxConnsPerHost < 0 || cfg.Performance.IdleConnTimeoutSeconds < 1 || cfg.Performance.ConnectTimeoutSeconds < 1 || cfg.Performance.FailureCooldownSeconds < 1 { + return Config{}, errors.New("performance values must be positive (max_conns_per_host may be zero for unlimited)") + } + for _, raw := range cfg.Proxies { + if raw == "direct" { + continue + } + u, err := url.Parse(raw) + if err != nil || u.Host == "" { + return Config{}, fmt.Errorf("invalid proxy URL %q", redactURL(raw)) + } + switch strings.ToLower(u.Scheme) { + case "http", "https", "socks5", "socks5h": + default: + return Config{}, fmt.Errorf("unsupported proxy scheme %q", u.Scheme) + } + } + for model, protocol := range cfg.Models.Protocols { + if model == "" || !validProtocol(Protocol(protocol)) { + return Config{}, fmt.Errorf("models.protocols contains invalid mapping %q: %q", model, protocol) + } + } + return cfg, nil +} + +func trimList(items *[]string) { + out := (*items)[:0] + for _, item := range *items { + if value := strings.TrimSpace(item); value != "" { + out = append(out, value) + } + } + *items = out +} + +func redactURL(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "" + } + if u.User != nil { + u.User = url.User("***") + } + return u.String() +} diff --git a/convert.go b/convert.go new file mode 100644 index 0000000..d0f0e0d --- /dev/null +++ b/convert.go @@ -0,0 +1,774 @@ +package main + +import ( + "encoding/json" + "fmt" + "strings" + "time" +) + +type canonicalBlock struct { + Type string + Text string + URL string + Media string + Data string + ID string + Name string + Input any + ToolID string + Content any + IsError bool +} + +type canonicalMessage struct { + Role string + Blocks []canonicalBlock +} + +type canonicalTool struct { + Name string + Description string + Parameters any + Strict bool +} + +type canonicalRequest struct { + Model string + System []canonicalBlock + Messages []canonicalMessage + Tools []canonicalTool + ToolChoice any + Stream bool + Temperature any + TopP any + MaxTokens any + Stop any + Reasoning any + Metadata any +} + +type canonicalUsage struct { + Input int + Output int + Total int + Cached int + Reasoning int +} + +type canonicalResponse struct { + ID string + Model string + Text string + Tools []canonicalBlock + Stop string + Usage canonicalUsage + Created int64 +} + +func convertRequest(from, to Protocol, input map[string]any) (map[string]any, error) { + if from == to { + return cloneMap(input), nil + } + canonical, err := decodeRequest(from, input) + if err != nil { + return nil, err + } + return encodeRequest(to, canonical), nil +} + +func decodeRequest(protocol Protocol, input map[string]any) (canonicalRequest, error) { + request := canonicalRequest{ + Model: stringAt(input, "model"), + Stream: boolAt(input, "stream"), + Temperature: input["temperature"], + TopP: input["top_p"], + Metadata: input["metadata"], + } + switch protocol { + case ProtocolChat: + request.MaxTokens = firstAny(input["max_completion_tokens"], input["max_tokens"]) + request.Stop = input["stop"] + request.Reasoning = firstAny(input["reasoning_effort"], input["reasoning"]) + for _, raw := range sliceAt(input, "messages") { + message, ok := raw.(map[string]any) + if !ok { + return request, fmt.Errorf("messages must contain objects") + } + role := stringAt(message, "role") + blocks := decodeOpenAIContent(message["content"]) + if role == "system" || role == "developer" { + request.System = append(request.System, blocks...) + continue + } + if role == "tool" { + blocks = []canonicalBlock{{Type: "tool_result", ToolID: stringAt(message, "tool_call_id"), Content: message["content"]}} + role = "user" + } + for _, rawCall := range sliceAt(message, "tool_calls") { + call, _ := rawCall.(map[string]any) + fn, _ := call["function"].(map[string]any) + blocks = append(blocks, canonicalBlock{Type: "tool_use", ID: stringAt(call, "id"), Name: stringAt(fn, "name"), Input: parseJSONOrString(stringAt(fn, "arguments"))}) + } + request.Messages = append(request.Messages, canonicalMessage{Role: role, Blocks: blocks}) + } + for _, raw := range sliceAt(input, "tools") { + tool, _ := raw.(map[string]any) + fn, _ := tool["function"].(map[string]any) + request.Tools = append(request.Tools, canonicalTool{Name: stringAt(fn, "name"), Description: stringAt(fn, "description"), Parameters: fn["parameters"], Strict: boolAt(fn, "strict")}) + } + request.ToolChoice = decodeChatToolChoice(input["tool_choice"]) + case ProtocolResponses: + request.MaxTokens = input["max_output_tokens"] + request.Stop = input["stop"] + request.Reasoning = input["reasoning"] + request.System = append(request.System, decodeOpenAIContent(input["instructions"])...) + switch raw := input["input"].(type) { + case string: + request.Messages = append(request.Messages, canonicalMessage{Role: "user", Blocks: []canonicalBlock{{Type: "text", Text: raw}}}) + case []any: + for _, itemRaw := range raw { + item, ok := itemRaw.(map[string]any) + if !ok { + return request, fmt.Errorf("input must contain objects") + } + switch stringAt(item, "type") { + case "function_call": + request.Messages = append(request.Messages, canonicalMessage{Role: "assistant", Blocks: []canonicalBlock{{Type: "tool_use", ID: stringAt(item, "call_id"), Name: stringAt(item, "name"), Input: parseJSONOrString(stringAt(item, "arguments"))}}}) + case "function_call_output": + request.Messages = append(request.Messages, canonicalMessage{Role: "user", Blocks: []canonicalBlock{{Type: "tool_result", ToolID: stringAt(item, "call_id"), Content: item["output"]}}}) + default: + role := stringAt(item, "role") + blocks := decodeOpenAIContent(item["content"]) + if role == "system" || role == "developer" { + request.System = append(request.System, blocks...) + } else { + request.Messages = append(request.Messages, canonicalMessage{Role: role, Blocks: blocks}) + } + } + } + default: + return request, fmt.Errorf("input must be a string or array") + } + for _, raw := range sliceAt(input, "tools") { + tool, _ := raw.(map[string]any) + if stringAt(tool, "type") != "function" { + return request, fmt.Errorf("only function tools can be converted between protocols") + } + request.Tools = append(request.Tools, canonicalTool{Name: stringAt(tool, "name"), Description: stringAt(tool, "description"), Parameters: tool["parameters"], Strict: boolAt(tool, "strict")}) + } + request.ToolChoice = decodeResponsesToolChoice(input["tool_choice"]) + case ProtocolAnthropic: + request.MaxTokens = input["max_tokens"] + request.Stop = input["stop_sequences"] + request.Reasoning = firstAny(input["thinking"], input["effort"]) + request.System = decodeAnthropicContent(input["system"]) + for _, raw := range sliceAt(input, "messages") { + message, ok := raw.(map[string]any) + if !ok { + return request, fmt.Errorf("messages must contain objects") + } + request.Messages = append(request.Messages, canonicalMessage{Role: stringAt(message, "role"), Blocks: decodeAnthropicContent(message["content"])}) + } + for _, raw := range sliceAt(input, "tools") { + tool, _ := raw.(map[string]any) + request.Tools = append(request.Tools, canonicalTool{Name: stringAt(tool, "name"), Description: stringAt(tool, "description"), Parameters: tool["input_schema"]}) + } + request.ToolChoice = decodeAnthropicToolChoice(input["tool_choice"]) + default: + return request, fmt.Errorf("unsupported input protocol %q", protocol) + } + return request, nil +} + +func encodeRequest(protocol Protocol, request canonicalRequest) map[string]any { + output := map[string]any{"model": request.Model, "stream": request.Stream} + put(output, "temperature", request.Temperature) + put(output, "top_p", request.TopP) + put(output, "metadata", request.Metadata) + switch protocol { + case ProtocolChat: + messages := make([]any, 0, len(request.Messages)+1) + if len(request.System) > 0 { + messages = append(messages, map[string]any{"role": "system", "content": encodeChatContent(request.System)}) + } + for _, message := range request.Messages { + messages = append(messages, encodeChatMessages(message)...) + } + output["messages"] = messages + put(output, "max_tokens", request.MaxTokens) + put(output, "stop", request.Stop) + if effort := reasoningEffort(request.Reasoning); effort != nil { + output["reasoning_effort"] = effort + } + if request.Stream { + output["stream_options"] = map[string]any{"include_usage": true} + } + if len(request.Tools) > 0 { + tools := make([]any, 0, len(request.Tools)) + for _, tool := range request.Tools { + tools = append(tools, map[string]any{"type": "function", "function": map[string]any{"name": tool.Name, "description": tool.Description, "parameters": schemaOrDefault(tool.Parameters), "strict": tool.Strict}}) + } + output["tools"] = tools + put(output, "tool_choice", encodeChatToolChoice(request.ToolChoice)) + } + case ProtocolResponses: + if len(request.System) > 0 { + output["instructions"] = blocksText(request.System) + } + items := make([]any, 0, len(request.Messages)) + for _, message := range request.Messages { + items = append(items, encodeResponsesMessage(message)...) + } + output["input"] = items + put(output, "max_output_tokens", request.MaxTokens) + put(output, "stop", request.Stop) + if request.Reasoning != nil { + switch v := request.Reasoning.(type) { + case string: + output["reasoning"] = map[string]any{"effort": v} + default: + output["reasoning"] = v + } + } + if len(request.Tools) > 0 { + tools := make([]any, 0, len(request.Tools)) + for _, tool := range request.Tools { + tools = append(tools, map[string]any{"type": "function", "name": tool.Name, "description": tool.Description, "parameters": schemaOrDefault(tool.Parameters), "strict": tool.Strict}) + } + output["tools"] = tools + put(output, "tool_choice", encodeResponsesToolChoice(request.ToolChoice)) + } + case ProtocolAnthropic: + if len(request.System) > 0 { + output["system"] = encodeAnthropicContent(request.System) + } + messages := make([]any, 0, len(request.Messages)) + for _, message := range request.Messages { + messages = append(messages, map[string]any{"role": normalizeAnthropicRole(message.Role), "content": encodeAnthropicContent(message.Blocks)}) + } + output["messages"] = messages + if request.MaxTokens == nil { + output["max_tokens"] = 4096 + } else { + output["max_tokens"] = request.MaxTokens + } + put(output, "stop_sequences", request.Stop) + if effort := reasoningEffort(request.Reasoning); effort != nil { + output["effort"] = effort + } + if len(request.Tools) > 0 { + tools := make([]any, 0, len(request.Tools)) + for _, tool := range request.Tools { + tools = append(tools, map[string]any{"name": tool.Name, "description": tool.Description, "input_schema": schemaOrDefault(tool.Parameters)}) + } + output["tools"] = tools + put(output, "tool_choice", encodeAnthropicToolChoice(request.ToolChoice)) + } + } + return output +} + +func decodeOpenAIContent(value any) []canonicalBlock { + switch value := value.(type) { + case string: + if value == "" { + return nil + } + return []canonicalBlock{{Type: "text", Text: value}} + case []any: + var blocks []canonicalBlock + for _, raw := range value { + part, _ := raw.(map[string]any) + switch stringAt(part, "type") { + case "text", "input_text", "output_text": + blocks = append(blocks, canonicalBlock{Type: "text", Text: stringAt(part, "text")}) + case "image_url": + blocks = append(blocks, canonicalBlock{Type: "image", URL: stringAt(part, "image_url", "url")}) + case "input_image": + blocks = append(blocks, canonicalBlock{Type: "image", URL: stringAt(part, "image_url")}) + } + } + return blocks + case map[string]any: + return decodeOpenAIContent([]any{value}) + default: + return nil + } +} + +func decodeAnthropicContent(value any) []canonicalBlock { + if text, ok := value.(string); ok { + return []canonicalBlock{{Type: "text", Text: text}} + } + var blocks []canonicalBlock + for _, raw := range asSlice(value) { + part, _ := raw.(map[string]any) + switch stringAt(part, "type") { + case "text": + blocks = append(blocks, canonicalBlock{Type: "text", Text: stringAt(part, "text")}) + case "image": + source, _ := part["source"].(map[string]any) + if stringAt(source, "type") == "url" { + blocks = append(blocks, canonicalBlock{Type: "image", URL: stringAt(source, "url")}) + } else { + blocks = append(blocks, canonicalBlock{Type: "image", Media: stringAt(source, "media_type"), Data: stringAt(source, "data")}) + } + case "tool_use": + blocks = append(blocks, canonicalBlock{Type: "tool_use", ID: stringAt(part, "id"), Name: stringAt(part, "name"), Input: part["input"]}) + case "tool_result": + blocks = append(blocks, canonicalBlock{Type: "tool_result", ToolID: stringAt(part, "tool_use_id"), Content: part["content"], IsError: boolAt(part, "is_error")}) + } + } + return blocks +} + +func encodeChatMessages(message canonicalMessage) []any { + out := map[string]any{"role": normalizeChatRole(message.Role)} + var content []canonicalBlock + var toolCalls []any + var results []any + for _, block := range message.Blocks { + switch block.Type { + case "tool_use": + args, _ := json.Marshal(block.Input) + toolCalls = append(toolCalls, map[string]any{"id": block.ID, "type": "function", "function": map[string]any{"name": block.Name, "arguments": string(args)}}) + case "tool_result": + results = append(results, map[string]any{"role": "tool", "tool_call_id": block.ToolID, "content": contentString(block.Content)}) + default: + content = append(content, block) + } + } + if len(content) > 0 { + out["content"] = encodeChatContent(content) + } else { + out["content"] = nil + } + if len(toolCalls) > 0 { + out["tool_calls"] = toolCalls + } + messages := make([]any, 0, len(results)+1) + if len(content) > 0 || len(toolCalls) > 0 { + messages = append(messages, out) + } + messages = append(messages, results...) + return messages +} + +func encodeChatContent(blocks []canonicalBlock) any { + if len(blocks) == 1 && blocks[0].Type == "text" { + return blocks[0].Text + } + parts := make([]any, 0, len(blocks)) + for _, block := range blocks { + switch block.Type { + case "text": + parts = append(parts, map[string]any{"type": "text", "text": block.Text}) + case "image": + url := block.URL + if url == "" && block.Data != "" { + url = "data:" + block.Media + ";base64," + block.Data + } + parts = append(parts, map[string]any{"type": "image_url", "image_url": map[string]any{"url": url}}) + } + } + return parts +} + +func encodeResponsesMessage(message canonicalMessage) []any { + var output []any + var content []any + for _, block := range message.Blocks { + switch block.Type { + case "text": + kind := "input_text" + if message.Role == "assistant" { + kind = "output_text" + } + content = append(content, map[string]any{"type": kind, "text": block.Text}) + case "image": + url := block.URL + if url == "" { + url = "data:" + block.Media + ";base64," + block.Data + } + content = append(content, map[string]any{"type": "input_image", "image_url": url}) + case "tool_use": + args, _ := json.Marshal(block.Input) + output = append(output, map[string]any{"type": "function_call", "call_id": block.ID, "name": block.Name, "arguments": string(args)}) + case "tool_result": + output = append(output, map[string]any{"type": "function_call_output", "call_id": block.ToolID, "output": contentString(block.Content)}) + } + } + if len(content) > 0 { + output = append([]any{map[string]any{"role": normalizeResponsesRole(message.Role), "content": content}}, output...) + } + return output +} + +func encodeAnthropicContent(blocks []canonicalBlock) []any { + parts := make([]any, 0, len(blocks)) + for _, block := range blocks { + switch block.Type { + case "text": + parts = append(parts, map[string]any{"type": "text", "text": block.Text}) + case "image": + if block.URL != "" { + parts = append(parts, map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": block.URL}}) + } else { + parts = append(parts, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": block.Media, "data": block.Data}}) + } + case "tool_use": + parts = append(parts, map[string]any{"type": "tool_use", "id": block.ID, "name": block.Name, "input": block.Input}) + case "tool_result": + parts = append(parts, map[string]any{"type": "tool_result", "tool_use_id": block.ToolID, "content": block.Content, "is_error": block.IsError}) + } + } + return parts +} + +func convertResponse(from, to Protocol, body []byte) ([]byte, error) { + var input map[string]any + if err := json.Unmarshal(body, &input); err != nil { + return nil, err + } + response, err := decodeResponse(from, input) + if err != nil { + return nil, err + } + return json.Marshal(encodeResponse(to, response)) +} + +func decodeResponse(protocol Protocol, input map[string]any) (canonicalResponse, error) { + response := canonicalResponse{ID: stringAt(input, "id"), Model: stringAt(input, "model"), Created: int64At(input, "created")} + if response.Created == 0 { + response.Created = int64At(input, "created_at") + } + if response.Created == 0 { + response.Created = time.Now().Unix() + } + switch protocol { + case ProtocolChat: + choices := sliceAt(input, "choices") + if len(choices) == 0 { + return response, fmt.Errorf("chat response has no choices") + } + choice, _ := choices[0].(map[string]any) + message, _ := choice["message"].(map[string]any) + response.Text = blocksText(decodeOpenAIContent(message["content"])) + for _, raw := range sliceAt(message, "tool_calls") { + call, _ := raw.(map[string]any) + fn, _ := call["function"].(map[string]any) + response.Tools = append(response.Tools, canonicalBlock{Type: "tool_use", ID: stringAt(call, "id"), Name: stringAt(fn, "name"), Input: parseJSONOrString(stringAt(fn, "arguments"))}) + } + response.Stop = stringAt(choice, "finish_reason") + response.Usage = decodeOpenAIUsage(mapAt(input, "usage")) + case ProtocolResponses: + for _, raw := range sliceAt(input, "output") { + item, _ := raw.(map[string]any) + switch stringAt(item, "type") { + case "message": + response.Text += blocksText(decodeOpenAIContent(item["content"])) + case "function_call": + response.Tools = append(response.Tools, canonicalBlock{Type: "tool_use", ID: stringAt(item, "call_id"), Name: stringAt(item, "name"), Input: parseJSONOrString(stringAt(item, "arguments"))}) + } + } + response.Stop = "stop" + if len(response.Tools) > 0 { + response.Stop = "tool_calls" + } + response.Usage = decodeOpenAIUsage(mapAt(input, "usage")) + case ProtocolAnthropic: + for _, block := range decodeAnthropicContent(input["content"]) { + if block.Type == "text" { + response.Text += block.Text + } else if block.Type == "tool_use" { + response.Tools = append(response.Tools, block) + } + } + response.Stop = stringAt(input, "stop_reason") + response.Usage = decodeAnthropicUsage(mapAt(input, "usage")) + default: + return response, fmt.Errorf("unsupported response protocol") + } + return response, nil +} + +func encodeResponse(protocol Protocol, response canonicalResponse) map[string]any { + if response.ID == "" { + response.ID = randomID("resp", 12) + } + switch protocol { + case ProtocolChat: + message := map[string]any{"role": "assistant", "content": response.Text} + if len(response.Tools) > 0 { + calls := make([]any, 0, len(response.Tools)) + for _, tool := range response.Tools { + args, _ := json.Marshal(tool.Input) + calls = append(calls, map[string]any{"id": tool.ID, "type": "function", "function": map[string]any{"name": tool.Name, "arguments": string(args)}}) + } + message["tool_calls"] = calls + } + return map[string]any{"id": asPrefix(response.ID, "chatcmpl"), "object": "chat.completion", "created": response.Created, "model": response.Model, "choices": []any{map[string]any{"index": 0, "message": message, "finish_reason": chatStop(response.Stop)}}, "usage": openAIUsage(response.Usage)} + case ProtocolResponses: + output := make([]any, 0, len(response.Tools)+1) + if response.Text != "" { + output = append(output, map[string]any{"id": randomID("msg", 12), "type": "message", "status": "completed", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": response.Text, "annotations": []any{}}}}) + } + for _, tool := range response.Tools { + args, _ := json.Marshal(tool.Input) + output = append(output, map[string]any{"id": randomID("fc", 12), "type": "function_call", "status": "completed", "call_id": tool.ID, "name": tool.Name, "arguments": string(args)}) + } + return map[string]any{"id": asPrefix(response.ID, "resp"), "object": "response", "created_at": response.Created, "status": "completed", "model": response.Model, "output": output, "usage": map[string]any{"input_tokens": response.Usage.Input, "output_tokens": response.Usage.Output, "total_tokens": response.Usage.Total, "input_tokens_details": map[string]any{"cached_tokens": response.Usage.Cached}, "output_tokens_details": map[string]any{"reasoning_tokens": response.Usage.Reasoning}}, "error": nil, "incomplete_details": nil} + case ProtocolAnthropic: + content := []any{} + if response.Text != "" { + content = append(content, map[string]any{"type": "text", "text": response.Text}) + } + for _, tool := range response.Tools { + content = append(content, map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": tool.Input}) + } + return map[string]any{"id": asPrefix(response.ID, "msg"), "type": "message", "role": "assistant", "model": response.Model, "content": content, "stop_reason": anthropicStop(response.Stop), "stop_sequence": nil, "usage": map[string]any{"input_tokens": response.Usage.Input, "output_tokens": response.Usage.Output, "cache_read_input_tokens": response.Usage.Cached}} + } + return map[string]any{} +} + +func decodeOpenAIUsage(u map[string]any) canonicalUsage { + input := intAt(u, "prompt_tokens") + if input == 0 { + input = intAt(u, "input_tokens") + } + output := intAt(u, "completion_tokens") + if output == 0 { + output = intAt(u, "output_tokens") + } + total := intAt(u, "total_tokens") + if total == 0 { + total = input + output + } + cached := intAt(u, "prompt_tokens_details", "cached_tokens") + if cached == 0 { + cached = intAt(u, "input_tokens_details", "cached_tokens") + } + reasoning := intAt(u, "completion_tokens_details", "reasoning_tokens") + if reasoning == 0 { + reasoning = intAt(u, "output_tokens_details", "reasoning_tokens") + } + return canonicalUsage{Input: input, Output: output, Total: total, Cached: cached, Reasoning: reasoning} +} +func decodeAnthropicUsage(u map[string]any) canonicalUsage { + input := intAt(u, "input_tokens") + output := intAt(u, "output_tokens") + cached := intAt(u, "cache_read_input_tokens") + return canonicalUsage{Input: input, Output: output, Total: input + output, Cached: cached} +} +func openAIUsage(u canonicalUsage) map[string]any { + return map[string]any{"prompt_tokens": u.Input, "completion_tokens": u.Output, "total_tokens": u.Total, "prompt_tokens_details": map[string]any{"cached_tokens": u.Cached}, "completion_tokens_details": map[string]any{"reasoning_tokens": u.Reasoning}} +} + +func decodeChatToolChoice(v any) any { + m, _ := v.(map[string]any) + if stringAt(m, "type") == "function" { + return map[string]any{"name": stringAt(m, "function", "name")} + } + return v +} +func decodeResponsesToolChoice(v any) any { + m, _ := v.(map[string]any) + if stringAt(m, "type") == "function" { + return map[string]any{"name": stringAt(m, "name")} + } + return v +} +func decodeAnthropicToolChoice(v any) any { + m, _ := v.(map[string]any) + if stringAt(m, "type") == "tool" { + return map[string]any{"name": stringAt(m, "name")} + } + if s := stringAt(m, "type"); s != "" { + return s + } + return v +} +func encodeChatToolChoice(v any) any { + if m, ok := v.(map[string]any); ok { + return map[string]any{"type": "function", "function": map[string]any{"name": stringAt(m, "name")}} + } + return v +} +func encodeResponsesToolChoice(v any) any { + if m, ok := v.(map[string]any); ok { + return map[string]any{"type": "function", "name": stringAt(m, "name")} + } + return v +} +func encodeAnthropicToolChoice(v any) any { + if m, ok := v.(map[string]any); ok { + return map[string]any{"type": "tool", "name": stringAt(m, "name")} + } + if v == "required" { + return map[string]any{"type": "any"} + } + if v == "none" { + return map[string]any{"type": "none"} + } + if v == "auto" { + return map[string]any{"type": "auto"} + } + return v +} + +func normalizeChatRole(role string) string { + if role == "developer" { + return "system" + } + return role +} +func normalizeResponsesRole(role string) string { + if role == "tool" { + return "user" + } + return role +} +func normalizeAnthropicRole(role string) string { + if role == "assistant" { + return role + } + return "user" +} +func chatStop(stop string) string { + switch stop { + case "tool_use", "tool_calls": + return "tool_calls" + case "max_tokens", "length": + return "length" + default: + return "stop" + } +} +func anthropicStop(stop string) string { + switch stop { + case "tool_use", "tool_calls": + return "tool_use" + case "max_tokens", "length": + return "max_tokens" + default: + return "end_turn" + } +} +func schemaOrDefault(v any) any { + if v == nil { + return map[string]any{"type": "object", "properties": map[string]any{}} + } + return v +} +func reasoningEffort(v any) any { + if m, ok := v.(map[string]any); ok { + return firstAny(m["effort"], m["type"]) + } + return v +} +func blocksText(blocks []canonicalBlock) string { + var b strings.Builder + for _, block := range blocks { + if block.Type == "text" { + b.WriteString(block.Text) + } + } + return b.String() +} +func contentString(v any) string { + if s, ok := v.(string); ok { + return s + } + data, _ := json.Marshal(v) + return string(data) +} +func parseJSONOrString(v string) any { + if v == "" { + return map[string]any{} + } + var out any + if json.Unmarshal([]byte(v), &out) == nil { + return out + } + return v +} +func asPrefix(id, prefix string) string { + if strings.HasPrefix(id, prefix+"_") { + return id + } + return prefix + "_" + strings.TrimPrefix(id, "resp_") +} +func put(m map[string]any, k string, v any) { + if v != nil { + m[k] = v + } +} +func firstAny(values ...any) any { + for _, v := range values { + if v != nil { + return v + } + } + return nil +} +func cloneMap(in map[string]any) map[string]any { + data, _ := json.Marshal(in) + var out map[string]any + _ = json.Unmarshal(data, &out) + return out +} +func asSlice(v any) []any { + if values, ok := v.([]any); ok { + return values + } + if v == nil { + return nil + } + return []any{v} +} +func sliceAt(m map[string]any, path ...string) []any { + v := anyAt(m, path...) + values, _ := v.([]any) + return values +} +func mapAt(m map[string]any, path ...string) map[string]any { + v := anyAt(m, path...) + value, _ := v.(map[string]any) + return value +} +func stringAt(m map[string]any, path ...string) string { + v := anyAt(m, path...) + value, _ := v.(string) + return value +} +func boolAt(m map[string]any, path ...string) bool { + v := anyAt(m, path...) + value, _ := v.(bool) + return value +} +func intAt(m map[string]any, path ...string) int { + v := anyAt(m, path...) + switch n := v.(type) { + case float64: + return int(n) + case int: + return n + case json.Number: + i, _ := n.Int64() + return int(i) + } + return 0 +} +func int64At(m map[string]any, path ...string) int64 { return int64(intAt(m, path...)) } +func anyAt(m map[string]any, path ...string) any { + var current any = m + for _, key := range path { + next, ok := current.(map[string]any) + if !ok { + return nil + } + current = next[key] + } + return current +} diff --git a/gateway.go b/gateway.go new file mode 100644 index 0000000..74d4a3c --- /dev/null +++ b/gateway.go @@ -0,0 +1,357 @@ +package main + +import ( + "bytes" + "context" + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "strings" + "sync" + "time" +) + +const maxRequestBody = 32 << 20 + +type Gateway struct { + cfg Config + logger *slog.Logger + zenNodes *nodePool + goNodes *nodePool + catalog *modelCatalog +} + +func NewGateway(cfg Config, logger *slog.Logger) (*Gateway, error) { + transports, err := newTransportPool(cfg.Proxies, cfg.Performance, time.Duration(cfg.Retry.TimeoutSeconds)*time.Second) + if err != nil { + return nil, err + } + cooldown := time.Duration(cfg.Performance.FailureCooldownSeconds) * time.Second + zenNodes, err := newNodePool(cfg.ZenKeys, transports, cooldown) + if err != nil { + return nil, fmt.Errorf("zen node pool: %w", err) + } + goNodes, err := newNodePool(cfg.GoKeys, transports, cooldown) + if err != nil { + return nil, fmt.Errorf("go node pool: %w", err) + } + return &Gateway{ + cfg: cfg, + logger: logger, + zenNodes: zenNodes, + goNodes: goNodes, + catalog: newModelCatalog(cfg.Models.Protocols), + }, nil +} + +func (g *Gateway) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /v1/models", g.authenticate(g.handleModels)) + mux.HandleFunc("POST /v1/chat/completions", g.authenticate(g.handleInference(ProtocolChat))) + mux.HandleFunc("POST /v1/responses", g.authenticate(g.handleInference(ProtocolResponses))) + mux.HandleFunc("POST /v1/messages", g.authenticate(g.handleInference(ProtocolAnthropic))) + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{"status": "ok"}) + }) + return recoveryMiddleware(g.logger, mux) +} + +func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + candidates := []string{strings.TrimSpace(r.Header.Get("x-api-key"))} + if auth := r.Header.Get("Authorization"); strings.HasPrefix(strings.ToLower(auth), "bearer ") { + candidates = append(candidates, strings.TrimSpace(auth[7:])) + } + valid := false + for _, key := range g.cfg.ServerKeys { + for _, candidate := range candidates { + if len(candidate) == len(key) && subtle.ConstantTimeCompare([]byte(candidate), []byte(key)) == 1 { + valid = true + } + } + } + if !valid { + protocol := ProtocolChat + if r.URL.Path == "/v1/messages" { + protocol = ProtocolAnthropic + } + writeAPIError(w, protocol, http.StatusUnauthorized, "invalid local API key", "authentication_error", "") + return + } + next(w, r) + } +} + +func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { + now := time.Now().Unix() + models := g.catalog.List() + data := make([]map[string]any, 0, len(models)) + for _, model := range models { + if !supportedModel(model) { + continue + } + data = append(data, map[string]any{"id": model, "object": "model", "created": now, "owned_by": "opencode"}) + } + writeJSON(w, http.StatusOK, map[string]any{"object": "list", "data": data}) +} + +func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBody)) + if err != nil { + writeAPIError(w, external, http.StatusBadRequest, "request body is too large or unreadable", "invalid_request_error", "") + return + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + writeAPIError(w, external, http.StatusBadRequest, "request body must be a JSON object", "invalid_request_error", "") + return + } + model := stringAt(payload, "model") + if model == "" { + writeAPIError(w, external, http.StatusBadRequest, "model is required", "invalid_request_error", "model") + return + } + if !supportedModel(model) { + writeAPIError(w, external, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model") + return + } + route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0) + if err != nil { + writeAPIError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "model") + return + } + encoded := body + if external != route.Protocol { + upstreamPayload, err := convertRequest(external, route.Protocol, payload) + if err != nil { + writeAPIError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "") + return + } + encoded, err = json.Marshal(upstreamPayload) + if err != nil { + writeAPIError(w, external, http.StatusBadRequest, "request contains unsupported JSON values", "invalid_request_error", "") + return + } + } + ids := deriveRequestIDs(r, payload) + stream := boolAt(payload, "stream") + requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second) + defer cancel() + resp, err := g.doUpstream(requestCtx, route, encoded, ids) + if err != nil { + g.logger.Warn("upstream request failed", "request_id", ids.Request, "tier", route.Tier, "error", err) + writeAPIError(w, external, http.StatusBadGateway, "all upstream attempts failed", "upstream_error", ids.Request) + return + } + defer resp.Body.Close() + w.Header().Set("x-request-id", ids.Request) + if resp.StatusCode/100 != 2 { + copyErrorResponse(w, external, resp, ids.Request) + return + } + if stream { + w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("X-Accel-Buffering", "no") + w.WriteHeader(resp.StatusCode) + if external == route.Protocol { + _, err = io.Copy(w, resp.Body) + } else { + err = transcodeStream(w, resp.Body, route.Protocol, external, model) + } + if err != nil && !errors.Is(err, context.Canceled) { + g.logger.Debug("stream ended with error", "request_id", ids.Request, "error", err) + } + return + } + responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20)) + if err != nil { + writeAPIError(w, external, http.StatusBadGateway, "failed to read upstream response", "upstream_error", ids.Request) + return + } + if external != route.Protocol { + responseBody, err = convertResponse(route.Protocol, external, responseBody) + if err != nil { + g.logger.Warn("response conversion failed", "request_id", ids.Request, "error", err) + writeAPIError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request) + return + } + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(resp.StatusCode) + _, _ = w.Write(responseBody) + } +} + +func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, ids requestIDs) (*http.Response, error) { + var lastResponse *http.Response + var lastErr error + nodes := g.zenNodes + baseURL := g.cfg.Upstream.Zen + if route.Tier == TierGo { + nodes = g.goNodes + baseURL = g.cfg.Upstream.Go + } + cursor := nodes.Cursor() + if nodes.Len() == 0 { + return nil, fmt.Errorf("no %s nodes configured", route.Tier) + } + for attempt := 1; attempt <= g.cfg.Retry.MaxAttempts; attempt++ { + node := cursor.Next() + if node == nil { + break + } + if lastResponse != nil { + drainAndClose(lastResponse.Body) + lastResponse = nil + } + endpoint := strings.TrimRight(baseURL, "/") + protocolPath(route.Protocol) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("User-Agent", opencodeUserAgent()) + req.Header.Set("x-opencode-client", "cli") + req.Header.Set("x-opencode-session", ids.Session) + req.Header.Set("x-opencode-request", ids.Request) + req.Header.Set("x-opencode-project", ids.Project) + if route.Protocol == ProtocolAnthropic { + req.Header.Set("x-api-key", node.key) + req.Header.Set("anthropic-version", "2023-06-01") + } else { + req.Header.Set("Authorization", "Bearer "+node.key) + } + resp, err := node.client.Do(req) + if err == nil && resp.StatusCode/100 == 2 { + nodes.MarkSuccess(node) + g.logger.Debug("upstream accepted request", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "proxy", redactURL(node.proxy)) + return resp, nil + } + nodes.MarkFailure(node, resp, err) + lastResponse = resp + lastErr = err + if err != nil { + g.logger.Debug("upstream transport error", "request_id", ids.Request, "attempt", attempt, "proxy", redactURL(node.proxy), "error", err) + } else { + g.logger.Debug("upstream rejected request", "request_id", ids.Request, "attempt", attempt, "status", resp.StatusCode, "proxy", redactURL(node.proxy)) + } + } + if lastResponse != nil { + return lastResponse, nil + } + return nil, lastErr +} + +func protocolPath(protocol Protocol) string { + switch protocol { + case ProtocolResponses: + return "/v1/responses" + case ProtocolAnthropic: + return "/v1/messages" + default: + return "/v1/chat/completions" + } +} + +func (g *Gateway) StartModelRefresh(ctx context.Context) { + refresh := func() { + var zen, goModels []string + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); zen = g.refreshTier(ctx, g.cfg.Upstream.Zen, g.zenNodes) }() + go func() { defer wg.Done(); goModels = g.refreshTier(ctx, g.cfg.Upstream.Go, g.goNodes) }() + wg.Wait() + if zen != nil || goModels != nil { + g.catalog.Replace(zen, goModels) + g.logger.Info("model catalog refreshed", "models", len(g.catalog.List())) + } + } + go func() { + refresh() + ticker := time.NewTicker(time.Duration(g.cfg.Models.RefreshSeconds) * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + refresh() + } + } + }() +} + +func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool) []string { + cursor := nodes.Cursor() + for attempt := 0; attempt < g.cfg.Retry.MaxAttempts; attempt++ { + node := cursor.Next() + if node == nil { + return nil + } + refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + models, err := fetchModels(refreshCtx, node.client, base, node.key) + cancel() + if err == nil { + nodes.MarkSuccess(node) + return models + } + nodes.MarkFailure(node, nil, err) + g.logger.Debug("model refresh attempt failed", "upstream", base, "attempt", attempt+1, "error", err) + } + g.logger.Warn("model refresh failed", "upstream", base) + return nil +} + +func copyErrorResponse(w http.ResponseWriter, protocol Protocol, resp *http.Response, requestID string) { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" { + w.Header().Set("Retry-After", retryAfter) + } + message := http.StatusText(resp.StatusCode) + var value map[string]any + if json.Unmarshal(body, &value) == nil { + message = firstString(stringAt(value, "error", "message"), stringAt(value, "message"), message) + } + writeAPIError(w, protocol, resp.StatusCode, message, "upstream_error", requestID) +} + +func writeAPIError(w http.ResponseWriter, protocol Protocol, status int, message, kind, requestID string) { + w.Header().Set("Content-Type", "application/json") + if requestID != "" { + w.Header().Set("x-request-id", requestID) + } + if protocol == ProtocolAnthropic { + writeJSONStatus(w, status, map[string]any{"type": "error", "error": map[string]any{"type": kind, "message": message}}) + return + } + writeJSONStatus(w, status, map[string]any{"error": map[string]any{"message": message, "type": kind, "param": nil, "code": nil}}) +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json") + writeJSONStatus(w, status, value) +} + +func writeJSONStatus(w http.ResponseWriter, status int, value any) { + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func recoveryMiddleware(logger *slog.Logger, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if value := recover(); value != nil { + logger.Error("request panic", "error", value) + writeAPIError(w, ProtocolChat, http.StatusInternalServerError, "internal server error", "server_error", "") + } + }() + next.ServeHTTP(w, r) + }) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..d634d2c --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module opencode2api + +go 1.24 diff --git a/ids.go b/ids.go new file mode 100644 index 0000000..f86f508 --- /dev/null +++ b/ids.go @@ -0,0 +1,94 @@ +package main + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "runtime" + "strings" +) + +type requestIDs struct { + Session string + Request string + Project string +} + +func deriveRequestIDs(r *http.Request, body map[string]any) requestIDs { + signal := firstString( + r.Header.Get("x-opencode-session"), + r.Header.Get("x-session-id"), + r.Header.Get("conversation-id"), + stringAt(body, "conversation_id"), + stringAt(body, "metadata", "session_id"), + ) + if signal == "" { + // Using the first user turn keeps a multi-turn conversation stable as its + // history grows while separating conversations with different beginnings. + signal = conversationSeed(body) + } + if signal == "" { + signal = stringAt(body, "previous_response_id") + } + if signal == "" || signal == `{}` { + signal = randomID("fallback", 16) + } + session := stableID("ses", signal) + projectSignal := firstString(r.Header.Get("x-opencode-project"), stringAt(body, "metadata", "project_id")) + if projectSignal == "" { + projectSignal = "opencode2api:default-project" + } + return requestIDs{ + Session: session, + Request: randomID("req", 16), + Project: stableID("prj", projectSignal), + } +} + +func conversationSeed(body map[string]any) string { + if input, ok := body["input"].(string); ok && input != "" { + return input + } + for _, field := range []string{"messages", "input"} { + for _, raw := range sliceAt(body, field) { + item, ok := raw.(map[string]any) + if !ok || stringAt(item, "role") != "user" { + continue + } + encoded, _ := json.Marshal(item["content"]) + if len(encoded) > 0 && string(encoded) != "null" { + return string(encoded) + } + } + } + return "" +} + +func stableID(prefix, value string) string { + sum := sha256.Sum256([]byte(prefix + "\x00" + value)) + return prefix + "_" + hex.EncodeToString(sum[:12]) +} + +func randomID(prefix string, size int) string { + buf := make([]byte, size) + if _, err := rand.Read(buf); err != nil { + panic(fmt.Sprintf("crypto/rand failed: %v", err)) + } + return prefix + "_" + hex.EncodeToString(buf) +} + +func firstString(values ...string) string { + for _, value := range values { + if value = strings.TrimSpace(value); value != "" { + return value + } + } + return "" +} + +func opencodeUserAgent() string { + return fmt.Sprintf("opencode/1.18.18 (%s %s; %s)", runtime.GOOS, runtime.GOARCH, runtime.Version()) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..830f0c9 --- /dev/null +++ b/main.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "flag" + "log/slog" + "net/http" + "os" + "os/signal" + "syscall" + "time" +) + +var version = "dev" + +func main() { + configPath := flag.String("config", "config.json", "path to config.json") + flag.Parse() + + cfg, err := LoadConfig(*configPath) + if err != nil { + slog.Error("configuration error", "error", err) + os.Exit(1) + } + level := slog.LevelInfo + if cfg.Logging.Level == "debug" { + level = slog.LevelDebug + } + logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: level})) + gateway, err := NewGateway(cfg, logger) + if err != nil { + logger.Error("failed to initialize gateway", "error", err) + os.Exit(1) + } + + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + gateway.StartModelRefresh(ctx) + + server := &http.Server{ + Addr: cfg.Listen, + Handler: gateway.Handler(), + ReadHeaderTimeout: 15 * time.Second, + IdleTimeout: 120 * time.Second, + } + go func() { + logger.Info("opencode2api listening", "address", cfg.Listen, "version", version) + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + logger.Error("server stopped", "error", err) + cancel() + } + }() + + <-ctx.Done() + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second) + defer shutdownCancel() + if err := server.Shutdown(shutdownCtx); err != nil { + logger.Error("graceful shutdown failed", "error", err) + } +} diff --git a/models.go b/models.go new file mode 100644 index 0000000..840b3c3 --- /dev/null +++ b/models.go @@ -0,0 +1,177 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "sort" + "strings" + "sync" + "time" +) + +type Protocol string + +const ( + ProtocolChat Protocol = "chat" + ProtocolResponses Protocol = "responses" + ProtocolAnthropic Protocol = "anthropic" +) + +func validProtocol(p Protocol) bool { + return p == ProtocolChat || p == ProtocolResponses || p == ProtocolAnthropic +} + +type Tier string + +const ( + TierZen Tier = "zen" + TierGo Tier = "go" +) + +type modelRoute struct { + ID string + Tier Tier + Protocol Protocol +} + +type modelCatalog struct { + mu sync.RWMutex + zen map[string]bool + goModels map[string]bool + protocols map[string]Protocol + updatedAt time.Time +} + +func newModelCatalog(overrides map[string]string) *modelCatalog { + protocols := make(map[string]Protocol, len(overrides)) + for model, protocol := range overrides { + protocols[model] = Protocol(protocol) + } + return &modelCatalog{zen: map[string]bool{}, goModels: map[string]bool{}, protocols: protocols} +} + +func (c *modelCatalog) Replace(zen, goModels []string) { + c.mu.Lock() + defer c.mu.Unlock() + if zen != nil { + c.zen = toSet(zen) + } + if goModels != nil { + c.goModels = toSet(goModels) + } + c.updatedAt = time.Now() +} + +func (c *modelCatalog) Route(model string, hasZenKeys, hasGoKeys bool) (modelRoute, error) { + c.mu.RLock() + defer c.mu.RUnlock() + protocol := c.protocols[model] + if protocol == "" { + protocol = inferProtocol(model) + } + if c.zen[model] && hasZenKeys { + return modelRoute{ID: model, Tier: TierZen, Protocol: protocol}, nil + } + if c.goModels[model] && hasGoKeys { + return modelRoute{ID: model, Tier: TierGo, Protocol: protocol}, nil + } + // Model discovery can temporarily fail. Prefer Zen as requested, then Go. + if len(c.zen) == 0 && len(c.goModels) == 0 { + if hasZenKeys { + return modelRoute{ID: model, Tier: TierZen, Protocol: protocol}, nil + } + if hasGoKeys { + return modelRoute{ID: model, Tier: TierGo, Protocol: protocol}, nil + } + } + return modelRoute{}, fmt.Errorf("model %q is not available in the configured Zen or Go pools", model) +} + +func (c *modelCatalog) List() []string { + c.mu.RLock() + defer c.mu.RUnlock() + seen := make(map[string]bool, len(c.zen)+len(c.goModels)) + for model := range c.zen { + seen[model] = true + } + for model := range c.goModels { + seen[model] = true + } + models := make([]string, 0, len(seen)) + for model := range seen { + models = append(models, model) + } + sort.Strings(models) + return models +} + +func toSet(items []string) map[string]bool { + out := make(map[string]bool, len(items)) + for _, item := range items { + out[item] = true + } + return out +} + +func inferProtocol(model string) Protocol { + m := strings.ToLower(model) + for _, prefix := range []string{"claude-", "qwen"} { + if strings.HasPrefix(m, prefix) { + return ProtocolAnthropic + } + } + for _, prefix := range []string{"gpt-", "o1", "o3", "o4", "grok-"} { + if strings.HasPrefix(m, prefix) { + return ProtocolResponses + } + } + return ProtocolChat +} + +func supportedModel(model string) bool { + m := strings.ToLower(model) + return !strings.HasPrefix(m, "gemini-") +} + +type modelsResponse struct { + Data []struct { + ID string `json:"id"` + } `json:"data"` +} + +func fetchModels(ctx context.Context, client *http.Client, baseURL, key string) ([]string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(baseURL, "/")+"/v1/models", nil) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+key) + req.Header.Set("User-Agent", opencodeUserAgent()) + req.Header.Set("x-opencode-client", "cli") + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + return nil, fmt.Errorf("models endpoint returned HTTP %d", resp.StatusCode) + } + var payload modelsResponse + dec := json.NewDecoder(io.LimitReader(resp.Body, 8<<20)) + if err := dec.Decode(&payload); err != nil { + return nil, err + } + models := make([]string, 0, len(payload.Data)) + for _, item := range payload.Data { + if item.ID != "" { + models = append(models, item.ID) + } + } + if len(models) == 0 { + return nil, errors.New("models endpoint returned an empty list") + } + return models, nil +} diff --git a/pool.go b/pool.go new file mode 100644 index 0000000..93ae875 --- /dev/null +++ b/pool.go @@ -0,0 +1,168 @@ +package main + +import ( + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "sync/atomic" + "time" +) + +type proxyTransport struct { + name string + client *http.Client +} + +type transportPool struct { + items []proxyTransport +} + +func newTransportPool(proxies []string, cfg PerformanceConfig, responseHeaderTimeout time.Duration) (*transportPool, error) { + p := &transportPool{items: make([]proxyTransport, 0, len(proxies))} + for _, raw := range proxies { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.MaxIdleConns = cfg.MaxIdleConns + transport.MaxIdleConnsPerHost = cfg.MaxIdleConnsPerHost + transport.MaxConnsPerHost = cfg.MaxConnsPerHost + transport.IdleConnTimeout = time.Duration(cfg.IdleConnTimeoutSeconds) * time.Second + transport.ResponseHeaderTimeout = responseHeaderTimeout + transport.ForceAttemptHTTP2 = true + transport.DialContext = (&net.Dialer{ + Timeout: time.Duration(cfg.ConnectTimeoutSeconds) * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext + if raw == "direct" { + transport.Proxy = nil + } else { + u, err := url.Parse(raw) + if err != nil { + return nil, fmt.Errorf("parse proxy %s: %w", redactURL(raw), err) + } + transport.Proxy = http.ProxyURL(u) + } + p.items = append(p.items, proxyTransport{name: raw, client: &http.Client{Transport: transport}}) + } + return p, nil +} + +// upstreamNode is immutable except for health counters. A key is permanently +// assigned to one proxy, so the request hot path never parses URLs or builds a +// key/proxy combination. +type upstreamNode struct { + key string + proxy string + client *http.Client + index int + failures atomic.Uint32 + cooldownUntil atomic.Int64 +} + +type nodePool struct { + nodes []*upstreamNode + next atomic.Uint64 + cooldown time.Duration +} + +// newNodePool distributes N keys over M proxies in round-robin order. N/M must +// be a positive integer, so every proxy receives exactly the same key count. +func newNodePool(keys []string, transports *transportPool, cooldown time.Duration) (*nodePool, error) { + if len(keys) == 0 { + return &nodePool{cooldown: cooldown}, nil + } + if len(transports.items) > len(keys) { + return nil, fmt.Errorf("cannot evenly assign %d keys to %d proxies: every proxy must receive at least one key", len(keys), len(transports.items)) + } + if len(keys)%len(transports.items) != 0 { + return nil, fmt.Errorf("cannot evenly assign %d keys to %d proxies: key count must be divisible by proxy count", len(keys), len(transports.items)) + } + pool := &nodePool{nodes: make([]*upstreamNode, 0, len(keys)), cooldown: cooldown} + for i, key := range keys { + proxy := transports.items[i%len(transports.items)] + pool.nodes = append(pool.nodes, &upstreamNode{key: key, proxy: proxy.name, client: proxy.client, index: i}) + } + return pool, nil +} + +func (p *nodePool) Len() int { return len(p.nodes) } + +type nodeCursor struct { + pool *nodePool + next int +} + +// Cursor reserves a different starting node for each concurrent request. +// Selection is delayed until Next, so a node marked failed by the preceding +// attempt is immediately skipped. Both Cursor and Next allocate no memory. +func (p *nodePool) Cursor() nodeCursor { + if len(p.nodes) == 0 { + return nodeCursor{pool: p} + } + return nodeCursor{pool: p, next: int((p.next.Add(1) - 1) % uint64(len(p.nodes)))} +} + +func (c *nodeCursor) Next() *upstreamNode { + if c.pool == nil || len(c.pool.nodes) == 0 { + return nil + } + now := time.Now().UnixNano() + choice := -1 + var earliest int64 + for offset := 0; offset < len(c.pool.nodes); offset++ { + i := (c.next + offset) % len(c.pool.nodes) + until := c.pool.nodes[i].cooldownUntil.Load() + if until <= now { + choice = i + break + } + if choice == -1 || until < earliest { + choice, earliest = i, until + } + } + if choice < 0 { + return nil + } + c.next = (choice + 1) % len(c.pool.nodes) + return c.pool.nodes[choice] +} + +func (p *nodePool) MarkSuccess(node *upstreamNode) { + node.failures.Store(0) + node.cooldownUntil.Store(0) +} + +func (p *nodePool) MarkFailure(node *upstreamNode, resp *http.Response, err error) { + if err == nil && resp != nil && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode < 500 { + return + } + failures := node.failures.Add(1) + multiplier := time.Duration(1 << min(failures-1, 3)) + delay := p.cooldown * multiplier + if resp != nil { + if retryAfter := parseRetryAfter(resp.Header.Get("Retry-After")); retryAfter > delay { + delay = retryAfter + } + } + node.cooldownUntil.Store(time.Now().Add(delay).UnixNano()) +} + +func parseRetryAfter(value string) time.Duration { + if seconds, err := strconv.Atoi(strings.TrimSpace(value)); err == nil && seconds > 0 { + return time.Duration(seconds) * time.Second + } + if when, err := http.ParseTime(value); err == nil { + return max(time.Until(when), 0) + } + return 0 +} + +func drainAndClose(body io.ReadCloser) { + if body == nil { + return + } + _, _ = io.Copy(io.Discard, io.LimitReader(body, 64<<10)) + _ = body.Close() +} diff --git a/stream.go b/stream.go new file mode 100644 index 0000000..b568110 --- /dev/null +++ b/stream.go @@ -0,0 +1,508 @@ +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" +) + +type streamEvent struct { + Kind string + ID string + Model string + Text string + Key string + ToolID string + Name string + Stop string + Usage *canonicalUsage +} + +type streamParser struct { + protocol Protocol + toolSeen map[string]bool +} + +func transcodeStream(w http.ResponseWriter, r io.Reader, from, to Protocol, model string) error { + flusher, ok := w.(http.Flusher) + if !ok { + return fmt.Errorf("response writer does not support streaming") + } + parser := &streamParser{protocol: from, toolSeen: map[string]bool{}} + emitter := newStreamEmitter(w, flusher, to, model) + err := readSSE(r, func(eventName, data string) error { + events, err := parser.Parse(eventName, data) + if err != nil { + return err + } + for _, event := range events { + if err := emitter.Emit(event); err != nil { + return err + } + } + return nil + }) + if err != nil { + return err + } + return emitter.Finish() +} + +func readSSE(r io.Reader, fn func(eventName, data string) error) error { + scanner := bufio.NewScanner(r) + scanner.Buffer(make([]byte, 64<<10), 16<<20) + var eventName string + var data []string + flush := func() error { + if len(data) == 0 { + eventName = "" + return nil + } + err := fn(eventName, strings.Join(data, "\n")) + eventName = "" + data = data[:0] + return err + } + for scanner.Scan() { + line := strings.TrimSuffix(scanner.Text(), "\r") + if line == "" { + if err := flush(); err != nil { + return err + } + continue + } + if strings.HasPrefix(line, "event:") { + eventName = strings.TrimSpace(strings.TrimPrefix(line, "event:")) + } + if strings.HasPrefix(line, "data:") { + data = append(data, strings.TrimSpace(strings.TrimPrefix(line, "data:"))) + } + } + if err := scanner.Err(); err != nil { + return err + } + return flush() +} + +func (p *streamParser) Parse(eventName, data string) ([]streamEvent, error) { + if data == "[DONE]" { + return []streamEvent{{Kind: "done"}}, nil + } + var value map[string]any + if err := json.Unmarshal([]byte(data), &value); err != nil { + return nil, fmt.Errorf("invalid upstream SSE JSON: %w", err) + } + switch p.protocol { + case ProtocolChat: + return p.parseChat(value), nil + case ProtocolAnthropic: + return p.parseAnthropic(value), nil + case ProtocolResponses: + return p.parseResponses(eventName, value), nil + default: + return nil, fmt.Errorf("unsupported stream protocol %q", p.protocol) + } +} + +func (p *streamParser) parseChat(v map[string]any) []streamEvent { + var events []streamEvent + if id := stringAt(v, "id"); id != "" { + events = append(events, streamEvent{Kind: "start", ID: id, Model: stringAt(v, "model")}) + } + if usageMap := mapAt(v, "usage"); len(usageMap) > 0 { + usage := decodeOpenAIUsage(usageMap) + events = append(events, streamEvent{Kind: "usage", Usage: &usage}) + } + for _, raw := range sliceAt(v, "choices") { + choice, _ := raw.(map[string]any) + delta := mapAt(choice, "delta") + if text := stringAt(delta, "content"); text != "" { + events = append(events, streamEvent{Kind: "text", Text: text}) + } + for _, rawCall := range sliceAt(delta, "tool_calls") { + call, _ := rawCall.(map[string]any) + key := fmt.Sprint(firstAny(call["index"], stringAt(call, "id"))) + fn := mapAt(call, "function") + if !p.toolSeen[key] { + p.toolSeen[key] = true + events = append(events, streamEvent{Kind: "tool_start", Key: key, ToolID: stringAt(call, "id"), Name: stringAt(fn, "name")}) + } + if args := stringAt(fn, "arguments"); args != "" { + events = append(events, streamEvent{Kind: "tool_delta", Key: key, Text: args}) + } + } + if stop := stringAt(choice, "finish_reason"); stop != "" { + events = append(events, streamEvent{Kind: "finish", Stop: stop}) + } + } + return events +} + +func (p *streamParser) parseAnthropic(v map[string]any) []streamEvent { + typeName := stringAt(v, "type") + switch typeName { + case "message_start": + message := mapAt(v, "message") + events := []streamEvent{{Kind: "start", ID: stringAt(message, "id"), Model: stringAt(message, "model")}} + if usageMap := mapAt(message, "usage"); len(usageMap) > 0 { + usage := decodeAnthropicUsage(usageMap) + events = append(events, streamEvent{Kind: "usage", Usage: &usage}) + } + return events + case "content_block_start": + block := mapAt(v, "content_block") + key := fmt.Sprint(v["index"]) + if stringAt(block, "type") == "tool_use" { + return []streamEvent{{Kind: "tool_start", Key: key, ToolID: stringAt(block, "id"), Name: stringAt(block, "name")}} + } + return nil + case "content_block_delta": + delta := mapAt(v, "delta") + key := fmt.Sprint(v["index"]) + if stringAt(delta, "type") == "input_json_delta" { + return []streamEvent{{Kind: "tool_delta", Key: key, Text: stringAt(delta, "partial_json")}} + } + if stringAt(delta, "type") == "text_delta" { + return []streamEvent{{Kind: "text", Text: stringAt(delta, "text")}} + } + case "message_delta": + var events []streamEvent + if usageMap := mapAt(v, "usage"); len(usageMap) > 0 { + usage := decodeAnthropicUsage(usageMap) + events = append(events, streamEvent{Kind: "usage", Usage: &usage}) + } + if stop := stringAt(v, "delta", "stop_reason"); stop != "" { + events = append(events, streamEvent{Kind: "finish", Stop: stop}) + } + return events + case "message_stop": + return []streamEvent{{Kind: "done"}} + case "error": + return []streamEvent{{Kind: "finish", Stop: "error"}, {Kind: "done"}} + } + return nil +} + +func (p *streamParser) parseResponses(eventName string, v map[string]any) []streamEvent { + typeName := stringAt(v, "type") + if typeName == "" { + typeName = eventName + } + switch typeName { + case "response.created": + response := mapAt(v, "response") + return []streamEvent{{Kind: "start", ID: stringAt(response, "id"), Model: stringAt(response, "model")}} + case "response.output_text.delta": + return []streamEvent{{Kind: "text", Text: stringAt(v, "delta")}} + case "response.output_item.added": + item := mapAt(v, "item") + if stringAt(item, "type") == "function_call" { + return []streamEvent{{Kind: "tool_start", Key: fmt.Sprint(v["output_index"]), ToolID: stringAt(item, "call_id"), Name: stringAt(item, "name")}} + } + case "response.function_call_arguments.delta": + return []streamEvent{{Kind: "tool_delta", Key: fmt.Sprint(v["output_index"]), Text: stringAt(v, "delta")}} + case "response.completed", "response.incomplete", "response.failed": + response := mapAt(v, "response") + usage := decodeOpenAIUsage(mapAt(response, "usage")) + stop := "stop" + if typeName == "response.incomplete" { + stop = "length" + } + if typeName == "response.failed" { + stop = "error" + } + return []streamEvent{{Kind: "usage", Usage: &usage}, {Kind: "finish", Stop: stop}, {Kind: "done"}} + } + return nil +} + +type bufferedTool struct { + ID string + ItemID string + Name string + Arguments strings.Builder +} + +type streamEmitter struct { + w io.Writer + flush http.Flusher + target Protocol + response canonicalResponse + started bool + finished bool + textOpen bool + textItem string + sequence int + tools map[string]*bufferedTool + order []string +} + +func newStreamEmitter(w io.Writer, flush http.Flusher, target Protocol, model string) *streamEmitter { + return &streamEmitter{w: w, flush: flush, target: target, response: canonicalResponse{Model: model, Created: time.Now().Unix()}, tools: map[string]*bufferedTool{}} +} + +func (e *streamEmitter) Emit(event streamEvent) error { + if event.ID != "" && e.response.ID == "" { + e.response.ID = event.ID + } + if event.Model != "" { + e.response.Model = event.Model + } + if !e.started && (event.Kind == "start" || event.Kind == "text" || event.Kind == "tool_start") { + if err := e.start(); err != nil { + return err + } + } + switch event.Kind { + case "text": + if event.Text == "" { + return nil + } + e.response.Text += event.Text + return e.emitText(event.Text) + case "tool_start": + if _, exists := e.tools[event.Key]; !exists { + id := event.ToolID + if id == "" { + id = randomID("call", 12) + } + e.tools[event.Key] = &bufferedTool{ID: id, ItemID: randomID("fc", 12), Name: event.Name} + e.order = append(e.order, event.Key) + } + case "tool_delta": + tool := e.tools[event.Key] + if tool == nil { + tool = &bufferedTool{ID: randomID("call", 12), ItemID: randomID("fc", 12)} + e.tools[event.Key] = tool + e.order = append(e.order, event.Key) + } + tool.Arguments.WriteString(event.Text) + case "usage": + if event.Usage != nil { + mergeUsage(&e.response.Usage, *event.Usage) + } + case "finish": + e.response.Stop = event.Stop + case "done": + return e.Finish() + } + return nil +} + +func (e *streamEmitter) start() error { + if e.started { + return nil + } + e.started = true + if e.response.ID == "" { + e.response.ID = randomID("resp", 12) + } + switch e.target { + case ProtocolChat: + return e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "content": ""}, "finish_reason": nil}}}) + case ProtocolAnthropic: + return e.sse("message_start", map[string]any{"type": "message_start", "message": map[string]any{"id": asPrefix(e.response.ID, "msg"), "type": "message", "role": "assistant", "model": e.response.Model, "content": []any{}, "stop_reason": nil, "stop_sequence": nil, "usage": map[string]any{"input_tokens": 0, "output_tokens": 0}}}) + case ProtocolResponses: + base := map[string]any{"id": asPrefix(e.response.ID, "resp"), "object": "response", "created_at": e.response.Created, "status": "in_progress", "model": e.response.Model, "output": []any{}, "error": nil} + if err := e.sse("response.created", map[string]any{"type": "response.created", "response": base, "sequence_number": e.nextSequence()}); err != nil { + return err + } + return e.sse("response.in_progress", map[string]any{"type": "response.in_progress", "response": base, "sequence_number": e.nextSequence()}) + } + return nil +} + +func (e *streamEmitter) emitText(delta string) error { + switch e.target { + case ProtocolChat: + return e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"content": delta}, "finish_reason": nil}}}) + case ProtocolAnthropic: + if !e.textOpen { + e.textOpen = true + if err := e.sse("content_block_start", map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "text", "text": ""}}); err != nil { + return err + } + } + return e.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]any{"type": "text_delta", "text": delta}}) + case ProtocolResponses: + if !e.textOpen { + e.textOpen = true + e.textItem = randomID("msg", 12) + item := map[string]any{"id": e.textItem, "type": "message", "status": "in_progress", "role": "assistant", "content": []any{}} + if err := e.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": 0, "item": item, "sequence_number": e.nextSequence()}); err != nil { + return err + } + if err := e.sse("response.content_part.added", map[string]any{"type": "response.content_part.added", "item_id": item["id"], "output_index": 0, "content_index": 0, "part": map[string]any{"type": "output_text", "text": "", "annotations": []any{}}, "sequence_number": e.nextSequence()}); err != nil { + return err + } + } + return e.sse("response.output_text.delta", map[string]any{"type": "response.output_text.delta", "delta": delta, "item_id": e.textItem, "output_index": 0, "content_index": 0, "sequence_number": e.nextSequence()}) + } + return nil +} + +func (e *streamEmitter) Finish() error { + if e.finished { + return nil + } + e.finished = true + if !e.started { + if err := e.start(); err != nil { + return err + } + } + for _, key := range e.order { + tool := e.tools[key] + if tool == nil { + continue + } + input := parseJSONOrString(tool.Arguments.String()) + e.response.Tools = append(e.response.Tools, canonicalBlock{Type: "tool_use", ID: tool.ID, Name: tool.Name, Input: input}) + } + if e.response.Stop == "" { + e.response.Stop = "stop" + } + switch e.target { + case ProtocolChat: + if len(e.response.Tools) > 0 { + calls := make([]any, 0, len(e.response.Tools)) + for i, tool := range e.response.Tools { + args, _ := json.Marshal(tool.Input) + calls = append(calls, map[string]any{"index": i, "id": tool.ID, "type": "function", "function": map[string]any{"name": tool.Name, "arguments": string(args)}}) + } + if err := e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"tool_calls": calls}, "finish_reason": nil}}}); err != nil { + return err + } + } + if err := e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": chatStop(e.response.Stop)}}}); err != nil { + return err + } + if err := e.sse("", map[string]any{"id": asPrefix(e.response.ID, "chatcmpl"), "object": "chat.completion.chunk", "created": e.response.Created, "model": e.response.Model, "choices": []any{}, "usage": openAIUsage(e.response.Usage)}); err != nil { + return err + } + return e.rawSSE("", "[DONE]") + case ProtocolAnthropic: + index := 0 + if e.textOpen { + if err := e.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil { + return err + } + index++ + } + for _, tool := range e.response.Tools { + if err := e.sse("content_block_start", map[string]any{"type": "content_block_start", "index": index, "content_block": map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": map[string]any{}}}); err != nil { + return err + } + args, _ := json.Marshal(tool.Input) + if err := e.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": index, "delta": map[string]any{"type": "input_json_delta", "partial_json": string(args)}}); err != nil { + return err + } + if err := e.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil { + return err + } + index++ + } + if err := e.sse("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": anthropicStop(e.response.Stop), "stop_sequence": nil}, "usage": map[string]any{"input_tokens": e.response.Usage.Input, "output_tokens": e.response.Usage.Output}}); err != nil { + return err + } + return e.sse("message_stop", map[string]any{"type": "message_stop"}) + case ProtocolResponses: + if e.textOpen { + if err := e.sse("response.output_text.done", map[string]any{"type": "response.output_text.done", "text": e.response.Text, "item_id": e.textItem, "output_index": 0, "content_index": 0, "sequence_number": e.nextSequence()}); err != nil { + return err + } + part := map[string]any{"type": "output_text", "text": e.response.Text, "annotations": []any{}} + if err := e.sse("response.content_part.done", map[string]any{"type": "response.content_part.done", "item_id": e.textItem, "output_index": 0, "content_index": 0, "part": part, "sequence_number": e.nextSequence()}); err != nil { + return err + } + item := map[string]any{"id": e.textItem, "type": "message", "status": "completed", "role": "assistant", "content": []any{part}} + if err := e.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": 0, "item": item, "sequence_number": e.nextSequence()}); err != nil { + return err + } + } + baseIndex := 0 + if e.textOpen { + baseIndex = 1 + } + for i, key := range e.order { + tool := e.tools[key] + if tool == nil { + continue + } + index := baseIndex + i + item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "in_progress", "arguments": "", "call_id": tool.ID, "name": tool.Name} + if err := e.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": index, "item": item, "sequence_number": e.nextSequence()}); err != nil { + return err + } + args := tool.Arguments.String() + if err := e.sse("response.function_call_arguments.delta", map[string]any{"type": "response.function_call_arguments.delta", "delta": args, "item_id": tool.ItemID, "output_index": index, "sequence_number": e.nextSequence()}); err != nil { + return err + } + if err := e.sse("response.function_call_arguments.done", map[string]any{"type": "response.function_call_arguments.done", "arguments": args, "item_id": tool.ItemID, "output_index": index, "sequence_number": e.nextSequence()}); err != nil { + return err + } + item["status"] = "completed" + item["arguments"] = args + if err := e.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": index, "item": item, "sequence_number": e.nextSequence()}); err != nil { + return err + } + } + output := encodeResponse(ProtocolResponses, e.response)["output"] + response := encodeResponse(ProtocolResponses, e.response) + response["output"] = output + return e.sse("response.completed", map[string]any{"type": "response.completed", "response": response, "sequence_number": e.nextSequence()}) + } + return nil +} + +func (e *streamEmitter) nextSequence() int { + value := e.sequence + e.sequence++ + return value +} + +func (e *streamEmitter) sse(event string, value any) error { + data, err := json.Marshal(value) + if err != nil { + return err + } + return e.rawSSE(event, string(data)) +} + +func (e *streamEmitter) rawSSE(event, data string) error { + if event != "" { + if _, err := fmt.Fprintf(e.w, "event: %s\n", event); err != nil { + return err + } + } + if _, err := fmt.Fprintf(e.w, "data: %s\n\n", data); err != nil { + return err + } + e.flush.Flush() + return nil +} + +func mergeUsage(dst *canonicalUsage, src canonicalUsage) { + if src.Input != 0 { + dst.Input = src.Input + } + if src.Output != 0 { + dst.Output = src.Output + } + if src.Total != 0 { + dst.Total = src.Total + } + if src.Cached != 0 { + dst.Cached = src.Cached + } + if src.Reasoning != 0 { + dst.Reasoning = src.Reasoning + } + if dst.Total == 0 { + dst.Total = dst.Input + dst.Output + } +}