diff --git a/.dockerignore b/.dockerignore index 3afacb7..299e1c0 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,8 @@ * -!*.go +!cmd/ +!cmd/** +!internal/ +!internal/** !go.mod !go.sum !webui/ diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 3717678..dcac458 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -14,7 +14,7 @@ concurrency: cancel-in-progress: true jobs: - test: + build: name: Go ${{ matrix.go }} / ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: @@ -30,14 +30,8 @@ jobs: cache: true - name: Vet run: go vet ./... - - name: Test with race detection - if: runner.os == 'Linux' - run: go test -race -coverprofile=coverage.out ./... - - name: Test on Windows - if: runner.os == 'Windows' - run: go test ./... - name: Build - run: go build ./... + run: go build -trimpath ./cmd/opencode2api format: name: Formatting and WebUI syntax diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dc10e30..c0db894 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,8 +44,8 @@ jobs: echo "release_tag=$release_tag" >> "$GITHUB_OUTPUT" echo "image_name=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT" - test: - name: Test + verify: + name: Verify source runs-on: ubuntu-latest steps: - name: Check out source @@ -57,12 +57,15 @@ jobs: go-version-file: go.mod cache: true - - name: Run tests - run: go test ./... + - name: Vet + run: go vet ./... + + - name: Build + run: go build ./... build: name: Build ${{ matrix.goos }}/${{ matrix.goarch }} - needs: [prepare, test] + needs: [prepare, verify] runs-on: ubuntu-latest strategy: fail-fast: false @@ -124,7 +127,7 @@ jobs: ARCHIVE_FORMAT: ${{ matrix.archive }} run: | mkdir -p "dist/$PACKAGE_NAME" - go build -trimpath -ldflags="-s -w -X main.version=$RELEASE_TAG" -o "dist/$PACKAGE_NAME/opencode2api$EXTENSION" ./ + go build -trimpath -ldflags="-s -w -X main.version=$RELEASE_TAG" -o "dist/$PACKAGE_NAME/opencode2api$EXTENSION" ./cmd/opencode2api cp README.md README.zh-CN.md config.example.json "dist/$PACKAGE_NAME/" if [[ "$ARCHIVE_FORMAT" == "zip" ]]; then (cd dist && zip -q -r "$PACKAGE_NAME.zip" "$PACKAGE_NAME") @@ -146,7 +149,7 @@ jobs: container: name: Publish GHCR image - needs: [prepare, test] + needs: [prepare, verify] runs-on: ubuntu-latest permissions: contents: read diff --git a/.gitignore b/.gitignore index cda442d..fe2e912 100644 --- a/.gitignore +++ b/.gitignore @@ -4,8 +4,8 @@ config.json.bak .config-*.tmp *.models.dev.json opencode/ -opencode2api -opencode2api.exe +/opencode2api +/opencode2api.exe *.log .tmp/ .gocache/ diff --git a/Dockerfile b/Dockerfile index 8018ce8..ef89733 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,7 +17,7 @@ RUN CGO_ENABLED=0 \ go build \ -trimpath \ -ldflags="-s -w -X main.version=${VERSION}" \ - -o /out/opencode2api ./ + -o /out/opencode2api ./cmd/opencode2api FROM alpine:3.22 diff --git a/README.md b/README.md index 874a59b..81e67fa 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Download a binary from [GitHub Releases](https://github.com/jasonxu114514/openco git clone https://github.com/jasonxu114514/opencode2api.git cd opencode2api cp config.example.json config.json -go build -o opencode2api . +go build -o opencode2api ./cmd/opencode2api ``` Before starting, edit `config.json`: @@ -38,7 +38,7 @@ Before starting, edit `config.json`: ./opencode2api -config config.json ``` -On Windows, use `Copy-Item config.example.json config.json`, build with `go build -o opencode2api.exe .`, then run `.\opencode2api.exe -config config.json`. +On Windows, use `Copy-Item config.example.json config.json`, build with `go build -o opencode2api.exe ./cmd/opencode2api`, then run `.\opencode2api.exe -config config.json`. The example listens on `127.0.0.1:8080` for the API and `0.0.0.0:8081` for the WebUI. Open `http://localhost:8081` locally. Restrict management access and use an HTTPS reverse proxy when accessing it over a network. @@ -352,30 +352,45 @@ The staleness threshold is twice `models.refresh_seconds`, with a minimum of 60 ## Development -Source organization: +Go source is organized into packages by responsibility. The command wires the service together; implementation packages live under `internal/`. -| Files | Responsibility | -| ------------------------------------------------------ | -------------------------------------------------------------------------- | -| `main.go`, `config.go`, `runtime.go` | Startup, validated configuration, runtime replacement. | -| `gateway*.go`, `upstream.go`, `pool.go`, `ids.go` | HTTP handlers, routing, retries, discovery refresh, connections, affinity. | -| `convert*.go` | Shared representation, request/response conversion, content mapping. | -| `stream.go`, `stream_parser.go`, `stream_emitter.go` | SSE transport, parsing, and protocol output. | -| `models.go`, `model_*.go` | Catalog, native capabilities, prices, and caches. | -| `admin*.go`, `password.go` | Management API, authentication, and diagnostics. | -| `observability.go`, `metrics.go`, `logging.go` | HTTP observation, aggregation, and redacted logs. | -| `webui/index.html`, `webui/app.js`, `webui/styles.css` | Embedded static interface; no frontend build step. | - -Run Go checks: - -```bash -gofmt -w . -go vet ./... -go test ./... -go test -race ./... -go build . +```text +cmd/ + opencode2api/main.go CLI flags, startup, and graceful shutdown +internal/ + admin/ Management API, login sessions, and Playground + buildinfo/ Version shared by health and management endpoints + config/ Configuration, persistence, passwords, and redaction + gateway/ HTTP routing, retries, pools, refresh, and runtime + httpx/ Shared HTTP responses, body handling, and headers + identity/ Request IDs and session affinity + jsonutil/ JSON access and decoding helpers + models/ Model catalog, capabilities, pricing, and caches + protocol/ Request/response conversion and SSE parsing/output + telemetry/ Request tracking, metrics, logs, and recovery +webui/ + embed.go Embeds the three static assets into the executable + index.html Page structure + app.js UI behavior + styles.css UI styles ``` -The race detector needs CGO and a supported C compiler. Tests use local servers or stub transports for inference; no production keys are required. +Suggested reading order: + +1. [Command entry](cmd/opencode2api/main.go) → [runtime management](internal/gateway/runtime.go) → [HTTP handlers](internal/gateway/gateway.go). +2. [Upstream attempts](internal/gateway/upstream.go) and [model routing](internal/models/catalog.go) explain how a request reaches a provider. +3. [Request conversion](internal/protocol/request.go), [response conversion](internal/protocol/response.go), and [stream transport](internal/protocol/stream.go) cover protocol behavior. +4. [Management routes](internal/admin/server.go) and [WebUI logic](webui/app.js) cover configuration and diagnostics. + +Run Go formatting, analysis, and the command build: + +```bash +gofmt -w cmd internal webui +go vet ./... +go build -o opencode2api ./cmd/opencode2api +``` + +For local development, start the service with `go run ./cmd/opencode2api -config config.json`. Release builds still inject the version with `-ldflags "-X main.version=vX.Y.Z"`. Node.js is only needed for development formatting and JavaScript syntax checks: @@ -386,7 +401,7 @@ npm run format:check npm run check:web ``` -`.editorconfig`, `.gitattributes`, Go formatting, and pinned Prettier settings standardize the source. PR checks cover Go 1.24 and stable Go on Linux/Windows, Linux race detection, formatting, WebUI syntax, and entrypoint shell syntax. Release archives include both READMEs. +`.editorconfig`, `.gitattributes`, Go formatting, and pinned Prettier settings standardize the source. CI runs `go vet` and builds with Go 1.24 and stable Go on Linux/Windows, plus formatting, WebUI syntax, and entrypoint shell syntax checks. Release archives include both READMEs. ## Troubleshooting diff --git a/README.zh-CN.md b/README.zh-CN.md index 2c06818..4144662 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -25,7 +25,7 @@ WebUI 内嵌在可执行文件中,运行服务无需 Node.js 或数据库。 git clone https://github.com/jasonxu114514/opencode2api.git cd opencode2api cp config.example.json config.json -go build -o opencode2api . +go build -o opencode2api ./cmd/opencode2api ``` 启动前编辑 `config.json`: @@ -38,7 +38,7 @@ go build -o opencode2api . ./opencode2api -config config.json ``` -Windows 下使用 `Copy-Item config.example.json config.json` 复制配置,执行 `go build -o opencode2api.exe .` 编译,再运行 `.\opencode2api.exe -config config.json`。 +Windows 下使用 `Copy-Item config.example.json config.json` 复制配置,执行 `go build -o opencode2api.exe ./cmd/opencode2api` 编译,再运行 `.\opencode2api.exe -config config.json`。 示例配置的 API 监听 `127.0.0.1:8080`,WebUI 监听 `0.0.0.0:8081`。本机可访问 `http://localhost:8081`。通过网络访问管理界面时,请限制访问范围,并使用 HTTPS 反向代理。 @@ -352,30 +352,45 @@ Token 统计仅使用上游报告的 usage。输入 Token 包含缓存读取和 ## 开发 -代码按职责组织: +Go 源码按职责拆分为独立包。程序入口负责组装服务,具体实现放在 `internal/` 中。 -| 文件 | 职责 | -| ------------------------------------------------------ | --------------------------------------------------- | -| `main.go`、`config.go`、`runtime.go` | 启动、配置校验与运行时切换。 | -| `gateway*.go`、`upstream.go`、`pool.go`、`ids.go` | HTTP 接口、路由、重试、目录刷新、连接与会话亲和性。 | -| `convert*.go` | 统一中间结构、请求和响应转换、内容映射。 | -| `stream.go`、`stream_parser.go`、`stream_emitter.go` | SSE 传输、解析及协议输出。 | -| `models.go`、`model_*.go` | 模型目录、原生能力、价格与缓存。 | -| `admin*.go`、`password.go` | 管理 API、认证与诊断。 | -| `observability.go`、`metrics.go`、`logging.go` | HTTP 观测、统计聚合与脱敏日志。 | -| `webui/index.html`、`webui/app.js`、`webui/styles.css` | 内嵌静态界面,无需前端构建。 | - -Go 检查: - -```bash -gofmt -w . -go vet ./... -go test ./... -go test -race ./... -go build . +```text +cmd/ + opencode2api/main.go 命令行参数、启动与优雅退出 +internal/ + admin/ 管理 API、登录会话与 Playground + buildinfo/ 健康检查和管理接口共享的版本信息 + config/ 配置解析、持久化、密码与脱敏 + gateway/ HTTP 路由、重试、资源池、刷新与运行时 + httpx/ 通用 HTTP 响应、响应体处理与请求头 + identity/ 请求标识与会话亲和性 + jsonutil/ JSON 取值与解码辅助函数 + models/ 模型目录、能力、价格与缓存 + protocol/ 请求和响应转换、SSE 解析与输出 + telemetry/ 请求跟踪、指标、日志与异常恢复 +webui/ + embed.go 将三个静态资源内嵌到可执行文件 + index.html 页面结构 + app.js 界面交互 + styles.css 界面样式 ``` -竞态检测需要启用 CGO 并安装受支持的 C 编译器。推理测试使用本地服务器或模拟 Transport,不需要生产 Key。 +建议阅读顺序: + +1. [程序入口](cmd/opencode2api/main.go) → [运行时管理](internal/gateway/runtime.go) → [HTTP 处理](internal/gateway/gateway.go)。 +2. [上游请求](internal/gateway/upstream.go)和[模型路由](internal/models/catalog.go)说明请求如何选择并到达上游。 +3. [请求转换](internal/protocol/request.go)、[响应转换](internal/protocol/response.go)和[流式传输](internal/protocol/stream.go)说明协议处理过程。 +4. [管理路由](internal/admin/server.go)和 [WebUI 交互](webui/app.js)说明配置编辑与诊断功能。 + +执行 Go 格式化、静态分析和程序构建: + +```bash +gofmt -w cmd internal webui +go vet ./... +go build -o opencode2api ./cmd/opencode2api +``` + +开发时可以直接运行 `go run ./cmd/opencode2api -config config.json`。发布构建仍通过 `-ldflags "-X main.version=vX.Y.Z"` 注入版本号。 Node.js 仅用于开发时的格式化和 JavaScript 语法检查: @@ -386,7 +401,7 @@ npm run format:check npm run check:web ``` -项目通过 `.editorconfig`、`.gitattributes`、Go 格式化和固定版本的 Prettier 统一格式。PR 检查覆盖 Linux / Windows 上的 Go 1.24 与稳定版 Go、Linux 竞态检测、格式、WebUI 语法和容器入口脚本语法。发布压缩包包含中英文两份 README。 +项目通过 `.editorconfig`、`.gitattributes`、Go 格式化和固定版本的 Prettier 统一格式。CI 覆盖 Linux / Windows 上的 Go 1.24 与稳定版 Go 的 `go vet` 和构建,以及格式、WebUI 语法和容器入口脚本语法检查。发布压缩包包含中英文两份 README。 ## 常见问题 diff --git a/admin_debug_test.go b/admin_debug_test.go deleted file mode 100644 index f6faea6..0000000 --- a/admin_debug_test.go +++ /dev/null @@ -1,260 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "net/http/httptest" - "reflect" - "strings" - "sync/atomic" - "testing" - "time" -) - -type testPoolState struct { - Keys []testKeyState - Anonymous []testKeyState - Healthy []bool -} - -type testKeyState struct { - Failures uint32 - Cooldown int64 - Proxy int64 -} - -func snapshotTestPools(g *Gateway) testPoolState { - state := testPoolState{} - for _, pool := range []*nodePool{g.zenNodes, g.goNodes} { - for _, node := range pool.nodes { - state.Keys = append(state.Keys, testKeyState{ - Failures: node.failures.Load(), Cooldown: node.cooldownUntil.Load(), - Proxy: node.proxyIndex.Load(), - }) - } - } - for _, node := range g.anonymous.nodes { - state.Anonymous = append(state.Anonymous, testKeyState{ - Failures: node.failures.Load(), Cooldown: node.cooldownUntil.Load(), - Proxy: int64(node.proxy.index), - }) - } - for _, proxy := range g.transports.items { - state.Healthy = append(state.Healthy, proxy.healthy.Load()) - } - return state -} - -func runDebugTest(t *testing.T, manager *RuntimeManager, key DebugKeySelection, model string) DebugInferenceResult { - t.Helper() - admin := NewAdminServer(manager, manager.monitor, manager.hub, manager.logger) - payload, err := json.Marshal(DebugInferenceRequest{ - Protocol: ProtocolChat, Key: key, - Request: map[string]any{ - "model": model, "stream": true, - "messages": []any{map[string]any{"role": "user", "content": "hello"}}, - }, - }) - if err != nil { - t.Fatal(err) - } - request := httptest.NewRequest(http.MethodPost, "/api/debug/inference", strings.NewReader(string(payload))) - recorder := httptest.NewRecorder() - admin.handleDebugInference(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("management status = %d: %s", recorder.Code, recorder.Body.String()) - } - var result DebugInferenceResult - if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil { - t.Fatal(err) - } - return result -} - -func TestAutomaticDiagnosticsPreserveProductionPools(t *testing.T) { - for _, lane := range []string{"key", "anonymous"} { - for _, outcome := range []string{"success", "unauthorized", "rate_limited", "transport_error"} { - t.Run(lane+"/"+outcome, func(t *testing.T) { - cfg := handlerTestConfig() - cfg.Proxies = []string{"http://first.invalid:8080", "http://second.invalid:8080"} - model := "example-model" - if lane == "anonymous" { - cfg.Anonymous = true - cfg.ZenKeys = nil - model = "example-free" - } - var probes atomic.Int32 - var calls atomic.Int32 - manager, gateway := newHandlerTestRuntime(t, cfg, func(r *http.Request) (*http.Response, error) { - if r.URL.Host == "cloudflare.com" { - probes.Add(1) - return stubResponse(200, "ok"), nil - } - calls.Add(1) - var request map[string]any - if err := json.NewDecoder(r.Body).Decode(&request); err != nil { - t.Fatal(err) - } - if boolAt(request, "stream") { - t.Fatal("Playground must force a non-streaming request") - } - switch outcome { - case "unauthorized": - return stubResponse(401, `{"error":{"message":"invalid key"}}`), nil - case "rate_limited": - return stubResponse(429, `{"error":{"message":"rate limited"}}`), nil - case "transport_error": - return nil, context.DeadlineExceeded - default: - return stubResponse(200, `{"choices":[{"message":{"role":"assistant","content":"ok"}}]}`), nil - } - }) - // Successful diagnostics must not clear prior production failures. - for _, node := range gateway.zenNodes.nodes { - node.failures.Store(2) - node.cooldownUntil.Store(time.Now().Add(time.Minute).UnixNano()) - } - for _, node := range gateway.anonymous.nodes { - node.failures.Store(2) - } - before := snapshotTestPools(gateway) - result := runDebugTest(t, manager, DebugKeySelection{Mode: "auto"}, model) - if after := snapshotTestPools(gateway); !reflect.DeepEqual(after, before) { - t.Fatalf("diagnostic mutated pools:\nbefore: %+v\nafter: %+v", before, after) - } - if probes.Load() != 0 { - t.Fatal("diagnostic triggered a proxy health probe") - } - if calls.Load() == 0 || result.Route.Attempts != int(calls.Load()) { - t.Fatalf("attempt trace = %+v, upstream calls = %d", result.Route, calls.Load()) - } - if result.OK != (outcome == "success") { - t.Fatalf("unexpected result: %+v", result) - } - }) - } - } -} - -func TestProductionFailuresStillUpdateKeyCooldown(t *testing.T) { - manager, gateway := newHandlerTestRuntime(t, handlerTestConfig(), func(r *http.Request) (*http.Response, error) { - if r.URL.Host == "cloudflare.com" { - return stubResponse(200, "ok"), nil - } - return stubResponse(401, `{"error":{"message":"invalid key"}}`), nil - }) - recorder := serveTestRequest(manager.Handler(), http.MethodPost, "/v1/chat/completions", - `{"model":"example-model","messages":[{"role":"user","content":"hello"}]}`) - node := gateway.zenNodes.nodes[0] - if recorder.Code != 401 || node.failures.Load() != 1 || node.cooldownUntil.Load() <= time.Now().UnixNano() { - t.Fatalf("production failure was not recorded: status=%d failures=%d", recorder.Code, node.failures.Load()) - } -} - -func TestSelectedDiagnosticClassifiesActualAttempt(t *testing.T) { - for _, test := range []struct { - name string - status int - err error - want string - }{ - {name: "connection failure", err: errors.New("connection failed"), want: "transport_error"}, - {name: "header timeout", err: context.DeadlineExceeded, want: "transport_error"}, - {name: "upstream error", status: 503, want: "upstream_error"}, - {name: "invalid key", status: 401, want: "rejected"}, - {name: "rate limit", status: 429, want: "rate_limited"}, - {name: "bad request", status: 422, want: "request_error"}, - {name: "success", status: 200, want: "usable"}, - } { - t.Run(test.name, func(t *testing.T) { - manager, gateway := newHandlerTestRuntime(t, handlerTestConfig(), func(_ *http.Request) (*http.Response, error) { - if test.err != nil { - return nil, test.err - } - return stubResponse(test.status, `{"choices":[{"message":{"content":"ok"}}]}`), nil - }) - result := runDebugTest(t, manager, DebugKeySelection{ - Mode: "selected", Tier: TierZen, ID: secretFingerprint(gateway.cfg.ZenKeys[0]), - }, "example-model") - if result.KeyTest != test.want || result.Route.Attempts != 1 || result.RequestID == "" { - t.Fatalf("diagnostic = %+v, want key_test=%s with one traced attempt", result, test.want) - } - assertPoolUntouched(t, gateway) - }) - } -} - -func TestAutomaticDiagnosticPreservesTierFallback(t *testing.T) { - cfg := handlerTestConfig() - cfg.Anonymous = true - cfg.GoKeys = []string{"go-handler-test-key"} - cfg.Prefer = TierGo - cfg.Proxies = []string{"http://first.invalid:8080", "http://second.invalid:8080"} - cfg.Models.Protocols = nil - var attempts []string - manager, gateway := newHandlerTestRuntime(t, cfg, func(r *http.Request) (*http.Response, error) { - switch { - case r.Header.Get("x-api-key") == anonymousZenKey: - attempts = append(attempts, "anonymous") - return stubResponse(429, `{"error":{"message":"anonymous limit"}}`), nil - case r.Header.Get("Authorization") == "Bearer "+cfg.GoKeys[0]: - attempts = append(attempts, "go") - if r.URL.Path != "/zen/go/v1/chat/completions" { - t.Fatalf("Go request used the wrong protocol: %s", r.URL.Path) - } - return stubResponse(503, `{"error":{"message":"unavailable"}}`), nil - default: - attempts = append(attempts, "zen") - if r.Header.Get("x-api-key") != cfg.ZenKeys[0] || r.URL.Path != "/zen/v1/messages" { - t.Fatalf("Zen request used the wrong credential or protocol: %s", r.URL.Path) - } - return stubResponse(200, `{"id":"msg_test","model":"example-free","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`), nil - } - }) - gateway.catalog.ReplaceWithCapabilities([]string{"example-free"}, []string{"example-free"}, - map[Tier]map[string]Protocol{ - TierZen: {"example-free": ProtocolAnthropic}, - TierGo: {"example-free": ProtocolChat}, - }, nil, nil) - before := snapshotTestPools(gateway) - result := runDebugTest(t, manager, DebugKeySelection{Mode: "auto"}, "example-free") - if want := []string{"anonymous", "anonymous", "go", "zen"}; !reflect.DeepEqual(attempts, want) { - t.Fatalf("fallback attempts = %v, want %v", attempts, want) - } - if !result.OK || result.Route.Tier != TierZen || result.Route.NativeProtocol != ProtocolAnthropic || result.Route.Anonymous || result.Route.Attempts != 4 { - t.Fatalf("incorrect final route: %+v", result) - } - if after := snapshotTestPools(gateway); !reflect.DeepEqual(after, before) { - t.Fatalf("fallback changed production state: before=%+v after=%+v", before, after) - } -} - -func TestSelectedDiagnosticDoesNotReplayStaleReasoning(t *testing.T) { - cfg := handlerTestConfig() - cfg.Models.Protocols["example-model"] = "responses" - var calls int - manager, gateway := newHandlerTestRuntime(t, cfg, func(_ *http.Request) (*http.Response, error) { - calls++ - return stubResponse(400, `{"error":{"message":"Referenced reasoning item rs_old was not found"}}`), nil - }) - admin := NewAdminServer(manager, manager.monitor, manager.hub, manager.logger) - body, err := json.Marshal(DebugInferenceRequest{ - Protocol: ProtocolResponses, - Key: DebugKeySelection{Mode: "selected", Tier: TierZen, ID: secretFingerprint(gateway.cfg.ZenKeys[0])}, - Request: map[string]any{ - "model": "example-model", - "previous_response_id": "resp_old", - "input": []any{map[string]any{"type": "reasoning", "id": "rs_old", "summary": []any{}}}, - }, - }) - if err != nil { - t.Fatal(err) - } - recorder := httptest.NewRecorder() - admin.handleDebugInference(recorder, httptest.NewRequest(http.MethodPost, "/api/debug/inference", strings.NewReader(string(body)))) - if recorder.Code != 200 || calls != 1 { - t.Fatalf("selected diagnostic replayed: calls=%d response=%s", calls, recorder.Body.String()) - } -} diff --git a/admin_test.go b/admin_test.go deleted file mode 100644 index dac62e5..0000000 --- a/admin_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestEmbeddedWebAssets(t *testing.T) { - manager, _ := newHandlerTestRuntime(t, handlerTestConfig(), nil) - admin := NewAdminServer(manager, manager.monitor, manager.hub, manager.logger) - for _, test := range []struct { - path string - contentType string - contains string - }{ - {path: "/", contentType: "text/html", contains: ``}, - {path: "/app.js", contentType: "javascript", contains: "async function boot()"}, - {path: "/styles.css", contentType: "text/css", contains: "#account-form"}, - } { - t.Run(test.path, func(t *testing.T) { - recorder := httptest.NewRecorder() - admin.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil)) - if recorder.Code != 200 || !strings.Contains(recorder.Header().Get("Content-Type"), test.contentType) || !strings.Contains(recorder.Body.String(), test.contains) { - t.Fatalf("asset %s: status=%d content-type=%s", test.path, recorder.Code, recorder.Header().Get("Content-Type")) - } - if policy := recorder.Header().Get("Content-Security-Policy"); strings.Contains(policy, "unsafe-inline") || !strings.Contains(policy, "script-src 'self'") { - t.Fatalf("unexpected asset policy: %s", policy) - } - }) - } -} - -func TestManagementEndpointsRequireSession(t *testing.T) { - manager, _ := newHandlerTestRuntime(t, handlerTestConfig(), nil) - admin := NewAdminServer(manager, manager.monitor, manager.hub, manager.logger) - for _, path := range []string{"/api/config", "/api/monitor", "/api/debug/models", "/api/logs", "/api/logs/stream"} { - recorder := httptest.NewRecorder() - admin.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil)) - if recorder.Code != http.StatusUnauthorized { - t.Errorf("%s: unauthenticated status = %d", path, recorder.Code) - } - } -} diff --git a/main.go b/cmd/opencode2api/main.go similarity index 71% rename from main.go rename to cmd/opencode2api/main.go index 2dd341c..0938863 100644 --- a/main.go +++ b/cmd/opencode2api/main.go @@ -1,3 +1,4 @@ +// Command opencode2api starts the API gateway and its management interface. package main import ( @@ -9,17 +10,25 @@ import ( "os/signal" "syscall" "time" + + adminui "opencode2api/internal/admin" + "opencode2api/internal/buildinfo" + "opencode2api/internal/config" + "opencode2api/internal/gateway" + "opencode2api/internal/telemetry" ) +// version remains the linker injection point used by release builds. var version = "dev" func main() { + buildinfo.Version = version configPath := flag.String("config", "config.json", "path to config.json") listen := flag.String("listen", "", "override the configured API listen address") webListen := flag.String("web-listen", "", "override the configured WebUI listen address") flag.Parse() - cfg, err := LoadConfig(*configPath) + cfg, err := config.Load(*configPath) if err != nil { slog.Error("configuration error", "error", err) os.Exit(1) @@ -34,13 +43,13 @@ func main() { ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer cancel() level := new(slog.LevelVar) - setLogLevel(level, cfg.Logging.Level) - hub := NewLogHub(cfg.Logging.RingSize) - redactor := NewSecretRedactor() + telemetry.SetLogLevel(level, cfg.Logging.Level) + hub := telemetry.NewLogHub(cfg.Logging.RingSize) + redactor := config.NewSecretRedactor() redactor.Replace(cfg) - logger := NewStructuredLogger(level, hub, redactor) - monitor := NewMonitor() - manager, err := NewRuntimeManager(ctx, *configPath, cfg, logger, monitor, hub, redactor, level) + logger := telemetry.NewStructuredLogger(level, hub, redactor) + monitor := telemetry.NewMonitor() + manager, err := gateway.NewRuntimeManager(ctx, *configPath, cfg, logger, monitor, hub, redactor, level) if err != nil { logger.Error("failed to initialize runtime", "component", "runtime", "event", "runtime_initialization_failed", "error", err) os.Exit(1) @@ -54,7 +63,7 @@ func main() { go serveHTTP(cancel, logger, apiServer, "api") if cfg.WebUI.Enabled { - admin := NewAdminServer(manager, monitor, hub, logger) + admin := adminui.New(manager, monitor, hub, logger) webServer := &http.Server{ Addr: cfg.WebUI.Listen, Handler: admin.Handler(), ReadHeaderTimeout: 15 * time.Second, IdleTimeout: 120 * time.Second, } @@ -73,7 +82,7 @@ func main() { } func serveHTTP(cancel context.CancelFunc, logger *slog.Logger, server *http.Server, component string) { - logger.Info("server listening", "component", component, "event", "server_started", "address", server.Addr, "version", version) + logger.Info("server listening", "component", component, "event", "server_started", "address", server.Addr, "version", buildinfo.Version) if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { logger.Error("server stopped unexpectedly", "component", component, "event", "server_failed", "address", server.Addr, "error", err) cancel() diff --git a/config_test.go b/config_test.go deleted file mode 100644 index 2706ef7..0000000 --- a/config_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package main - -import ( - "testing" - "time" -) - -// The knob must be inert by default: existing configs keep using the -// request-level retry timeout. -func TestAttemptTimeoutDefaultsToRequestTimeout(t *testing.T) { - request := 45 * time.Second - if got := (PerformanceConfig{}).AttemptTimeout(request); got != request { - t.Fatalf("AttemptTimeout = %v, want %v", got, request) - } - if got := (PerformanceConfig{AttemptTimeoutSeconds: -1}).AttemptTimeout(request); got != request { - t.Fatalf("negative value = %v, want %v", got, request) - } -} - -func TestAttemptTimeoutIsBoundedByRequestTimeout(t *testing.T) { - request := 45 * time.Second - if got := (PerformanceConfig{AttemptTimeoutSeconds: 10}).AttemptTimeout(request); got != 10*time.Second { - t.Fatalf("AttemptTimeout = %v, want 10s", got) - } - if got := (PerformanceConfig{AttemptTimeoutSeconds: 600}).AttemptTimeout(request); got != request { - t.Fatalf("AttemptTimeout = %v, want the request timeout %v", got, request) - } -} - -func TestNormalizeConfigRejectsNegativeAttemptTimeout(t *testing.T) { - cfg := testConfig() - cfg.Listen = "127.0.0.1:8080" - cfg.ServerKeys = []string{"local-key"} - cfg.ZenKeys = []string{"sk-zen"} - cfg.Performance.AttemptTimeoutSeconds = -5 - if _, err := NormalizeConfig("config.json", cfg); err == nil { - t.Fatal("negative attempt_timeout_seconds must be rejected") - } -} - -// Adding a field to the logging section must not make the management API reject -// configs that carry the new key. -func TestNormalizeConfigAcceptsBodyDumpFlag(t *testing.T) { - cfg := testConfig() - cfg.Listen = "127.0.0.1:8080" - cfg.ServerKeys = []string{"local-key"} - cfg.ZenKeys = []string{"sk-zen"} - cfg.Logging.DumpRequestBodies = true - normalized, err := NormalizeConfig("config.json", cfg) - if err != nil { - t.Fatalf("NormalizeConfig: %v", err) - } - if !normalized.Logging.DumpRequestBodies { - t.Fatal("dump_request_bodies was dropped during normalization") - } -} diff --git a/convert_test.go b/convert_test.go deleted file mode 100644 index 12aff1c..0000000 --- a/convert_test.go +++ /dev/null @@ -1,201 +0,0 @@ -package main - -import ( - "encoding/json" - "testing" -) - -func mustConvert(t *testing.T, from, to Protocol, input map[string]any) map[string]any { - t.Helper() - output, err := convertRequest(from, to, input) - if err != nil { - t.Fatalf("convertRequest(%s -> %s): %v", from, to, err) - } - return output -} - -// firstContentBlock returns the leading content block of an Anthropic-style -// request body built by the tests above. -func firstContentBlock(t *testing.T, input map[string]any) map[string]any { - t.Helper() - messages := sliceAt(input, "messages") - if len(messages) == 0 { - t.Fatal("converted request has no messages") - } - message, ok := messages[0].(map[string]any) - if !ok { - t.Fatalf("messages[0] is %T, want object", messages[0]) - } - content := sliceAt(message, "content") - if len(content) == 0 { - t.Fatal("messages[0] has no content blocks") - } - block, ok := content[0].(map[string]any) - if !ok { - t.Fatalf("messages[0].content[0] is %T, want object", content[0]) - } - return block -} - -// A client that asks for JSON mode must not silently receive plain text. The -// sampling and response-shape knobs have to survive the bridge. -func TestChatToResponsesKeepsSamplingKnobs(t *testing.T) { - output := mustConvert(t, ProtocolChat, ProtocolResponses, map[string]any{ - "model": "example-model", - "messages": []any{map[string]any{"role": "user", "content": "hi"}}, - "response_format": map[string]any{"type": "json_object"}, - "parallel_tool_calls": false, - "temperature": 0.2, - }) - - format := mapAt(output, "text", "format") - if stringAt(format, "type") != "json_object" { - t.Fatalf("text.format.type = %q, want json_object (output: %v)", stringAt(format, "type"), output) - } - if value, exists := output["parallel_tool_calls"]; !exists || value != false { - t.Fatalf("parallel_tool_calls = %v (present=%v), want explicit false", value, exists) - } -} - -func TestResponsesToChatFlattensJSONSchema(t *testing.T) { - output := mustConvert(t, ProtocolResponses, ProtocolChat, map[string]any{ - "model": "example-model", - "input": "hi", - "text": map[string]any{"format": map[string]any{ - "type": "json_schema", - "name": "answer", - "strict": true, - "schema": map[string]any{"type": "object"}, - }}, - }) - - schema := mapAt(output, "response_format", "json_schema") - if stringAt(schema, "name") != "answer" { - t.Fatalf("response_format.json_schema.name = %q, want answer (output: %v)", stringAt(schema, "name"), output) - } - if stringAt(schema, "schema", "type") != "object" { - t.Fatalf("response_format.json_schema.schema.type = %q, want object", stringAt(schema, "schema", "type")) - } -} - -func TestChatToAnthropicOmitsUnmappableKnobs(t *testing.T) { - output := mustConvert(t, ProtocolChat, ProtocolAnthropic, map[string]any{ - "model": "example-model", - "messages": []any{map[string]any{"role": "user", "content": "hi"}}, - "response_format": map[string]any{"type": "json_object"}, - "seed": 7, - }) - - // Anthropic has no native shape for these; they must be omitted rather than - // forwarded as unknown fields. - for _, key := range []string{"response_format", "seed", "frequency_penalty", "presence_penalty", "parallel_tool_calls"} { - if _, exists := output[key]; exists { - t.Fatalf("Anthropic request unexpectedly carries %q: %v", key, output) - } - } -} - -// Chat history has no server-side reasoning id. Synthesizing one makes the -// upstream reject the request as a stale reference, which used to force every -// tool-bearing turn through the strip-and-retry path. -func TestChatReasoningReplayOmitsSyntheticReference(t *testing.T) { - output := mustConvert(t, ProtocolChat, ProtocolResponses, map[string]any{ - "model": "example-model", - "messages": []any{ - map[string]any{"role": "user", "content": "run it"}, - map[string]any{ - "role": "assistant", - "content": "", - "reasoning_content": "I should call the tool", - "tool_calls": []any{map[string]any{ - "id": "call_1", - "type": "function", - "function": map[string]any{"name": "lookup", "arguments": `{"q":"x"}`}, - }}, - }, - map[string]any{"role": "tool", "tool_call_id": "call_1", "content": "result"}, - }, - }) - - var sawFunctionCall bool - for _, raw := range sliceAt(output, "input") { - item, _ := raw.(map[string]any) - switch stringAt(item, "type") { - case "reasoning": - t.Fatalf("replayed reasoning item has no upstream id and must be omitted: %v", item) - case "function_call": - sawFunctionCall = true - } - } - if !sawFunctionCall { - t.Fatalf("function_call item missing from converted input: %v", output["input"]) - } -} - -// A reasoning block the upstream actually issued must still be replayed with -// its original id. -func TestResponsesReasoningReplayKeepsServerID(t *testing.T) { - output := mustConvert(t, ProtocolResponses, ProtocolChat, map[string]any{ - "model": "example-model", - "input": []any{ - map[string]any{"type": "message", "role": "user", "content": "hi"}, - }, - }) - if _, err := json.Marshal(output); err != nil { - t.Fatalf("converted request is not encodable: %v", err) - } - - block := bridgeBlock{Kind: "reasoning", ID: "rs_abc", Text: "because"} - encoded, ok := encodeResponsesReasoningInput(block) - if !ok { - t.Fatal("reasoning block with a server id must be replayed") - } - if stringAt(encoded, "id") != "rs_abc" { - t.Fatalf("reasoning id = %q, want rs_abc", stringAt(encoded, "id")) - } - - if _, ok := encodeResponsesReasoningInput(bridgeBlock{Kind: "reasoning", Text: "plain"}); ok { - t.Fatal("reasoning block without an id or encrypted content must be skipped") - } -} - -// Deleting thinking signatures or rewriting redacted_thinking is a repair for -// specific vendors. Applying it to a native Anthropic endpoint discards state -// that endpoint re-validates and shifts the cached prompt prefix. -func TestAnthropicThinkingRepairIsVendorGated(t *testing.T) { - newInput := func() map[string]any { - return map[string]any{ - "messages": []any{map[string]any{ - "role": "assistant", - "content": []any{ - map[string]any{"type": "thinking", "thinking": "", "signature": "sig-real"}, - map[string]any{"type": "tool_use", "id": "toolu_1", "name": "lookup", "input": map[string]any{}}, - }, - }}, - } - } - - native := newInput() - if normalizeToolReasoningHistory(ProtocolAnthropic, "claude-sonnet-5", "https://opencode.ai/zen", native) { - t.Fatal("native Anthropic model must not have its thinking history rewritten") - } - thinking := firstContentBlock(t, native) - if stringAt(thinking, "signature") != "sig-real" { - t.Fatalf("signature was dropped for a native Anthropic model: %v", thinking) - } - if stringAt(thinking, "thinking") != "" { - t.Fatalf("empty thinking text was overwritten for a native Anthropic model: %v", thinking) - } - - vendor := newInput() - if !normalizeToolReasoningHistory(ProtocolAnthropic, "deepseek-chat", "https://opencode.ai/zen", vendor) { - t.Fatal("vendor model should still receive the thinking repair") - } - vendorThinking := firstContentBlock(t, vendor) - if _, exists := vendorThinking["signature"]; exists { - t.Fatalf("vendor repair must remove the signature: %v", vendorThinking) - } - if stringAt(vendorThinking, "thinking") != toolReasoningPlaceholder { - t.Fatalf("vendor repair must fill empty thinking text: %v", vendorThinking) - } -} diff --git a/gateway_health_test.go b/gateway_health_test.go deleted file mode 100644 index 3d62af2..0000000 --- a/gateway_health_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package main - -import ( - "encoding/json" - "net/http" - "reflect" - "testing" - "time" -) - -func TestHealthAndModelsUseTheSameRoutes(t *testing.T) { - for _, test := range []struct { - name string - anonymous bool - zenKeys bool - zenModels []string - goModels []string - stale bool - wantModels []string - wantStatus int - }{ - {name: "anonymous paid only", anonymous: true, zenModels: []string{"example-model"}, wantStatus: 503}, - {name: "anonymous free", anonymous: true, zenModels: []string{"example-model", "example-free"}, wantModels: []string{"example-free"}, wantStatus: 200}, - {name: "configured key", zenKeys: true, zenModels: []string{"example-model"}, wantModels: []string{"example-model"}, wantStatus: 200}, - {name: "cached models for a removed tier", zenKeys: true, goModels: []string{"example-model"}, wantStatus: 503}, - {name: "stale usable catalog", zenKeys: true, zenModels: []string{"example-model"}, stale: true, wantModels: []string{"example-model"}, wantStatus: 200}, - } { - t.Run(test.name, func(t *testing.T) { - cfg := handlerTestConfig() - cfg.Anonymous = test.anonymous - if !test.zenKeys { - cfg.ZenKeys = nil - } - manager, gateway := newHandlerTestRuntime(t, cfg, func(_ *http.Request) (*http.Response, error) { - t.Fatal("discovery and health must not make upstream requests") - return nil, nil - }) - gateway.catalog.Replace([]string{}, []string{}) - gateway.catalog.Replace(test.zenModels, test.goModels) - if test.stale { - gateway.catalog.updatedAt = time.Now().Add(-time.Hour) - } - modelsRecorder := serveTestRequest(manager.Handler(), http.MethodGet, "/v1/models", "") - var models struct { - Data []struct { - ID string `json:"id"` - } `json:"data"` - } - if err := json.Unmarshal(modelsRecorder.Body.Bytes(), &models); err != nil { - t.Fatal(err) - } - var ids []string - for _, model := range models.Data { - ids = append(ids, model.ID) - } - if !reflect.DeepEqual(ids, test.wantModels) { - t.Fatalf("models = %v, want %v", ids, test.wantModels) - } - before := manager.monitor.Snapshot().Lifetime.Total - healthRecorder := serveTestRequest(manager.Handler(), http.MethodGet, "/healthz", "") - var health healthResponse - if err := json.Unmarshal(healthRecorder.Body.Bytes(), &health); err != nil { - t.Fatal(err) - } - if healthRecorder.Code != test.wantStatus || health.Ready != (test.wantStatus == 200) || health.Models.Exposed != len(ids) { - t.Fatalf("health status=%d body=%s, discovered=%v", healthRecorder.Code, healthRecorder.Body.String(), ids) - } - if health.Models.Stale != test.stale || manager.Resources().Models.Exposed != len(ids) { - t.Fatalf("resource snapshot disagrees with discovery: %+v", health) - } - if manager.monitor.Snapshot().Lifetime.Total != before { - t.Fatal("health check changed request metrics") - } - }) - } -} diff --git a/gateway_stream_test.go b/gateway_stream_test.go deleted file mode 100644 index bc24299..0000000 --- a/gateway_stream_test.go +++ /dev/null @@ -1,181 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "errors" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func streamTestPayload(protocol Protocol) string { - payload := map[string]any{"model": "example-model", "stream": true} - if protocol == ProtocolResponses { - payload["input"] = "hello" - } else { - payload["messages"] = []any{map[string]any{"role": "user", "content": "hello"}} - payload["max_tokens"] = 16 - } - body, _ := json.Marshal(payload) - return string(body) -} - -func streamTestFixture(protocol Protocol, outcome string) string { - if outcome == "malformed" { - return "data: {invalid JSON}\n\n" - } - if outcome == "error" { - switch protocol { - case ProtocolAnthropic: - return "event: error\ndata: " + `{"type":"error","error":{"type":"overloaded_error","message":"mock stream failure"}}` + "\n\n" - case ProtocolResponses: - return "event: response.failed\ndata: " + `{"type":"response.failed","response":{"id":"resp_test","status":"failed","error":{"code":"server_error","message":"mock stream failure"}}}` + "\n\n" - default: - return "data: " + `{"error":{"type":"server_error","message":"mock stream failure"}}` + "\n\ndata: [DONE]\n\n" - } - } - var prefix, suffix string - switch protocol { - case ProtocolAnthropic: - prefix = "event: message_start\ndata: " + `{"type":"message_start","message":{"id":"msg_test","model":"example-model","role":"assistant","content":[],"usage":{"input_tokens":3,"output_tokens":0}}}` + "\n\n" + - "event: content_block_start\ndata: " + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}` + "\n\n" + - "event: content_block_delta\ndata: " + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}` + "\n\n" - suffix = "event: content_block_stop\ndata: " + `{"type":"content_block_stop","index":0}` + "\n\n" + - "event: message_delta\ndata: " + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}` + "\n\n" + - "event: message_stop\ndata: " + `{"type":"message_stop"}` + "\n\n" - case ProtocolResponses: - prefix = "event: response.created\ndata: " + `{"type":"response.created","response":{"id":"resp_test","model":"example-model","status":"in_progress"}}` + "\n\n" + - "event: response.output_text.delta\ndata: " + `{"type":"response.output_text.delta","item_id":"msg_test","output_index":0,"content_index":0,"delta":"hello"}` + "\n\n" - suffix = "event: response.completed\ndata: " + `{"type":"response.completed","response":{"id":"resp_test","model":"example-model","status":"completed","output":[{"type":"message","id":"msg_test","role":"assistant","content":[{"type":"output_text","text":"hello"}]}],"usage":{"input_tokens":3,"output_tokens":2,"total_tokens":5}}}` + "\n\n" - default: - prefix = "data: " + `{"id":"chatcmpl_test","model":"example-model","choices":[{"index":0,"delta":{"role":"assistant","content":"hello"}}]}` + "\n\n" - suffix = "data: " + `{"id":"chatcmpl_test","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}` + "\n\ndata: [DONE]\n\n" - } - if outcome == "truncated" { - return prefix - } - return prefix + suffix -} - -func TestStreamingResultsAcrossProtocols(t *testing.T) { - protocols := []Protocol{ProtocolChat, ProtocolResponses, ProtocolAnthropic} - for _, upstream := range protocols { - for _, client := range protocols { - for _, outcome := range []string{"success", "error", "malformed", "truncated"} { - t.Run(string(upstream)+"/"+string(client)+"/"+outcome, func(t *testing.T) { - cfg := handlerTestConfig() - cfg.Models.Protocols["example-model"] = string(upstream) - manager, _ := newHandlerTestRuntime(t, cfg, func(r *http.Request) (*http.Response, error) { - if want := "/zen" + protocolPath(upstream); r.URL.Path != want { - t.Fatalf("upstream path = %q, want %q", r.URL.Path, want) - } - response := stubResponse(200, streamTestFixture(upstream, outcome)) - response.Header.Set("Content-Type", "text/event-stream") - return response, nil - }) - recorder := serveTestRequest(manager.Handler(), http.MethodPost, protocolPath(client), streamTestPayload(client)) - if recorder.Code != 200 { - t.Fatalf("HTTP status = %d: %s", recorder.Code, recorder.Body.String()) - } - observer := newStreamUsageObserver(client) - _, _ = observer.Write(recorder.Body.Bytes()) - observer.Finish() - snapshot := manager.monitor.Snapshot() - if snapshot.Lifetime.Total != 1 || snapshot.Active != 0 || snapshot.ActiveStreams != 0 || len(snapshot.Upstream.Requests) != 1 { - t.Fatalf("unexpected completed request metrics: %+v", snapshot) - } - request := snapshot.Upstream.Requests[0] - if request.Status != 200 || request.RequestID == "" { - t.Fatalf("HTTP status or request trace lost: %+v", request) - } - if outcome == "success" { - if !observer.NormalTermination() || observer.ErrorTermination() || observer.ParseError() != nil { - t.Fatalf("invalid successful client stream: %s", recorder.Body.String()) - } - if snapshot.Lifetime.Success != 1 || snapshot.Lifetime.Errors != 0 || !request.Success || request.Outcome != "success" { - t.Fatalf("normal stream misclassified: %+v, %+v", snapshot.Lifetime, request) - } - tokens := snapshot.Usage.Lifetime.Tokens - if tokens.Input != 3 || tokens.Output != 2 || tokens.Total != 5 { - t.Fatalf("usage was lost in the stream bridge: %+v", tokens) - } - } else { - if !observer.ErrorTermination() { - t.Fatalf("client did not receive a terminal error: %s", recorder.Body.String()) - } - if snapshot.Lifetime.Success != 0 || snapshot.Lifetime.Errors != 1 || request.Success || request.Outcome != "stream_error" { - t.Fatalf("failed stream misclassified: %+v, %+v", snapshot.Lifetime, request) - } - if snapshot.Window.Errors != 1 { - t.Fatalf("rolling metrics missed the error: %+v", snapshot.Window) - } - } - }) - } - } - } -} - -type terminalTestReader struct { - err error - cancel context.CancelFunc -} - -func (reader terminalTestReader) Read([]byte) (int, error) { - if reader.cancel != nil { - reader.cancel() - } - return 0, reader.err -} - -func TestStreamReadFailureAndClientCancellation(t *testing.T) { - for _, client := range []Protocol{ProtocolChat, ProtocolResponses, ProtocolAnthropic} { - for _, canceled := range []bool{false, true} { - name := string(client) + "/read_error" - if canceled { - name = string(client) + "/canceled" - } - t.Run(name, func(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - terminal := terminalTestReader{err: io.ErrUnexpectedEOF} - if canceled { - terminal.err, terminal.cancel = context.Canceled, cancel - } - manager, _ := newHandlerTestRuntime(t, handlerTestConfig(), func(_ *http.Request) (*http.Response, error) { - response := stubResponse(200, "") - response.Body = io.NopCloser(io.MultiReader(strings.NewReader(streamTestFixture(ProtocolChat, "truncated")), terminal)) - return response, nil - }) - request := httptest.NewRequest(http.MethodPost, protocolPath(client), strings.NewReader(streamTestPayload(client))).WithContext(ctx) - request.Header.Set("Authorization", "Bearer "+testServerKey) - recorder := httptest.NewRecorder() - manager.Handler().ServeHTTP(recorder, request) - snapshot := manager.monitor.Snapshot() - wantOutcome := "stream_error" - if canceled { - wantOutcome = "client_canceled" - if strings.Contains(recorder.Body.String(), "upstream_error") { - t.Fatal("client cancellation emitted a synthetic upstream error") - } - } - if recorder.Code != 200 || snapshot.Lifetime.Errors != 1 || snapshot.Lifetime.Success != 0 || snapshot.Upstream.Requests[0].Outcome != wantOutcome { - t.Fatalf("unexpected termination: %+v, %+v", snapshot.Lifetime, snapshot.Upstream.Requests) - } - }) - } - } -} - -func TestStreamErrorsAreReturnedAfterDelivery(t *testing.T) { - for _, target := range []Protocol{ProtocolChat, ProtocolResponses, ProtocolAnthropic} { - recorder := httptest.NewRecorder() - _, _, err := transcodeStreamWithUsage(recorder, strings.NewReader(streamTestFixture(ProtocolChat, "error")), ProtocolChat, target, "example-model") - if !errors.Is(err, errStreamUpstreamFailure) { - t.Fatalf("%s: terminal error = %v", target, err) - } - } -} diff --git a/gateway_test.go b/gateway_test.go deleted file mode 100644 index 705461a..0000000 --- a/gateway_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package main - -import ( - "bytes" - "context" - "log/slog" - "testing" - "time" -) - -func testConfig() Config { - return Config{ - Upstream: UpstreamConfig{Zen: "https://example.invalid/zen", Go: "https://example.invalid/zen/go"}, - Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 30}, - Performance: PerformanceConfig{ - MaxIdleConns: 16, MaxIdleConnsPerHost: 8, MaxConnsPerHost: 0, - IdleConnTimeoutSeconds: 30, ConnectTimeoutSeconds: 1, FailureCooldownSeconds: 15, - }, - Logging: LoggingConfig{Level: "error", RingSize: 2000}, - Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}}, - Prefer: TierGo, - } -} - -func newTestGateway(t *testing.T, sink *bytes.Buffer) *Gateway { - t.Helper() - cfg := testConfig() - transports, err := newTransportPool([]string{"direct"}, cfg.Performance, time.Second) - if err != nil { - t.Fatalf("newTransportPool: %v", err) - } - cooldown := time.Duration(cfg.Performance.FailureCooldownSeconds) * time.Second - zenNodes, err := newNodePool([]string{"sk-zen-test"}, transports, cooldown) - if err != nil { - t.Fatalf("newNodePool: %v", err) - } - goNodes, err := newNodePool([]string{"sk-go-test"}, transports, cooldown) - if err != nil { - t.Fatalf("newNodePool: %v", err) - } - var handler slog.Handler = slog.NewTextHandler(sink, &slog.HandlerOptions{Level: slog.LevelDebug}) - return &Gateway{ - cfg: cfg, logger: slog.New(handler), transports: transports, zenNodes: zenNodes, goNodes: goNodes, - anonymous: newAnonymousPool(true, transports, cooldown), - } -} - -func assertPoolUntouched(t *testing.T, g *Gateway) { - t.Helper() - for _, pool := range []*nodePool{g.zenNodes, g.goNodes} { - for _, node := range pool.nodes { - if failures := node.failures.Load(); failures != 0 { - t.Fatalf("key %s recorded %d failures", node.key, failures) - } - if until := node.cooldownUntil.Load(); until != 0 { - t.Fatalf("key %s was cooled until %d", node.key, until) - } - } - } - for _, proxy := range g.transports.items { - if !proxy.healthy.Load() { - t.Fatal("healthy proxy was evicted") - } - } -} - -// An exhausted request budget must not be spent rotating keys: every attempt -// would fail instantly, cool a healthy key and evict a healthy proxy. -func TestExpiredContextDoesNotCoolKeysOrEvictProxies(t *testing.T) { - g := newTestGateway(t, &bytes.Buffer{}) - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - route := modelRoute{ID: "example-model", Tier: TierZen, Protocol: ProtocolChat, KeyTiers: []Tier{TierZen}} - bodies := map[Tier][]byte{TierZen: []byte(`{"model":"example-model"}`)} - ids := requestIDs{Session: "ses_test", Request: "req_test", Project: "prj_test"} - - resp, err, attempts := g.doKeyUpstream(ctx, route, bodies, ids, 0) - if resp != nil { - t.Fatalf("response = %v, want nil", resp) - } - if err == nil { - t.Fatal("expected an error from the exhausted context") - } - if attempts != 0 { - t.Fatalf("attempts = %d, want 0", attempts) - } - assertPoolUntouched(t, g) -} - -// The same guard applies to the anonymous phase, and the authenticated fallback -// must not run once the budget is gone. -func TestExpiredContextSkipsAnonymousScanAndKeyFallback(t *testing.T) { - g := newTestGateway(t, &bytes.Buffer{}) - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - route := modelRoute{ - ID: "example-model", Tier: TierZen, Protocol: ProtocolChat, - Anonymous: true, KeyTiers: []Tier{TierZen, TierGo}, - } - bodies := map[Tier][]byte{ - TierZen: []byte(`{"model":"example-model"}`), - TierGo: []byte(`{"model":"example-model"}`), - } - ids := requestIDs{Session: "ses_test", Request: "req_test", Project: "prj_test"} - - resp, _, attempts, err := g.doUpstreamTiers(ctx, route, bodies, ids, 0) - if resp != nil { - t.Fatalf("response = %v, want nil", resp) - } - if err == nil { - t.Fatal("expected an error from the exhausted context") - } - if attempts != 0 { - t.Fatalf("attempts = %d, want 0", attempts) - } - assertPoolUntouched(t, g) - for _, node := range g.anonymous.nodes { - if until := node.cooldownUntil.Load(); until != 0 { - t.Fatalf("anonymous node was cooled until %d", until) - } - } -} - -// The body dump is off unless configured, and when enabled must carry the -// reference ids a retry investigation needs. -func TestDumpOutboundBodiesIsOptIn(t *testing.T) { - var sink bytes.Buffer - g := newTestGateway(t, &sink) - route := modelRoute{ID: "example-model", Tier: TierZen, Protocol: ProtocolResponses} - bodies := map[Tier][]byte{TierZen: []byte(`{"model":"example-model","previous_response_id":"resp_1"}`)} - ids := requestIDs{Request: "req_test"} - - g.dumpOutboundBodies(route, bodies, ids, 0) - if sink.Len() != 0 { - t.Fatalf("dump emitted while disabled: %s", sink.String()) - } - - g.cfg.Logging.DumpRequestBodies = true - g.dumpOutboundBodies(route, bodies, ids, 1) - dumped := sink.String() - for _, want := range []string{"upstream_request_body", "previous_response_id", "phase=retry"} { - if !bytes.Contains([]byte(dumped), []byte(want)) { - t.Fatalf("dump is missing %q: %s", want, dumped) - } - } -} diff --git a/admin_auth.go b/internal/admin/auth.go similarity index 84% rename from admin_auth.go rename to internal/admin/auth.go index 560775c..cf21b2b 100644 --- a/admin_auth.go +++ b/internal/admin/auth.go @@ -1,4 +1,4 @@ -package main +package admin import ( "context" @@ -12,6 +12,9 @@ import ( "net/url" "strings" "time" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" ) const adminCookieName = "opencode2api_session" @@ -28,7 +31,7 @@ type loginWindow struct { Count int } -func (a *AdminServer) handleLogin(w http.ResponseWriter, r *http.Request) { +func (a *Server) handleLogin(w http.ResponseWriter, r *http.Request) { client := clientIP(r) if !a.allowLogin(client) { writeAdminError(w, http.StatusTooManyRequests, "rate_limited", "too many login attempts; try again later") @@ -44,7 +47,7 @@ func (a *AdminServer) handleLogin(w http.ResponseWriter, r *http.Request) { } cfg := a.manager.Config() usernameMatch := len(input.Username) == len(cfg.WebUI.Username) && subtle.ConstantTimeCompare([]byte(input.Username), []byte(cfg.WebUI.Username)) == 1 - passwordMatch := verifyPassword(cfg.WebUI.PasswordHash, input.Password) + passwordMatch := config.VerifyPassword(cfg.WebUI.PasswordHash, input.Password) if !usernameMatch || !passwordMatch { a.recordLoginFailure(client) a.logger.Warn("admin login failed", "component", "auth", "event", "login_failed", "client_ip", client) @@ -68,21 +71,21 @@ func (a *AdminServer) handleLogin(w http.ResponseWriter, r *http.Request) { if len(a.sessions) >= 2048 { a.removeEarliestSessionLocked() } - a.sessions[tokenDigest(token)] = adminSession{Username: cfg.WebUI.Username, AuthVersion: secretFingerprint(cfg.WebUI.PasswordHash), CSRF: csrf, Expires: expires} + a.sessions[tokenDigest(token)] = adminSession{Username: cfg.WebUI.Username, AuthVersion: config.Fingerprint(cfg.WebUI.PasswordHash), CSRF: csrf, Expires: expires} a.mu.Unlock() http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: token, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, Expires: expires, MaxAge: int(time.Until(expires).Seconds()), Secure: requestIsSecure(r)}) w.Header().Set("Cache-Control", "no-store") a.logger.Info("admin login succeeded", "component", "auth", "event", "login_succeeded", "client_ip", client) - writeJSON(w, http.StatusOK, map[string]any{"username": cfg.WebUI.Username, "csrf_token": csrf, "expires_at": expires.UTC()}) + httpx.WriteJSON(w, http.StatusOK, map[string]any{"username": cfg.WebUI.Username, "csrf_token": csrf, "expires_at": expires.UTC()}) } -func (a *AdminServer) handleSession(w http.ResponseWriter, r *http.Request) { +func (a *Server) handleSession(w http.ResponseWriter, r *http.Request) { session, _ := sessionFromContext(r) w.Header().Set("Cache-Control", "no-store") - writeJSON(w, http.StatusOK, map[string]any{"authenticated": true, "username": session.Username, "csrf_token": session.CSRF, "expires_at": session.Expires.UTC()}) + httpx.WriteJSON(w, http.StatusOK, map[string]any{"authenticated": true, "username": session.Username, "csrf_token": session.CSRF, "expires_at": session.Expires.UTC()}) } -func (a *AdminServer) handleLogout(w http.ResponseWriter, r *http.Request) { +func (a *Server) handleLogout(w http.ResponseWriter, r *http.Request) { cookie, _ := r.Cookie(adminCookieName) if cookie != nil { a.mu.Lock() @@ -95,7 +98,7 @@ func (a *AdminServer) handleLogout(w http.ResponseWriter, r *http.Request) { type sessionContextKey struct{} -func (a *AdminServer) authenticate(next http.Handler) http.Handler { +func (a *Server) authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie(adminCookieName) if err != nil || cookie.Value == "" { @@ -115,7 +118,7 @@ func (a *AdminServer) authenticate(next http.Handler) http.Handler { return } cfg := a.manager.Config() - if session.Username != cfg.WebUI.Username || session.AuthVersion != secretFingerprint(cfg.WebUI.PasswordHash) { + if session.Username != cfg.WebUI.Username || session.AuthVersion != config.Fingerprint(cfg.WebUI.PasswordHash) { writeAdminError(w, http.StatusUnauthorized, "authentication_required", "session is no longer valid") return } @@ -129,7 +132,7 @@ func sessionFromContext(r *http.Request) (adminSession, bool) { return session, ok } -func (a *AdminServer) csrf(next http.Handler) http.Handler { +func (a *Server) csrf(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { session, ok := sessionFromContext(r) if !ok || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-CSRF-Token")), []byte(session.CSRF)) != 1 { @@ -151,7 +154,7 @@ func (a *AdminServer) csrf(next http.Handler) http.Handler { }) } -func (a *AdminServer) handleAccount(w http.ResponseWriter, r *http.Request) { +func (a *Server) handleAccount(w http.ResponseWriter, r *http.Request) { var input struct { CurrentPassword string `json:"current_password"` Username string `json:"username"` @@ -162,7 +165,7 @@ func (a *AdminServer) handleAccount(w http.ResponseWriter, r *http.Request) { return } cfg := a.manager.Config() - if !verifyPassword(cfg.WebUI.PasswordHash, input.CurrentPassword) { + if !config.VerifyPassword(cfg.WebUI.PasswordHash, input.CurrentPassword) { writeAdminError(w, http.StatusForbidden, "verification_failed", "current password is incorrect") return } @@ -181,10 +184,10 @@ func (a *AdminServer) handleAccount(w http.ResponseWriter, r *http.Request) { a.mu.Unlock() http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1, Secure: requestIsSecure(r)}) a.logger.Info("admin account updated", "component", "auth", "event", "account_updated", "client_ip", clientIP(r)) - writeJSON(w, http.StatusOK, map[string]any{"updated": true, "reauthenticate": true}) + httpx.WriteJSON(w, http.StatusOK, map[string]any{"updated": true, "reauthenticate": true}) } -func (a *AdminServer) allowLogin(client string) bool { +func (a *Server) allowLogin(client string) bool { a.mu.Lock() defer a.mu.Unlock() now := time.Now() @@ -205,7 +208,7 @@ func (a *AdminServer) allowLogin(client string) bool { return window.Count < 5 } -func (a *AdminServer) recordLoginFailure(client string) { +func (a *Server) recordLoginFailure(client string) { a.mu.Lock() defer a.mu.Unlock() now := time.Now() @@ -217,7 +220,7 @@ func (a *AdminServer) recordLoginFailure(client string) { a.attempts[client] = window } -func (a *AdminServer) cleanupSessionsLocked(now time.Time) { +func (a *Server) cleanupSessionsLocked(now time.Time) { for token, session := range a.sessions { if now.After(session.Expires) { delete(a.sessions, token) @@ -225,7 +228,7 @@ func (a *AdminServer) cleanupSessionsLocked(now time.Time) { } } -func (a *AdminServer) removeEarliestSessionLocked() { +func (a *Server) removeEarliestSessionLocked() { var earliestToken string var earliest time.Time for token, session := range a.sessions { diff --git a/admin_debug.go b/internal/admin/debug.go similarity index 75% rename from admin_debug.go rename to internal/admin/debug.go index 2e7eb69..3435dbe 100644 --- a/admin_debug.go +++ b/internal/admin/debug.go @@ -1,40 +1,47 @@ -package main +package admin import ( "bytes" - "context" "encoding/json" "net/http" "strings" "time" + + "opencode2api/internal/config" + "opencode2api/internal/gateway" + "opencode2api/internal/httpx" + "opencode2api/internal/jsonutil" + modelcatalog "opencode2api/internal/models" + "opencode2api/internal/protocol" + "opencode2api/internal/telemetry" ) // DebugKeySelection tells the Playground whether to use normal routing or to // exercise one explicitly chosen upstream key. type DebugKeySelection struct { - Mode string `json:"mode,omitempty"` - Tier Tier `json:"tier,omitempty"` - ID string `json:"id,omitempty"` + Mode string `json:"mode,omitempty"` + Tier config.Tier `json:"tier,omitempty"` + ID string `json:"id,omitempty"` } type DebugInferenceRequest struct { - Protocol Protocol `json:"protocol"` + Protocol protocol.Protocol `json:"protocol"` Key DebugKeySelection `json:"key,omitempty"` Request map[string]any `json:"request"` } type DebugInferenceResult struct { - OK bool `json:"ok"` - HTTPStatus int `json:"http_status"` - DurationMS int64 `json:"duration_ms"` - RequestID string `json:"request_id,omitempty"` - Route ModelRouteDiagnostic `json:"route"` - SelectedKey *DebugKeyView `json:"selected_key,omitempty"` - KeyTest string `json:"key_test,omitempty"` - Response any `json:"response"` + OK bool `json:"ok"` + HTTPStatus int `json:"http_status"` + DurationMS int64 `json:"duration_ms"` + RequestID string `json:"request_id,omitempty"` + Route modelcatalog.RouteDiagnostic `json:"route"` + SelectedKey *gateway.DebugKeyView `json:"selected_key,omitempty"` + KeyTest string `json:"key_test,omitempty"` + Response any `json:"response"` } -func (a *AdminServer) handleDebugModels(w http.ResponseWriter, _ *http.Request) { +func (a *Server) handleDebugModels(w http.ResponseWriter, _ *http.Request) { models, metadata := a.manager.DebugModels() catalog := a.manager.Resources().Models keys := a.manager.DebugKeys() @@ -42,10 +49,10 @@ func (a *AdminServer) handleDebugModels(w http.ResponseWriter, _ *http.Request) last := a.lastInference a.mu.Unlock() w.Header().Set("Cache-Control", "no-store") - writeJSON(w, http.StatusOK, map[string]any{"models": models, "keys": keys, "metadata": metadata, "catalog": catalog, "last_inference": last}) + httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": models, "keys": keys, "metadata": metadata, "catalog": catalog, "last_inference": last}) } -func (a *AdminServer) handleDebugInference(w http.ResponseWriter, r *http.Request) { +func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) { if !a.allowDebug(clientIP(r)) { writeAdminError(w, http.StatusTooManyRequests, "debug_rate_limited", "too many Playground requests; retry in one minute") return @@ -55,7 +62,7 @@ func (a *AdminServer) handleDebugInference(w http.ResponseWriter, r *http.Reques writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) return } - if !validProtocol(input.Protocol) { + if !protocol.Valid(input.Protocol) { writeAdminError(w, http.StatusBadRequest, "invalid_protocol", "protocol must be chat, responses, or anthropic") return } @@ -63,9 +70,9 @@ func (a *AdminServer) handleDebugInference(w http.ResponseWriter, r *http.Reques writeAdminError(w, http.StatusBadRequest, "invalid_request", "request must be a JSON object") return } - payload := cloneMap(input.Request) + payload := jsonutil.CloneMap(input.Request) payload["stream"] = false - model := stringAt(payload, "model") + model := jsonutil.StringAt(payload, "model") if model == "" { writeAdminError(w, http.StatusBadRequest, "invalid_request", "request.model is required") return @@ -77,7 +84,7 @@ func (a *AdminServer) handleDebugInference(w http.ResponseWriter, r *http.Reques writeAdminError(w, http.StatusBadRequest, "invalid_key_mode", "key.mode must be auto or selected") return } - var selectedKey *DebugKeyView + var selectedKey *gateway.DebugKeyView if input.Key.Mode == "selected" { selectedKey = a.manager.DebugKey(input.Key.Tier, input.Key.ID) if selectedKey == nil { @@ -99,9 +106,9 @@ func (a *AdminServer) handleDebugInference(w http.ResponseWriter, r *http.Reques writeAdminError(w, http.StatusBadRequest, "invalid_request", "request contains unsupported JSON values") return } - path := protocolPath(input.Protocol) - trace := &requestMeta{} - ctx := context.WithValue(withDiagnosticRequest(r.Context()), requestMetaKey{}, trace) + path := protocol.Path(input.Protocol) + trace := &telemetry.RequestMeta{} + ctx := telemetry.WithRequestMeta(gateway.WithDiagnosticRequest(r.Context()), trace) request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://gateway.local"+path, bytes.NewReader(encoded)) if err != nil { writeAdminError(w, http.StatusInternalServerError, "debug_request_failed", "could not construct Gateway request") @@ -114,7 +121,7 @@ func (a *AdminServer) handleDebugInference(w http.ResponseWriter, r *http.Reques } request.Header.Set("Authorization", "Bearer "+cfg.ServerKeys[0]) if selectedKey != nil { - request = request.WithContext(withDebugKeyOverride(request.Context(), debugKeyOverride{Tier: selectedKey.Tier, KeyID: selectedKey.ID})) + request = request.WithContext(gateway.WithDebugKeyOverride(request.Context(), gateway.DebugKeyOverride{Tier: selectedKey.Tier, KeyID: selectedKey.ID})) } request.Header.Set("Content-Type", "application/json") request.Header.Set("Accept", "application/json") @@ -125,7 +132,7 @@ func (a *AdminServer) handleDebugInference(w http.ResponseWriter, r *http.Reques requestID := recorder.Header().Get("x-request-id") if trace.Channel != "" { route.Anonymous = trace.Anonymous - route.Tier = Tier(trace.Tier) + route.Tier = config.Tier(trace.Tier) route.KeyID = trace.KeyID route.Channel = trace.Channel route.Attempts = trace.Attempts @@ -135,7 +142,7 @@ func (a *AdminServer) handleDebugInference(w http.ResponseWriter, r *http.Reques if json.Unmarshal(recorder.body.Bytes(), &raw) != nil { raw = recorder.body.String() } - raw = sanitizeDebugValue(raw, a.manager.redactor) + raw = sanitizeDebugValue(raw, a.manager.Redact) keyTest := "" if selectedKey != nil { if current := a.manager.DebugKey(selectedKey.Tier, selectedKey.ID); current != nil { @@ -152,7 +159,7 @@ func (a *AdminServer) handleDebugInference(w http.ResponseWriter, r *http.Reques a.lastInference = &result a.mu.Unlock() w.Header().Set("Cache-Control", "no-store") - writeJSON(w, http.StatusOK, result) + httpx.WriteJSON(w, http.StatusOK, result) } type debugResponseRecorder struct { @@ -178,7 +185,7 @@ func (recorder *debugResponseRecorder) Write(data []byte) (int, error) { return recorder.body.Write(data) } -func sanitizeDebugValue(value any, redactor *SecretRedactor) any { +func sanitizeDebugValue(value any, redact func(string) string) any { switch current := value.(type) { case map[string]any: result := make(map[string]any, len(current)) @@ -188,23 +195,23 @@ func sanitizeDebugValue(value any, redactor *SecretRedactor) any { result[key] = "***" continue } - result[key] = sanitizeDebugValue(item, redactor) + result[key] = sanitizeDebugValue(item, redact) } return result case []any: result := make([]any, len(current)) for index, item := range current { - result[index] = sanitizeDebugValue(item, redactor) + result[index] = sanitizeDebugValue(item, redact) } return result case string: - return redactor.String(current) + return redact(current) default: return value } } -func (a *AdminServer) allowDebug(client string) bool { +func (a *Server) allowDebug(client string) bool { a.mu.Lock() defer a.mu.Unlock() now := time.Now() diff --git a/admin.go b/internal/admin/server.go similarity index 66% rename from admin.go rename to internal/admin/server.go index 365588b..4b11c1d 100644 --- a/admin.go +++ b/internal/admin/server.go @@ -1,7 +1,7 @@ -package main +// Package admin serves configuration, authentication, diagnostics, and the WebUI. +package admin import ( - "embed" "encoding/json" "errors" "fmt" @@ -13,15 +13,19 @@ import ( "strings" "sync" "time" + + "opencode2api/internal/buildinfo" + "opencode2api/internal/config" + "opencode2api/internal/gateway" + "opencode2api/internal/httpx" + "opencode2api/internal/telemetry" + "opencode2api/webui" ) -//go:embed webui/* -var webAssets embed.FS - -type AdminServer struct { - manager *RuntimeManager - monitor *Monitor - logs *LogHub +type Server struct { + manager *gateway.RuntimeManager + monitor *telemetry.Monitor + logs *telemetry.LogHub logger *slog.Logger mu sync.Mutex sessions map[string]adminSession @@ -30,14 +34,14 @@ type AdminServer struct { lastInference *DebugInferenceResult } -func NewAdminServer(manager *RuntimeManager, monitor *Monitor, logs *LogHub, logger *slog.Logger) *AdminServer { - return &AdminServer{ +func New(manager *gateway.RuntimeManager, monitor *telemetry.Monitor, logs *telemetry.LogHub, logger *slog.Logger) *Server { + return &Server{ manager: manager, monitor: monitor, logs: logs, logger: logger, sessions: make(map[string]adminSession), attempts: make(map[string]loginWindow), debugAttempts: make(map[string]loginWindow), } } -func (a *AdminServer) Handler() http.Handler { +func (a *Server) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("POST /api/auth/login", a.handleLogin) mux.Handle("GET /api/auth/session", a.authenticate(http.HandlerFunc(a.handleSession))) @@ -53,14 +57,11 @@ func (a *AdminServer) Handler() http.Handler { mux.Handle("GET /api/logs", a.authenticate(http.HandlerFunc(a.handleLogs))) mux.Handle("GET /api/logs/stream", a.authenticate(http.HandlerFunc(a.handleLogStream))) mux.Handle("/", a.staticHandler()) - return a.securityHeaders(recoveryMiddleware(a.logger, mux)) + return a.securityHeaders(telemetry.Recover(a.logger, mux)) } -func (a *AdminServer) staticHandler() http.Handler { - assets, err := fs.Sub(webAssets, "webui") - if err != nil { - panic(err) - } +func (a *Server) staticHandler() http.Handler { + assets := webui.Assets files := http.FileServer(http.FS(assets)) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/api/") { @@ -76,7 +77,7 @@ func (a *AdminServer) staticHandler() http.Handler { }) } -func (a *AdminServer) securityHeaders(next http.Handler) http.Handler { +func (a *Server) securityHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self'; script-src 'self'; connect-src 'self'; img-src 'self' data:") w.Header().Set("Referrer-Policy", "no-referrer") @@ -94,22 +95,22 @@ type SecretView struct { } type ConfigView struct { - Listen string `json:"listen"` - ServerKeys []SecretView `json:"server_keys"` - ZenKeys []SecretView `json:"zen_keys"` - GoKeys []SecretView `json:"go_keys"` - Anonymous bool `json:"anonymous"` - Proxies []SecretView `json:"proxies"` - ProxyFile string `json:"proxyfile"` - Upstream UpstreamConfig `json:"upstream"` - Retry RetryConfig `json:"retry"` - Models ModelsConfig `json:"models"` - Performance PerformanceConfig `json:"performance"` - Logging LoggingConfig `json:"logging"` - Prefer Tier `json:"prefer"` - WebUI WebUIView `json:"webui"` - Effective EffectiveView `json:"effective"` - Restart []string `json:"restart_required_fields,omitempty"` + Listen string `json:"listen"` + ServerKeys []SecretView `json:"server_keys"` + ZenKeys []SecretView `json:"zen_keys"` + GoKeys []SecretView `json:"go_keys"` + Anonymous bool `json:"anonymous"` + Proxies []SecretView `json:"proxies"` + ProxyFile string `json:"proxyfile"` + Upstream config.UpstreamConfig `json:"upstream"` + Retry config.RetryConfig `json:"retry"` + Models config.ModelsConfig `json:"models"` + Performance config.PerformanceConfig `json:"performance"` + Logging config.LoggingConfig `json:"logging"` + Prefer config.Tier `json:"prefer"` + WebUI WebUIView `json:"webui"` + Effective EffectiveView `json:"effective"` + Restart []string `json:"restart_required_fields,omitempty"` } type EffectiveView struct { @@ -131,28 +132,28 @@ type SecretInput struct { } type ConfigUpdate struct { - Listen string `json:"listen"` - ServerKeys []SecretInput `json:"server_keys"` - ZenKeys []SecretInput `json:"zen_keys"` - GoKeys []SecretInput `json:"go_keys"` - Anonymous bool `json:"anonymous"` - Proxies []SecretInput `json:"proxies"` - ProxyFile string `json:"proxyfile"` - Upstream UpstreamConfig `json:"upstream"` - Retry RetryConfig `json:"retry"` - Models ModelsConfig `json:"models"` - Performance PerformanceConfig `json:"performance"` - Logging LoggingConfig `json:"logging"` - Prefer Tier `json:"prefer"` - WebUI WebUIView `json:"webui"` + Listen string `json:"listen"` + ServerKeys []SecretInput `json:"server_keys"` + ZenKeys []SecretInput `json:"zen_keys"` + GoKeys []SecretInput `json:"go_keys"` + Anonymous bool `json:"anonymous"` + Proxies []SecretInput `json:"proxies"` + ProxyFile string `json:"proxyfile"` + Upstream config.UpstreamConfig `json:"upstream"` + Retry config.RetryConfig `json:"retry"` + Models config.ModelsConfig `json:"models"` + Performance config.PerformanceConfig `json:"performance"` + Logging config.LoggingConfig `json:"logging"` + Prefer config.Tier `json:"prefer"` + WebUI WebUIView `json:"webui"` } -func (a *AdminServer) handleGetConfig(w http.ResponseWriter, _ *http.Request) { +func (a *Server) handleGetConfig(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Cache-Control", "no-store") - writeJSON(w, http.StatusOK, a.configView()) + httpx.WriteJSON(w, http.StatusOK, a.configView()) } -func (a *AdminServer) handlePutConfig(w http.ResponseWriter, r *http.Request) { +func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { var update ConfigUpdate if err := decodeAdminJSON(w, r, &update); err != nil { writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) @@ -179,10 +180,10 @@ func (a *AdminServer) handlePutConfig(w http.ResponseWriter, r *http.Request) { writeAdminError(w, http.StatusBadRequest, "invalid_proxies", err.Error()) return } - candidate := Config{ + candidate := config.Config{ Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Proxies: proxies, ProxyFile: update.ProxyFile, Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, - WebUI: WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, + WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, } result, err := a.manager.Apply(candidate, true) if err != nil { @@ -190,19 +191,19 @@ func (a *AdminServer) handlePutConfig(w http.ResponseWriter, r *http.Request) { writeAdminError(w, http.StatusBadRequest, "configuration_rejected", err.Error()) return } - writeJSON(w, http.StatusOK, map[string]any{"result": result, "config": a.configView()}) + httpx.WriteJSON(w, http.StatusOK, map[string]any{"result": result, "config": a.configView()}) } -func (a *AdminServer) handleReload(w http.ResponseWriter, _ *http.Request) { +func (a *Server) handleReload(w http.ResponseWriter, _ *http.Request) { result, err := a.manager.Reload() if err != nil { writeAdminError(w, http.StatusBadRequest, "reload_failed", err.Error()) return } - writeJSON(w, http.StatusOK, result) + httpx.WriteJSON(w, http.StatusOK, result) } -func (a *AdminServer) handleReveal(w http.ResponseWriter, r *http.Request) { +func (a *Server) handleReveal(w http.ResponseWriter, r *http.Request) { var input struct { Password string `json:"password"` } @@ -211,30 +212,30 @@ func (a *AdminServer) handleReveal(w http.ResponseWriter, r *http.Request) { return } cfg := a.manager.Config() - if !verifyPassword(cfg.WebUI.PasswordHash, input.Password) { + if !config.VerifyPassword(cfg.WebUI.PasswordHash, input.Password) { writeAdminError(w, http.StatusForbidden, "verification_failed", "password verification failed") return } w.Header().Set("Cache-Control", "no-store") a.logger.Info("sensitive configuration revealed", "component", "auth", "event", "secrets_revealed", "client_ip", clientIP(r)) - writeJSON(w, http.StatusOK, map[string]any{"server_keys": cfg.ServerKeys, "zen_keys": cfg.ZenKeys, "go_keys": cfg.GoKeys, "proxies": cfg.Proxies}) + httpx.WriteJSON(w, http.StatusOK, map[string]any{"server_keys": cfg.ServerKeys, "zen_keys": cfg.ZenKeys, "go_keys": cfg.GoKeys, "proxies": cfg.Proxies}) } -func (a *AdminServer) handleMonitor(w http.ResponseWriter, _ *http.Request) { +func (a *Server) handleMonitor(w http.ResponseWriter, _ *http.Request) { metrics := a.monitor.Snapshot() - writeJSON(w, http.StatusOK, map[string]any{ - "version": version, "metrics": metrics, "usage": metrics.Usage, "upstream": metrics.Upstream, "resources": a.manager.Resources(), + httpx.WriteJSON(w, http.StatusOK, map[string]any{ + "version": buildinfo.Version, "metrics": metrics, "usage": metrics.Usage, "upstream": metrics.Upstream, "resources": a.manager.Resources(), }) } -func (a *AdminServer) handleLogs(w http.ResponseWriter, r *http.Request) { +func (a *Server) handleLogs(w http.ResponseWriter, r *http.Request) { after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64) limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) events, gap := a.logs.Recent(after, limit) - writeJSON(w, http.StatusOK, map[string]any{"events": events, "gap": gap}) + httpx.WriteJSON(w, http.StatusOK, map[string]any{"events": events, "gap": gap}) } -func (a *AdminServer) handleLogStream(w http.ResponseWriter, r *http.Request) { +func (a *Server) handleLogStream(w http.ResponseWriter, r *http.Request) { flusher, ok := w.(http.Flusher) if !ok { writeAdminError(w, http.StatusInternalServerError, "stream_unsupported", "streaming is unavailable") @@ -249,10 +250,10 @@ func (a *AdminServer) handleLogStream(w http.ResponseWriter, r *http.Request) { } recent, gap := a.logs.Recent(after, 2000) if gap { - _ = encodeSSE(w, "gap", 0, map[string]any{"message": "older log events have expired"}) + _ = httpx.WriteSSE(w, "gap", 0, map[string]any{"message": "older log events have expired"}) } for _, event := range recent { - if err := encodeSSE(w, "log", event.Sequence, event); err != nil { + if err := httpx.WriteSSE(w, "log", event.Sequence, event); err != nil { return } after = event.Sequence @@ -269,9 +270,9 @@ func (a *AdminServer) handleLogStream(w http.ResponseWriter, r *http.Request) { return case event := <-stream: if after > 0 && event.Sequence > after+1 { - _ = encodeSSE(w, "gap", 0, map[string]any{"message": "slow client missed log events", "after": after, "next": event.Sequence}) + _ = httpx.WriteSSE(w, "gap", 0, map[string]any{"message": "slow client missed log events", "after": after, "next": event.Sequence}) } - if err := encodeSSE(w, "log", event.Sequence, event); err != nil { + if err := httpx.WriteSSE(w, "log", event.Sequence, event); err != nil { return } after = event.Sequence @@ -286,7 +287,7 @@ func (a *AdminServer) handleLogStream(w http.ResponseWriter, r *http.Request) { } } -func (a *AdminServer) sessionTokenValid(token string) bool { +func (a *Server) sessionTokenValid(token string) bool { a.mu.Lock() session, ok := a.sessions[tokenDigest(token)] if ok && time.Now().After(session.Expires) { @@ -298,10 +299,10 @@ func (a *AdminServer) sessionTokenValid(token string) bool { return false } cfg := a.manager.Config() - return session.Username == cfg.WebUI.Username && session.AuthVersion == secretFingerprint(cfg.WebUI.PasswordHash) + return session.Username == cfg.WebUI.Username && session.AuthVersion == config.Fingerprint(cfg.WebUI.PasswordHash) } -func (a *AdminServer) configView() ConfigView { +func (a *Server) configView() ConfigView { cfg := a.manager.Config() effective, restart := a.manager.RestartStatus() return ConfigView{ @@ -317,27 +318,19 @@ func (a *AdminServer) configView() ConfigView { func maskSecrets(values []string, proxy bool) []SecretView { result := make([]SecretView, 0, len(values)) for _, value := range values { - display := maskValue(value) + display := config.MaskValue(value) if proxy { - display = redactURL(value) + display = config.RedactURL(value) } - result = append(result, SecretView{ID: secretFingerprint(value), Display: display}) + result = append(result, SecretView{ID: config.Fingerprint(value), Display: display}) } return result } -func maskValue(value string) string { - runes := []rune(value) - if len(runes) <= 5 { - return "••••" - } - return "••••" + string(runes[len(runes)-5:]) -} - func resolveSecrets(inputs []SecretInput, existing []string) ([]string, error) { known := make(map[string]string, len(existing)) for _, value := range existing { - known[secretFingerprint(value)] = value + known[config.Fingerprint(value)] = value } result := make([]string, 0, len(inputs)) for _, input := range inputs { @@ -374,5 +367,5 @@ func decodeAdminJSON(w http.ResponseWriter, r *http.Request, target any) error { } func writeAdminError(w http.ResponseWriter, status int, code, message string) { - writeJSON(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}}) + httpx.WriteJSON(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}}) } diff --git a/internal/buildinfo/version.go b/internal/buildinfo/version.go new file mode 100644 index 0000000..81b4bea --- /dev/null +++ b/internal/buildinfo/version.go @@ -0,0 +1,5 @@ +// Package buildinfo shares the executable version with HTTP handlers. +package buildinfo + +// Version is set once by the command before any background work starts. +var Version = "dev" diff --git a/config.go b/internal/config/config.go similarity index 57% rename from config.go rename to internal/config/config.go index 64fe648..7cf7a82 100644 --- a/config.go +++ b/internal/config/config.go @@ -1,18 +1,18 @@ -package main +// Package config loads, validates, persists, and redacts service configuration. +package config import ( - "bufio" "bytes" "encoding/json" "errors" "fmt" - "io" "net/url" "os" - "path/filepath" - "runtime" "strings" "time" + + "opencode2api/internal/jsonutil" + wire "opencode2api/internal/protocol" ) type Config struct { @@ -99,7 +99,7 @@ func (cfg PerformanceConfig) AttemptTimeout(requestTimeout time.Duration) time.D return requestTimeout } -func LoadConfig(path string) (Config, error) { +func Load(path string) (Config, error) { data, err := os.ReadFile(path) if err != nil { return Config{}, fmt.Errorf("read %s: %w", path, err) @@ -123,15 +123,15 @@ func LoadConfig(path string) (Config, error) { if err := dec.Decode(&cfg); err != nil { return Config{}, fmt.Errorf("parse %s: %w", path, err) } - if err := ensureJSONEOF(dec); err != nil { + if err := jsonutil.EnsureEOF(dec); err != nil { return Config{}, fmt.Errorf("parse %s: %w", path, err) } - return NormalizeConfig(path, cfg) + return Normalize(path, cfg) } -// NormalizeConfig resolves external inputs and validates a Config supplied by +// Normalize resolves external inputs and validates a Config supplied by // either the JSON file or the authenticated management API. -func NormalizeConfig(path string, cfg Config) (Config, error) { +func Normalize(path string, cfg Config) (Config, error) { trimList(&cfg.ServerKeys) trimList(&cfg.ZenKeys) trimList(&cfg.GoKeys) @@ -205,7 +205,7 @@ func NormalizeConfig(path string, cfg Config) (Config, error) { } u, err := url.Parse(raw) if err != nil || u.Host == "" { - return Config{}, fmt.Errorf("invalid proxy URL %q", redactURL(raw)) + return Config{}, fmt.Errorf("invalid proxy URL %q", RedactURL(raw)) } switch strings.ToLower(u.Scheme) { case "http", "https", "socks5", "socks5h": @@ -214,7 +214,7 @@ func NormalizeConfig(path string, cfg Config) (Config, error) { } } for model, protocol := range cfg.Models.Protocols { - if model == "" || !validProtocol(Protocol(protocol)) { + if model == "" || !wire.Valid(wire.Protocol(protocol)) { return Config{}, fmt.Errorf("models.protocols contains invalid mapping %q: %q", model, protocol) } } @@ -234,262 +234,24 @@ func (cfg Config) RuntimeProxies() []string { return []string{"direct"} } -func ensureJSONEOF(dec *json.Decoder) error { - var extra any - if err := dec.Decode(&extra); err != io.EOF { - if err == nil { - return errors.New("multiple JSON values") - } - return err - } - return nil -} - -// stripJSONComments removes // and /* */ comments without changing newlines, -// so syntax errors still point at the correct line in config.json. Comment -// markers inside JSON strings (for example, https:// URLs) are preserved. -func stripJSONComments(data []byte) ([]byte, error) { - data = bytes.TrimPrefix(data, []byte{0xef, 0xbb, 0xbf}) - out := make([]byte, 0, len(data)) - inString := false - escaped := false - lineComment := false - blockComment := false - - for i := 0; i < len(data); i++ { - current := data[i] - if lineComment { - if current == '\n' || current == '\r' { - lineComment = false - out = append(out, current) - } else { - out = append(out, ' ') - } - continue - } - if blockComment { - if current == '*' && i+1 < len(data) && data[i+1] == '/' { - out = append(out, ' ', ' ') - i++ - blockComment = false - } else if current == '\n' || current == '\r' { - out = append(out, current) - } else { - out = append(out, ' ') - } - continue - } - if inString { - out = append(out, current) - if escaped { - escaped = false - } else if current == '\\' { - escaped = true - } else if current == '"' { - inString = false - } - continue - } - - switch { - case current == '"': - inString = true - out = append(out, current) - case current == '/' && i+1 < len(data) && data[i+1] == '/': - lineComment = true - out = append(out, ' ', ' ') - i++ - case current == '/' && i+1 < len(data) && data[i+1] == '*': - blockComment = true - out = append(out, ' ', ' ') - i++ - default: - out = append(out, current) - } - } - if blockComment { - return nil, errors.New("unterminated block comment") - } - return out, nil -} - -func resolveProxyFiles(configPath string, cfg *Config) error { - trimList(&cfg.Proxies) - effective := append([]string(nil), cfg.Proxies...) - if cfg.ProxyFile != "" { - resolved := cfg.ProxyFile - if !filepath.IsAbs(resolved) { - resolved = filepath.Join(filepath.Dir(configPath), resolved) - } - proxies, err := readProxyFile(resolved) - if err != nil { - return fmt.Errorf("load proxy file %s: %w", resolved, err) - } - effective = append(effective, proxies...) - } - - effective = uniqueStrings(effective) - if len(effective) == 0 { - effective = []string{"direct"} - } - cfg.effectiveProxies = effective - return nil -} - -// SaveConfigAtomic writes normalized JSON and keeps the preceding file as -// config.json.bak. The temporary file is created beside the target so the -// final rename stays on the same filesystem. -func SaveConfigAtomic(path string, cfg Config) error { - cfg.PasswordForSave() - data, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return fmt.Errorf("encode config: %w", err) - } - data = append(data, '\n') - dir := filepath.Dir(path) - temp, err := os.CreateTemp(dir, ".config-*.tmp") - if err != nil { - return fmt.Errorf("create temporary config: %w", err) - } - tempPath := temp.Name() - defer os.Remove(tempPath) - if _, err = temp.Write(data); err == nil { - err = temp.Sync() - } - closeErr := temp.Close() - if err == nil { - err = closeErr - } - if err != nil { - return fmt.Errorf("write temporary config: %w", err) - } - if info, statErr := os.Stat(path); statErr == nil { - _ = os.Chmod(tempPath, info.Mode().Perm()) - } - - backup := path + ".bak" - if runtime.GOOS == "windows" { - _ = os.Remove(backup) - if _, statErr := os.Stat(path); statErr == nil { - if err := os.Rename(path, backup); err != nil { - return fmt.Errorf("backup config: %w", err) - } - } - if err := os.Rename(tempPath, path); err != nil { - _ = os.Rename(backup, path) - return fmt.Errorf("replace config: %w", err) - } - return nil - } - if _, statErr := os.Stat(path); statErr == nil { - if err := copyFile(path, backup); err != nil { - return fmt.Errorf("backup config: %w", err) - } - } - if err := os.Rename(tempPath, path); err != nil { - return fmt.Errorf("replace config: %w", err) - } - return nil -} - // PasswordForSave ensures resolved-only data is excluded. The method is kept // separate to make accidental persistence of effective proxy values obvious. func (cfg *Config) PasswordForSave() { cfg.effectiveProxies = nil } -func copyFile(source, target string) error { - in, err := os.Open(source) - if err != nil { - return err - } - defer in.Close() - mode := os.FileMode(0600) - if info, statErr := in.Stat(); statErr == nil { - mode = info.Mode().Perm() - } - out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode) - if err != nil { - return err - } - _ = out.Chmod(mode) - _, copyErr := io.Copy(out, in) - syncErr := out.Sync() - closeErr := out.Close() - if copyErr != nil { - return copyErr - } - if syncErr != nil { - return syncErr - } - return closeErr -} - -func readProxyFile(path string) ([]string, error) { - file, err := os.Open(path) - if err != nil { - return nil, err - } - defer file.Close() - - var proxies []string - scanner := bufio.NewScanner(file) - scanner.Buffer(make([]byte, 4096), 1024*1024) - for scanner.Scan() { - value := strings.TrimSpace(strings.TrimPrefix(scanner.Text(), "\ufeff")) - value = strings.TrimSpace(stripProxyLineComment(value)) - if value != "" { - proxies = append(proxies, value) +func Clone(cfg Config) Config { + cfg.ServerKeys = append([]string(nil), cfg.ServerKeys...) + cfg.ZenKeys = append([]string(nil), cfg.ZenKeys...) + cfg.GoKeys = append([]string(nil), cfg.GoKeys...) + cfg.Proxies = append([]string(nil), cfg.Proxies...) + cfg.effectiveProxies = append([]string(nil), cfg.effectiveProxies...) + if cfg.Models.Protocols != nil { + protocols := make(map[string]string, len(cfg.Models.Protocols)) + for key, value := range cfg.Models.Protocols { + protocols[key] = value } + cfg.Models.Protocols = protocols } - if err := scanner.Err(); err != nil { - return nil, err - } - return proxies, nil -} - -func stripProxyLineComment(line string) string { - for i := 0; i < len(line); i++ { - if i > 0 && line[i-1] != ' ' && line[i-1] != '\t' { - continue - } - if line[i] == '#' || line[i] == ';' || (line[i] == '/' && i+1 < len(line) && line[i+1] == '/') { - return line[:i] - } - } - return line -} - -func uniqueStrings(items []string) []string { - out := items[:0] - seen := make(map[string]struct{}, len(items)) - for _, item := range items { - if _, exists := seen[item]; exists { - continue - } - seen[item] = struct{}{} - out = append(out, item) - } - return out -} - -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() + return cfg } diff --git a/internal/config/json.go b/internal/config/json.go new file mode 100644 index 0000000..1c66c28 --- /dev/null +++ b/internal/config/json.go @@ -0,0 +1,74 @@ +package config + +import ( + "bytes" + "errors" +) + +// stripJSONComments removes // and /* */ comments without changing newlines, +// so syntax errors still point at the correct line in config.json. Comment +// markers inside JSON strings (for example, https:// URLs) are preserved. +func stripJSONComments(data []byte) ([]byte, error) { + data = bytes.TrimPrefix(data, []byte{0xef, 0xbb, 0xbf}) + out := make([]byte, 0, len(data)) + inString := false + escaped := false + lineComment := false + blockComment := false + + for i := 0; i < len(data); i++ { + current := data[i] + if lineComment { + if current == '\n' || current == '\r' { + lineComment = false + out = append(out, current) + } else { + out = append(out, ' ') + } + continue + } + if blockComment { + if current == '*' && i+1 < len(data) && data[i+1] == '/' { + out = append(out, ' ', ' ') + i++ + blockComment = false + } else if current == '\n' || current == '\r' { + out = append(out, current) + } else { + out = append(out, ' ') + } + continue + } + if inString { + out = append(out, current) + if escaped { + escaped = false + } else if current == '\\' { + escaped = true + } else if current == '"' { + inString = false + } + continue + } + + switch { + case current == '"': + inString = true + out = append(out, current) + case current == '/' && i+1 < len(data) && data[i+1] == '/': + lineComment = true + out = append(out, ' ', ' ') + i++ + case current == '/' && i+1 < len(data) && data[i+1] == '*': + blockComment = true + out = append(out, ' ', ' ') + i++ + default: + out = append(out, current) + } + } + if blockComment { + return nil, errors.New("unterminated block comment") + } + return out, nil +} diff --git a/password.go b/internal/config/password.go similarity index 94% rename from password.go rename to internal/config/password.go index d333fcb..19494c7 100644 --- a/password.go +++ b/internal/config/password.go @@ -1,4 +1,4 @@ -package main +package config import ( "crypto/rand" @@ -20,7 +20,7 @@ const ( argonKeyLength = 32 ) -func hashPassword(password string) (string, error) { +func HashPassword(password string) (string, error) { if len(password) < 10 { return "", errors.New("webui password must contain at least 10 characters") } @@ -33,7 +33,7 @@ func hashPassword(password string) (string, error) { base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(hash)), nil } -func verifyPassword(encoded, password string) bool { +func VerifyPassword(encoded, password string) bool { parts := strings.Split(encoded, "$") if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" { return false diff --git a/internal/config/persistence.go b/internal/config/persistence.go new file mode 100644 index 0000000..0cc1ea5 --- /dev/null +++ b/internal/config/persistence.go @@ -0,0 +1,93 @@ +package config + +import ( + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "runtime" +) + +// SaveAtomic writes normalized JSON and keeps the preceding file as +// config.json.bak. The temporary file is created beside the target so the +// final rename stays on the same filesystem. +func SaveAtomic(path string, cfg Config) error { + cfg.PasswordForSave() + data, err := json.MarshalIndent(cfg, "", " ") + if err != nil { + return fmt.Errorf("encode config: %w", err) + } + data = append(data, '\n') + dir := filepath.Dir(path) + temp, err := os.CreateTemp(dir, ".config-*.tmp") + if err != nil { + return fmt.Errorf("create temporary config: %w", err) + } + tempPath := temp.Name() + defer os.Remove(tempPath) + if _, err = temp.Write(data); err == nil { + err = temp.Sync() + } + closeErr := temp.Close() + if err == nil { + err = closeErr + } + if err != nil { + return fmt.Errorf("write temporary config: %w", err) + } + if info, statErr := os.Stat(path); statErr == nil { + _ = os.Chmod(tempPath, info.Mode().Perm()) + } + + backup := path + ".bak" + if runtime.GOOS == "windows" { + _ = os.Remove(backup) + if _, statErr := os.Stat(path); statErr == nil { + if err := os.Rename(path, backup); err != nil { + return fmt.Errorf("backup config: %w", err) + } + } + if err := os.Rename(tempPath, path); err != nil { + _ = os.Rename(backup, path) + return fmt.Errorf("replace config: %w", err) + } + return nil + } + if _, statErr := os.Stat(path); statErr == nil { + if err := copyFile(path, backup); err != nil { + return fmt.Errorf("backup config: %w", err) + } + } + if err := os.Rename(tempPath, path); err != nil { + return fmt.Errorf("replace config: %w", err) + } + return nil +} + +func copyFile(source, target string) error { + in, err := os.Open(source) + if err != nil { + return err + } + defer in.Close() + mode := os.FileMode(0600) + if info, statErr := in.Stat(); statErr == nil { + mode = info.Mode().Perm() + } + out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode) + if err != nil { + return err + } + _ = out.Chmod(mode) + _, copyErr := io.Copy(out, in) + syncErr := out.Sync() + closeErr := out.Close() + if copyErr != nil { + return copyErr + } + if syncErr != nil { + return syncErr + } + return closeErr +} diff --git a/internal/config/proxy.go b/internal/config/proxy.go new file mode 100644 index 0000000..7faf2da --- /dev/null +++ b/internal/config/proxy.go @@ -0,0 +1,90 @@ +package config + +import ( + "bufio" + "fmt" + "os" + "path/filepath" + "strings" +) + +func resolveProxyFiles(configPath string, cfg *Config) error { + trimList(&cfg.Proxies) + effective := append([]string(nil), cfg.Proxies...) + if cfg.ProxyFile != "" { + resolved := cfg.ProxyFile + if !filepath.IsAbs(resolved) { + resolved = filepath.Join(filepath.Dir(configPath), resolved) + } + proxies, err := readProxyFile(resolved) + if err != nil { + return fmt.Errorf("load proxy file %s: %w", resolved, err) + } + effective = append(effective, proxies...) + } + + effective = uniqueStrings(effective) + if len(effective) == 0 { + effective = []string{"direct"} + } + cfg.effectiveProxies = effective + return nil +} + +func readProxyFile(path string) ([]string, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + + var proxies []string + scanner := bufio.NewScanner(file) + scanner.Buffer(make([]byte, 4096), 1024*1024) + for scanner.Scan() { + value := strings.TrimSpace(strings.TrimPrefix(scanner.Text(), "\ufeff")) + value = strings.TrimSpace(stripProxyLineComment(value)) + if value != "" { + proxies = append(proxies, value) + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return proxies, nil +} + +func stripProxyLineComment(line string) string { + for i := 0; i < len(line); i++ { + if i > 0 && line[i-1] != ' ' && line[i-1] != '\t' { + continue + } + if line[i] == '#' || line[i] == ';' || (line[i] == '/' && i+1 < len(line) && line[i+1] == '/') { + return line[:i] + } + } + return line +} + +func uniqueStrings(items []string) []string { + out := items[:0] + seen := make(map[string]struct{}, len(items)) + for _, item := range items { + if _, exists := seen[item]; exists { + continue + } + seen[item] = struct{}{} + out = append(out, item) + } + return out +} + +func trimList(items *[]string) { + out := (*items)[:0] + for _, item := range *items { + if value := strings.TrimSpace(item); value != "" { + out = append(out, value) + } + } + *items = out +} diff --git a/internal/config/secrets.go b/internal/config/secrets.go new file mode 100644 index 0000000..5ed4592 --- /dev/null +++ b/internal/config/secrets.go @@ -0,0 +1,95 @@ +package config + +import ( + "crypto/sha256" + "encoding/hex" + "net/url" + "sort" + "strings" + "sync/atomic" +) + +func MaskValue(value string) string { + runes := []rune(value) + if len(runes) <= 5 { + return "••••" + } + return "••••" + string(runes[len(runes)-5:]) +} + +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() +} + +type SecretRedactor struct { + values atomic.Value +} + +func NewSecretRedactor() *SecretRedactor { + r := &SecretRedactor{} + r.values.Store([]string(nil)) + return r +} + +func (r *SecretRedactor) Replace(cfg Config) { + values := make([]string, 0, len(cfg.ServerKeys)+len(cfg.ZenKeys)+len(cfg.GoKeys)+2) + values = append(values, cfg.ServerKeys...) + values = append(values, cfg.ZenKeys...) + values = append(values, cfg.GoKeys...) + if cfg.WebUI.Password != "" { + values = append(values, cfg.WebUI.Password) + } + for _, value := range []string{cfg.Upstream.Zen, cfg.Upstream.Go} { + if parsed, err := url.Parse(value); err == nil && parsed.User != nil { + values = append(values, value, parsed.User.Username()) + if password, ok := parsed.User.Password(); ok { + values = append(values, password) + } + } + } + for _, value := range cfg.RuntimeProxies() { + if value != "direct" { + values = append(values, value) + if parsed, err := url.Parse(value); err == nil && parsed.User != nil { + values = append(values, parsed.User.Username()) + if password, ok := parsed.User.Password(); ok { + values = append(values, password) + } + } + } + } + sort.Slice(values, func(i, j int) bool { return len(values[i]) > len(values[j]) }) + r.values.Store(values) +} + +func (r *SecretRedactor) String(value string) string { + for _, secret := range r.values.Load().([]string) { + if len(secret) >= 4 { + value = strings.ReplaceAll(value, secret, "***") + } + } + return value +} + +func Fingerprint(value string) string { + sum := sha256.Sum256([]byte(value)) + return hex.EncodeToString(sum[:])[:10] +} + +// keyDisplayID is intentionally separate from secretFingerprint. The latter +// is an internal stable identifier used by session/config bookkeeping; this +// value is safe for logs and the operator UI and shows only the key suffix. +func KeyDisplayID(value string) string { + runes := []rune(value) + if len(runes) <= 5 { + return string(runes) + } + return string(runes[len(runes)-5:]) +} diff --git a/internal/config/tier.go b/internal/config/tier.go new file mode 100644 index 0000000..b0220f4 --- /dev/null +++ b/internal/config/tier.go @@ -0,0 +1,8 @@ +package config + +type Tier string + +const ( + TierZen Tier = "zen" + TierGo Tier = "go" +) diff --git a/gateway.go b/internal/gateway/gateway.go similarity index 61% rename from gateway.go rename to internal/gateway/gateway.go index 3564ac7..a68ad15 100644 --- a/gateway.go +++ b/internal/gateway/gateway.go @@ -1,4 +1,5 @@ -package main +// Package gateway routes inference requests through managed upstream pools. +package gateway import ( "context" @@ -11,6 +12,13 @@ import ( "net/http" "strings" "time" + + "opencode2api/internal/config" + "opencode2api/internal/identity" + "opencode2api/internal/jsonutil" + "opencode2api/internal/models" + wire "opencode2api/internal/protocol" + "opencode2api/internal/telemetry" ) const maxRequestBody = 32 << 20 @@ -18,17 +26,17 @@ const maxRequestBody = 32 << 20 const anonymousZenKey = "public" type Gateway struct { - cfg Config + cfg config.Config logger *slog.Logger transports *transportPool zenNodes *nodePool goNodes *nodePool anonymous *anonymousPool - catalog *modelCatalog - monitor *Monitor + catalog *models.Catalog + monitor *telemetry.Monitor } -func NewGateway(cfg Config, logger *slog.Logger, monitor *Monitor) (*Gateway, error) { +func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor) (*Gateway, error) { transports, err := newTransportPool(cfg.RuntimeProxies(), cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second)) if err != nil { return nil, err @@ -42,7 +50,7 @@ func NewGateway(cfg Config, logger *slog.Logger, monitor *Monitor) (*Gateway, er if err != nil { return nil, fmt.Errorf("go node pool: %w", err) } - catalog := newModelCatalog(cfg.Prefer, cfg.Models.Protocols) + catalog := models.NewCatalog(cfg.Prefer, cfg.Models.Protocols) catalog.SetRefreshInterval(time.Duration(cfg.Models.RefreshSeconds) * time.Second) return &Gateway{ cfg: cfg, @@ -59,11 +67,11 @@ func NewGateway(cfg Config, logger *slog.Logger, monitor *Monitor) (*Gateway, er 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("POST /v1/chat/completions", g.authenticate(g.handleInference(wire.Chat))) + mux.HandleFunc("POST /v1/responses", g.authenticate(g.handleInference(wire.Responses))) + mux.HandleFunc("POST /v1/messages", g.authenticate(g.handleInference(wire.Anthropic))) mux.HandleFunc("GET /healthz", g.handleHealth) - return recoveryMiddleware(g.logger, mux) + return telemetry.Recover(g.logger, mux) } func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc { @@ -81,40 +89,40 @@ func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc { } } if !valid { - protocol := ProtocolChat + protocol := wire.Chat if r.URL.Path == "/v1/messages" { - protocol = ProtocolAnthropic + protocol = wire.Anthropic } - writeAPIError(w, protocol, http.StatusUnauthorized, "invalid local API key", "authentication_error", "") + wire.WriteError(w, protocol, http.StatusUnauthorized, "invalid local API key", "authentication_error", "") return } next(w, r) } } -func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { +func (g *Gateway) handleInference(external wire.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", "") + wire.WriteError(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", "") + wire.WriteError(w, external, http.StatusBadRequest, "request body must be a JSON object", "invalid_request_error", "") return } - model := stringAt(payload, "model") - meta := metaFromRequest(r) + model := jsonutil.StringAt(payload, "model") + meta := telemetry.MetaFromRequest(r) if meta != nil { meta.Model = model } if model == "" { - writeAPIError(w, external, http.StatusBadRequest, "model is required", "invalid_request_error", "model") + wire.WriteError(w, external, http.StatusBadRequest, "model is required", "invalid_request_error", "model") return } if !g.catalog.Supported(model) { - writeAPIError(w, external, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model") + wire.WriteError(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, g.cfg.Anonymous) @@ -124,7 +132,7 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { route, err = g.catalog.RouteForTier(model, override.Tier, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0) } if err != nil { - writeAPIError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "model") + wire.WriteError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "model") return } if meta != nil { @@ -133,31 +141,31 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { } bodies, err := g.prepareRouteBodies(external, route, payload) if err != nil { - writeAPIError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "") + wire.WriteError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "") return } - ids := deriveRequestIDs(r, payload) + ids := identity.DeriveRequestIDs(r, payload) if meta != nil { meta.Request = ids.Request } - stream := boolAt(payload, "stream") + stream := jsonutil.BoolAt(payload, "stream") requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second) defer cancel() resp, upstreamRoute, err := g.doUpstream(requestCtx, route, bodies, ids) if err != nil { finalTier := route.Tier if meta != nil && meta.Tier != "" { - finalTier = Tier(meta.Tier) + finalTier = config.Tier(meta.Tier) } keyID, channel, anonymous := requestCredential(requestCtx) g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "tier", finalTier, "key_id", keyID, "channel", channel, "anonymous", anonymous, "error", err) // An exhausted request budget is a timeout, not a bad gateway: the // distinction matters to clients that retry on 502. if errors.Is(err, context.DeadlineExceeded) { - writeAPIError(w, external, http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout", ids.Request) + wire.WriteError(w, external, http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout", ids.Request) return } - writeAPIError(w, external, http.StatusBadGateway, "all upstream attempts failed", "upstream_error", ids.Request) + wire.WriteError(w, external, http.StatusBadGateway, "all upstream attempts failed", "upstream_error", ids.Request) return } defer resp.Body.Close() @@ -175,25 +183,25 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { meta.Stream = true } if g.monitor != nil { - g.monitor.activeStreams.Add(1) - defer g.monitor.activeStreams.Add(-1) + g.monitor.BeginStream() + defer g.monitor.EndStream() } 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) - var usage bridgeUsage + var usage wire.Usage var usageReported bool if external == upstreamRoute.Protocol { - usage, usageReported, err = forwardSSEWithUsageContext(r.Context(), w, resp.Body, upstreamRoute.Protocol, model) + usage, usageReported, err = wire.ForwardStream(r.Context(), w, resp.Body, upstreamRoute.Protocol, model) } else { - usage, usageReported, err = transcodeStreamWithUsageContext(r.Context(), w, resp.Body, upstreamRoute.Protocol, external, model) + usage, usageReported, err = wire.TranscodeStream(r.Context(), w, resp.Body, upstreamRoute.Protocol, external, model) } if meta != nil { meta.Usage, meta.UsageReported = usage, usageReported if err != nil { meta.Outcome = "stream_error" - if streamClientCancelled(r.Context(), err) { + if wire.ClientCanceled(r.Context(), err) { meta.Outcome = "client_canceled" } } @@ -205,17 +213,17 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { } 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) + wire.WriteError(w, external, http.StatusBadGateway, "failed to read upstream response", "upstream_error", ids.Request) return } - if usage, reported := extractResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil { + if usage, reported := wire.ResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil { meta.Usage, meta.UsageReported = usage, reported } if external != upstreamRoute.Protocol { - responseBody, err = convertResponse(upstreamRoute.Protocol, external, responseBody) + responseBody, err = wire.ConvertResponse(upstreamRoute.Protocol, external, responseBody) if err != nil { g.logger.Warn("response protocol conversion failed", "component", "conversion", "event", "response_conversion_failed", "request_id", ids.Request, "model", model, "source_protocol", upstreamRoute.Protocol, "target_protocol", external, "error", err) - writeAPIError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request) + wire.WriteError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request) return } } @@ -225,11 +233,11 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { } } -func (g *Gateway) prepareRouteBodies(from Protocol, route modelRoute, input map[string]any) (map[Tier][]byte, error) { - tiers := make([]Tier, 0, len(route.KeyTiers)+1) - seen := make(map[Tier]bool, len(route.KeyTiers)+1) - addTier := func(tier Tier) { - if tier != TierZen && tier != TierGo || seen[tier] { +func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, input map[string]any) (map[config.Tier][]byte, error) { + tiers := make([]config.Tier, 0, len(route.KeyTiers)+1) + seen := make(map[config.Tier]bool, len(route.KeyTiers)+1) + addTier := func(tier config.Tier) { + if tier != config.TierZen && tier != config.TierGo || seen[tier] { return } seen[tier] = true @@ -242,14 +250,14 @@ func (g *Gateway) prepareRouteBodies(from Protocol, route modelRoute, input map[ if len(tiers) == 0 { return nil, errors.New("no usable upstream tier") } - bodies := make(map[Tier][]byte, len(tiers)) + bodies := make(map[config.Tier][]byte, len(tiers)) for _, tier := range tiers { protocol := route.ProtocolFor(tier) baseURL := g.cfg.Upstream.Zen - if tier == TierGo { + if tier == config.TierGo { baseURL = g.cfg.Upstream.Go } - upstreamPayload, err := prepareUpstreamRequest(from, protocol, input, baseURL) + upstreamPayload, err := wire.PrepareRequest(from, protocol, input, baseURL) if err != nil { if tier != route.Tier { // A fallback tier may use a stricter wire format than the @@ -269,7 +277,7 @@ func (g *Gateway) prepareRouteBodies(from Protocol, route modelRoute, input map[ return bodies, nil } -func copyErrorResponse(w http.ResponseWriter, protocol Protocol, resp *http.Response, requestID string) { +func copyErrorResponse(w http.ResponseWriter, protocol wire.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) @@ -277,41 +285,7 @@ func copyErrorResponse(w http.ResponseWriter, protocol Protocol, resp *http.Resp 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) + message = jsonutil.FirstString(jsonutil.StringAt(value, "error", "message"), jsonutil.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 handler panicked", "component", "http", "event", "request_panic", "error", value) - writeAPIError(w, ProtocolChat, http.StatusInternalServerError, "internal server error", "server_error", "") - } - }() - next.ServeHTTP(w, r) - }) + wire.WriteError(w, protocol, resp.StatusCode, message, "upstream_error", requestID) } diff --git a/gateway_health.go b/internal/gateway/health.go similarity index 91% rename from gateway_health.go rename to internal/gateway/health.go index ec7c49b..929f2d8 100644 --- a/gateway_health.go +++ b/internal/gateway/health.go @@ -1,8 +1,12 @@ -package main +package gateway import ( "net/http" "time" + + "opencode2api/internal/buildinfo" + "opencode2api/internal/httpx" + modelcatalog "opencode2api/internal/models" ) type healthResponse struct { @@ -83,10 +87,10 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { status = "starting" } } - writeJSON(w, httpStatus, healthResponse{ + httpx.WriteJSON(w, httpStatus, healthResponse{ Status: status, Ready: ready, - Version: version, + Version: buildinfo.Version, Models: healthModels{ Status: modelStatus, Total: models.Total, @@ -108,7 +112,7 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { }) } -func (g *Gateway) availableModels() ([]modelRoute, modelCatalogSnapshot) { +func (g *Gateway) availableModels() ([]modelcatalog.Route, modelcatalog.CatalogSnapshot) { return g.catalog.AvailableModels(g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) } @@ -149,5 +153,5 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { } data = append(data, entry) } - writeJSON(w, http.StatusOK, map[string]any{"object": "list", "data": data}) + httpx.WriteJSON(w, http.StatusOK, map[string]any{"object": "list", "data": data}) } diff --git a/pool.go b/internal/gateway/pool.go similarity index 96% rename from pool.go rename to internal/gateway/pool.go index d757b7a..8605310 100644 --- a/pool.go +++ b/internal/gateway/pool.go @@ -1,4 +1,4 @@ -package main +package gateway import ( "context" @@ -6,7 +6,7 @@ import ( "fmt" "hash/fnv" "io" - "math/rand/v2" + rand "math/rand/v2" "net" "net/http" "net/url" @@ -16,6 +16,9 @@ import ( "sync/atomic" "syscall" "time" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" ) type proxyTransport struct { @@ -147,7 +150,7 @@ func (p *transportPool) healthCounts() (total, healthy int) { return len(p.items), healthy } -func newTransportPool(proxies []string, cfg PerformanceConfig, responseHeaderTimeout time.Duration) (*transportPool, error) { +func newTransportPool(proxies []string, cfg config.PerformanceConfig, responseHeaderTimeout time.Duration) (*transportPool, error) { p := &transportPool{items: make([]*proxyTransport, 0, len(proxies))} for _, raw := range proxies { transport := http.DefaultTransport.(*http.Transport).Clone() @@ -166,7 +169,7 @@ func newTransportPool(proxies []string, cfg PerformanceConfig, responseHeaderTim } else { u, err := url.Parse(raw) if err != nil { - return nil, fmt.Errorf("parse proxy %s: %w", redactURL(raw), err) + return nil, fmt.Errorf("parse proxy %s: %w", config.RedactURL(raw), err) } transport.Proxy = http.ProxyURL(u) } @@ -220,7 +223,7 @@ func (p *transportPool) checkClaimedProxy(ctx context.Context, proxy *proxyTrans defer cancel() req, err := http.NewRequestWithContext(checkCtx, http.MethodGet, target, nil) if err == nil { - req.Header.Set("User-Agent", opencodeUserAgent()) + req.Header.Set("User-Agent", httpx.UserAgent()) resp, requestErr := proxy.client.Do(req) err = requestErr if resp != nil { @@ -335,7 +338,7 @@ func (p *nodePool) NodeByID(id string) *upstreamNode { return nil } for _, node := range p.nodes { - if secretFingerprint(node.key) == id { + if config.Fingerprint(node.key) == id { return node } } @@ -493,11 +496,3 @@ func parseRetryAfter(value string) time.Duration { } 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/gateway_refresh.go b/internal/gateway/refresh.go similarity index 82% rename from gateway_refresh.go rename to internal/gateway/refresh.go index e431fa7..b3d843a 100644 --- a/gateway_refresh.go +++ b/internal/gateway/refresh.go @@ -1,4 +1,4 @@ -package main +package gateway import ( "context" @@ -6,6 +6,9 @@ import ( "net/http" "sync" "time" + + "opencode2api/internal/config" + modelcatalog "opencode2api/internal/models" ) const ( @@ -68,7 +71,7 @@ func (g *Gateway) rebindUnavailableProxy(proxy *proxyTransport, wasHealthy bool) zenMoved = g.zenNodes.RebindProxy(proxy.index) goMoved = g.goNodes.RebindProxy(proxy.index) if wasHealthy || zenMoved+goMoved > 0 { - g.logger.Warn("proxy became unavailable", "component", "proxy", "event", "proxy_unavailable", "proxy", redactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved) + g.logger.Warn("proxy became unavailable", "component", "proxy", "event", "proxy_unavailable", "proxy", config.RedactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved) } return zenMoved, goMoved } @@ -80,7 +83,7 @@ func (g *Gateway) restoreProxy(proxy *proxyTransport) (zenMoved, goMoved int) { zenMoved = g.zenNodes.RestoreProxy(proxy.index) goMoved = g.goNodes.RestoreProxy(proxy.index) if zenMoved+goMoved > 0 { - g.logger.Info("proxy connectivity restored", "component", "proxy", "event", "proxy_restored", "proxy", redactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved) + g.logger.Info("proxy connectivity restored", "component", "proxy", "event", "proxy_restored", "proxy", config.RedactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved) } return zenMoved, goMoved } @@ -111,27 +114,27 @@ func (g *Gateway) applyProxyHealthResult(result proxyHealthResult, source string if !result.wasHealthy { g.restoreProxy(result.proxy) } - g.logger.Debug("proxy health check passed", "component", "proxy", "event", "health_check_passed", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name)) + g.logger.Debug("proxy health check passed", "component", "proxy", "event", "health_check_passed", "source", source, "upstream_status", upstreamStatus, "proxy", config.RedactURL(result.proxy.name)) return } if !result.failed { - g.logger.Debug("proxy health check was inconclusive", "component", "proxy", "event", "health_check_inconclusive", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "error", result.err) + g.logger.Debug("proxy health check was inconclusive", "component", "proxy", "event", "health_check_inconclusive", "source", source, "upstream_status", upstreamStatus, "proxy", config.RedactURL(result.proxy.name), "error", result.err) return } if g.transports.hasHealthy() { zenMoved, goMoved := g.rebindUnavailableProxy(result.proxy, result.wasHealthy) if result.wasHealthy || zenMoved+goMoved > 0 { - g.logger.Warn("proxy health check failed", "component", "proxy", "event", "health_check_failed", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved, "error", result.err) + g.logger.Warn("proxy health check failed", "component", "proxy", "event", "health_check_failed", "source", source, "upstream_status", upstreamStatus, "proxy", config.RedactURL(result.proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved, "error", result.err) return } } - g.logger.Debug("proxy health check is still failing", "component", "proxy", "event", "health_check_still_failing", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "error", result.err) + g.logger.Debug("proxy health check is still failing", "component", "proxy", "event", "health_check_still_failing", "source", source, "upstream_status", upstreamStatus, "proxy", config.RedactURL(result.proxy.name), "error", result.err) } func (g *Gateway) StartModelRefresh(ctx context.Context) { refresh := func() { var zen, goModels []string - var capabilities protocolCapabilities + var capabilities modelcatalog.Capabilities var capabilitiesErr error var wg sync.WaitGroup wg.Add(3) @@ -175,16 +178,16 @@ func (g *Gateway) StartModelRefresh(ctx context.Context) { }() } -func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (protocolCapabilities, error) { +func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (modelcatalog.Capabilities, error) { if g.transports == nil || len(g.transports.items) == 0 { - return fetchProtocolCapabilities(ctx, &http.Client{Timeout: 30 * time.Second}, openCodeCapabilitiesURL) + return modelcatalog.FetchCapabilities(ctx, &http.Client{Timeout: 30 * time.Second}, modelcatalog.CapabilitiesURL) } var lastErr error for _, proxy := range g.transports.items { if proxy == nil || !proxy.healthy.Load() { continue } - capabilities, err := fetchProtocolCapabilities(ctx, proxy.client, openCodeCapabilitiesURL) + capabilities, err := modelcatalog.FetchCapabilities(ctx, proxy.client, modelcatalog.CapabilitiesURL) if err == nil { return capabilities, nil } @@ -193,7 +196,7 @@ func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (protocolCapa if lastErr == nil { lastErr = errors.New("no healthy proxy available for OpenCode capability catalog") } - return protocolCapabilities{}, lastErr + return modelcatalog.Capabilities{}, lastErr } func (g *Gateway) refreshZen(ctx context.Context) []string { @@ -215,7 +218,7 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin break } refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) - models, status, err := fetchModels(refreshCtx, node.proxy.client, base, anonymousZenKey) + models, status, err := modelcatalog.FetchModels(refreshCtx, node.proxy.client, base, anonymousZenKey) g.syncProxyResult(refreshCtx, node.proxy, status, err) cancel() if err == nil { @@ -223,9 +226,9 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin return models } g.anonymous.MarkFailure(node, nil, err) - g.logger.Debug("anonymous model catalog refresh attempt failed", "component", "models", "event", "anonymous_refresh_attempt_failed", "upstream", redactURL(base), "attempt", attempt, "proxy", redactURL(node.proxy.name), "error", err) + g.logger.Debug("anonymous model catalog refresh attempt failed", "component", "models", "event", "anonymous_refresh_attempt_failed", "upstream", config.RedactURL(base), "attempt", attempt, "proxy", config.RedactURL(node.proxy.name), "error", err) } - g.logger.Warn("anonymous model catalog refresh failed", "component", "models", "event", "anonymous_refresh_failed", "upstream", redactURL(base)) + g.logger.Warn("anonymous model catalog refresh failed", "component", "models", "event", "anonymous_refresh_failed", "upstream", config.RedactURL(base)) return nil } @@ -242,7 +245,7 @@ func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool) cancel() return nil } - models, status, err := fetchModels(refreshCtx, proxy.client, base, node.key) + models, status, err := modelcatalog.FetchModels(refreshCtx, proxy.client, base, node.key) g.syncProxyResult(refreshCtx, proxy, status, err) cancel() if err == nil { @@ -250,8 +253,8 @@ func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool) return models } nodes.MarkFailure(node, nil, err) - g.logger.Debug("model catalog refresh attempt failed", "component", "models", "event", "refresh_attempt_failed", "upstream", redactURL(base), "attempt", attempt+1, "error", err) + g.logger.Debug("model catalog refresh attempt failed", "component", "models", "event", "refresh_attempt_failed", "upstream", config.RedactURL(base), "attempt", attempt+1, "error", err) } - g.logger.Warn("model catalog refresh failed", "component", "models", "event", "refresh_failed", "upstream", redactURL(base)) + g.logger.Warn("model catalog refresh failed", "component", "models", "event", "refresh_failed", "upstream", config.RedactURL(base)) return nil } diff --git a/runtime.go b/internal/gateway/runtime.go similarity index 68% rename from runtime.go rename to internal/gateway/runtime.go index b0ba957..2b97c50 100644 --- a/runtime.go +++ b/internal/gateway/runtime.go @@ -1,9 +1,7 @@ -package main +package gateway import ( "context" - "crypto/sha256" - "encoding/hex" "fmt" "log/slog" "net/http" @@ -11,10 +9,15 @@ import ( "sync" "sync/atomic" "time" + + "opencode2api/internal/config" + modelcatalog "opencode2api/internal/models" + "opencode2api/internal/protocol" + "opencode2api/internal/telemetry" ) type gatewayRuntime struct { - config Config + config config.Config gateway *Gateway handler http.Handler cancel context.CancelFunc @@ -30,14 +33,14 @@ type RuntimeManager struct { configPath string root context.Context logger *slog.Logger - monitor *Monitor - hub *LogHub - redactor *SecretRedactor + monitor *telemetry.Monitor + hub *telemetry.LogHub + redactor *config.SecretRedactor level *slog.LevelVar current atomic.Pointer[gatewayRuntime] updateMu sync.Mutex effective effectiveListeners - metadata *modelMetadataStore + metadata *modelcatalog.PricingStore } type effectiveListeners struct { @@ -46,12 +49,12 @@ type effectiveListeners struct { WebUIEnabled bool } -func NewRuntimeManager(root context.Context, configPath string, cfg Config, logger *slog.Logger, monitor *Monitor, hub *LogHub, redactor *SecretRedactor, level *slog.LevelVar) (*RuntimeManager, error) { +func NewRuntimeManager(root context.Context, configPath string, cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor, hub *telemetry.LogHub, redactor *config.SecretRedactor, level *slog.LevelVar) (*RuntimeManager, error) { manager := &RuntimeManager{ configPath: configPath, root: root, logger: logger, monitor: monitor, hub: hub, redactor: redactor, level: level, effective: effectiveListeners{API: cfg.Listen, WebUI: cfg.WebUI.Listen, WebUIEnabled: cfg.WebUI.Enabled}, } - manager.metadata = newModelMetadataStore(configPath, logger) + manager.metadata = modelcatalog.NewPricingStore(configPath, logger) // models.dev refreshes ride the active runtime's healthy proxy transports // and fall back to the store's direct client when none are available. manager.metadata.SetClientProvider(func() []*http.Client { @@ -68,13 +71,13 @@ func NewRuntimeManager(root context.Context, configPath string, cfg Config, logg return clients }) if cfg.WebUI.Password != "" { - hash, err := hashPassword(cfg.WebUI.Password) + hash, err := config.HashPassword(cfg.WebUI.Password) if err != nil { return nil, fmt.Errorf("hash webui password: %w", err) } cfg.WebUI.PasswordHash = hash cfg.WebUI.Password = "" - if err := SaveConfigAtomic(configPath, cfg); err != nil { + if err := config.SaveAtomic(configPath, cfg); err != nil { return nil, fmt.Errorf("persist webui password migration: %w", err) } // The automatically-created backup contains the one-time plaintext @@ -85,26 +88,26 @@ func NewRuntimeManager(root context.Context, configPath string, cfg Config, logg if err != nil { return nil, err } - if err := runtime.gateway.catalog.LoadCache(modelCatalogCachePath(configPath)); err != nil && !os.IsNotExist(err) { + if err := runtime.gateway.catalog.LoadCache(modelcatalog.CatalogCachePath(configPath)); err != nil && !os.IsNotExist(err) { if manager.logger != nil { - manager.logger.Warn("model catalog cache ignored", "component", "models", "event", "catalog_cache_load_failed", "path", modelCatalogCachePath(configPath), "error", err) + manager.logger.Warn("model catalog cache ignored", "component", "models", "event", "catalog_cache_load_failed", "path", modelcatalog.CatalogCachePath(configPath), "error", err) } } manager.current.Store(runtime) manager.redactor.Replace(cfg) - setLogLevel(manager.level, cfg.Logging.Level) + telemetry.SetLogLevel(manager.level, cfg.Logging.Level) manager.start(runtime) manager.metadata.Start(root) return manager, nil } -func (m *RuntimeManager) build(cfg Config) (*gatewayRuntime, error) { - gateway, err := NewGateway(cfg, m.logger, m.monitor) +func (m *RuntimeManager) build(cfg config.Config) (*gatewayRuntime, error) { + gateway, err := New(cfg, m.logger, m.monitor) if err != nil { return nil, err } - gateway.catalog.metadata = m.metadata - gateway.catalog.SetCachePath(modelCatalogCachePath(m.configPath)) + gateway.catalog.SetPricingStore(m.metadata) + gateway.catalog.SetCachePath(modelcatalog.CatalogCachePath(m.configPath)) return &gatewayRuntime{config: cfg, gateway: gateway, handler: gateway.Handler(), cancel: func() {}}, nil } @@ -126,15 +129,20 @@ func (m *RuntimeManager) Handler() http.Handler { } runtime.handler.ServeHTTP(w, r) }) - return monitorMiddleware(m.monitor, m.logger, dynamic) + return telemetry.Middleware(m.monitor, m.logger, dynamic) } -func (m *RuntimeManager) Config() Config { +// Redact removes configured credentials from diagnostic output. +func (m *RuntimeManager) Redact(value string) string { + return m.redactor.String(value) +} + +func (m *RuntimeManager) Config() config.Config { runtime := m.current.Load() if runtime == nil { - return Config{} + return config.Config{} } - return cloneConfig(runtime.config) + return config.Clone(runtime.config) } func (m *RuntimeManager) RestartStatus() (effectiveListeners, []string) { @@ -152,37 +160,21 @@ func (m *RuntimeManager) RestartStatus() (effectiveListeners, []string) { return m.effective, fields } -func cloneConfig(cfg Config) Config { - cfg.ServerKeys = append([]string(nil), cfg.ServerKeys...) - cfg.ZenKeys = append([]string(nil), cfg.ZenKeys...) - cfg.GoKeys = append([]string(nil), cfg.GoKeys...) - cfg.Proxies = append([]string(nil), cfg.Proxies...) - cfg.effectiveProxies = append([]string(nil), cfg.effectiveProxies...) - if cfg.Models.Protocols != nil { - protocols := make(map[string]string, len(cfg.Models.Protocols)) - for key, value := range cfg.Models.Protocols { - protocols[key] = value - } - cfg.Models.Protocols = protocols - } - return cfg -} - -func (m *RuntimeManager) Apply(candidate Config, persist bool) (ApplyResult, error) { +func (m *RuntimeManager) Apply(candidate config.Config, persist bool) (ApplyResult, error) { m.updateMu.Lock() defer m.updateMu.Unlock() current := m.current.Load() hadPlaintextPassword := candidate.WebUI.Password != "" if hadPlaintextPassword { - hash, err := hashPassword(candidate.WebUI.Password) + hash, err := config.HashPassword(candidate.WebUI.Password) if err != nil { return ApplyResult{}, err } candidate.WebUI.PasswordHash = hash candidate.WebUI.Password = "" } - normalized, err := NormalizeConfig(m.configPath, candidate) + normalized, err := config.Normalize(m.configPath, candidate) if err != nil { return ApplyResult{}, err } @@ -194,7 +186,7 @@ func (m *RuntimeManager) Apply(candidate Config, persist bool) (ApplyResult, err next.gateway.catalog.CopyState(current.gateway.catalog) } if persist || hadPlaintextPassword { - if err := SaveConfigAtomic(m.configPath, normalized); err != nil { + if err := config.SaveAtomic(m.configPath, normalized); err != nil { next.cancel() return ApplyResult{}, err } @@ -212,7 +204,7 @@ func (m *RuntimeManager) Apply(candidate Config, persist bool) (ApplyResult, err } result.RestartRequired = len(result.RestartFields) > 0 m.redactor.Replace(normalized) - setLogLevel(m.level, normalized.Logging.Level) + telemetry.SetLogLevel(m.level, normalized.Logging.Level) if current == nil || normalized.Logging.RingSize != current.config.Logging.RingSize { m.hub.Resize(normalized.Logging.RingSize) } @@ -226,7 +218,7 @@ func (m *RuntimeManager) Apply(candidate Config, persist bool) (ApplyResult, err } func (m *RuntimeManager) Reload() (ApplyResult, error) { - cfg, err := LoadConfig(m.configPath) + cfg, err := config.Load(m.configPath) if err != nil { return ApplyResult{}, err } @@ -245,11 +237,11 @@ func (m *RuntimeManager) Shutdown() { } type ResourceSnapshot struct { - Models modelCatalogSnapshot `json:"models"` - Keys []KeyStatus `json:"keys"` - Proxies []ProxyStatus `json:"proxies"` - Anonymous bool `json:"anonymous"` - Metadata MetadataSnapshot `json:"metadata"` + Models modelcatalog.CatalogSnapshot `json:"models"` + Keys []KeyStatus `json:"keys"` + Proxies []ProxyStatus `json:"proxies"` + Anonymous bool `json:"anonymous"` + Metadata modelcatalog.MetadataSnapshot `json:"metadata"` } type KeyStatus struct { @@ -279,9 +271,7 @@ func (m *RuntimeManager) Resources() ResourceSnapshot { gateway := runtime.gateway _, models := gateway.availableModels() result := ResourceSnapshot{Models: models, Anonymous: gateway.cfg.Anonymous} - if gateway.catalog.metadata != nil { - result.Metadata = gateway.catalog.metadata.Snapshot() - } + result.Metadata = gateway.catalog.MetadataSnapshot() result.Keys = append(result.Keys, keyStatuses("zen", gateway.zenNodes)...) result.Keys = append(result.Keys, keyStatuses("go", gateway.goNodes)...) gateway.zenNodes.bindingsMu.Lock() @@ -291,7 +281,7 @@ func (m *RuntimeManager) Resources() ResourceSnapshot { goBindings := append([]int(nil), gateway.goNodes.bindingCount...) gateway.goNodes.bindingsMu.Unlock() for _, proxy := range gateway.transports.items { - status := ProxyStatus{Index: proxy.index, Address: redactURL(proxy.name), Healthy: proxy.healthy.Load(), Checking: proxy.checking.Load(), Anonymous: gateway.cfg.Anonymous} + status := ProxyStatus{Index: proxy.index, Address: config.RedactURL(proxy.name), Healthy: proxy.healthy.Load(), Checking: proxy.checking.Load(), Anonymous: gateway.cfg.Anonymous} if proxy.index < len(zenBindings) { status.ZenKeys = zenBindings[proxy.index] } @@ -303,28 +293,25 @@ func (m *RuntimeManager) Resources() ResourceSnapshot { return result } -func (m *RuntimeManager) DebugModels() ([]ModelRouteDiagnostic, MetadataSnapshot) { +func (m *RuntimeManager) DebugModels() ([]modelcatalog.RouteDiagnostic, modelcatalog.MetadataSnapshot) { runtime := m.current.Load() if runtime == nil { - return nil, MetadataSnapshot{} + return nil, modelcatalog.MetadataSnapshot{} } gateway := runtime.gateway models := gateway.catalog.List() - result := make([]ModelRouteDiagnostic, 0, len(models)) + result := make([]modelcatalog.RouteDiagnostic, 0, len(models)) for _, model := range models { result = append(result, gateway.catalog.Diagnostic(model, "", len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0, gateway.cfg.Anonymous)) } - metadata := MetadataSnapshot{} - if gateway.catalog.metadata != nil { - metadata = gateway.catalog.metadata.Snapshot() - } + metadata := gateway.catalog.MetadataSnapshot() return result, metadata } -func (m *RuntimeManager) DebugRoute(model string, requested Protocol) ModelRouteDiagnostic { +func (m *RuntimeManager) DebugRoute(model string, requested protocol.Protocol) modelcatalog.RouteDiagnostic { runtime := m.current.Load() if runtime == nil { - return ModelRouteDiagnostic{Model: model, RequestedProtocol: requested, RouteError: "gateway runtime is unavailable"} + return modelcatalog.RouteDiagnostic{Model: model, RequestedProtocol: requested, RouteError: "gateway runtime is unavailable"} } gateway := runtime.gateway return gateway.catalog.Diagnostic(model, requested, len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0, gateway.cfg.Anonymous) @@ -333,12 +320,12 @@ func (m *RuntimeManager) DebugRoute(model string, requested Protocol) ModelRoute // DebugKeyView is the operator-facing view of one configured upstream key. It // carries only the redacted suffix and the stable fingerprint, never the value. type DebugKeyView struct { - ID string `json:"id"` - Tier Tier `json:"tier"` - Display string `json:"display"` - Index int `json:"index"` - Failures uint32 `json:"failures"` - CooldownUntil *time.Time `json:"cooldown_until,omitempty"` + ID string `json:"id"` + Tier config.Tier `json:"tier"` + Display string `json:"display"` + Index int `json:"index"` + Failures uint32 `json:"failures"` + CooldownUntil *time.Time `json:"cooldown_until,omitempty"` } // DebugKeys lists every configured upstream key per tier so the Playground can @@ -349,10 +336,10 @@ func (m *RuntimeManager) DebugKeys() map[string][]DebugKeyView { if runtime == nil { return result } - appendKeys := func(tier Tier, nodes []*upstreamNode) { + appendKeys := func(tier config.Tier, nodes []*upstreamNode) { for _, node := range nodes { view := DebugKeyView{ - ID: secretFingerprint(node.key), Tier: tier, Display: maskValue(node.key), + ID: config.Fingerprint(node.key), Tier: tier, Display: config.MaskValue(node.key), Index: node.index, Failures: node.failures.Load(), } if until := node.cooldownUntil.Load(); until > time.Now().UnixNano() { @@ -362,12 +349,12 @@ func (m *RuntimeManager) DebugKeys() map[string][]DebugKeyView { result[string(tier)] = append(result[string(tier)], view) } } - appendKeys(TierZen, runtime.gateway.zenNodes.nodes) - appendKeys(TierGo, runtime.gateway.goNodes.nodes) + appendKeys(config.TierZen, runtime.gateway.zenNodes.nodes) + appendKeys(config.TierGo, runtime.gateway.goNodes.nodes) return result } -func (m *RuntimeManager) DebugKey(tier Tier, id string) *DebugKeyView { +func (m *RuntimeManager) DebugKey(tier config.Tier, id string) *DebugKeyView { for _, view := range m.DebugKeys()[string(tier)] { if view.ID == id { selected := view @@ -378,10 +365,10 @@ func (m *RuntimeManager) DebugKey(tier Tier, id string) *DebugKeyView { } // DebugRouteForTier reports the route a diagnostic against one tier would take. -func (m *RuntimeManager) DebugRouteForTier(model string, tier Tier) (ModelRouteDiagnostic, error) { +func (m *RuntimeManager) DebugRouteForTier(model string, tier config.Tier) (modelcatalog.RouteDiagnostic, error) { runtime := m.current.Load() if runtime == nil { - return ModelRouteDiagnostic{Model: model, RouteError: "gateway runtime is unavailable"}, fmt.Errorf("gateway runtime is unavailable") + return modelcatalog.RouteDiagnostic{Model: model, RouteError: "gateway runtime is unavailable"}, fmt.Errorf("gateway runtime is unavailable") } gateway := runtime.gateway hasZen, hasGo := len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0 @@ -393,7 +380,7 @@ func (m *RuntimeManager) DebugRouteForTier(model string, tier Tier) (ModelRouteD } diagnostic.RouteError = "" diagnostic.Tier, diagnostic.Anonymous = route.Tier, false - diagnostic.KeyTiers = []Tier{tier} + diagnostic.KeyTiers = []config.Tier{tier} diagnostic.NativeProtocol, diagnostic.NativeProtocols = route.Protocol, route.Protocols return diagnostic, nil } @@ -401,7 +388,7 @@ func (m *RuntimeManager) DebugRouteForTier(model string, tier Tier) (ModelRouteD func keyStatuses(tier string, pool *nodePool) []KeyStatus { result := make([]KeyStatus, 0, len(pool.nodes)) for _, node := range pool.nodes { - status := KeyStatus{ID: keyDisplayID(node.key), Tier: tier, Index: node.index, ProxyIndex: int(node.proxyIndex.Load()), Failures: node.failures.Load()} + status := KeyStatus{ID: config.KeyDisplayID(node.key), Tier: tier, Index: node.index, ProxyIndex: int(node.proxyIndex.Load()), Failures: node.failures.Load()} if until := node.cooldownUntil.Load(); until > time.Now().UnixNano() { value := time.Unix(0, until).UTC() status.CooldownUntil = &value @@ -410,19 +397,3 @@ func keyStatuses(tier string, pool *nodePool) []KeyStatus { } return result } - -func secretFingerprint(value string) string { - sum := sha256.Sum256([]byte(value)) - return hex.EncodeToString(sum[:])[:10] -} - -// keyDisplayID is intentionally separate from secretFingerprint. The latter -// is an internal stable identifier used by session/config bookkeeping; this -// value is safe for logs and the operator UI and shows only the key suffix. -func keyDisplayID(value string) string { - runes := []rune(value) - if len(runes) <= 5 { - return string(runes) - } - return string(runes[len(runes)-5:]) -} diff --git a/upstream.go b/internal/gateway/upstream.go similarity index 81% rename from upstream.go rename to internal/gateway/upstream.go index e29409c..e065cd0 100644 --- a/upstream.go +++ b/internal/gateway/upstream.go @@ -1,4 +1,4 @@ -package main +package gateway import ( "bytes" @@ -13,12 +13,20 @@ import ( "sort" "strings" "time" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" + "opencode2api/internal/identity" + "opencode2api/internal/jsonutil" + "opencode2api/internal/models" + wire "opencode2api/internal/protocol" + "opencode2api/internal/telemetry" ) -// debugKeyOverride pins one inference request to a single configured upstream +// DebugKeyOverride pins one inference request to a single configured upstream // key so the Playground can exercise that key in isolation. -type debugKeyOverride struct { - Tier Tier +type DebugKeyOverride struct { + Tier config.Tier KeyID string } @@ -26,7 +34,7 @@ type debugKeyOverrideContextKey struct{} type diagnosticContextKey struct{} -func withDiagnosticRequest(ctx context.Context) context.Context { +func WithDiagnosticRequest(ctx context.Context) context.Context { return context.WithValue(ctx, diagnosticContextKey{}, true) } @@ -35,16 +43,16 @@ func isDiagnosticRequest(ctx context.Context) bool { return diagnostic } -func withDebugKeyOverride(ctx context.Context, override debugKeyOverride) context.Context { - return context.WithValue(withDiagnosticRequest(ctx), debugKeyOverrideContextKey{}, override) +func WithDebugKeyOverride(ctx context.Context, override DebugKeyOverride) context.Context { + return context.WithValue(WithDiagnosticRequest(ctx), debugKeyOverrideContextKey{}, override) } -func debugKeyOverrideFrom(ctx context.Context) (debugKeyOverride, bool) { - override, ok := ctx.Value(debugKeyOverrideContextKey{}).(debugKeyOverride) +func debugKeyOverrideFrom(ctx context.Context) (DebugKeyOverride, bool) { + override, ok := ctx.Value(debugKeyOverrideContextKey{}).(DebugKeyOverride) return override, ok && override.KeyID != "" } -func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs) (*http.Response, modelRoute, error) { +func (g *Gateway) doUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs) (*http.Response, models.Route, error) { resp, effectiveRoute, attempts, err := g.doUpstreamTiers(ctx, route, bodies, ids, 0) if _, selected := debugKeyOverrideFrom(ctx); selected { return resp, effectiveRoute, err @@ -57,7 +65,7 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, bodies map[T // The original network body is always closed here: the retry path below // reuses the connection, otherwise downstream receives a fresh in-memory // reader over the cached bytes. - drainAndClose(origBody) + httpx.DrainAndClose(origBody) if readErr != nil { resp.Body = io.NopCloser(bytes.NewReader(errBody)) return resp, effectiveRoute, nil @@ -89,7 +97,7 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, bodies map[T retryStatus := 0 if retryResp != nil { retryStatus = retryResp.StatusCode - drainAndClose(retryResp.Body) + httpx.DrainAndClose(retryResp.Body) } g.logger.Warn("reasoning reference retry failed; returning original error", "component", "upstream", "event", "reasoning_reference_retry_failed", "request_id", ids.Request, "model", route.ID, "tier", effectiveRoute.Tier, "error", retryErr, "retry_status", retryStatus) fallback := *resp @@ -122,11 +130,11 @@ func isStaleReasoningReference(body []byte) bool { // Responses-protocol upstream payloads: replayed "reasoning" input items and // any previous_response_id chain link. Other tiers/protocols are passed // through untouched. It reports whether any payload actually changed. -func stripStaleReasoningInputs(route modelRoute, bodies map[Tier][]byte) (map[Tier][]byte, bool) { +func stripStaleReasoningInputs(route models.Route, bodies map[config.Tier][]byte) (map[config.Tier][]byte, bool) { changed := false - out := make(map[Tier][]byte, len(bodies)) + out := make(map[config.Tier][]byte, len(bodies)) for tier, body := range bodies { - if len(body) == 0 || route.ProtocolFor(tier) != ProtocolResponses { + if len(body) == 0 || route.ProtocolFor(tier) != wire.Responses { out[tier] = body continue } @@ -143,7 +151,7 @@ func stripStaleReasoningInputs(route modelRoute, bodies map[Tier][]byte) (map[Ti if raw, ok := payload["input"].([]any); ok { kept := make([]any, 0, len(raw)) for _, item := range raw { - if m, ok := item.(map[string]any); ok && stringAt(m, "type") == "reasoning" { + if m, ok := item.(map[string]any); ok && jsonutil.StringAt(m, "type") == "reasoning" { tierChanged = true continue } @@ -168,7 +176,7 @@ func stripStaleReasoningInputs(route modelRoute, bodies map[Tier][]byte) (map[Ti return out, changed } -func (g *Gateway) doUpstreamTiers(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs, attemptOffset int) (*http.Response, modelRoute, int, error) { +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) { var lastResponse *http.Response var lastErr error effectiveRoute := route @@ -203,12 +211,12 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route modelRoute, bodies } keyTiers := route.KeyTiers - if !route.Anonymous && len(keyTiers) == 0 && (route.Tier == TierZen || route.Tier == TierGo) { - keyTiers = []Tier{route.Tier} + if !route.Anonymous && len(keyTiers) == 0 && (route.Tier == config.TierZen || route.Tier == config.TierGo) { + keyTiers = []config.Tier{route.Tier} } for _, tier := range keyTiers { if lastResponse != nil { - drainAndClose(lastResponse.Body) + httpx.DrainAndClose(lastResponse.Body) lastResponse = nil } keyRoute := route @@ -236,13 +244,13 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route modelRoute, bodies // failure, including an HTTP error response, advances to the next proxy. Only a // successful response ends the anonymous phase; exhausting the proxy cursor // returns control to the preferred authenticated tiers. -func (g *Gateway) doAnonymousUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids 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) (*http.Response, error, int) { var lastResponse *http.Response var lastErr error cursor := g.anonymous.CursorFor(ids.Session) limit := g.anonymous.Len() attempts := 0 - body := bodies[TierZen] + body := bodies[config.TierZen] if len(body) == 0 { return nil, errors.New("no prepared Zen request body"), 0 } @@ -261,19 +269,19 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route modelRoute, bod break } attempts++ - if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil { + if meta := telemetry.MetaFromContext(ctx); meta != nil { meta.Attempts = attemptOffset + attempts - meta.Tier = string(TierZen) + meta.Tier = string(config.TierZen) } if lastResponse != nil { - drainAndClose(lastResponse.Body) + httpx.DrainAndClose(lastResponse.Body) lastResponse = nil } req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Zen, route.Protocol, body, ids, anonymousZenKey) if err != nil { return nil, err, attempts } - setRequestCredential(ctx, TierZen, "anonymous", "anonymous", true, node.proxy) + setRequestCredential(ctx, config.TierZen, "anonymous", "anonymous", true, node.proxy) started := time.Now() resp, err := node.proxy.client.Do(req) duration := time.Since(started) @@ -290,15 +298,15 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route modelRoute, bod g.observeAnonymousResult(ctx, node, resp, err) g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, node.proxy, resp, err, duration) if err == nil && resp.StatusCode/100 == 2 { - g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", TierZen, "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", redactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) + g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "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 = 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", TierZen, "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", redactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err) + g.logger.Debug("anonymous transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err) } else { - g.logger.Debug("anonymous upstream returned an error response; trying the next proxy", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", TierZen, "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", redactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) + g.logger.Debug("anonymous upstream returned an error response; trying the next proxy", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) } } if lastResponse != nil { @@ -319,7 +327,7 @@ const requestBodyDumpLimit = 64 << 10 // diagnosed without patching the binary. Credentials travel in headers and never // in the body. The logger redacts configured secrets, but conversation content // can still be sensitive. Reference IDs are retained for replay diagnostics. -func (g *Gateway) dumpOutboundBodies(route modelRoute, bodies map[Tier][]byte, ids requestIDs, attemptOffset int) { +func (g *Gateway) dumpOutboundBodies(route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) { if !g.cfg.Logging.DumpRequestBodies || len(bodies) == 0 { return } @@ -333,7 +341,7 @@ func (g *Gateway) dumpOutboundBodies(route modelRoute, bodies map[Tier][]byte, i } sort.Strings(tiers) for _, name := range tiers { - tier := Tier(name) + tier := config.Tier(name) body := bodies[tier] if len(body) == 0 { continue @@ -357,10 +365,10 @@ func (g *Gateway) dumpOutboundBodies(route modelRoute, bodies map[Tier][]byte, i // untouched on purpose: a diagnostic request must never cool a production key or // evict a proxy, which is exactly what made a bad Playground request degrade // live traffic before. -func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs, override debugKeyOverride, attemptOffset int) (*http.Response, error, int) { +func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, override DebugKeyOverride, attemptOffset int) (*http.Response, error, int) { nodes := g.zenNodes baseURL := g.cfg.Upstream.Zen - if override.Tier == TierGo { + if override.Tier == config.TierGo { nodes = g.goNodes baseURL = g.cfg.Upstream.Go } @@ -376,11 +384,11 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route modelRoute, b if proxy == nil { return nil, errors.New("selected upstream key has no proxy binding"), 0 } - if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil { + if meta := telemetry.MetaFromContext(ctx); meta != nil { meta.Attempts = attemptOffset + 1 meta.Tier = string(override.Tier) } - keyID := keyDisplayID(node.key) + keyID := config.KeyDisplayID(node.key) setRequestCredential(ctx, override.Tier, keyID, "key", false, proxy) req, err := newUpstreamRequest(ctx, baseURL, route.ProtocolFor(override.Tier), body, ids, node.key) if err != nil { @@ -396,12 +404,12 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route modelRoute, b return resp, nil, 1 } -func (g *Gateway) doKeyUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids 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) (*http.Response, error, int) { var lastResponse *http.Response var lastErr error nodes := g.zenNodes baseURL := g.cfg.Upstream.Zen - if route.Tier == TierGo { + if route.Tier == config.TierGo { nodes = g.goNodes baseURL = g.cfg.Upstream.Go } @@ -430,12 +438,12 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route modelRoute, bodies ma attempts++ // Keep the request-level trace synchronized with the attempt that is // about to be sent. Only the redacted key suffix is retained. - if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil { + if meta := telemetry.MetaFromContext(ctx); meta != nil { meta.Attempts = attemptOffset + attempts meta.Tier = string(route.Tier) } if lastResponse != nil { - drainAndClose(lastResponse.Body) + httpx.DrainAndClose(lastResponse.Body) lastResponse = nil } req, err := newUpstreamRequest(ctx, baseURL, route.Protocol, body, ids, node.key) @@ -447,7 +455,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route modelRoute, bodies ma lastErr = errors.New("upstream key has no proxy binding") break } - keyID := keyDisplayID(node.key) + keyID := config.KeyDisplayID(node.key) setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy) attemptStarted := time.Now() resp, err := proxy.client.Do(req) @@ -466,7 +474,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route modelRoute, bodies ma g.observeKeyResult(ctx, nodes, node, proxy, resp, err) g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, keyID, "key", false, proxy, resp, err, attemptDuration) if err == nil && resp.StatusCode/100 == 2 { - g.logger.Debug("upstream accepted request", "component", "upstream", "event", "attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", redactURL(proxy.name), "status", resp.StatusCode, "duration_ms", attemptDuration.Milliseconds()) + g.logger.Debug("upstream accepted request", "component", "upstream", "event", "attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", config.RedactURL(proxy.name), "status", resp.StatusCode, "duration_ms", attemptDuration.Milliseconds()) return resp, nil, attempts } // Request-shape errors are deterministic and must leave this tier without @@ -474,15 +482,15 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route modelRoute, bodies ma // tier in prefer order. Authentication, throttling, server, and transport // failures remain retryable inside this tier. if isNonRetryableClientResponse(resp, err) { - 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", redactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds()) + 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", config.RedactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds()) return resp, nil, attempts } lastResponse = resp lastErr = err if err != nil { - g.logger.Debug("upstream transport attempt failed", "component", "upstream", "event", "attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", redactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds(), "error", err) + g.logger.Debug("upstream transport attempt failed", "component", "upstream", "event", "attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", config.RedactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds(), "error", err) } else { - 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", redactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds()) + 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", config.RedactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds()) } } if lastResponse != nil { @@ -528,8 +536,8 @@ func upstreamStatus(resp *http.Response) int { return resp.StatusCode } -func setRequestCredential(ctx context.Context, tier Tier, keyID, channel string, anonymous bool, proxy *proxyTransport) { - meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta) +func setRequestCredential(ctx context.Context, tier config.Tier, keyID, channel string, anonymous bool, proxy *proxyTransport) { + meta := telemetry.MetaFromContext(ctx) if meta == nil { return } @@ -539,34 +547,19 @@ func setRequestCredential(ctx context.Context, tier Tier, keyID, channel string, meta.Anonymous = anonymous meta.Proxy = "" if proxy != nil { - meta.Proxy = redactURL(proxy.name) + meta.Proxy = config.RedactURL(proxy.name) } } func requestCredential(ctx context.Context) (string, string, bool) { - meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta) + meta := telemetry.MetaFromContext(ctx) if meta == nil { return "", "", false } return meta.KeyID, meta.Channel, meta.Anonymous } -func extractResponseUsage(protocol Protocol, body []byte) (bridgeUsage, bool) { - var payload map[string]any - if json.Unmarshal(body, &payload) != nil { - return bridgeUsage{}, false - } - usage := mapAt(payload, "usage") - if len(usage) == 0 { - return bridgeUsage{}, false - } - if protocol == ProtocolAnthropic { - return decodeAnthropicUsage(usage), true - } - return decodeOpenAIUsage(usage), true -} - -func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route modelRoute, ids requestIDs, attempt int, keyID, channel string, anonymous bool, proxy *proxyTransport, resp *http.Response, err error, duration time.Duration) { +func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route, ids identity.RequestIDs, attempt int, keyID, channel string, anonymous bool, proxy *proxyTransport, resp *http.Response, err error, duration time.Duration) { status := upstreamStatus(resp) success := err == nil && status >= 200 && status < 300 outcome := "retryable_failure" @@ -577,7 +570,7 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route modelRoute, i } else if isNonRetryableClientResponse(resp, nil) { outcome = "rejected" } - if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil { + if meta := telemetry.MetaFromContext(ctx); meta != nil { meta.AttemptOutcome = outcome meta.Protocol = route.Protocol } @@ -586,24 +579,24 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route modelRoute, i } proxyName := "unavailable" if proxy != nil { - proxyName = redactURL(proxy.name) + proxyName = config.RedactURL(proxy.name) } - g.monitor.RecordAttempt(UpstreamAttempt{ + g.monitor.RecordAttempt(telemetry.UpstreamAttempt{ Time: time.Now().UTC(), RequestID: ids.Request, Model: route.ID, Tier: string(route.Tier), Attempt: attempt, KeyID: keyID, Channel: channel, Anonymous: anonymous, Proxy: proxyName, Status: status, DurationMS: max(duration.Milliseconds(), 0), Success: success, Outcome: outcome, }) } -func newUpstreamRequest(ctx context.Context, baseURL string, protocol Protocol, body []byte, ids requestIDs, key string) (*http.Request, error) { - endpoint := strings.TrimRight(baseURL, "/") + protocolPath(protocol) +func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Protocol, body []byte, ids identity.RequestIDs, key string) (*http.Request, error) { + endpoint := strings.TrimRight(baseURL, "/") + wire.Path(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("User-Agent", httpx.UserAgent()) req.Header.Set("x-opencode-client", "cli") req.Header.Set("x-opencode-session", ids.Session) // OpenCode 1.18.x sends these correlation headers to preserve provider-side @@ -616,7 +609,7 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol Protocol, if ids.ParentSession != "" { req.Header.Set("x-parent-session-id", ids.ParentSession) } - if protocol == ProtocolAnthropic { + if protocol == wire.Anthropic { req.Header.Set("x-api-key", key) req.Header.Set("anthropic-version", "2023-06-01") req.Header.Set("anthropic-beta", "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14") @@ -629,14 +622,3 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol Protocol, func isNonRetryableClientResponse(resp *http.Response, err error) bool { return err == nil && resp != nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests } - -func protocolPath(protocol Protocol) string { - switch protocol { - case ProtocolResponses: - return "/v1/responses" - case ProtocolAnthropic: - return "/v1/messages" - default: - return "/v1/chat/completions" - } -} diff --git a/internal/httpx/body.go b/internal/httpx/body.go new file mode 100644 index 0000000..b6f38d3 --- /dev/null +++ b/internal/httpx/body.go @@ -0,0 +1,13 @@ +package httpx + +import ( + "io" +) + +func DrainAndClose(body io.ReadCloser) { + if body == nil { + return + } + _, _ = io.Copy(io.Discard, io.LimitReader(body, 64<<10)) + _ = body.Close() +} diff --git a/internal/httpx/client.go b/internal/httpx/client.go new file mode 100644 index 0000000..7cf868c --- /dev/null +++ b/internal/httpx/client.go @@ -0,0 +1,10 @@ +package httpx + +import ( + "fmt" + "runtime" +) + +func UserAgent() string { + return fmt.Sprintf("opencode/1.18.21 (%s %s; %s)", runtime.GOOS, runtime.GOARCH, runtime.Version()) +} diff --git a/internal/httpx/response.go b/internal/httpx/response.go new file mode 100644 index 0000000..c52e01a --- /dev/null +++ b/internal/httpx/response.go @@ -0,0 +1,33 @@ +// Package httpx provides shared HTTP response and transport helpers. +package httpx + +import ( + "encoding/json" + "fmt" + "net/http" +) + +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 WriteSSE(w http.ResponseWriter, event string, id uint64, value any) error { + data, err := json.Marshal(value) + if err != nil { + return err + } + if id > 0 { + _, _ = fmt.Fprintf(w, "id: %d\n", id) + } + if event != "" { + _, _ = fmt.Fprintf(w, "event: %s\n", event) + } + _, err = fmt.Fprintf(w, "data: %s\n\n", data) + return err +} diff --git a/ids.go b/internal/identity/request.go similarity index 57% rename from ids.go rename to internal/identity/request.go index e6485bb..19d2ed3 100644 --- a/ids.go +++ b/internal/identity/request.go @@ -1,4 +1,5 @@ -package main +// Package identity derives stable session identities and unique request IDs. +package identity import ( "crypto/rand" @@ -7,26 +8,26 @@ import ( "encoding/json" "fmt" "net/http" - "runtime" - "strings" + + "opencode2api/internal/jsonutil" ) -type requestIDs struct { +type RequestIDs struct { Session string Request string Project string ParentSession string } -func deriveRequestIDs(r *http.Request, body map[string]any) requestIDs { - signal := firstString( +func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs { + signal := jsonutil.FirstString( r.Header.Get("x-opencode-session"), r.Header.Get("x-session-affinity"), r.Header.Get("X-Session-Id"), r.Header.Get("x-session-id"), r.Header.Get("conversation-id"), - stringAt(body, "conversation_id"), - stringAt(body, "metadata", "session_id"), + jsonutil.StringAt(body, "conversation_id"), + jsonutil.StringAt(body, "metadata", "session_id"), ) if signal == "" { // Using the first user turn keeps a multi-turn conversation stable as its @@ -34,24 +35,24 @@ func deriveRequestIDs(r *http.Request, body map[string]any) requestIDs { signal = conversationSeed(body) } if signal == "" { - signal = stringAt(body, "previous_response_id") + signal = jsonutil.StringAt(body, "previous_response_id") } if signal == "" || signal == `{}` { - signal = randomID("fallback", 16) + signal = RandomID("fallback", 16) } - session := stableID("ses", signal) - projectSignal := firstString(r.Header.Get("x-opencode-project"), stringAt(body, "metadata", "project_id")) + session := StableID("ses", signal) + projectSignal := jsonutil.FirstString(r.Header.Get("x-opencode-project"), jsonutil.StringAt(body, "metadata", "project_id")) if projectSignal == "" { projectSignal = "opencode2api:default-project" } - parentSession := firstString( + parentSession := jsonutil.FirstString( r.Header.Get("x-parent-session-id"), - stringAt(body, "metadata", "parent_session_id"), + jsonutil.StringAt(body, "metadata", "parent_session_id"), ) - return requestIDs{ + return RequestIDs{ Session: session, - Request: randomID("req", 16), - Project: stableID("prj", projectSignal), + Request: RandomID("req", 16), + Project: StableID("prj", projectSignal), ParentSession: parentSession, } } @@ -61,9 +62,9 @@ func conversationSeed(body map[string]any) string { return input } for _, field := range []string{"messages", "input"} { - for _, raw := range sliceAt(body, field) { + for _, raw := range jsonutil.SliceAt(body, field) { item, ok := raw.(map[string]any) - if !ok || stringAt(item, "role") != "user" { + if !ok || jsonutil.StringAt(item, "role") != "user" { continue } encoded, _ := json.Marshal(item["content"]) @@ -75,28 +76,15 @@ func conversationSeed(body map[string]any) string { return "" } -func stableID(prefix, value string) string { +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 { +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.21 (%s %s; %s)", runtime.GOOS, runtime.GOARCH, runtime.Version()) -} diff --git a/internal/jsonutil/decode.go b/internal/jsonutil/decode.go new file mode 100644 index 0000000..c8e2d36 --- /dev/null +++ b/internal/jsonutil/decode.go @@ -0,0 +1,18 @@ +package jsonutil + +import ( + "encoding/json" + "errors" + "io" +) + +func EnsureEOF(dec *json.Decoder) error { + var extra any + if err := dec.Decode(&extra); err != io.EOF { + if err == nil { + return errors.New("multiple JSON values") + } + return err + } + return nil +} diff --git a/internal/jsonutil/value.go b/internal/jsonutil/value.go new file mode 100644 index 0000000..3d929b9 --- /dev/null +++ b/internal/jsonutil/value.go @@ -0,0 +1,119 @@ +// Package jsonutil provides accessors for decoded JSON values. +package jsonutil + +import ( + "encoding/json" + "strings" +) + +func FirstNonZero(values ...int) int { + for _, value := range values { + if value != 0 { + return value + } + } + return 0 +} + +func ParseJSONOrString(value string) any { + if value == "" { + return map[string]any{} + } + var decoded any + if json.Unmarshal([]byte(value), &decoded) == nil { + return decoded + } + return value +} + +func Put(object map[string]any, key string, value any) { + if value != nil { + object[key] = value + } +} + +func FirstAny(values ...any) any { + for _, value := range values { + if value != nil { + return value + } + } + return nil +} + +func CloneMap(input map[string]any) map[string]any { + data, _ := json.Marshal(input) + var output map[string]any + _ = json.Unmarshal(data, &output) + return output +} + +func AsSlice(value any) []any { + if values, ok := value.([]any); ok { + return values + } + if value == nil { + return nil + } + return []any{value} +} + +func SliceAt(object map[string]any, path ...string) []any { + values, _ := AnyAt(object, path...).([]any) + return values +} + +func MapAt(object map[string]any, path ...string) map[string]any { + value, _ := AnyAt(object, path...).(map[string]any) + return value +} + +func StringAt(object map[string]any, path ...string) string { + value, _ := AnyAt(object, path...).(string) + return value +} + +func BoolAt(object map[string]any, path ...string) bool { + value, _ := AnyAt(object, path...).(bool) + return value +} + +func IntAt(object map[string]any, path ...string) int { + value := AnyAt(object, path...) + switch number := value.(type) { + case float64: + return int(number) + case int: + return number + case json.Number: + integer, _ := number.Int64() + return int(integer) + default: + return 0 + } +} + +func Int64At(object map[string]any, path ...string) int64 { + return int64(IntAt(object, path...)) +} + +func AnyAt(object map[string]any, path ...string) any { + var current any = object + for _, key := range path { + next, ok := current.(map[string]any) + if !ok { + return nil + } + current = next[key] + } + return current +} + +func FirstString(values ...string) string { + for _, value := range values { + if value = strings.TrimSpace(value); value != "" { + return value + } + } + return "" +} diff --git a/model_cache.go b/internal/models/cache.go similarity index 83% rename from model_cache.go rename to internal/models/cache.go index fafacc4..5d836d4 100644 --- a/model_cache.go +++ b/internal/models/cache.go @@ -1,4 +1,4 @@ -package main +package models import ( "encoding/json" @@ -12,6 +12,9 @@ import ( "strings" "sync" "time" + + "opencode2api/internal/config" + wire "opencode2api/internal/protocol" ) const modelCatalogCacheSchemaVersion = 3 @@ -19,19 +22,19 @@ const modelCatalogCacheSchemaVersion = 3 var modelCatalogCacheWriteMu sync.Mutex type modelCatalogCache struct { - SchemaVersion int `json:"schema_version"` - UpdatedAt time.Time `json:"updated_at"` - Zen []string `json:"zen"` - Go []string `json:"go"` - NativeProtocols map[Tier]map[string]Protocol `json:"native_protocols"` - Unsupported map[Tier]map[string]bool `json:"unsupported"` - Metadata map[Tier]map[string]ModelMetadata `json:"metadata,omitempty"` + SchemaVersion int `json:"schema_version"` + UpdatedAt time.Time `json:"updated_at"` + Zen []string `json:"zen"` + Go []string `json:"go"` + NativeProtocols map[config.Tier]map[string]wire.Protocol `json:"native_protocols"` + Unsupported map[config.Tier]map[string]bool `json:"unsupported"` + Metadata map[config.Tier]map[string]Metadata `json:"metadata,omitempty"` } // LoadCache installs a validated disk snapshot into a catalog. It deliberately // changes only discovered state; configured protocol overrides and routing // preferences stay owned by the current Config. -func (c *modelCatalog) LoadCache(path string) error { +func (c *Catalog) LoadCache(path string) error { cache, err := loadModelCatalogCache(path) if err != nil { return err @@ -55,7 +58,7 @@ func (c *modelCatalog) LoadCache(path string) error { // SaveCache snapshots only public model capability data. Credentials and // proxy configuration are not part of modelCatalog and can never enter this // file. -func (c *modelCatalog) SaveCache() error { +func (c *Catalog) SaveCache() error { c.mu.RLock() path := c.cachePath cache := modelCatalogCache{ @@ -74,7 +77,7 @@ func (c *modelCatalog) SaveCache() error { return saveModelCatalogCache(path, cache) } -func modelCatalogCachePath(configPath string) string { +func CatalogCachePath(configPath string) string { if configPath == "" { return "" } @@ -140,19 +143,19 @@ func normalizeModelIDs(items []string) []string { return result } -func validateCatalogCapabilities(native map[Tier]map[string]Protocol, unsupported map[Tier]map[string]bool) error { +func validateCatalogCapabilities(native map[config.Tier]map[string]wire.Protocol, unsupported map[config.Tier]map[string]bool) error { for tier, protocols := range native { - if tier != TierZen && tier != TierGo { + if tier != config.TierZen && tier != config.TierGo { return fmt.Errorf("model catalog cache contains unknown tier %q", tier) } for model, protocol := range protocols { - if model == "" || !validProtocol(protocol) { + if model == "" || !wire.Valid(protocol) { return fmt.Errorf("model catalog cache contains invalid protocol for %q", model) } } } for tier, models := range unsupported { - if tier != TierZen && tier != TierGo { + if tier != config.TierZen && tier != config.TierGo { return fmt.Errorf("model catalog cache contains unknown tier %q", tier) } for model := range models { diff --git a/models.go b/internal/models/catalog.go similarity index 56% rename from models.go rename to internal/models/catalog.go index 4e3f995..18b7b6f 100644 --- a/models.go +++ b/internal/models/catalog.go @@ -1,4 +1,5 @@ -package main +// Package models discovers model capabilities, pricing, and available routes. +package models import ( "errors" @@ -7,82 +8,66 @@ import ( "strings" "sync" "time" + + "opencode2api/internal/config" + wire "opencode2api/internal/protocol" ) -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 { +type Route struct { ID string - Tier Tier - Protocol Protocol + Tier config.Tier + Protocol wire.Protocol // Protocols is the native protocol for each possible upstream tier. Zen // and Go intentionally do not share one global protocol: OpenCode's // catalog currently exposes, for example, MiniMax through Chat on Zen and // Messages on Go. The request must therefore be re-encoded when a retry // crosses tiers. - Protocols map[Tier]Protocol + Protocols map[config.Tier]wire.Protocol Anonymous bool // KeyTiers is the ordered authenticated fallback plan. Anonymous requests // always start on Zen, then enter this list when the public credential does // not succeed. - KeyTiers []Tier + KeyTiers []config.Tier } -type ModelRouteDiagnostic struct { - Model string `json:"model"` - RequestedProtocol Protocol `json:"requested_protocol,omitempty"` - NativeProtocol Protocol `json:"native_protocol"` - NativeProtocols map[Tier]Protocol `json:"native_protocols,omitempty"` - ProtocolSource string `json:"protocol_source"` - AvailableZen bool `json:"available_zen"` - AvailableGo bool `json:"available_go"` - Tier Tier `json:"tier,omitempty"` - Anonymous bool `json:"anonymous"` - KeyID string `json:"key_id,omitempty"` - Channel string `json:"channel,omitempty"` - Attempts int `json:"attempts,omitempty"` - KeyTiers []Tier `json:"key_tiers,omitempty"` - AnonymousEligibility AnonymousDecision `json:"anonymous_eligibility"` - RouteError string `json:"route_error,omitempty"` +type RouteDiagnostic struct { + Model string `json:"model"` + RequestedProtocol wire.Protocol `json:"requested_protocol,omitempty"` + NativeProtocol wire.Protocol `json:"native_protocol"` + NativeProtocols map[config.Tier]wire.Protocol `json:"native_protocols,omitempty"` + ProtocolSource string `json:"protocol_source"` + AvailableZen bool `json:"available_zen"` + AvailableGo bool `json:"available_go"` + Tier config.Tier `json:"tier,omitempty"` + Anonymous bool `json:"anonymous"` + KeyID string `json:"key_id,omitempty"` + Channel string `json:"channel,omitempty"` + Attempts int `json:"attempts,omitempty"` + KeyTiers []config.Tier `json:"key_tiers,omitempty"` + AnonymousEligibility AnonymousDecision `json:"anonymous_eligibility"` + RouteError string `json:"route_error,omitempty"` } -type modelCatalog struct { +type Catalog struct { mu sync.RWMutex zen map[string]bool goModels map[string]bool - protocols map[string]Protocol + protocols map[string]wire.Protocol // nativeProtocols is populated from OpenCode's public model capability // catalog. protocols remains the user-configured override map. - nativeProtocols map[Tier]map[string]Protocol - unsupported map[Tier]map[string]bool - modelMeta map[Tier]map[string]ModelMetadata + nativeProtocols map[config.Tier]map[string]wire.Protocol + unsupported map[config.Tier]map[string]bool + modelMeta map[config.Tier]map[string]Metadata updatedAt time.Time - prefer Tier - metadata *modelMetadataStore + prefer config.Tier + pricing *PricingStore cachePath string cacheSource string stale bool refreshAfter time.Duration } -type modelCatalogSnapshot struct { +type CatalogSnapshot struct { Zen int `json:"zen"` Go int `json:"go"` Total int `json:"total"` @@ -92,36 +77,54 @@ type modelCatalogSnapshot struct { Stale bool `json:"stale"` } -func newModelCatalog(prefer Tier, overrides map[string]string) *modelCatalog { - protocols := make(map[string]Protocol, len(overrides)) +func NewCatalog(prefer config.Tier, overrides map[string]string) *Catalog { + protocols := make(map[string]wire.Protocol, len(overrides)) for model, protocol := range overrides { - protocols[model] = Protocol(protocol) + protocols[model] = wire.Protocol(protocol) } - return &modelCatalog{ + return &Catalog{ zen: map[string]bool{}, goModels: map[string]bool{}, protocols: protocols, - nativeProtocols: map[Tier]map[string]Protocol{TierZen: {}, TierGo: {}}, - unsupported: map[Tier]map[string]bool{TierZen: {}, TierGo: {}}, prefer: prefer, + nativeProtocols: map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}}, + unsupported: map[config.Tier]map[string]bool{config.TierZen: {}, config.TierGo: {}}, prefer: prefer, cacheSource: "none", } } -func (c *modelCatalog) SetCachePath(path string) { +// SetPricingStore connects routing decisions to the shared pricing metadata. +func (c *Catalog) SetPricingStore(store *PricingStore) { + c.mu.Lock() + c.pricing = store + c.mu.Unlock() +} + +// MetadataSnapshot reports pricing freshness without exposing the store. +func (c *Catalog) MetadataSnapshot() MetadataSnapshot { + c.mu.RLock() + store := c.pricing + c.mu.RUnlock() + if store == nil { + return MetadataSnapshot{} + } + return store.Snapshot() +} + +func (c *Catalog) SetCachePath(path string) { c.mu.Lock() c.cachePath = path c.mu.Unlock() } -func (c *modelCatalog) SetRefreshInterval(interval time.Duration) { +func (c *Catalog) SetRefreshInterval(interval time.Duration) { c.mu.Lock() c.refreshAfter = interval c.mu.Unlock() } -func (c *modelCatalog) Replace(zen, goModels []string) { +func (c *Catalog) Replace(zen, goModels []string) { c.ReplaceWithCapabilities(zen, goModels, nil, nil, nil) } -func (c *modelCatalog) ReplaceWithCapabilities(zen, goModels []string, native map[Tier]map[string]Protocol, unsupported map[Tier]map[string]bool, metadata map[Tier]map[string]ModelMetadata) { +func (c *Catalog) ReplaceWithCapabilities(zen, goModels []string, native map[config.Tier]map[string]wire.Protocol, unsupported map[config.Tier]map[string]bool, metadata map[config.Tier]map[string]Metadata) { c.mu.Lock() defer c.mu.Unlock() if zen != nil { @@ -131,14 +134,14 @@ func (c *modelCatalog) ReplaceWithCapabilities(zen, goModels []string, native ma c.goModels = toSet(goModels) } if native != nil { - for _, tier := range []Tier{TierZen, TierGo} { + for _, tier := range []config.Tier{config.TierZen, config.TierGo} { if protocols, ok := native[tier]; ok { c.nativeProtocols[tier] = cloneProtocols(protocols) } } } if unsupported != nil { - for _, tier := range []Tier{TierZen, TierGo} { + for _, tier := range []config.Tier{config.TierZen, config.TierGo} { if models, ok := unsupported[tier]; ok { c.unsupported[tier] = cloneBools(models) } @@ -152,7 +155,7 @@ func (c *modelCatalog) ReplaceWithCapabilities(zen, goModels []string, native ma c.stale = false } -func (c *modelCatalog) CopyState(source *modelCatalog) { +func (c *Catalog) CopyState(source *Catalog) { if source == nil { return } @@ -165,9 +168,9 @@ func (c *modelCatalog) CopyState(source *modelCatalog) { for model, available := range source.goModels { goModels[model] = available } - native := map[Tier]map[string]Protocol{TierZen: {}, TierGo: {}} - unsupported := map[Tier]map[string]bool{TierZen: {}, TierGo: {}} - for _, tier := range []Tier{TierZen, TierGo} { + native := map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}} + unsupported := map[config.Tier]map[string]bool{config.TierZen: {}, config.TierGo: {}} + for _, tier := range []config.Tier{config.TierZen, config.TierGo} { for model, protocol := range source.nativeProtocols[tier] { native[tier][model] = protocol } @@ -187,41 +190,41 @@ func (c *modelCatalog) CopyState(source *modelCatalog) { c.mu.Unlock() } -func (c *modelCatalog) Route(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (modelRoute, error) { +func (c *Catalog) Route(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (Route, error) { c.mu.RLock() defer c.mu.RUnlock() return c.routeLocked(model, hasZenKeys, hasGoKeys, hasAnonymous) } -func (c *modelCatalog) routeLocked(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (modelRoute, error) { +func (c *Catalog) routeLocked(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (Route, error) { keyTiers := c.keyTierOrderLocked(model, hasZenKeys, hasGoKeys) // OpenCode's public credential is a Zen-only lane. Every free model starts // there, even if the current catalog only advertises it on Go: an upstream // rejection will move the request into the authenticated fallback plan. decision := c.anonymousDecision(model) - if hasAnonymous && decision.Allowed && (c.protocols[model] != "" || !c.unsupported[TierZen][model]) && + if hasAnonymous && decision.Allowed && (c.protocols[model] != "" || !c.unsupported[config.TierZen][model]) && (len(c.zen) == 0 && len(c.goModels) == 0 || c.zen[model] || c.goModels[model]) { protocols := c.protocolsForLocked(model, keyTiers, true) - return modelRoute{ID: model, Tier: TierZen, Protocol: protocols[TierZen], Protocols: protocols, Anonymous: true, KeyTiers: keyTiers}, nil + return Route{ID: model, Tier: config.TierZen, Protocol: protocols[config.TierZen], Protocols: protocols, Anonymous: true, KeyTiers: keyTiers}, nil } if len(keyTiers) > 0 { protocols := c.protocolsForLocked(model, keyTiers, false) - return modelRoute{ID: model, Tier: keyTiers[0], Protocol: protocols[keyTiers[0]], Protocols: protocols, KeyTiers: keyTiers}, nil + return Route{ID: model, Tier: keyTiers[0], Protocol: protocols[keyTiers[0]], Protocols: protocols, KeyTiers: keyTiers}, nil } - return modelRoute{}, fmt.Errorf("model %q is not available in the configured Zen or Go pools", model) + return Route{}, fmt.Errorf("model %q is not available in the configured Zen or Go pools", model) } -func (r modelRoute) ProtocolFor(tier Tier) Protocol { +func (r Route) ProtocolFor(tier config.Tier) wire.Protocol { if protocol := r.Protocols[tier]; protocol != "" { return protocol } return r.Protocol } -func (c *modelCatalog) protocolsForLocked(model string, keyTiers []Tier, includeZen bool) map[Tier]Protocol { - protocols := make(map[Tier]Protocol, len(keyTiers)+1) +func (c *Catalog) protocolsForLocked(model string, keyTiers []config.Tier, includeZen bool) map[config.Tier]wire.Protocol { + protocols := make(map[config.Tier]wire.Protocol, len(keyTiers)+1) if includeZen { - protocols[TierZen] = c.protocolForLocked(model, TierZen) + protocols[config.TierZen] = c.protocolForLocked(model, config.TierZen) } for _, tier := range keyTiers { protocols[tier] = c.protocolForLocked(model, tier) @@ -229,7 +232,7 @@ func (c *modelCatalog) protocolsForLocked(model string, keyTiers []Tier, include return protocols } -func (c *modelCatalog) protocolForLocked(model string, tier Tier) Protocol { +func (c *Catalog) protocolForLocked(model string, tier config.Tier) wire.Protocol { if protocol := c.protocols[model]; protocol != "" { return protocol } @@ -239,30 +242,30 @@ func (c *modelCatalog) protocolForLocked(model string, tier Tier) Protocol { // The OpenCode capability catalog is authoritative when available. Chat is // the only safe protocol-neutral fallback for an ID that has just appeared // in /v1/models but is not present in the capability snapshot yet. - return ProtocolChat + return wire.Chat } // keyTierOrderLocked builds an authenticated route in prefer order. A tier is // included only when it has a key and advertises the model. Before the first // successful catalog refresh, configured key pools remain usable so temporary // discovery failures do not take the gateway offline. -func (c *modelCatalog) keyTierOrderLocked(model string, hasZenKeys, hasGoKeys bool) []Tier { +func (c *Catalog) keyTierOrderLocked(model string, hasZenKeys, hasGoKeys bool) []config.Tier { catalogPending := len(c.zen) == 0 && len(c.goModels) == 0 - available := func(tier Tier) bool { + available := func(tier config.Tier) bool { switch tier { - case TierZen: - return hasZenKeys && (catalogPending || c.zen[model]) && c.tierSupportedLocked(model, TierZen) - case TierGo: - return hasGoKeys && (catalogPending || c.goModels[model]) && c.tierSupportedLocked(model, TierGo) + case config.TierZen: + return hasZenKeys && (catalogPending || c.zen[model]) && c.tierSupportedLocked(model, config.TierZen) + case config.TierGo: + return hasGoKeys && (catalogPending || c.goModels[model]) && c.tierSupportedLocked(model, config.TierGo) default: return false } } - order := []Tier{TierZen, TierGo} - if c.prefer == TierGo { + order := []config.Tier{config.TierZen, config.TierGo} + if c.prefer == config.TierGo { order[0], order[1] = order[1], order[0] } - result := make([]Tier, 0, len(order)) + result := make([]config.Tier, 0, len(order)) for _, tier := range order { if available(tier) { result = append(result, tier) @@ -275,55 +278,55 @@ func (c *modelCatalog) keyTierOrderLocked(model string, hasZenKeys, hasGoKeys bo // per-key diagnostics. It never selects the anonymous lane and never adds a // fallback tier: the operator asked to exercise one configured key, so the // result describes that key and nothing else. -func (c *modelCatalog) RouteForTier(model string, tier Tier, hasZenKeys, hasGoKeys bool) (modelRoute, error) { - if tier != TierZen && tier != TierGo { - return modelRoute{}, errors.New("selected key tier must be zen or go") +func (c *Catalog) RouteForTier(model string, tier config.Tier, hasZenKeys, hasGoKeys bool) (Route, error) { + if tier != config.TierZen && tier != config.TierGo { + return Route{}, errors.New("selected key tier must be zen or go") } hasKeys := hasZenKeys - if tier == TierGo { + if tier == config.TierGo { hasKeys = hasGoKeys } if !hasKeys { - return modelRoute{}, fmt.Errorf("no %s key is configured", tier) + return Route{}, fmt.Errorf("no %s key is configured", tier) } c.mu.RLock() defer c.mu.RUnlock() catalogPending := len(c.zen) == 0 && len(c.goModels) == 0 advertised := c.zen[model] - if tier == TierGo { + if tier == config.TierGo { advertised = c.goModels[model] } if !catalogPending && !advertised { - return modelRoute{}, fmt.Errorf("model %q is not available in the selected %s key tier", model, tier) + return Route{}, fmt.Errorf("model %q is not available in the selected %s key tier", model, tier) } if !c.tierSupportedLocked(model, tier) { - return modelRoute{}, fmt.Errorf("model %q uses an upstream protocol that is not available on the selected %s key tier", model, tier) + return Route{}, fmt.Errorf("model %q uses an upstream protocol that is not available on the selected %s key tier", model, tier) } protocol := c.protocolForLocked(model, tier) - return modelRoute{ + return Route{ ID: model, Tier: tier, Protocol: protocol, - Protocols: map[Tier]Protocol{tier: protocol}, - KeyTiers: []Tier{tier}, + Protocols: map[config.Tier]wire.Protocol{tier: protocol}, + KeyTiers: []config.Tier{tier}, }, nil } -func (c *modelCatalog) anonymousDecision(model string) AnonymousDecision { - if c.metadata != nil { - return c.metadata.Decide(model) +func (c *Catalog) anonymousDecision(model string) AnonymousDecision { + if c.pricing != nil { + return c.pricing.Decide(model) } return AnonymousDecision{Allowed: isFreeModel(model), Source: "name_fallback_metadata_pending"} } -func (c *modelCatalog) Diagnostic(model string, requested Protocol, hasZenKeys, hasGoKeys, hasAnonymous bool) ModelRouteDiagnostic { +func (c *Catalog) Diagnostic(model string, requested wire.Protocol, hasZenKeys, hasGoKeys, hasAnonymous bool) RouteDiagnostic { c.mu.RLock() configured, explicit := c.protocols[model] zen, goModel := c.zen[model], c.goModels[model] - nativeProtocols := map[Tier]Protocol{ - TierZen: c.protocolForLocked(model, TierZen), - TierGo: c.protocolForLocked(model, TierGo), + nativeProtocols := map[config.Tier]wire.Protocol{ + config.TierZen: c.protocolForLocked(model, config.TierZen), + config.TierGo: c.protocolForLocked(model, config.TierGo), } - _, zenKnown := c.nativeProtocols[TierZen][model] - _, goKnown := c.nativeProtocols[TierGo][model] + _, zenKnown := c.nativeProtocols[config.TierZen][model] + _, goKnown := c.nativeProtocols[config.TierGo][model] c.mu.RUnlock() source := "configured" if !explicit { @@ -336,12 +339,12 @@ func (c *modelCatalog) Diagnostic(model string, requested Protocol, hasZenKeys, if protocol == "" { // Route() below selects the preferred available tier. This is only the // fallback shown when no route can currently be built. - protocol = nativeProtocols[TierZen] - if c.prefer == TierGo { - protocol = nativeProtocols[TierGo] + protocol = nativeProtocols[config.TierZen] + if c.prefer == config.TierGo { + protocol = nativeProtocols[config.TierGo] } } - diagnostic := ModelRouteDiagnostic{ + diagnostic := RouteDiagnostic{ Model: model, RequestedProtocol: requested, NativeProtocol: protocol, NativeProtocols: nativeProtocols, ProtocolSource: source, AvailableZen: zen, AvailableGo: goModel, AnonymousEligibility: c.anonymousDecision(model), } @@ -353,7 +356,7 @@ func (c *modelCatalog) Diagnostic(model string, requested Protocol, hasZenKeys, diagnostic.NativeProtocol = route.Protocol diagnostic.NativeProtocols = route.Protocols diagnostic.Tier, diagnostic.Anonymous = route.Tier, route.Anonymous - diagnostic.KeyTiers = append([]Tier(nil), route.KeyTiers...) + diagnostic.KeyTiers = append([]config.Tier(nil), route.KeyTiers...) return diagnostic } @@ -361,7 +364,7 @@ func isFreeModel(model string) bool { return strings.Contains(strings.ToLower(model), "free") } -func (c *modelCatalog) List() []string { +func (c *Catalog) List() []string { c.mu.RLock() defer c.mu.RUnlock() ids := c.modelIDsLocked() @@ -374,7 +377,7 @@ func (c *modelCatalog) List() []string { return models } -func (c *modelCatalog) modelIDsLocked() []string { +func (c *Catalog) modelIDsLocked() []string { seen := make(map[string]bool, len(c.zen)+len(c.goModels)) for model := range c.zen { seen[model] = true @@ -385,7 +388,7 @@ func (c *modelCatalog) modelIDsLocked() []string { return sortedSetKeys(seen) } -func (c *modelCatalog) Snapshot() modelCatalogSnapshot { +func (c *Catalog) Snapshot() CatalogSnapshot { c.mu.RLock() defer c.mu.RUnlock() return c.snapshotLocked(c.modelIDsLocked()) @@ -393,11 +396,11 @@ func (c *modelCatalog) Snapshot() modelCatalogSnapshot { // AvailableModels provides discovery and readiness with the same route // filtering, including configured key tiers and anonymous eligibility. -func (c *modelCatalog) AvailableModels(hasZenKeys, hasGoKeys, hasAnonymous bool) ([]modelRoute, modelCatalogSnapshot) { +func (c *Catalog) AvailableModels(hasZenKeys, hasGoKeys, hasAnonymous bool) ([]Route, CatalogSnapshot) { c.mu.RLock() defer c.mu.RUnlock() ids := c.modelIDsLocked() - routes := make([]modelRoute, 0, len(ids)) + routes := make([]Route, 0, len(ids)) for _, model := range ids { if !c.supportedLocked(model) { continue @@ -411,7 +414,7 @@ func (c *modelCatalog) AvailableModels(hasZenKeys, hasGoKeys, hasAnonymous bool) return routes, snapshot } -func (c *modelCatalog) snapshotLocked(ids []string) modelCatalogSnapshot { +func (c *Catalog) snapshotLocked(ids []string) CatalogSnapshot { exposed := 0 for _, model := range ids { if c.supportedLocked(model) { @@ -422,13 +425,13 @@ func (c *modelCatalog) snapshotLocked(ids []string) modelCatalogSnapshot { if !c.updatedAt.IsZero() && c.refreshAfter > 0 { stale = stale || time.Since(c.updatedAt) > max(2*c.refreshAfter, time.Minute) } - return modelCatalogSnapshot{ + return CatalogSnapshot{ Zen: len(c.zen), Go: len(c.goModels), Total: len(ids), Exposed: exposed, UpdatedAt: c.updatedAt, CacheSource: c.cacheSource, Stale: stale, } } -func (c *modelCatalog) Supported(model string) bool { +func (c *Catalog) Supported(model string) bool { c.mu.RLock() defer c.mu.RUnlock() return c.supportedLocked(model) @@ -441,26 +444,26 @@ func (c *modelCatalog) Supported(model string) bool { // tier-blind lookup. Anonymous routes always resolve to TierZen, which keeps // the keyless path on Zen metadata. The zero value is returned for models // the catalog does not describe (or before the first capability refresh). -func (c *modelCatalog) MetadataForTier(model string, tier Tier) ModelMetadata { +func (c *Catalog) MetadataForTier(model string, tier config.Tier) Metadata { c.mu.RLock() defer c.mu.RUnlock() return c.modelMeta[tier][model] } -func (c *modelCatalog) supportedLocked(model string) bool { +func (c *Catalog) supportedLocked(model string) bool { if len(c.zen) == 0 && len(c.goModels) == 0 { return true } - if c.zen[model] && c.tierSupportedLocked(model, TierZen) { + if c.zen[model] && c.tierSupportedLocked(model, config.TierZen) { return true } - if c.goModels[model] && c.tierSupportedLocked(model, TierGo) { + if c.goModels[model] && c.tierSupportedLocked(model, config.TierGo) { return true } return false } -func (c *modelCatalog) tierSupportedLocked(model string, tier Tier) bool { +func (c *Catalog) tierSupportedLocked(model string, tier config.Tier) bool { if c.protocols[model] != "" { return true } @@ -483,8 +486,8 @@ func toSet(items []string) map[string]bool { return out } -func cloneProtocols(source map[string]Protocol) map[string]Protocol { - result := make(map[string]Protocol, len(source)) +func cloneProtocols(source map[string]wire.Protocol) map[string]wire.Protocol { + result := make(map[string]wire.Protocol, len(source)) for model, protocol := range source { result[model] = protocol } @@ -499,9 +502,9 @@ func cloneBools(source map[string]bool) map[string]bool { return result } -func cloneModelMeta(source map[Tier]map[string]ModelMetadata) map[Tier]map[string]ModelMetadata { - result := map[Tier]map[string]ModelMetadata{TierZen: {}, TierGo: {}} - for _, tier := range []Tier{TierZen, TierGo} { +func cloneModelMeta(source map[config.Tier]map[string]Metadata) map[config.Tier]map[string]Metadata { + result := map[config.Tier]map[string]Metadata{config.TierZen: {}, config.TierGo: {}} + for _, tier := range []config.Tier{config.TierZen, config.TierGo} { for id, md := range source[tier] { result[tier][id] = md } @@ -520,9 +523,9 @@ func sortedSetKeys(source map[string]bool) []string { return result } -func cloneTierProtocols(source map[Tier]map[string]Protocol) map[Tier]map[string]Protocol { - result := map[Tier]map[string]Protocol{TierZen: {}, TierGo: {}} - for _, tier := range []Tier{TierZen, TierGo} { +func cloneTierProtocols(source map[config.Tier]map[string]wire.Protocol) map[config.Tier]map[string]wire.Protocol { + result := map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}} + for _, tier := range []config.Tier{config.TierZen, config.TierGo} { if protocols, ok := source[tier]; ok { result[tier] = cloneProtocols(protocols) } @@ -530,9 +533,9 @@ func cloneTierProtocols(source map[Tier]map[string]Protocol) map[Tier]map[string return result } -func cloneTierBools(source map[Tier]map[string]bool) map[Tier]map[string]bool { - result := map[Tier]map[string]bool{TierZen: {}, TierGo: {}} - for _, tier := range []Tier{TierZen, TierGo} { +func cloneTierBools(source map[config.Tier]map[string]bool) map[config.Tier]map[string]bool { + result := map[config.Tier]map[string]bool{config.TierZen: {}, config.TierGo: {}} + for _, tier := range []config.Tier{config.TierZen, config.TierGo} { if models, ok := source[tier]; ok { result[tier] = cloneBools(models) } diff --git a/model_discovery.go b/internal/models/discovery.go similarity index 73% rename from model_discovery.go rename to internal/models/discovery.go index 88db1cb..7dfc967 100644 --- a/model_discovery.go +++ b/internal/models/discovery.go @@ -1,4 +1,4 @@ -package main +package models import ( "context" @@ -9,20 +9,24 @@ import ( "net/http" "regexp" "strings" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" + wire "opencode2api/internal/protocol" ) const ( - openCodeCapabilitiesURL = "https://models.opencode.ai/api.json" - openCodeZenDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/zen.mdx" - openCodeGoDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/go.mdx" + CapabilitiesURL = "https://models.opencode.ai/api.json" + ZenDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/zen.mdx" + GoDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/go.mdx" ) var protocolDocEndpointPattern = regexp.MustCompile("\\|[^|]+\\|\\s*`?([^|`\\s]+)`?\\s*\\|\\s*`[^`]+/v1/(chat/completions|responses|messages)`") -type protocolCapabilities struct { - Protocols map[Tier]map[string]Protocol - Unsupported map[Tier]map[string]bool - Metadata map[Tier]map[string]ModelMetadata +type Capabilities struct { + Protocols map[config.Tier]map[string]wire.Protocol + Unsupported map[config.Tier]map[string]bool + Metadata map[config.Tier]map[string]Metadata } type capabilityProvider struct { @@ -53,11 +57,11 @@ type capabilityModelLimit struct { Output int `json:"output"` } -// ModelMetadata carries the per-model capability fields surfaced through +// Metadata carries the per-model capability fields surfaced through // /v1/models so consumers (harnesses like Pi or jcode) get real context // windows and feature flags from the catalog instead of guessing. It is // purely additive: routing does not depend on any of these fields. -type ModelMetadata struct { +type Metadata struct { ContextWindow int `json:"context_window,omitempty"` MaxInput int `json:"max_input,omitempty"` MaxOutput int `json:"max_output,omitempty"` @@ -68,8 +72,8 @@ type ModelMetadata struct { OutputModalities []string `json:"output_modalities,omitempty"` } -func (m *capabilityModel) metadata() ModelMetadata { - md := ModelMetadata{ +func (m *capabilityModel) metadata() Metadata { + md := Metadata{ Reasoning: m.Reasoning, ToolCall: m.ToolCall, StructuredOutput: m.StructuredOutput, @@ -94,33 +98,33 @@ type capabilityModelProvider struct { // catalog. Unlike /v1/models, this source includes the SDK selected for each // model, which is the upstream's protocol declaration. No model IDs are kept // in this project. -func fetchProtocolCapabilities(ctx context.Context, client *http.Client, endpoint string) (protocolCapabilities, error) { +func FetchCapabilities(ctx context.Context, client *http.Client, endpoint string) (Capabilities, error) { if client == nil { client = http.DefaultClient } req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { - return protocolCapabilities{}, err + return Capabilities{}, err } req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", opencodeUserAgent()) + req.Header.Set("User-Agent", httpx.UserAgent()) resp, err := client.Do(req) if err != nil { - return protocolCapabilities{}, err + return Capabilities{}, err } defer resp.Body.Close() if resp.StatusCode/100 != 2 { - return protocolCapabilities{}, fmt.Errorf("OpenCode capability endpoint returned HTTP %d", resp.StatusCode) + return Capabilities{}, fmt.Errorf("OpenCode capability endpoint returned HTTP %d", resp.StatusCode) } var providers map[string]capabilityProvider dec := json.NewDecoder(io.LimitReader(resp.Body, 64<<20)) if err := dec.Decode(&providers); err != nil { - return protocolCapabilities{}, err + return Capabilities{}, err } - result := protocolCapabilities{ - Protocols: map[Tier]map[string]Protocol{TierZen: {}, TierGo: {}}, - Unsupported: map[Tier]map[string]bool{TierZen: {}, TierGo: {}}, - Metadata: map[Tier]map[string]ModelMetadata{TierZen: {}, TierGo: {}}, + result := Capabilities{ + Protocols: map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}}, + Unsupported: map[config.Tier]map[string]bool{config.TierZen: {}, config.TierGo: {}}, + Metadata: map[config.Tier]map[string]Metadata{config.TierZen: {}, config.TierGo: {}}, } for providerID, provider := range providers { tier, ok := capabilityTier(providerID, provider.API) @@ -148,13 +152,13 @@ func fetchProtocolCapabilities(ctx context.Context, client *http.Client, endpoin // but whose published endpoint is more specific (for example a Messages // route). This remains data-driven: no model IDs are embedded here. for _, doc := range []struct { - tier Tier + tier config.Tier url string }{ - {TierZen, openCodeZenDocsURL}, - {TierGo, openCodeGoDocsURL}, + {config.TierZen, ZenDocsURL}, + {config.TierGo, GoDocsURL}, } { - protocols, err := fetchProtocolDocs(ctx, client, doc.url) + protocols, err := FetchProtocolDocs(ctx, client, doc.url) if err != nil { continue } @@ -163,19 +167,19 @@ func fetchProtocolCapabilities(ctx context.Context, client *http.Client, endpoin delete(result.Unsupported[doc.tier], modelID) } } - if len(result.Protocols[TierZen]) == 0 && len(result.Protocols[TierGo]) == 0 && len(result.Unsupported[TierZen]) == 0 && len(result.Unsupported[TierGo]) == 0 { - return protocolCapabilities{}, errors.New("OpenCode capability endpoint returned no Zen or Go models") + if len(result.Protocols[config.TierZen]) == 0 && len(result.Protocols[config.TierGo]) == 0 && len(result.Unsupported[config.TierZen]) == 0 && len(result.Unsupported[config.TierGo]) == 0 { + return Capabilities{}, errors.New("OpenCode capability endpoint returned no Zen or Go models") } return result, nil } -func fetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string) (map[string]Protocol, error) { +func FetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string) (map[string]wire.Protocol, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, err } req.Header.Set("Accept", "text/plain, text/markdown, */*") - req.Header.Set("User-Agent", opencodeUserAgent()) + req.Header.Set("User-Agent", httpx.UserAgent()) resp, err := client.Do(req) if err != nil { return nil, err @@ -188,7 +192,7 @@ func fetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string if err != nil { return nil, err } - result := make(map[string]Protocol) + result := make(map[string]wire.Protocol) for _, line := range strings.Split(string(body), "\n") { match := protocolDocEndpointPattern.FindStringSubmatch(line) if len(match) != 3 { @@ -198,14 +202,14 @@ func fetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string if modelID == "" || strings.ContainsAny(modelID, " `|") { continue } - var protocol Protocol + var protocol wire.Protocol switch match[2] { case "chat/completions": - protocol = ProtocolChat + protocol = wire.Chat case "responses": - protocol = ProtocolResponses + protocol = wire.Responses case "messages": - protocol = ProtocolAnthropic + protocol = wire.Anthropic } if protocol != "" { result[modelID] = protocol @@ -217,26 +221,26 @@ func fetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string return result, nil } -func capabilityTier(providerID, api string) (Tier, bool) { +func capabilityTier(providerID, api string) (config.Tier, bool) { value := strings.ToLower(strings.TrimSpace(providerID + " " + api)) if strings.Contains(value, "opencode-go") || strings.Contains(value, "/go/") { - return TierGo, true + return config.TierGo, true } if strings.Contains(value, "opencode") || strings.Contains(value, "/zen/") { - return TierZen, true + return config.TierZen, true } return "", false } -func protocolForSDK(npm string) (Protocol, bool) { +func protocolForSDK(npm string) (wire.Protocol, bool) { value := strings.ToLower(strings.TrimSpace(npm)) switch { case strings.Contains(value, "anthropic"): - return ProtocolAnthropic, true + return wire.Anthropic, true case value == "@ai-sdk/openai" || strings.HasSuffix(value, "/openai"): - return ProtocolResponses, true + return wire.Responses, true case strings.Contains(value, "openai-compatible"): - return ProtocolChat, true + return wire.Chat, true default: return "", false } @@ -248,13 +252,13 @@ type modelsResponse struct { } `json:"data"` } -func fetchModels(ctx context.Context, client *http.Client, baseURL, key string) ([]string, int, error) { +func FetchModels(ctx context.Context, client *http.Client, baseURL, key string) ([]string, int, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(baseURL, "/")+"/v1/models", nil) if err != nil { return nil, 0, err } req.Header.Set("Authorization", "Bearer "+key) - req.Header.Set("User-Agent", opencodeUserAgent()) + req.Header.Set("User-Agent", httpx.UserAgent()) req.Header.Set("x-opencode-client", "cli") resp, err := client.Do(req) if err != nil { diff --git a/model_metadata.go b/internal/models/pricing.go similarity index 84% rename from model_metadata.go rename to internal/models/pricing.go index 3d88b0e..923e581 100644 --- a/model_metadata.go +++ b/internal/models/pricing.go @@ -1,4 +1,4 @@ -package main +package models import ( "context" @@ -15,6 +15,9 @@ import ( "strings" "sync" "time" + + "opencode2api/internal/httpx" + "opencode2api/internal/jsonutil" ) const ( @@ -23,7 +26,7 @@ const ( modelsDevTimeout = 30 * time.Second ) -type ModelPrice struct { +type Price struct { ID string `json:"id"` Input *float64 `json:"input_cost,omitempty"` Output *float64 `json:"output_cost,omitempty"` @@ -50,13 +53,13 @@ type MetadataSnapshot struct { } type modelMetadataCache struct { - UpdatedAt time.Time `json:"updated_at"` - Models map[string]ModelPrice `json:"models"` + UpdatedAt time.Time `json:"updated_at"` + Models map[string]Price `json:"models"` } -type modelMetadataStore struct { +type PricingStore struct { mu sync.RWMutex - models map[string]ModelPrice + models map[string]Price updatedAt time.Time lastError string cachePath string @@ -66,13 +69,13 @@ type modelMetadataStore struct { logger *slog.Logger } -func newModelMetadataStore(configPath string, logger *slog.Logger) *modelMetadataStore { +func NewPricingStore(configPath string, logger *slog.Logger) *PricingStore { cachePath := "" if configPath != "" { cachePath = configPath + ".models.dev.json" } - store := &modelMetadataStore{ - models: make(map[string]ModelPrice), cachePath: cachePath, endpoint: modelsDevDefaultURL, + store := &PricingStore{ + models: make(map[string]Price), cachePath: cachePath, endpoint: modelsDevDefaultURL, client: &http.Client{Timeout: modelsDevTimeout}, logger: logger, } if err := store.loadCache(); err != nil && !errors.Is(err, os.ErrNotExist) { @@ -84,13 +87,13 @@ func newModelMetadataStore(configPath string, logger *slog.Logger) *modelMetadat // SetClientProvider supplies candidate HTTP clients for refresh attempts, most // preferred first. It lets the periodic models.dev refresh ride the proxy // transports exposed by whichever gateway runtime is currently active. -func (store *modelMetadataStore) SetClientProvider(provider func() []*http.Client) { +func (store *PricingStore) SetClientProvider(provider func() []*http.Client) { store.mu.Lock() defer store.mu.Unlock() store.clientProvider = provider } -func (store *modelMetadataStore) refreshClients() []*http.Client { +func (store *PricingStore) refreshClients() []*http.Client { store.mu.RLock() provider := store.clientProvider store.mu.RUnlock() @@ -104,7 +107,7 @@ func (store *modelMetadataStore) refreshClients() []*http.Client { return clients } -func (store *modelMetadataStore) Start(ctx context.Context) { +func (store *PricingStore) Start(ctx context.Context) { go func() { store.refreshAndLog(ctx) ticker := time.NewTicker(modelsDevRefresh) @@ -120,7 +123,7 @@ func (store *modelMetadataStore) Start(ctx context.Context) { }() } -func (store *modelMetadataStore) refreshAndLog(ctx context.Context) { +func (store *PricingStore) refreshAndLog(ctx context.Context) { if err := store.Refresh(ctx); err != nil { if store.logger != nil { store.logger.Warn("models.dev metadata refresh failed", "component", "models", "event", "metadata_refresh_failed", "error", err) @@ -132,7 +135,7 @@ func (store *modelMetadataStore) refreshAndLog(ctx context.Context) { } } -func (store *modelMetadataStore) Refresh(ctx context.Context) error { +func (store *PricingStore) Refresh(ctx context.Context) error { var lastErr error for _, client := range store.refreshClients() { data, err := store.fetch(ctx, client) @@ -162,7 +165,7 @@ func (store *modelMetadataStore) Refresh(ctx context.Context) error { return store.recordError(lastErr) } -func (store *modelMetadataStore) fetch(ctx context.Context, client *http.Client) ([]byte, error) { +func (store *PricingStore) fetch(ctx context.Context, client *http.Client) ([]byte, error) { refreshCtx, cancel := context.WithTimeout(ctx, modelsDevTimeout) defer cancel() req, err := http.NewRequestWithContext(refreshCtx, http.MethodGet, store.endpoint, nil) @@ -170,7 +173,7 @@ func (store *modelMetadataStore) fetch(ctx context.Context, client *http.Client) return nil, err } req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", opencodeUserAgent()) + req.Header.Set("User-Agent", httpx.UserAgent()) resp, err := client.Do(req) if err != nil { return nil, err @@ -182,14 +185,14 @@ func (store *modelMetadataStore) fetch(ctx context.Context, client *http.Client) return io.ReadAll(io.LimitReader(resp.Body, 32<<20)) } -func (store *modelMetadataStore) recordError(err error) error { +func (store *PricingStore) recordError(err error) error { store.mu.Lock() store.lastError = err.Error() store.mu.Unlock() return err } -func (store *modelMetadataStore) Decide(model string) AnonymousDecision { +func (store *PricingStore) Decide(model string) AnonymousDecision { store.mu.RLock() price, exists := store.models[model] ready := !store.updatedAt.IsZero() && len(store.models) > 0 @@ -236,14 +239,14 @@ func (store *modelMetadataStore) Decide(model string) AnonymousDecision { return decision } -func (store *modelMetadataStore) Price(model string) (ModelPrice, bool) { +func (store *PricingStore) Price(model string) (Price, bool) { store.mu.RLock() defer store.mu.RUnlock() price, ok := store.models[model] return price, ok } -func (store *modelMetadataStore) Snapshot() MetadataSnapshot { +func (store *PricingStore) Snapshot() MetadataSnapshot { store.mu.RLock() defer store.mu.RUnlock() snapshot := MetadataSnapshot{Ready: !store.updatedAt.IsZero() && len(store.models) > 0, Models: len(store.models), LastError: store.lastError, CachePath: store.cachePath} @@ -256,7 +259,7 @@ func (store *modelMetadataStore) Snapshot() MetadataSnapshot { return snapshot } -func (store *modelMetadataStore) loadCache() error { +func (store *PricingStore) loadCache() error { if store.cachePath == "" { return nil } @@ -277,7 +280,7 @@ func (store *modelMetadataStore) loadCache() error { return nil } -func decodeModelsDev(data []byte) (map[string]ModelPrice, error) { +func decodeModelsDev(data []byte) (map[string]Price, error) { var providers map[string]json.RawMessage if err := json.Unmarshal(data, &providers); err != nil { return nil, fmt.Errorf("decode models.dev: %w", err) @@ -302,21 +305,21 @@ func decodeModelsDev(data []byte) (map[string]ModelPrice, error) { continue } if metadataProviderRank(key) == 1 { - identity := strings.ToLower(firstString(stringAt(provider, "id"), stringAt(provider, "name"))) + identity := strings.ToLower(jsonutil.FirstString(jsonutil.StringAt(provider, "id"), jsonutil.StringAt(provider, "name"))) if !strings.Contains(identity, "opencode") { continue } } - models := mapAt(provider, "models") + models := jsonutil.MapAt(provider, "models") if len(models) == 0 { continue } - result := make(map[string]ModelPrice, len(models)) + result := make(map[string]Price, len(models)) for id, raw := range models { model, _ := raw.(map[string]any) - modelID := firstString(stringAt(model, "id"), id) - cost := mapAt(model, "cost") - result[modelID] = ModelPrice{ + modelID := jsonutil.FirstString(jsonutil.StringAt(model, "id"), id) + cost := jsonutil.MapAt(model, "cost") + result[modelID] = Price{ ID: modelID, Input: numberPointer(cost, "input"), Output: numberPointer(cost, "output"), Deprecated: metadataDeprecated(model), } } @@ -351,10 +354,10 @@ func numberPointer(object map[string]any, key string) *float64 { } func metadataDeprecated(model map[string]any) bool { - if boolAt(model, "deprecated") { + if jsonutil.BoolAt(model, "deprecated") { return true } - status := strings.ToLower(firstString(stringAt(model, "status"), stringAt(model, "lifecycle"))) + status := strings.ToLower(jsonutil.FirstString(jsonutil.StringAt(model, "status"), jsonutil.StringAt(model, "lifecycle"))) if status == "deprecated" || status == "retired" || status == "disabled" { return true } diff --git a/convert.go b/internal/protocol/bridge.go similarity index 70% rename from convert.go rename to internal/protocol/bridge.go index 86e7e3b..37f0353 100644 --- a/convert.go +++ b/internal/protocol/bridge.go @@ -1,8 +1,9 @@ -package main +package protocol import ( - "encoding/json" "strings" + + "opencode2api/internal/jsonutil" ) const ( @@ -74,7 +75,7 @@ type bridgeRequest struct { Seed any } -type bridgeUsage struct { +type Usage struct { // Input is the total prompt input, including cache reads and writes. This // matches OpenAI's prompt_tokens semantics and lets each output encoder // split the provider-specific cache fields exactly once. @@ -94,13 +95,13 @@ type bridgeResponse struct { Tools []bridgeBlock Stop string Error string - Usage bridgeUsage + Usage Usage Created int64 } -func convertRequest(from, to Protocol, input map[string]any) (map[string]any, error) { +func ConvertRequest(from, to Protocol, input map[string]any) (map[string]any, error) { if from == to { - return cloneMap(input), nil + return jsonutil.CloneMap(input), nil } request, err := decodeBridgeRequest(from, input) if err != nil { @@ -109,15 +110,6 @@ func convertRequest(from, to Protocol, input map[string]any) (map[string]any, er return encodeBridgeRequest(to, request) } -func firstNonZero(values ...int) int { - for _, value := range values { - if value != 0 { - return value - } - } - return 0 -} - func normalizeResponsesRole(role string) string { if role == "assistant" { return "assistant" @@ -142,7 +134,7 @@ func chatResponseFormat(format any) any { if !ok { return nil } - switch stringAt(object, "type") { + switch jsonutil.StringAt(object, "type") { case "json_object": return map[string]any{"type": "json_object"} case "json_schema": @@ -172,7 +164,7 @@ func responsesTextFormat(format any) any { if !ok { return nil } - switch stringAt(object, "type") { + switch jsonutil.StringAt(object, "type") { case "text", "json_object": return object case "json_schema": @@ -195,11 +187,11 @@ func reasoningEffort(value any) any { if effort := object["effort"]; effort != nil { return effort } - switch stringAt(object, "type") { + switch jsonutil.StringAt(object, "type") { case "disabled": return nil case "enabled", "adaptive": - return effortForThinkingBudget(intAt(object, "budget_tokens")) + return effortForThinkingBudget(jsonutil.IntAt(object, "budget_tokens")) default: return object["type"] } @@ -212,11 +204,11 @@ func anthropicThinking(value any) (any, map[string]any) { return nil, nil } if object, ok := value.(map[string]any); ok { - kind := stringAt(object, "type") + kind := jsonutil.StringAt(object, "type") if kind == "enabled" || kind == "adaptive" || kind == "disabled" { return value, nil } - value = firstAny(object["effort"], object["type"]) + value = jsonutil.FirstAny(object["effort"], object["type"]) } effort, _ := value.(string) effort = strings.ToLower(strings.TrimSpace(effort)) @@ -255,17 +247,6 @@ func bridgeBlocksText(blocks []bridgeBlock) string { return text.String() } -func parseJSONOrString(value string) any { - if value == "" { - return map[string]any{} - } - var decoded any - if json.Unmarshal([]byte(value), &decoded) == nil { - return decoded - } - return value -} - func asPrefix(id, prefix string) string { if strings.HasPrefix(id, prefix+"_") { return id @@ -275,86 +256,3 @@ func asPrefix(id, prefix string) string { } return prefix + "_" + id } - -func put(object map[string]any, key string, value any) { - if value != nil { - object[key] = value - } -} - -func firstAny(values ...any) any { - for _, value := range values { - if value != nil { - return value - } - } - return nil -} - -func cloneMap(input map[string]any) map[string]any { - data, _ := json.Marshal(input) - var output map[string]any - _ = json.Unmarshal(data, &output) - return output -} - -func asSlice(value any) []any { - if values, ok := value.([]any); ok { - return values - } - if value == nil { - return nil - } - return []any{value} -} - -func sliceAt(object map[string]any, path ...string) []any { - values, _ := anyAt(object, path...).([]any) - return values -} - -func mapAt(object map[string]any, path ...string) map[string]any { - value, _ := anyAt(object, path...).(map[string]any) - return value -} - -func stringAt(object map[string]any, path ...string) string { - value, _ := anyAt(object, path...).(string) - return value -} - -func boolAt(object map[string]any, path ...string) bool { - value, _ := anyAt(object, path...).(bool) - return value -} - -func intAt(object map[string]any, path ...string) int { - value := anyAt(object, path...) - switch number := value.(type) { - case float64: - return int(number) - case int: - return number - case json.Number: - integer, _ := number.Int64() - return int(integer) - default: - return 0 - } -} - -func int64At(object map[string]any, path ...string) int64 { - return int64(intAt(object, path...)) -} - -func anyAt(object map[string]any, path ...string) any { - var current any = object - for _, key := range path { - next, ok := current.(map[string]any) - if !ok { - return nil - } - current = next[key] - } - return current -} diff --git a/convert_content.go b/internal/protocol/content.go similarity index 71% rename from convert_content.go rename to internal/protocol/content.go index f40cd7e..2ca5269 100644 --- a/convert_content.go +++ b/internal/protocol/content.go @@ -1,10 +1,13 @@ -package main +package protocol import ( "encoding/json" "errors" "fmt" "strings" + + "opencode2api/internal/identity" + "opencode2api/internal/jsonutil" ) func decodeOpenAIBlocks(value any) []bridgeBlock { @@ -28,24 +31,24 @@ func decodeOpenAIBlocksChecked(value any) ([]bridgeBlock, error) { if !ok { return nil, errors.New("OpenAI content block must be an object") } - switch stringAt(part, "type") { + switch jsonutil.StringAt(part, "type") { case "text", "input_text", "output_text": - blocks = append(blocks, bridgeBlock{Kind: "text", Text: stringAt(part, "text")}) + blocks = append(blocks, bridgeBlock{Kind: "text", Text: jsonutil.StringAt(part, "text")}) case "image_url": - blocks = append(blocks, bridgeBlock{Kind: "image", URL: firstString(stringAt(part, "image_url", "url"), stringAt(part, "image_url"))}) + blocks = append(blocks, bridgeBlock{Kind: "image", URL: jsonutil.FirstString(jsonutil.StringAt(part, "image_url", "url"), jsonutil.StringAt(part, "image_url"))}) case "input_image": - blocks = append(blocks, bridgeBlock{Kind: "image", URL: stringAt(part, "image_url")}) + blocks = append(blocks, bridgeBlock{Kind: "image", URL: jsonutil.StringAt(part, "image_url")}) case "file", "input_file": - file := mapAt(part, "file") + file := jsonutil.MapAt(part, "file") blocks = append(blocks, bridgeBlock{ Kind: "file", - FileID: firstString(stringAt(part, "file_id"), stringAt(file, "file_id")), - Filename: firstString(stringAt(part, "filename"), stringAt(file, "filename")), - MediaType: firstString(stringAt(part, "media_type"), stringAt(file, "media_type")), - Data: firstString(stringAt(part, "file_data"), stringAt(file, "file_data")), + FileID: jsonutil.FirstString(jsonutil.StringAt(part, "file_id"), jsonutil.StringAt(file, "file_id")), + Filename: jsonutil.FirstString(jsonutil.StringAt(part, "filename"), jsonutil.StringAt(file, "filename")), + MediaType: jsonutil.FirstString(jsonutil.StringAt(part, "media_type"), jsonutil.StringAt(file, "media_type")), + Data: jsonutil.FirstString(jsonutil.StringAt(part, "file_data"), jsonutil.StringAt(file, "file_data")), }) default: - return nil, fmt.Errorf("unsupported OpenAI content block type %q", stringAt(part, "type")) + return nil, fmt.Errorf("unsupported OpenAI content block type %q", jsonutil.StringAt(part, "type")) } } return blocks, nil @@ -70,58 +73,58 @@ func decodeAnthropicBlocksChecked(value any) ([]bridgeBlock, error) { return []bridgeBlock{{Kind: "text", Text: text}}, nil } var blocks []bridgeBlock - for _, raw := range asSlice(value) { + for _, raw := range jsonutil.AsSlice(value) { part, ok := raw.(map[string]any) if !ok { return nil, errors.New("Anthropic content block must be an object") } - switch stringAt(part, "type") { + switch jsonutil.StringAt(part, "type") { case "thinking": blocks = append(blocks, bridgeBlock{ Kind: "reasoning", - Text: stringAt(part, "thinking"), - Signature: stringAt(part, "signature"), + Text: jsonutil.StringAt(part, "thinking"), + Signature: jsonutil.StringAt(part, "signature"), }) case "redacted_thinking": - blocks = append(blocks, bridgeBlock{Kind: "reasoning", Encrypted: stringAt(part, "data")}) + blocks = append(blocks, bridgeBlock{Kind: "reasoning", Encrypted: jsonutil.StringAt(part, "data")}) case "text": - blocks = append(blocks, bridgeBlock{Kind: "text", Text: stringAt(part, "text")}) + blocks = append(blocks, bridgeBlock{Kind: "text", Text: jsonutil.StringAt(part, "text")}) case "image": - source := mapAt(part, "source") - if stringAt(source, "type") == "url" { - blocks = append(blocks, bridgeBlock{Kind: "image", URL: stringAt(source, "url")}) + source := jsonutil.MapAt(part, "source") + if jsonutil.StringAt(source, "type") == "url" { + blocks = append(blocks, bridgeBlock{Kind: "image", URL: jsonutil.StringAt(source, "url")}) } else { - blocks = append(blocks, bridgeBlock{Kind: "image", MediaType: stringAt(source, "media_type"), Data: stringAt(source, "data")}) + blocks = append(blocks, bridgeBlock{Kind: "image", MediaType: jsonutil.StringAt(source, "media_type"), Data: jsonutil.StringAt(source, "data")}) } case "document": - source := mapAt(part, "source") - if stringAt(source, "type") == "text" { - blocks = append(blocks, bridgeBlock{Kind: "text", Text: firstString(stringAt(source, "data"), stringAt(source, "text"))}) + source := jsonutil.MapAt(part, "source") + if jsonutil.StringAt(source, "type") == "text" { + blocks = append(blocks, bridgeBlock{Kind: "text", Text: jsonutil.FirstString(jsonutil.StringAt(source, "data"), jsonutil.StringAt(source, "text"))}) continue } blocks = append(blocks, bridgeBlock{ Kind: "file", - URL: stringAt(source, "url"), - MediaType: stringAt(source, "media_type"), - Data: firstString(stringAt(source, "data"), stringAt(source, "text")), - Filename: stringAt(part, "title"), + URL: jsonutil.StringAt(source, "url"), + MediaType: jsonutil.StringAt(source, "media_type"), + Data: jsonutil.FirstString(jsonutil.StringAt(source, "data"), jsonutil.StringAt(source, "text")), + Filename: jsonutil.StringAt(part, "title"), }) case "tool_use": blocks = append(blocks, bridgeBlock{ Kind: "tool_call", - ID: stringAt(part, "id"), - Name: stringAt(part, "name"), + ID: jsonutil.StringAt(part, "id"), + Name: jsonutil.StringAt(part, "name"), Arguments: part["input"], }) case "tool_result": blocks = append(blocks, bridgeBlock{ Kind: "tool_result", - CallID: stringAt(part, "tool_use_id"), + CallID: jsonutil.StringAt(part, "tool_use_id"), Result: part["content"], - IsError: boolAt(part, "is_error"), + IsError: jsonutil.BoolAt(part, "is_error"), }) default: - return nil, fmt.Errorf("unsupported Anthropic content block type %q", stringAt(part, "type")) + return nil, fmt.Errorf("unsupported Anthropic content block type %q", jsonutil.StringAt(part, "type")) } } return blocks, nil @@ -139,29 +142,29 @@ func decodeChatReasoning(message map[string]any) []bridgeBlock { return []bridgeBlock{{ Kind: "reasoning", Text: text, - Signature: stringAt(message, "reasoning_signature"), + Signature: jsonutil.StringAt(message, "reasoning_signature"), }} } func decodeResponsesReasoning(item map[string]any) []bridgeBlock { var text strings.Builder - for _, raw := range asSlice(item["summary"]) { + for _, raw := range jsonutil.AsSlice(item["summary"]) { part, _ := raw.(map[string]any) - text.WriteString(stringAt(part, "text")) + text.WriteString(jsonutil.StringAt(part, "text")) } if content := item["content"]; content != nil { - for _, raw := range asSlice(content) { + for _, raw := range jsonutil.AsSlice(content) { part, _ := raw.(map[string]any) - text.WriteString(stringAt(part, "text")) + text.WriteString(jsonutil.StringAt(part, "text")) } } - encrypted := stringAt(item, "encrypted_content") + encrypted := jsonutil.StringAt(item, "encrypted_content") if text.Len() == 0 && encrypted == "" { return nil } return []bridgeBlock{{ Kind: "reasoning", - ID: stringAt(item, "id"), + ID: jsonutil.StringAt(item, "id"), Text: text.String(), Encrypted: encrypted, }} @@ -182,7 +185,7 @@ func encodeResponsesReasoningInput(block bridgeBlock) (map[string]any, bool) { func encodeResponsesReasoning(block bridgeBlock, completed bool) map[string]any { id := block.ID if id == "" { - id = randomID("rs", 12) + id = identity.RandomID("rs", 12) } summary := []any{} if block.Text != "" { @@ -239,9 +242,9 @@ func encodeChatBlocks(blocks []bridgeBlock) any { parts = append(parts, map[string]any{"type": "image_url", "image_url": map[string]any{"url": url}}) case "file": file := map[string]any{} - put(file, "file_id", block.FileID) - put(file, "file_data", block.Data) - put(file, "filename", block.Filename) + jsonutil.Put(file, "file_id", block.FileID) + jsonutil.Put(file, "file_data", block.Data) + jsonutil.Put(file, "filename", block.Filename) parts = append(parts, map[string]any{"type": "file", "file": file}) } } @@ -265,17 +268,17 @@ func encodeAnthropicBlocks(blocks []bridgeBlock) []any { if block.URL != "" { source = map[string]any{"type": "url", "url": block.URL} } else if block.Data != "" { - source = map[string]any{"type": "base64", "media_type": firstString(block.MediaType, "application/octet-stream"), "data": block.Data} + source = map[string]any{"type": "base64", "media_type": jsonutil.FirstString(block.MediaType, "application/octet-stream"), "data": block.Data} } if source != nil { part := map[string]any{"type": "document", "source": source} - put(part, "title", block.Filename) + jsonutil.Put(part, "title", block.Filename) parts = append(parts, part) } case "tool_call": input := block.Arguments if input == nil { - input = parseJSONOrString(block.ArgumentsJSON) + input = jsonutil.ParseJSONOrString(block.ArgumentsJSON) } parts = append(parts, map[string]any{"type": "tool_use", "id": block.ID, "name": block.Name, "input": input}) case "tool_result": @@ -315,11 +318,11 @@ func bridgeToolResultContent(value any) string { allText := true for _, raw := range parts { part, ok := raw.(map[string]any) - if !ok || stringAt(part, "type") != "text" { + if !ok || jsonutil.StringAt(part, "type") != "text" { allText = false break } - text.WriteString(stringAt(part, "text")) + text.WriteString(jsonutil.StringAt(part, "text")) } if allText { return text.String() @@ -337,8 +340,8 @@ func decodeChatToolChoice(value any) bridgeToolChoice { return bridgeToolChoice{Mode: mode} } choice, _ := value.(map[string]any) - if stringAt(choice, "type") == "function" { - return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "function", "name")} + if jsonutil.StringAt(choice, "type") == "function" { + return bridgeToolChoice{Mode: "named", Name: jsonutil.StringAt(choice, "function", "name")} } return bridgeToolChoice{} } @@ -348,8 +351,8 @@ func decodeResponsesToolChoice(value any) bridgeToolChoice { return bridgeToolChoice{Mode: mode} } choice, _ := value.(map[string]any) - if stringAt(choice, "type") == "function" { - return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "name")} + if jsonutil.StringAt(choice, "type") == "function" { + return bridgeToolChoice{Mode: "named", Name: jsonutil.StringAt(choice, "name")} } return bridgeToolChoice{} } @@ -362,7 +365,7 @@ func decodeAnthropicToolChoice(value any) bridgeToolChoice { return decodeAnthropicToolChoice(map[string]any{"type": mode}) } choice, _ := value.(map[string]any) - switch stringAt(choice, "type") { + switch jsonutil.StringAt(choice, "type") { case "auto": return bridgeToolChoice{Mode: "auto"} case "none": @@ -370,7 +373,7 @@ func decodeAnthropicToolChoice(value any) bridgeToolChoice { case "any": return bridgeToolChoice{Mode: "required"} case "tool": - return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "name")} + return bridgeToolChoice{Mode: "named", Name: jsonutil.StringAt(choice, "name")} default: return bridgeToolChoice{} } diff --git a/internal/protocol/errors.go b/internal/protocol/errors.go new file mode 100644 index 0000000..369243c --- /dev/null +++ b/internal/protocol/errors.go @@ -0,0 +1,19 @@ +package protocol + +import ( + "net/http" + + "opencode2api/internal/httpx" +) + +func WriteError(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 == Anthropic { + httpx.WriteJSONStatus(w, status, map[string]any{"type": "error", "error": map[string]any{"type": kind, "message": message}}) + return + } + httpx.WriteJSONStatus(w, status, map[string]any{"error": map[string]any{"message": message, "type": kind, "param": nil, "code": nil}}) +} diff --git a/internal/protocol/protocol.go b/internal/protocol/protocol.go new file mode 100644 index 0000000..4f35ad3 --- /dev/null +++ b/internal/protocol/protocol.go @@ -0,0 +1,25 @@ +// Package protocol translates Chat, Responses, and Anthropic payloads and streams. +package protocol + +type Protocol string + +const ( + Chat Protocol = "chat" + Responses Protocol = "responses" + Anthropic Protocol = "anthropic" +) + +func Valid(p Protocol) bool { + return p == Chat || p == Responses || p == Anthropic +} + +func Path(protocol Protocol) string { + switch protocol { + case Responses: + return "/v1/responses" + case Anthropic: + return "/v1/messages" + default: + return "/v1/chat/completions" + } +} diff --git a/convert_request.go b/internal/protocol/request.go similarity index 83% rename from convert_request.go rename to internal/protocol/request.go index 425e3e5..7787858 100644 --- a/convert_request.go +++ b/internal/protocol/request.go @@ -1,23 +1,25 @@ -package main +package protocol import ( "errors" "fmt" "sort" "strings" + + "opencode2api/internal/jsonutil" ) -// prepareUpstreamRequest is the single request preparation path for both +// PrepareRequest is the single request preparation path for both // pass-through and transcoded requests. Same-protocol requests are cloned so // provider-specific fields survive, while cross-protocol requests go through // the bridge. Target-protocol normalization then repairs reasoning history in // either case. -func prepareUpstreamRequest(from, to Protocol, input map[string]any, upstreamURL string) (map[string]any, error) { - output, err := convertRequest(from, to, input) +func PrepareRequest(from, to Protocol, input map[string]any, upstreamURL string) (map[string]any, error) { + output, err := ConvertRequest(from, to, input) if err != nil { return nil, err } - normalizeToolReasoningHistory(to, stringAt(output, "model"), upstreamURL, output) + normalizeToolReasoningHistory(to, jsonutil.StringAt(output, "model"), upstreamURL, output) return output, nil } @@ -29,7 +31,7 @@ func normalizeToolReasoningHistory(protocol Protocol, model, upstreamURL string, vendor := isReasoningVendorIdentifier(model) || isReasoningVendorIdentifier(upstreamURL) widened := vendor || requestEnablesReasoning(input) switch protocol { - case ProtocolChat: + case Chat: // The Chat repair is additive: it only supplies reasoning_content that // a compatible endpoint ignores when it does not understand the field. // The widened gate is therefore safe here. @@ -37,7 +39,7 @@ func normalizeToolReasoningHistory(protocol Protocol, model, upstreamURL string, return false } return normalizeChatToolReasoningHistory(input) - case ProtocolAnthropic: + case Anthropic: // Every repair below is destructive for a native Anthropic endpoint: // it deletes thinking signatures, discards redacted_thinking payloads // and overwrites empty thinking text. Those are precisely the shapes a @@ -80,7 +82,7 @@ func requestEnablesReasoning(input map[string]any) bool { return true } case map[string]any: - mode := strings.ToLower(strings.TrimSpace(firstString(stringAt(typed, "type"), stringAt(typed, "effort")))) + mode := strings.ToLower(strings.TrimSpace(jsonutil.FirstString(jsonutil.StringAt(typed, "type"), jsonutil.StringAt(typed, "effort")))) if mode == "none" || mode == "disabled" { continue } @@ -105,7 +107,7 @@ func normalizeChatToolReasoningHistory(input map[string]any) bool { changed := false for _, rawMessage := range messages { message, ok := rawMessage.(map[string]any) - if !ok || stringAt(message, "role") != "assistant" || len(sliceAt(message, "tool_calls")) == 0 { + if !ok || jsonutil.StringAt(message, "role") != "assistant" || len(jsonutil.SliceAt(message, "tool_calls")) == 0 { continue } if reasoning, ok := message["reasoning_content"].(string); ok && strings.TrimSpace(reasoning) != "" { @@ -134,7 +136,7 @@ func normalizeAnthropicToolThinkingHistory(input map[string]any) bool { changed := false for _, rawMessage := range messages { message, ok := rawMessage.(map[string]any) - if !ok || stringAt(message, "role") != "assistant" { + if !ok || jsonutil.StringAt(message, "role") != "assistant" { continue } content, ok := message["content"].([]any) @@ -148,7 +150,7 @@ func normalizeAnthropicToolThinkingHistory(input map[string]any) bool { if !ok { continue } - switch stringAt(block, "type") { + switch jsonutil.StringAt(block, "type") { case "thinking": hasThinking = true if _, exists := block["signature"]; exists { @@ -184,7 +186,7 @@ func normalizeAnthropicToolThinkingHistory(input map[string]any) bool { func anthropicContentHasType(content []any, kind string) bool { for _, rawBlock := range content { block, _ := rawBlock.(map[string]any) - if stringAt(block, "type") == kind { + if jsonutil.StringAt(block, "type") == kind { return true } } @@ -193,23 +195,23 @@ func anthropicContentHasType(content []any, kind string) bool { func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest, error) { request := bridgeRequest{ - Model: stringAt(input, "model"), - Stream: boolAt(input, "stream"), + Model: jsonutil.StringAt(input, "model"), + Stream: jsonutil.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"]) + case Chat: + request.MaxTokens = jsonutil.FirstAny(input["max_completion_tokens"], input["max_tokens"]) request.Stop = input["stop"] - request.Reasoning = firstAny(input["reasoning_effort"], input["reasoning"]) - for i, raw := range sliceAt(input, "messages") { + request.Reasoning = jsonutil.FirstAny(input["reasoning_effort"], input["reasoning"]) + for i, raw := range jsonutil.SliceAt(input, "messages") { message, ok := raw.(map[string]any) if !ok { return request, fmt.Errorf("messages[%d] must be an object", i) } - role := stringAt(message, "role") + role := jsonutil.StringAt(message, "role") blocks, err := decodeOpenAIBlocksChecked(message["content"]) if err != nil { return request, fmt.Errorf("messages[%d]: %w", i, err) @@ -217,17 +219,17 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest if role == "assistant" { blocks = append(decodeChatReasoning(message), blocks...) } - for j, rawCall := range sliceAt(message, "tool_calls") { + for j, rawCall := range jsonutil.SliceAt(message, "tool_calls") { call, ok := rawCall.(map[string]any) if !ok { return request, fmt.Errorf("messages[%d].tool_calls[%d] must be an object", i, j) } - function := mapAt(call, "function") + function := jsonutil.MapAt(call, "function") blocks = append(blocks, bridgeBlock{ Kind: "tool_call", - ID: stringAt(call, "id"), - Name: stringAt(function, "name"), - ArgumentsJSON: stringAt(function, "arguments"), + ID: jsonutil.StringAt(call, "id"), + Name: jsonutil.StringAt(function, "name"), + ArgumentsJSON: jsonutil.StringAt(function, "arguments"), }) } switch role { @@ -238,7 +240,7 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest case "tool": request.Messages = append(request.Messages, bridgeMessage{Role: "user", Blocks: []bridgeBlock{{ Kind: "tool_result", - CallID: stringAt(message, "tool_call_id"), + CallID: jsonutil.StringAt(message, "tool_call_id"), Result: message["content"], }}}) case "user", "assistant": @@ -247,17 +249,17 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest return request, fmt.Errorf("messages[%d] has unsupported role %q", i, role) } } - for i, raw := range sliceAt(input, "tools") { + for i, raw := range jsonutil.SliceAt(input, "tools") { tool, ok := raw.(map[string]any) - if !ok || stringAt(tool, "type") != "function" { + if !ok || jsonutil.StringAt(tool, "type") != "function" { return request, fmt.Errorf("tools[%d] must be a function tool", i) } - function := mapAt(tool, "function") + function := jsonutil.MapAt(tool, "function") request.Tools = append(request.Tools, bridgeTool{ - Name: stringAt(function, "name"), - Description: stringAt(function, "description"), + Name: jsonutil.StringAt(function, "name"), + Description: jsonutil.StringAt(function, "description"), Schema: function["parameters"], - Strict: boolAt(function, "strict"), + Strict: jsonutil.BoolAt(function, "strict"), }) } request.ToolChoice = decodeChatToolChoice(input["tool_choice"]) @@ -267,10 +269,10 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest request.PresencePenalty = input["presence_penalty"] request.Seed = input["seed"] - case ProtocolResponses: + case Responses: request.MaxTokens = input["max_output_tokens"] request.Stop = input["stop"] - request.Reasoning = firstAny(input["reasoning"], input["reasoning_effort"]) + request.Reasoning = jsonutil.FirstAny(input["reasoning"], input["reasoning_effort"]) instructions, err := decodeOpenAIBlocksChecked(input["instructions"]) if err != nil { return request, fmt.Errorf("instructions: %w", err) @@ -285,7 +287,7 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest if !ok { return request, fmt.Errorf("input[%d] must be an object", i) } - switch stringAt(item, "type") { + switch jsonutil.StringAt(item, "type") { case "reasoning": for _, block := range decodeResponsesReasoning(item) { appendBridgeBlock(&request.Messages, "assistant", block) @@ -293,18 +295,18 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest case "function_call": appendBridgeBlock(&request.Messages, "assistant", bridgeBlock{ Kind: "tool_call", - ID: firstString(stringAt(item, "call_id"), stringAt(item, "id")), - Name: stringAt(item, "name"), - ArgumentsJSON: stringAt(item, "arguments"), + ID: jsonutil.FirstString(jsonutil.StringAt(item, "call_id"), jsonutil.StringAt(item, "id")), + Name: jsonutil.StringAt(item, "name"), + ArgumentsJSON: jsonutil.StringAt(item, "arguments"), }) case "function_call_output": appendBridgeBlock(&request.Messages, "user", bridgeBlock{ Kind: "tool_result", - CallID: stringAt(item, "call_id"), + CallID: jsonutil.StringAt(item, "call_id"), Result: item["output"], }) case "message", "": - role := stringAt(item, "role") + role := jsonutil.StringAt(item, "role") blocks, err := decodeOpenAIBlocksChecked(item["content"]) if err != nil { return request, fmt.Errorf("input[%d]: %w", i, err) @@ -317,43 +319,43 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks}) } default: - return request, fmt.Errorf("input[%d] has unsupported Responses item type %q", i, stringAt(item, "type")) + return request, fmt.Errorf("input[%d] has unsupported Responses item type %q", i, jsonutil.StringAt(item, "type")) } } default: return request, fmt.Errorf("input must be a string or array") } - for i, raw := range sliceAt(input, "tools") { + for i, raw := range jsonutil.SliceAt(input, "tools") { tool, ok := raw.(map[string]any) - if !ok || stringAt(tool, "type") != "function" { + if !ok || jsonutil.StringAt(tool, "type") != "function" { return request, fmt.Errorf("tools[%d] must be a function tool", i) } request.Tools = append(request.Tools, bridgeTool{ - Name: stringAt(tool, "name"), - Description: stringAt(tool, "description"), + Name: jsonutil.StringAt(tool, "name"), + Description: jsonutil.StringAt(tool, "description"), Schema: tool["parameters"], - Strict: boolAt(tool, "strict"), + Strict: jsonutil.BoolAt(tool, "strict"), }) } request.ToolChoice = decodeResponsesToolChoice(input["tool_choice"]) - request.ResponseFormat = mapAt(input, "text", "format") + request.ResponseFormat = jsonutil.MapAt(input, "text", "format") request.ParallelToolCalls = input["parallel_tool_calls"] - case ProtocolAnthropic: + case Anthropic: request.MaxTokens = input["max_tokens"] request.Stop = input["stop_sequences"] - request.Reasoning = firstAny(input["thinking"], anyAt(input, "output_config", "effort"), input["effort"]) + request.Reasoning = jsonutil.FirstAny(input["thinking"], jsonutil.AnyAt(input, "output_config", "effort"), input["effort"]) blocks, err := decodeAnthropicBlocksChecked(input["system"]) if err != nil { return request, fmt.Errorf("system: %w", err) } request.System = blocks - for i, raw := range sliceAt(input, "messages") { + for i, raw := range jsonutil.SliceAt(input, "messages") { message, ok := raw.(map[string]any) if !ok { return request, fmt.Errorf("messages[%d] must be an object", i) } - role := stringAt(message, "role") + role := jsonutil.StringAt(message, "role") // Some clients (e.g. Claude Code) inline system/developer messages // into the messages array instead of using the top-level system // field. Fold them into the system prompt rather than rejecting. @@ -382,14 +384,14 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest } request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks}) } - for i, raw := range sliceAt(input, "tools") { + for i, raw := range jsonutil.SliceAt(input, "tools") { tool, ok := raw.(map[string]any) if !ok { return request, fmt.Errorf("tools[%d] must be an object", i) } request.Tools = append(request.Tools, bridgeTool{ - Name: stringAt(tool, "name"), - Description: stringAt(tool, "description"), + Name: jsonutil.StringAt(tool, "name"), + Description: jsonutil.StringAt(tool, "description"), Schema: tool["input_schema"], }) } @@ -429,11 +431,11 @@ func encodeBridgeRequest(protocol Protocol, request bridgeRequest) (map[string]a return nil, err } switch protocol { - case ProtocolChat: + case Chat: return encodeChatRequest(request) - case ProtocolResponses: + case Responses: return encodeResponsesRequest(request), nil - case ProtocolAnthropic: + case Anthropic: return encodeAnthropicRequest(request), nil default: return nil, fmt.Errorf("unsupported output protocol %q", protocol) @@ -441,7 +443,7 @@ func encodeBridgeRequest(protocol Protocol, request bridgeRequest) (map[string]a } func validateBridgeRequest(protocol Protocol, request bridgeRequest) error { - if protocol == ProtocolResponses { + if protocol == Responses { for _, block := range request.System { if block.Kind == "file" { return errors.New("file content is not valid inside Responses instructions; send it as a message input item") @@ -455,7 +457,7 @@ func validateBridgeRequest(protocol Protocol, request bridgeRequest) error { blocks = append(blocks, message.Blocks...) } for _, block := range blocks { - if block.Kind == "file" && protocol == ProtocolAnthropic && block.FileID != "" && block.Data == "" && block.URL == "" { + if block.Kind == "file" && protocol == Anthropic && block.FileID != "" && block.Data == "" && block.URL == "" { return fmt.Errorf("file %q cannot be represented by Anthropic Messages without file data or a URL", block.FileID) } } @@ -464,18 +466,18 @@ func validateBridgeRequest(protocol Protocol, request bridgeRequest) error { func encodeChatRequest(request bridgeRequest) (map[string]any, error) { output := map[string]any{"model": request.Model, "stream": request.Stream} - put(output, "temperature", request.Temperature) - put(output, "top_p", request.TopP) - put(output, "max_tokens", request.MaxTokens) - put(output, "stop", request.Stop) + jsonutil.Put(output, "temperature", request.Temperature) + jsonutil.Put(output, "top_p", request.TopP) + jsonutil.Put(output, "max_tokens", request.MaxTokens) + jsonutil.Put(output, "stop", request.Stop) if effort := reasoningEffort(request.Reasoning); effort != nil { output["reasoning_effort"] = effort } - put(output, "response_format", chatResponseFormat(request.ResponseFormat)) - put(output, "parallel_tool_calls", request.ParallelToolCalls) - put(output, "frequency_penalty", request.FrequencyPenalty) - put(output, "presence_penalty", request.PresencePenalty) - put(output, "seed", request.Seed) + jsonutil.Put(output, "response_format", chatResponseFormat(request.ResponseFormat)) + jsonutil.Put(output, "parallel_tool_calls", request.ParallelToolCalls) + jsonutil.Put(output, "frequency_penalty", request.FrequencyPenalty) + jsonutil.Put(output, "presence_penalty", request.PresencePenalty) + jsonutil.Put(output, "seed", request.Seed) if request.Stream { output["stream_options"] = map[string]any{"include_usage": true} } @@ -645,11 +647,11 @@ func missingToolIDs(order []string, pending map[string]bool) []string { func encodeResponsesRequest(request bridgeRequest) 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, "max_output_tokens", request.MaxTokens) - put(output, "stop", request.Stop) - put(output, "metadata", request.Metadata) + jsonutil.Put(output, "temperature", request.Temperature) + jsonutil.Put(output, "top_p", request.TopP) + jsonutil.Put(output, "max_output_tokens", request.MaxTokens) + jsonutil.Put(output, "stop", request.Stop) + jsonutil.Put(output, "metadata", request.Metadata) if len(request.System) > 0 { output["instructions"] = bridgeBlocksText(request.System) } @@ -664,7 +666,7 @@ func encodeResponsesRequest(request bridgeRequest) map[string]any { if format := responsesTextFormat(request.ResponseFormat); format != nil { output["text"] = map[string]any{"format": format} } - put(output, "parallel_tool_calls", request.ParallelToolCalls) + jsonutil.Put(output, "parallel_tool_calls", request.ParallelToolCalls) items := make([]any, 0, len(request.Messages)+1) if len(request.Developer) > 0 { @@ -712,9 +714,9 @@ func encodeResponsesRequest(request bridgeRequest) map[string]any { content = append(content, map[string]any{"type": "input_image", "image_url": url}) case "file": item := map[string]any{"type": "input_file"} - put(item, "file_id", block.FileID) - put(item, "file_data", block.Data) - put(item, "filename", block.Filename) + jsonutil.Put(item, "file_id", block.FileID) + jsonutil.Put(item, "file_data", block.Data) + jsonutil.Put(item, "filename", block.Filename) content = append(content, item) case "tool_call": flushContent() @@ -757,9 +759,9 @@ func encodeResponsesRequest(request bridgeRequest) map[string]any { func encodeAnthropicRequest(request bridgeRequest) 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, "stop_sequences", request.Stop) + jsonutil.Put(output, "temperature", request.Temperature) + jsonutil.Put(output, "top_p", request.TopP) + jsonutil.Put(output, "stop_sequences", request.Stop) if request.MaxTokens == nil { output["max_tokens"] = 4096 } else { @@ -789,8 +791,8 @@ func encodeAnthropicRequest(request bridgeRequest) map[string]any { } if len(messages) > 0 { last, _ := messages[len(messages)-1].(map[string]any) - if stringAt(last, "role") == role { - last["content"] = append(asSlice(last["content"]), content...) + if jsonutil.StringAt(last, "role") == role { + last["content"] = append(jsonutil.AsSlice(last["content"]), content...) continue } } diff --git a/convert_response.go b/internal/protocol/response.go similarity index 67% rename from convert_response.go rename to internal/protocol/response.go index a82829b..d95bf33 100644 --- a/convert_response.go +++ b/internal/protocol/response.go @@ -1,12 +1,15 @@ -package main +package protocol import ( "encoding/json" "fmt" "time" + + "opencode2api/internal/identity" + "opencode2api/internal/jsonutil" ) -func convertResponse(from, to Protocol, body []byte) ([]byte, error) { +func ConvertResponse(from, to Protocol, body []byte) ([]byte, error) { if from == to { return append([]byte(nil), body...), nil } @@ -19,37 +22,37 @@ func convertResponse(from, to Protocol, body []byte) ([]byte, error) { return nil, err } if response.Error != "" || response.Stop == "error" { - return nil, fmt.Errorf("upstream response failed: %s", firstString(response.Error, "upstream response failed")) + return nil, fmt.Errorf("upstream response failed: %s", jsonutil.FirstString(response.Error, "upstream response failed")) } return json.Marshal(encodeBridgeResponse(to, response)) } func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeResponse, error) { response := bridgeResponse{ - ID: stringAt(input, "id"), - Model: stringAt(input, "model"), - Created: int64At(input, "created"), + ID: jsonutil.StringAt(input, "id"), + Model: jsonutil.StringAt(input, "model"), + Created: jsonutil.Int64At(input, "created"), } if response.Created == 0 { - response.Created = int64At(input, "created_at") + response.Created = jsonutil.Int64At(input, "created_at") } if response.Created == 0 { response.Created = time.Now().Unix() } switch protocol { - case ProtocolChat: - if message := stringAt(input, "error", "message"); message != "" { + case Chat: + if message := jsonutil.StringAt(input, "error", "message"); message != "" { response.Error = message } if response.Error != "" { return response, nil } - choices := sliceAt(input, "choices") + choices := jsonutil.SliceAt(input, "choices") if len(choices) == 0 { return response, fmt.Errorf("chat response contains no choices") } choice, _ := choices[0].(map[string]any) - message := mapAt(choice, "message") + message := jsonutil.MapAt(choice, "message") response.Reasoning = decodeChatReasoning(message) blocks, err := decodeOpenAIBlocksChecked(message["content"]) if err != nil { @@ -59,22 +62,22 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon if err != nil { return response, err } - for _, raw := range sliceAt(message, "tool_calls") { + for _, raw := range jsonutil.SliceAt(message, "tool_calls") { call, _ := raw.(map[string]any) - function := mapAt(call, "function") + function := jsonutil.MapAt(call, "function") response.Tools = append(response.Tools, bridgeBlock{ Kind: "tool_call", - ID: stringAt(call, "id"), - Name: stringAt(function, "name"), - ArgumentsJSON: stringAt(function, "arguments"), + ID: jsonutil.StringAt(call, "id"), + Name: jsonutil.StringAt(function, "name"), + ArgumentsJSON: jsonutil.StringAt(function, "arguments"), }) } - response.Stop = canonicalChatStop(stringAt(choice, "finish_reason")) - response.Usage = decodeOpenAIUsage(mapAt(input, "usage")) - case ProtocolResponses: - for _, raw := range sliceAt(input, "output") { + response.Stop = canonicalChatStop(jsonutil.StringAt(choice, "finish_reason")) + response.Usage = decodeOpenAIUsage(jsonutil.MapAt(input, "usage")) + case Responses: + for _, raw := range jsonutil.SliceAt(input, "output") { item, _ := raw.(map[string]any) - switch stringAt(item, "type") { + switch jsonutil.StringAt(item, "type") { case "reasoning": response.Reasoning = append(response.Reasoning, decodeResponsesReasoning(item)...) case "message": @@ -90,28 +93,28 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon case "function_call": response.Tools = append(response.Tools, bridgeBlock{ Kind: "tool_call", - ID: firstString(stringAt(item, "call_id"), stringAt(item, "id")), - Name: stringAt(item, "name"), - ArgumentsJSON: stringAt(item, "arguments"), + ID: jsonutil.FirstString(jsonutil.StringAt(item, "call_id"), jsonutil.StringAt(item, "id")), + Name: jsonutil.StringAt(item, "name"), + ArgumentsJSON: jsonutil.StringAt(item, "arguments"), }) default: - return response, fmt.Errorf("Responses response has unsupported output item type %q", stringAt(item, "type")) + return response, fmt.Errorf("Responses response has unsupported output item type %q", jsonutil.StringAt(item, "type")) } } response.Stop = "stop" if len(response.Tools) > 0 { response.Stop = "tool_calls" } - if stringAt(input, "status") == "incomplete" { - response.Stop = canonicalResponsesIncomplete(stringAt(input, "incomplete_details", "reason")) - } else if stringAt(input, "status") == "failed" { + if jsonutil.StringAt(input, "status") == "incomplete" { + response.Stop = canonicalResponsesIncomplete(jsonutil.StringAt(input, "incomplete_details", "reason")) + } else if jsonutil.StringAt(input, "status") == "failed" { response.Stop = "error" - response.Error = firstString(stringAt(input, "error", "message"), "upstream Responses request failed") + response.Error = jsonutil.FirstString(jsonutil.StringAt(input, "error", "message"), "upstream Responses request failed") } - response.Usage = decodeOpenAIUsage(mapAt(input, "usage")) - case ProtocolAnthropic: - if stringAt(input, "type") == "error" { - response.Error = firstString(stringAt(input, "error", "message"), "upstream Anthropic request failed") + response.Usage = decodeOpenAIUsage(jsonutil.MapAt(input, "usage")) + case Anthropic: + if jsonutil.StringAt(input, "type") == "error" { + response.Error = jsonutil.FirstString(jsonutil.StringAt(input, "error", "message"), "upstream Anthropic request failed") } blocks, err := decodeAnthropicBlocksChecked(input["content"]) if err != nil { @@ -128,8 +131,8 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon return response, fmt.Errorf("Anthropic response contains unsupported %s content block", block.Kind) } } - response.Stop = canonicalAnthropicStop(stringAt(input, "stop_reason")) - response.Usage = decodeAnthropicUsage(mapAt(input, "usage")) + response.Stop = canonicalAnthropicStop(jsonutil.StringAt(input, "stop_reason")) + response.Usage = decodeAnthropicUsage(jsonutil.MapAt(input, "usage")) default: return response, fmt.Errorf("unsupported response protocol %q", protocol) } @@ -138,10 +141,10 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string]any { if response.ID == "" { - response.ID = randomID("resp", 12) + response.ID = identity.RandomID("resp", 12) } switch protocol { - case ProtocolChat: + case Chat: message := map[string]any{"role": "assistant", "content": response.Text} if value, ok := bridgeReasoningText(response.Reasoning); ok { message["reasoning_content"] = value @@ -175,14 +178,14 @@ func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string }}, "usage": openAIUsage(response.Usage), } - case ProtocolResponses: + case Responses: output := make([]any, 0, len(response.Reasoning)+len(response.Tools)+1) for _, reasoning := range response.Reasoning { output = append(output, encodeResponsesReasoning(reasoning, true)) } if response.Text != "" { output = append(output, map[string]any{ - "id": randomID("msg", 12), + "id": identity.RandomID("msg", 12), "type": "message", "status": "completed", "role": "assistant", @@ -195,7 +198,7 @@ func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string } for _, tool := range response.Tools { output = append(output, map[string]any{ - "id": randomID("fc", 12), + "id": identity.RandomID("fc", 12), "type": "function_call", "status": "completed", "call_id": tool.ID, @@ -232,7 +235,7 @@ func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string }, }, } - case ProtocolAnthropic: + case Anthropic: content := make([]any, 0, len(response.Reasoning)+len(response.Tools)+1) content = append(content, encodeAnthropicBlocks(response.Reasoning)...) if response.Text != "" { @@ -241,7 +244,7 @@ func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string for _, tool := range response.Tools { input := tool.Arguments if input == nil { - input = parseJSONOrString(tool.ArgumentsJSON) + input = jsonutil.ParseJSONOrString(tool.ArgumentsJSON) } content = append(content, map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": input}) } @@ -260,31 +263,31 @@ func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string } } -func decodeOpenAIUsage(usage map[string]any) bridgeUsage { - input := firstNonZero(intAt(usage, "prompt_tokens"), intAt(usage, "input_tokens")) - output := firstNonZero(intAt(usage, "completion_tokens"), intAt(usage, "output_tokens")) - total := intAt(usage, "total_tokens") +func decodeOpenAIUsage(usage map[string]any) Usage { + input := jsonutil.FirstNonZero(jsonutil.IntAt(usage, "prompt_tokens"), jsonutil.IntAt(usage, "input_tokens")) + output := jsonutil.FirstNonZero(jsonutil.IntAt(usage, "completion_tokens"), jsonutil.IntAt(usage, "output_tokens")) + total := jsonutil.IntAt(usage, "total_tokens") if total == 0 { total = input + output } - cached := firstNonZero(intAt(usage, "prompt_tokens_details", "cached_tokens"), intAt(usage, "input_tokens_details", "cached_tokens")) - cacheCreation := firstNonZero( - intAt(usage, "cache_creation_input_tokens"), - intAt(usage, "prompt_tokens_details", "cache_creation_input_tokens"), - intAt(usage, "prompt_tokens_details", "cache_write_tokens"), - intAt(usage, "input_tokens_details", "cache_creation_input_tokens"), + cached := jsonutil.FirstNonZero(jsonutil.IntAt(usage, "prompt_tokens_details", "cached_tokens"), jsonutil.IntAt(usage, "input_tokens_details", "cached_tokens")) + cacheCreation := jsonutil.FirstNonZero( + jsonutil.IntAt(usage, "cache_creation_input_tokens"), + jsonutil.IntAt(usage, "prompt_tokens_details", "cache_creation_input_tokens"), + jsonutil.IntAt(usage, "prompt_tokens_details", "cache_write_tokens"), + jsonutil.IntAt(usage, "input_tokens_details", "cache_creation_input_tokens"), ) - reasoning := firstNonZero(intAt(usage, "completion_tokens_details", "reasoning_tokens"), intAt(usage, "output_tokens_details", "reasoning_tokens")) - return bridgeUsage{Input: input, Output: output, Total: total, Cached: cached, CacheCreation: cacheCreation, Reasoning: reasoning} + reasoning := jsonutil.FirstNonZero(jsonutil.IntAt(usage, "completion_tokens_details", "reasoning_tokens"), jsonutil.IntAt(usage, "output_tokens_details", "reasoning_tokens")) + return Usage{Input: input, Output: output, Total: total, Cached: cached, CacheCreation: cacheCreation, Reasoning: reasoning} } -func decodeAnthropicUsage(usage map[string]any) bridgeUsage { - input := intAt(usage, "input_tokens") - cached := intAt(usage, "cache_read_input_tokens") - cacheCreation := intAt(usage, "cache_creation_input_tokens") - output := intAt(usage, "output_tokens") +func decodeAnthropicUsage(usage map[string]any) Usage { + input := jsonutil.IntAt(usage, "input_tokens") + cached := jsonutil.IntAt(usage, "cache_read_input_tokens") + cacheCreation := jsonutil.IntAt(usage, "cache_creation_input_tokens") + output := jsonutil.IntAt(usage, "output_tokens") input += cached + cacheCreation - return bridgeUsage{ + return Usage{ Input: input, Output: output, Total: input + output, @@ -293,7 +296,7 @@ func decodeAnthropicUsage(usage map[string]any) bridgeUsage { } } -func openAIUsage(usage bridgeUsage) map[string]any { +func openAIUsage(usage Usage) map[string]any { return map[string]any{ "prompt_tokens": usage.Input, "completion_tokens": usage.Output, @@ -307,7 +310,7 @@ func openAIUsage(usage bridgeUsage) map[string]any { } } -func anthropicUsage(usage bridgeUsage) map[string]any { +func anthropicUsage(usage Usage) map[string]any { return map[string]any{ "input_tokens": max(usage.Input-usage.Cached-usage.CacheCreation, 0), "output_tokens": usage.Output, @@ -396,3 +399,18 @@ func responseTextBlocks(blocks []bridgeBlock, protocol string) (string, error) { } return bridgeBlocksText(blocks), nil } + +func ResponseUsage(protocol Protocol, body []byte) (Usage, bool) { + var payload map[string]any + if json.Unmarshal(body, &payload) != nil { + return Usage{}, false + } + usage := jsonutil.MapAt(payload, "usage") + if len(usage) == 0 { + return Usage{}, false + } + if protocol == Anthropic { + return decodeAnthropicUsage(usage), true + } + return decodeOpenAIUsage(usage), true +} diff --git a/stream.go b/internal/protocol/stream.go similarity index 87% rename from stream.go rename to internal/protocol/stream.go index fc8c34f..66bc6d1 100644 --- a/stream.go +++ b/internal/protocol/stream.go @@ -1,4 +1,4 @@ -package main +package protocol import ( "bufio" @@ -38,7 +38,7 @@ type bridgeStreamEvent struct { Error string ErrorType string Encrypted string - Usage *bridgeUsage + Usage *Usage } func transcodeStream(w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) error { @@ -46,17 +46,17 @@ func transcodeStream(w http.ResponseWriter, reader io.Reader, from, to Protocol, return err } -func transcodeStreamWithUsage(w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) (bridgeUsage, bool, error) { - return transcodeStreamWithUsageContext(context.Background(), w, reader, from, to, model) +func transcodeStreamWithUsage(w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) (Usage, bool, error) { + return TranscodeStream(context.Background(), w, reader, from, to, model) } -// transcodeStreamWithUsageContext is the request-aware form used by the +// TranscodeStream is the request-aware form used by the // gateway. A cancelled client must not receive a synthetic upstream error // after its connection has gone away. -func transcodeStreamWithUsageContext(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) (bridgeUsage, bool, error) { +func TranscodeStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) (Usage, bool, error) { flusher, ok := w.(http.Flusher) if !ok { - return bridgeUsage{}, false, fmt.Errorf("response writer does not support streaming") + return Usage{}, false, fmt.Errorf("response writer does not support streaming") } parser := &bridgeStreamParser{ protocol: from, @@ -97,7 +97,7 @@ func transcodeStreamWithUsageContext(ctx context.Context, w http.ResponseWriter, if errors.Is(readErr, errStreamNormalTermination) { return emitter.usage, emitter.usageReported, nil } - if streamClientCancelled(ctx, readErr) { + if ClientCanceled(ctx, readErr) { return emitter.usage, emitter.usageReported, readErr } if termination == streamOpen { @@ -113,7 +113,7 @@ func transcodeStreamWithUsageContext(ctx context.Context, w http.ResponseWriter, if termination == streamErrorTermination { return emitter.usage, emitter.usageReported, errStreamUpstreamFailure } - if streamClientCancelled(ctx, nil) { + if ClientCanceled(ctx, nil) { return emitter.usage, emitter.usageReported, ctx.Err() } if err := emitUnexpectedStreamError(emitter, errSSEUnexpectedEOF); err != nil { @@ -134,7 +134,7 @@ func emitUnexpectedStreamError(emitter *bridgeStreamEmitter, cause error) error return err } -func streamClientCancelled(ctx context.Context, streamErr error) bool { +func ClientCanceled(ctx context.Context, streamErr error) bool { if errors.Is(streamErr, context.Canceled) { return true } @@ -158,14 +158,14 @@ func (writer *sseFlushWriter) Write(data []byte) (int, error) { return n, err } -func forwardSSEWithUsage(w http.ResponseWriter, reader io.Reader, protocol Protocol, model string) (bridgeUsage, bool, error) { - return forwardSSEWithUsageContext(context.Background(), w, reader, protocol, model) +func forwardSSEWithUsage(w http.ResponseWriter, reader io.Reader, protocol Protocol, model string) (Usage, bool, error) { + return ForwardStream(context.Background(), w, reader, protocol, model) } -func forwardSSEWithUsageContext(ctx context.Context, w http.ResponseWriter, reader io.Reader, protocol Protocol, model string) (bridgeUsage, bool, error) { +func ForwardStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, protocol Protocol, model string) (Usage, bool, error) { flusher, ok := w.(http.Flusher) if !ok { - return bridgeUsage{}, false, fmt.Errorf("response writer does not support streaming") + return Usage{}, false, fmt.Errorf("response writer does not support streaming") } observer := newStreamUsageObserver(protocol) _, copyErr := io.Copy(&sseFlushWriter{writer: w, flusher: flusher}, io.TeeReader(reader, observer)) @@ -179,7 +179,7 @@ func forwardSSEWithUsageContext(ctx context.Context, w http.ResponseWriter, read if observer.NormalTermination() && observer.ParseError() == nil { return usage, observer.Reported(), copyErr } - if streamClientCancelled(ctx, copyErr) { + if ClientCanceled(ctx, copyErr) { if copyErr == nil { copyErr = ctx.Err() } @@ -202,7 +202,7 @@ func forwardSSEWithUsageContext(ctx context.Context, w http.ResponseWriter, read type streamUsageObserver struct { parser *bridgeStreamParser buffer []byte - usage bridgeUsage + usage Usage reported bool normal bool error bool @@ -230,7 +230,7 @@ func (observer *streamUsageObserver) Write(data []byte) (int, error) { return len(data), nil } -func (observer *streamUsageObserver) Finish() bridgeUsage { +func (observer *streamUsageObserver) Finish() Usage { // An unterminated final line is not an SSE frame. In particular, do not // count a usage object from a response that was cut off at EOF. observer.buffer = nil diff --git a/stream_emitter.go b/internal/protocol/stream_emitter.go similarity index 93% rename from stream_emitter.go rename to internal/protocol/stream_emitter.go index 0ecd1d6..fa498d1 100644 --- a/stream_emitter.go +++ b/internal/protocol/stream_emitter.go @@ -1,4 +1,4 @@ -package main +package protocol import ( "encoding/json" @@ -7,6 +7,9 @@ import ( "net/http" "strings" "time" + + "opencode2api/internal/identity" + "opencode2api/internal/jsonutil" ) type bridgeStreamTool struct { @@ -31,7 +34,7 @@ type bridgeStreamEmitter struct { started bool done bool stop string - usage bridgeUsage + usage Usage usageReported bool reasoningEncrypted string text strings.Builder @@ -83,10 +86,10 @@ func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error { case "reasoning": if event.Encrypted != "" { emitter.reasoningEncrypted = event.Encrypted - if emitter.target != ProtocolResponses && event.Text == "" { + if emitter.target != Responses && event.Text == "" { event.Text = anthropicRedactedThinkingPlaceholder } - if emitter.target == ProtocolResponses && event.Text == "" { + if emitter.target == Responses && event.Text == "" { return emitter.startReasoning() } } @@ -141,7 +144,7 @@ func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error { emitter.stop = event.Stop case "error": emitter.done = true - if err := emitter.emitError(firstString(event.Error, "upstream stream failed"), firstString(event.ErrorType, "upstream_error")); err != nil { + if err := emitter.emitError(jsonutil.FirstString(event.Error, "upstream stream failed"), jsonutil.FirstString(event.ErrorType, "upstream_error")); err != nil { return err } return errStreamUpstreamFailure @@ -153,12 +156,12 @@ func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error { func (emitter *bridgeStreamEmitter) emitError(message, errorType string) error { switch emitter.target { - case ProtocolAnthropic: + case Anthropic: return emitter.sse("error", map[string]any{ "type": "error", "error": map[string]any{"type": errorType, "message": message}, }) - case ProtocolResponses: + case Responses: response := emitter.responsesBase("failed", []any{}) response["error"] = map[string]any{"code": errorType, "message": message} return emitter.sse("response.failed", map[string]any{ @@ -188,8 +191,8 @@ func (emitter *bridgeStreamEmitter) tool(key string) *bridgeStreamTool { } tool := &bridgeStreamTool{ Key: key, - ID: randomID("call", 12), - ItemID: randomID("fc", 12), + ID: identity.RandomID("call", 12), + ItemID: identity.RandomID("fc", 12), Index: len(emitter.order), } emitter.tools[key] = tool @@ -203,10 +206,10 @@ func (emitter *bridgeStreamEmitter) start() error { } emitter.started = true if emitter.id == "" { - emitter.id = randomID("resp", 12) + emitter.id = identity.RandomID("resp", 12) } switch emitter.target { - case ProtocolChat: + case Chat: return emitter.sse("", map[string]any{ "id": asPrefix(emitter.id, "chatcmpl"), "object": "chat.completion.chunk", @@ -218,7 +221,7 @@ func (emitter *bridgeStreamEmitter) start() error { "finish_reason": nil, }}, }) - case ProtocolAnthropic: + case Anthropic: return emitter.sse("message_start", map[string]any{ "type": "message_start", "message": map[string]any{ @@ -229,10 +232,10 @@ func (emitter *bridgeStreamEmitter) start() error { "content": []any{}, "stop_reason": nil, "stop_sequence": nil, - "usage": anthropicUsage(bridgeUsage{}), + "usage": anthropicUsage(Usage{}), }, }) - case ProtocolResponses: + case Responses: response := emitter.responsesBase("in_progress", []any{}) if err := emitter.sse("response.created", map[string]any{"type": "response.created", "response": response, "sequence_number": emitter.nextSequence()}); err != nil { return err @@ -244,15 +247,15 @@ func (emitter *bridgeStreamEmitter) start() error { } func (emitter *bridgeStreamEmitter) emitText(delta string) error { - if emitter.target == ProtocolAnthropic || emitter.target == ProtocolResponses { + if emitter.target == Anthropic || emitter.target == Responses { if err := emitter.finishReasoning(); err != nil { return err } } switch emitter.target { - case ProtocolChat: + case Chat: return emitter.chatChunk(map[string]any{"content": delta}, nil) - case ProtocolAnthropic: + case Anthropic: if !emitter.textOpen { emitter.textOpen = true emitter.textIndex = emitter.nextAnthropic @@ -270,10 +273,10 @@ func (emitter *bridgeStreamEmitter) emitText(delta string) error { "index": emitter.textIndex, "delta": map[string]any{"type": "text_delta", "text": delta}, }) - case ProtocolResponses: + case Responses: if !emitter.textOpen { emitter.textOpen = true - emitter.textItemID = randomID("msg", 12) + emitter.textItemID = identity.RandomID("msg", 12) emitter.textOutput = emitter.nextOutput emitter.nextOutput++ item := map[string]any{"id": emitter.textItemID, "type": "message", "status": "in_progress", "role": "assistant", "content": []any{}} @@ -295,15 +298,15 @@ func (emitter *bridgeStreamEmitter) emitReasoning(delta string) error { return err } switch emitter.target { - case ProtocolChat: + case Chat: return emitter.chatChunk(map[string]any{"reasoning_content": delta}, nil) - case ProtocolAnthropic: + case Anthropic: return emitter.sse("content_block_delta", map[string]any{ "type": "content_block_delta", "index": emitter.reasoningIndex, "delta": map[string]any{"type": "thinking_delta", "thinking": delta}, }) - case ProtocolResponses: + case Responses: return emitter.sse("response.reasoning_summary_text.delta", map[string]any{"type": "response.reasoning_summary_text.delta", "delta": delta, "item_id": emitter.reasoningItemID, "output_index": emitter.reasoningOutput, "summary_index": 0, "sequence_number": emitter.nextSequence()}) } return nil @@ -314,9 +317,9 @@ func (emitter *bridgeStreamEmitter) emitReasoningSignature(signature string) err return err } switch emitter.target { - case ProtocolChat: + case Chat: return emitter.chatChunk(map[string]any{"reasoning_signature": signature}, nil) - case ProtocolAnthropic: + case Anthropic: return emitter.sse("content_block_delta", map[string]any{ "type": "content_block_delta", "index": emitter.reasoningIndex, @@ -332,7 +335,7 @@ func (emitter *bridgeStreamEmitter) startReasoning() error { } emitter.reasoningOpen = true switch emitter.target { - case ProtocolAnthropic: + case Anthropic: emitter.reasoningIndex = emitter.nextAnthropic emitter.nextAnthropic++ return emitter.sse("content_block_start", map[string]any{ @@ -340,8 +343,8 @@ func (emitter *bridgeStreamEmitter) startReasoning() error { "index": emitter.reasoningIndex, "content_block": map[string]any{"type": "thinking", "thinking": "", "signature": ""}, }) - case ProtocolResponses: - emitter.reasoningItemID = randomID("rs", 12) + case Responses: + emitter.reasoningItemID = identity.RandomID("rs", 12) emitter.reasoningOutput = emitter.nextOutput emitter.nextOutput++ item := map[string]any{"id": emitter.reasoningItemID, "type": "reasoning", "status": "in_progress", "summary": []any{}} @@ -361,9 +364,9 @@ func (emitter *bridgeStreamEmitter) finishReasoning() error { emitter.reasoningClosed = true text := emitter.reasoning.String() switch emitter.target { - case ProtocolAnthropic: + case Anthropic: return emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.reasoningIndex}) - case ProtocolResponses: + case Responses: if err := emitter.sse("response.reasoning_summary_text.done", map[string]any{"type": "response.reasoning_summary_text.done", "text": text, "item_id": emitter.reasoningItemID, "output_index": emitter.reasoningOutput, "summary_index": 0, "sequence_number": emitter.nextSequence()}); err != nil { return err } @@ -384,12 +387,12 @@ func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error { if tool.Started || tool.Name == "" { return nil } - if emitter.target == ProtocolResponses || emitter.target == ProtocolAnthropic { + if emitter.target == Responses || emitter.target == Anthropic { if err := emitter.finishReasoning(); err != nil { return err } } - if emitter.target == ProtocolAnthropic && emitter.textOpen { + if emitter.target == Anthropic && emitter.textOpen { if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.textIndex}); err != nil { return err } @@ -397,7 +400,7 @@ func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error { } tool.Started = true switch emitter.target { - case ProtocolChat: + case Chat: return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{ "index": tool.Index, "id": tool.ID, @@ -407,12 +410,12 @@ func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error { "arguments": "", }, }}}, nil) - case ProtocolResponses: + case Responses: tool.Index = emitter.nextOutput emitter.nextOutput++ item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "in_progress", "arguments": "", "call_id": tool.ID, "name": tool.Name} return emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": tool.Index, "item": item, "sequence_number": emitter.nextSequence()}) - case ProtocolAnthropic: + case Anthropic: tool.AnthropicIndex = emitter.nextAnthropic emitter.nextAnthropic++ return emitter.sse("content_block_start", map[string]any{ @@ -428,14 +431,14 @@ func (emitter *bridgeStreamEmitter) emitToolDelta(tool *bridgeStreamTool, delta return nil } switch emitter.target { - case ProtocolChat: + case Chat: return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{ "index": tool.Index, "function": map[string]any{"arguments": delta}, }}}, nil) - case ProtocolResponses: + case Responses: return emitter.sse("response.function_call_arguments.delta", map[string]any{"type": "response.function_call_arguments.delta", "delta": delta, "item_id": tool.ItemID, "output_index": tool.Index, "sequence_number": emitter.nextSequence()}) - case ProtocolAnthropic: + case Anthropic: return emitter.sse("content_block_delta", map[string]any{"type": "content_block_delta", "index": tool.AnthropicIndex, "delta": map[string]any{"type": "input_json_delta", "partial_json": delta}}) } return nil @@ -475,7 +478,7 @@ func (emitter *bridgeStreamEmitter) Finish() error { return err } switch emitter.target { - case ProtocolChat: + case Chat: if err := emitter.chatChunk(map[string]any{}, chatStop(emitter.stop)); err != nil { return err } @@ -491,7 +494,7 @@ func (emitter *bridgeStreamEmitter) Finish() error { } return emitter.rawSSE("", "[DONE]") - case ProtocolAnthropic: + case Anthropic: if emitter.textOpen { if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.textIndex}); err != nil { return err @@ -520,7 +523,7 @@ func (emitter *bridgeStreamEmitter) Finish() error { } return emitter.sse("message_stop", map[string]any{"type": "message_stop"}) - case ProtocolResponses: + case Responses: if err := emitter.finishResponsesItems(); err != nil { return err } @@ -540,7 +543,7 @@ func (emitter *bridgeStreamEmitter) Finish() error { tool := emitter.tools[key] response.Tools = append(response.Tools, bridgeBlock{Kind: "tool_call", ID: tool.ID, Name: tool.Name, ArgumentsJSON: tool.Arguments.String()}) } - completed := encodeBridgeResponse(ProtocolResponses, response) + completed := encodeBridgeResponse(Responses, response) return emitter.sse("response.completed", map[string]any{"type": "response.completed", "response": completed, "sequence_number": emitter.nextSequence()}) } return nil @@ -637,7 +640,7 @@ func (emitter *bridgeStreamEmitter) rawSSE(eventName, data string) error { return nil } -func mergeBridgeUsage(destination *bridgeUsage, source bridgeUsage) { +func mergeBridgeUsage(destination *Usage, source Usage) { if source.Input != 0 { destination.Input = source.Input } diff --git a/stream_parser.go b/internal/protocol/stream_parser.go similarity index 67% rename from stream_parser.go rename to internal/protocol/stream_parser.go index c35ceaf..64115d6 100644 --- a/stream_parser.go +++ b/internal/protocol/stream_parser.go @@ -1,9 +1,11 @@ -package main +package protocol import ( "encoding/json" "fmt" "strings" + + "opencode2api/internal/jsonutil" ) type bridgeStreamParser struct { @@ -19,7 +21,7 @@ type bridgeStreamParser struct { func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamEvent, error) { if data == "[DONE]" { - if parser.protocol != ProtocolChat { + if parser.protocol != Chat { return nil, fmt.Errorf("unexpected [DONE] terminator for %s stream", parser.protocol) } return []bridgeStreamEvent{{Kind: "done"}}, nil @@ -29,11 +31,11 @@ func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamE return nil, fmt.Errorf("invalid upstream SSE JSON: %w", err) } switch parser.protocol { - case ProtocolChat: + case Chat: return parser.parseChatEvent(eventName, value), nil - case ProtocolAnthropic: + case Anthropic: return parser.parseAnthropicEvent(eventName, value) - case ProtocolResponses: + case Responses: return parser.parseResponses(eventName, value), nil default: return nil, fmt.Errorf("unsupported stream protocol %q", parser.protocol) @@ -53,29 +55,29 @@ func (parser *bridgeStreamParser) parseChatEvent(eventName string, value map[str return []bridgeStreamEvent{{Kind: "error", Error: streamErrorMessage(value, "upstream Chat stream error"), ErrorType: streamErrorType(value)}} } if !parser.started { - if id := stringAt(value, "id"); id != "" { + if id := jsonutil.StringAt(value, "id"); id != "" { parser.started = true - events = append(events, bridgeStreamEvent{Kind: "start", ResponseID: id, Model: stringAt(value, "model")}) + events = append(events, bridgeStreamEvent{Kind: "start", ResponseID: id, Model: jsonutil.StringAt(value, "model")}) } } - if usageMap := mapAt(value, "usage"); len(usageMap) > 0 { + if usageMap := jsonutil.MapAt(value, "usage"); len(usageMap) > 0 { usage := decodeOpenAIUsage(usageMap) events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) } - for _, raw := range sliceAt(value, "choices") { + for _, raw := range jsonutil.SliceAt(value, "choices") { choice, _ := raw.(map[string]any) - delta := mapAt(choice, "delta") - if reasoning := firstString(stringAt(delta, "reasoning_content"), stringAt(delta, "reasoning")); reasoning != "" { + delta := jsonutil.MapAt(choice, "delta") + if reasoning := jsonutil.FirstString(jsonutil.StringAt(delta, "reasoning_content"), jsonutil.StringAt(delta, "reasoning")); reasoning != "" { events = append(events, bridgeStreamEvent{Kind: "reasoning", Text: reasoning}) } - if text := stringAt(delta, "content"); text != "" { + if text := jsonutil.StringAt(delta, "content"); text != "" { events = append(events, bridgeStreamEvent{Kind: "text", Text: text}) } - for _, rawCall := range sliceAt(delta, "tool_calls") { + for _, rawCall := range jsonutil.SliceAt(delta, "tool_calls") { call, _ := rawCall.(map[string]any) - key := fmt.Sprint(firstAny(call["index"], stringAt(call, "id"))) - function := mapAt(call, "function") - id := stringAt(call, "id") + key := fmt.Sprint(jsonutil.FirstAny(call["index"], jsonutil.StringAt(call, "id"))) + function := jsonutil.MapAt(call, "function") + id := jsonutil.StringAt(call, "id") if _, seen := parser.tools[key]; !seen { parser.tools[key] = false parser.toolOrder = append(parser.toolOrder, key) @@ -83,10 +85,10 @@ func (parser *bridgeStreamParser) parseChatEvent(eventName string, value map[str if id != "" { parser.toolIDs[key] = id } - if name := stringAt(function, "name"); name != "" { + if name := jsonutil.StringAt(function, "name"); name != "" { parser.toolNames[key] = mergeToolName(parser.toolNames[key], name) } - if arguments := stringAt(function, "arguments"); arguments != "" { + if arguments := jsonutil.StringAt(function, "arguments"); arguments != "" { if !parser.tools[key] && parser.toolNames[key] != "" { parser.tools[key] = true events = append(events, bridgeStreamEvent{Kind: "tool_start", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key]}) @@ -94,9 +96,9 @@ func (parser *bridgeStreamParser) parseChatEvent(eventName string, value map[str events = append(events, bridgeStreamEvent{Kind: "tool_delta", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key], Text: arguments}) } } - if stop := stringAt(choice, "finish_reason"); stop != "" { + if stop := jsonutil.StringAt(choice, "finish_reason"); stop != "" { if isStreamErrorFinish(stop) { - events = append(events, bridgeStreamEvent{Kind: "error", Error: firstString(stringAt(choice, "error", "message"), "upstream Chat stream failed"), ErrorType: "upstream_error"}) + events = append(events, bridgeStreamEvent{Kind: "error", Error: jsonutil.FirstString(jsonutil.StringAt(choice, "error", "message"), "upstream Chat stream failed"), ErrorType: "upstream_error"}) continue } for _, key := range parser.toolOrder { @@ -116,62 +118,62 @@ func (parser *bridgeStreamParser) parseAnthropic(value map[string]any) ([]bridge } func (parser *bridgeStreamParser) parseAnthropicEvent(eventName string, value map[string]any) ([]bridgeStreamEvent, error) { - typeName := stringAt(value, "type") + typeName := jsonutil.StringAt(value, "type") if typeName == "" { typeName = eventName } switch typeName { case "message_start": - message := mapAt(value, "message") - events := []bridgeStreamEvent{{Kind: "start", ResponseID: stringAt(message, "id"), Model: stringAt(message, "model")}} - if usageMap := mapAt(message, "usage"); len(usageMap) > 0 { + message := jsonutil.MapAt(value, "message") + events := []bridgeStreamEvent{{Kind: "start", ResponseID: jsonutil.StringAt(message, "id"), Model: jsonutil.StringAt(message, "model")}} + if usageMap := jsonutil.MapAt(message, "usage"); len(usageMap) > 0 { usage := decodeAnthropicUsage(usageMap) events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) } return events, nil case "content_block_start": - block := mapAt(value, "content_block") + block := jsonutil.MapAt(value, "content_block") key := fmt.Sprint(value["index"]) - switch stringAt(block, "type") { + switch jsonutil.StringAt(block, "type") { case "thinking": events := make([]bridgeStreamEvent, 0, 2) - if thinking := stringAt(block, "thinking"); thinking != "" { + if thinking := jsonutil.StringAt(block, "thinking"); thinking != "" { events = append(events, bridgeStreamEvent{Kind: "reasoning", Text: thinking}) } - if signature := stringAt(block, "signature"); signature != "" { + if signature := jsonutil.StringAt(block, "signature"); signature != "" { events = append(events, bridgeStreamEvent{Kind: "reasoning_signature", Signature: signature}) } return events, nil case "redacted_thinking": - return []bridgeStreamEvent{{Kind: "reasoning", Encrypted: stringAt(block, "data")}}, nil + return []bridgeStreamEvent{{Kind: "reasoning", Encrypted: jsonutil.StringAt(block, "data")}}, nil case "tool_use": parser.tools[key] = true - return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: stringAt(block, "id"), ToolName: stringAt(block, "name")}}, nil + return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: jsonutil.StringAt(block, "id"), ToolName: jsonutil.StringAt(block, "name")}}, nil case "text": - if text := stringAt(block, "text"); text != "" { + if text := jsonutil.StringAt(block, "text"); text != "" { return []bridgeStreamEvent{{Kind: "text", Text: text}}, nil } } case "content_block_delta": - delta := mapAt(value, "delta") + delta := jsonutil.MapAt(value, "delta") key := fmt.Sprint(value["index"]) - switch stringAt(delta, "type") { + switch jsonutil.StringAt(delta, "type") { case "thinking_delta": - return []bridgeStreamEvent{{Kind: "reasoning", Text: stringAt(delta, "thinking")}}, nil + return []bridgeStreamEvent{{Kind: "reasoning", Text: jsonutil.StringAt(delta, "thinking")}}, nil case "signature_delta": - return []bridgeStreamEvent{{Kind: "reasoning_signature", Signature: stringAt(delta, "signature")}}, nil + return []bridgeStreamEvent{{Kind: "reasoning_signature", Signature: jsonutil.StringAt(delta, "signature")}}, nil case "text_delta": - return []bridgeStreamEvent{{Kind: "text", Text: stringAt(delta, "text")}}, nil + return []bridgeStreamEvent{{Kind: "text", Text: jsonutil.StringAt(delta, "text")}}, nil case "input_json_delta": - return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, Text: stringAt(delta, "partial_json")}}, nil + return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, Text: jsonutil.StringAt(delta, "partial_json")}}, nil } case "message_delta": events := make([]bridgeStreamEvent, 0, 2) - if usageMap := mapAt(value, "usage"); len(usageMap) > 0 { + if usageMap := jsonutil.MapAt(value, "usage"); len(usageMap) > 0 { usage := decodeAnthropicUsage(usageMap) events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) } - if stop := stringAt(value, "delta", "stop_reason"); stop != "" { + if stop := jsonutil.StringAt(value, "delta", "stop_reason"); stop != "" { if isStreamErrorFinish(stop) { events = append(events, bridgeStreamEvent{Kind: "error", Error: "upstream Anthropic stream failed", ErrorType: "upstream_error"}) return events, nil @@ -182,14 +184,14 @@ func (parser *bridgeStreamParser) parseAnthropicEvent(eventName string, value ma case "message_stop": return []bridgeStreamEvent{{Kind: "done"}}, nil case "error": - message := firstString(stringAt(value, "error", "message"), "upstream Anthropic stream error") - return []bridgeStreamEvent{{Kind: "error", Error: message, ErrorType: firstString(stringAt(value, "error", "type"), "upstream_error")}}, nil + message := jsonutil.FirstString(jsonutil.StringAt(value, "error", "message"), "upstream Anthropic stream error") + return []bridgeStreamEvent{{Kind: "error", Error: message, ErrorType: jsonutil.FirstString(jsonutil.StringAt(value, "error", "type"), "upstream_error")}}, nil } return nil, nil } func (parser *bridgeStreamParser) parseResponses(eventName string, value map[string]any) []bridgeStreamEvent { - typeName := stringAt(value, "type") + typeName := jsonutil.StringAt(value, "type") if typeName == "" { typeName = eventName } @@ -197,19 +199,19 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str case "error": return []bridgeStreamEvent{{Kind: "error", Error: streamErrorMessage(value, "upstream Responses stream error"), ErrorType: streamErrorType(value)}} case "response.created": - response := mapAt(value, "response") - return []bridgeStreamEvent{{Kind: "start", ResponseID: stringAt(response, "id"), Model: stringAt(response, "model")}} + response := jsonutil.MapAt(value, "response") + return []bridgeStreamEvent{{Kind: "start", ResponseID: jsonutil.StringAt(response, "id"), Model: jsonutil.StringAt(response, "model")}} case "response.output_text.delta": - return []bridgeStreamEvent{{Kind: "text", Text: stringAt(value, "delta")}} + return []bridgeStreamEvent{{Kind: "text", Text: jsonutil.StringAt(value, "delta")}} case "response.reasoning_summary_text.delta": key := responseToolKey(value, nil) parser.responseReasoning[key] = true - return []bridgeStreamEvent{{Kind: "reasoning", Text: stringAt(value, "delta")}} + return []bridgeStreamEvent{{Kind: "reasoning", Text: jsonutil.StringAt(value, "delta")}} case "response.output_item.added": - item := mapAt(value, "item") - if stringAt(item, "type") == "function_call" { + item := jsonutil.MapAt(value, "item") + if jsonutil.StringAt(item, "type") == "function_call" { key := responseToolKey(value, item) - parser.rememberTool(key, stringAt(item, "call_id"), stringAt(item, "name")) + parser.rememberTool(key, jsonutil.StringAt(item, "call_id"), jsonutil.StringAt(item, "name")) if parser.toolNames[key] != "" { parser.tools[key] = true return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key]}} @@ -218,16 +220,16 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str case "response.function_call_arguments.delta": key := responseToolKey(value, nil) parser.responseArgs[key] = true - return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key], Text: stringAt(value, "delta")}} + return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key], Text: jsonutil.StringAt(value, "delta")}} case "response.function_call_arguments.done": key := responseToolKey(value, nil) if !parser.responseArgs[key] { parser.responseArgs[key] = true - return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key], Text: stringAt(value, "arguments")}} + return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key], Text: jsonutil.StringAt(value, "arguments")}} } case "response.output_item.done": - item := mapAt(value, "item") - if stringAt(item, "type") == "reasoning" { + item := jsonutil.MapAt(value, "item") + if jsonutil.StringAt(item, "type") == "reasoning" { key := responseToolKey(value, item) if parser.responseReasoning[key] { return nil @@ -238,27 +240,27 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str } return nil } - if stringAt(item, "type") == "function_call" { + if jsonutil.StringAt(item, "type") == "function_call" { key := responseToolKey(value, item) - parser.rememberTool(key, stringAt(item, "call_id"), stringAt(item, "name")) + parser.rememberTool(key, jsonutil.StringAt(item, "call_id"), jsonutil.StringAt(item, "name")) events := make([]bridgeStreamEvent, 0, 2) if !parser.tools[key] { parser.tools[key] = true events = append(events, bridgeStreamEvent{Kind: "tool_start", ToolKey: key, ToolID: parser.toolIDs[key], ToolName: parser.toolNames[key]}) } if !parser.responseArgs[key] { - if arguments := stringAt(item, "arguments"); arguments != "" { + if arguments := jsonutil.StringAt(item, "arguments"); arguments != "" { events = append(events, bridgeStreamEvent{Kind: "tool_delta", ToolKey: key, Text: arguments}) } } return events } case "response.completed", "response.incomplete", "response.failed", "response.done": - response := mapAt(value, "response") - usageMap := mapAt(response, "usage") - if typeName == "response.failed" || stringAt(response, "status") == "failed" { - message := firstString(stringAt(response, "error", "message"), stringAt(value, "error", "message"), "upstream Responses request failed") - events := []bridgeStreamEvent{{Kind: "error", Error: message, ErrorType: firstString(stringAt(response, "error", "code"), "upstream_error")}} + response := jsonutil.MapAt(value, "response") + usageMap := jsonutil.MapAt(response, "usage") + if typeName == "response.failed" || jsonutil.StringAt(response, "status") == "failed" { + message := jsonutil.FirstString(jsonutil.StringAt(response, "error", "message"), jsonutil.StringAt(value, "error", "message"), "upstream Responses request failed") + events := []bridgeStreamEvent{{Kind: "error", Error: message, ErrorType: jsonutil.FirstString(jsonutil.StringAt(response, "error", "code"), "upstream_error")}} if len(usageMap) > 0 { usage := decodeOpenAIUsage(usageMap) events = append([]bridgeStreamEvent{{Kind: "usage", Usage: &usage}}, events...) @@ -267,7 +269,7 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str } stop := "stop" if typeName == "response.incomplete" { - stop = canonicalResponsesIncomplete(stringAt(response, "incomplete_details", "reason")) + stop = canonicalResponsesIncomplete(jsonutil.StringAt(response, "incomplete_details", "reason")) } else { stop = parser.responsesCompletedStop(response) } @@ -288,9 +290,9 @@ func (parser *bridgeStreamParser) parseResponses(eventName string, value map[str // "stop" made every tool step terminate the downstream turn instead of chaining // inside it. func (parser *bridgeStreamParser) responsesCompletedStop(response map[string]any) string { - for _, raw := range sliceAt(response, "output") { + for _, raw := range jsonutil.SliceAt(response, "output") { item, _ := raw.(map[string]any) - if stringAt(item, "type") == "function_call" { + if jsonutil.StringAt(item, "type") == "function_call" { return "tool_calls" } } @@ -301,10 +303,10 @@ func (parser *bridgeStreamParser) responsesCompletedStop(response map[string]any } func streamErrorMessage(value map[string]any, fallback string) string { - if message := stringAt(value, "error", "message"); message != "" { + if message := jsonutil.StringAt(value, "error", "message"); message != "" { return message } - if message := stringAt(value, "message"); message != "" { + if message := jsonutil.StringAt(value, "message"); message != "" { return message } if message, ok := value["error"].(string); ok && message != "" { @@ -314,7 +316,7 @@ func streamErrorMessage(value map[string]any, fallback string) string { } func streamErrorType(value map[string]any) string { - return firstString(stringAt(value, "error", "type"), stringAt(value, "error", "code"), "upstream_error") + return jsonutil.FirstString(jsonutil.StringAt(value, "error", "type"), jsonutil.StringAt(value, "error", "code"), "upstream_error") } func isStreamErrorFinish(stop string) bool { @@ -351,11 +353,11 @@ func mergeToolName(current, fragment string) string { func responseToolKey(event map[string]any, item map[string]any) string { if item != nil { - if id := stringAt(item, "id"); id != "" { + if id := jsonutil.StringAt(item, "id"); id != "" { return id } } - if id := stringAt(event, "item_id"); id != "" { + if id := jsonutil.StringAt(event, "item_id"); id != "" { return id } return fmt.Sprint(event["output_index"]) diff --git a/observability.go b/internal/telemetry/http.go similarity index 72% rename from observability.go rename to internal/telemetry/http.go index 8871e47..ea3c3c6 100644 --- a/observability.go +++ b/internal/telemetry/http.go @@ -1,18 +1,19 @@ -package main +// Package telemetry records request outcomes, metrics, and structured logs. +package telemetry import ( "context" - "encoding/json" - "fmt" "log/slog" "net/http" "time" + + "opencode2api/internal/protocol" ) -type requestMeta struct { +type RequestMeta struct { Model string Tier string - Protocol Protocol + Protocol protocol.Protocol Request string KeyID string Channel string @@ -20,7 +21,7 @@ type requestMeta struct { Proxy string Attempts int Stream bool - Usage bridgeUsage + Usage protocol.Usage UsageReported bool AttemptOutcome string Outcome string @@ -28,11 +29,21 @@ type requestMeta struct { type requestMetaKey struct{} -func metaFromRequest(r *http.Request) *requestMeta { - meta, _ := r.Context().Value(requestMetaKey{}).(*requestMeta) +// WithRequestMeta shares request-local outcomes across HTTP and gateway layers. +func WithRequestMeta(ctx context.Context, meta *RequestMeta) context.Context { + return context.WithValue(ctx, requestMetaKey{}, meta) +} + +// MetaFromContext returns the request-local trace, or nil when it is absent. +func MetaFromContext(ctx context.Context) *RequestMeta { + meta, _ := ctx.Value(requestMetaKey{}).(*RequestMeta) return meta } +func MetaFromRequest(r *http.Request) *RequestMeta { + return MetaFromContext(r.Context()) +} + type statusWriter struct { http.ResponseWriter status int @@ -62,17 +73,17 @@ func (w *statusWriter) Flush() { func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } -func monitorMiddleware(monitor *Monitor, logger *slog.Logger, next http.Handler) http.Handler { +func Middleware(monitor *Monitor, logger *slog.Logger, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/healthz" { next.ServeHTTP(w, r) return } started := time.Now() - meta := metaFromRequest(r) + meta := MetaFromRequest(r) if meta == nil { - meta = &requestMeta{} - r = r.WithContext(context.WithValue(r.Context(), requestMetaKey{}, meta)) + meta = &RequestMeta{} + r = r.WithContext(WithRequestMeta(r.Context(), meta)) } writer := &statusWriter{ResponseWriter: w} monitor.active.Add(1) @@ -102,18 +113,3 @@ func monitorMiddleware(monitor *Monitor, logger *slog.Logger, next http.Handler) next.ServeHTTP(writer, r) }) } - -func encodeSSE(w http.ResponseWriter, event string, id uint64, value any) error { - data, err := json.Marshal(value) - if err != nil { - return err - } - if id > 0 { - _, _ = fmt.Fprintf(w, "id: %d\n", id) - } - if event != "" { - _, _ = fmt.Fprintf(w, "event: %s\n", event) - } - _, err = fmt.Fprintf(w, "data: %s\n\n", data) - return err -} diff --git a/logging.go b/internal/telemetry/logging.go similarity index 77% rename from logging.go rename to internal/telemetry/logging.go index b1b57d7..92d8ba3 100644 --- a/logging.go +++ b/internal/telemetry/logging.go @@ -1,17 +1,16 @@ -package main +package telemetry import ( "context" "fmt" "io" "log/slog" - "net/url" "os" - "sort" "strings" "sync" - "sync/atomic" "time" + + "opencode2api/internal/config" ) type LogEvent struct { @@ -124,76 +123,26 @@ func (h *LogHub) Subscribe() (<-chan LogEvent, func()) { } } -type SecretRedactor struct { - values atomic.Value -} - -func NewSecretRedactor() *SecretRedactor { - r := &SecretRedactor{} - r.values.Store([]string(nil)) - return r -} - -func (r *SecretRedactor) Replace(cfg Config) { - values := make([]string, 0, len(cfg.ServerKeys)+len(cfg.ZenKeys)+len(cfg.GoKeys)+2) - values = append(values, cfg.ServerKeys...) - values = append(values, cfg.ZenKeys...) - values = append(values, cfg.GoKeys...) - if cfg.WebUI.Password != "" { - values = append(values, cfg.WebUI.Password) - } - for _, value := range []string{cfg.Upstream.Zen, cfg.Upstream.Go} { - if parsed, err := url.Parse(value); err == nil && parsed.User != nil { - values = append(values, value, parsed.User.Username()) - if password, ok := parsed.User.Password(); ok { - values = append(values, password) - } - } - } - for _, value := range cfg.RuntimeProxies() { - if value != "direct" { - values = append(values, value) - if parsed, err := url.Parse(value); err == nil && parsed.User != nil { - values = append(values, parsed.User.Username()) - if password, ok := parsed.User.Password(); ok { - values = append(values, password) - } - } - } - } - sort.Slice(values, func(i, j int) bool { return len(values[i]) > len(values[j]) }) - r.values.Store(values) -} - -func (r *SecretRedactor) String(value string) string { - for _, secret := range r.values.Load().([]string) { - if len(secret) >= 4 { - value = strings.ReplaceAll(value, secret, "***") - } - } - return value -} - type hubHandler struct { base slog.Handler hub *LogHub - redactor *SecretRedactor + redactor *config.SecretRedactor attrs []slog.Attr groups []string } -func NewStructuredLogger(level *slog.LevelVar, hub *LogHub, redactor *SecretRedactor) *slog.Logger { +func NewStructuredLogger(level *slog.LevelVar, hub *LogHub, redactor *config.SecretRedactor) *slog.Logger { return newStructuredLogger(os.Stdout, level, hub, redactor) } -func newStructuredLogger(output io.Writer, level *slog.LevelVar, hub *LogHub, redactor *SecretRedactor) *slog.Logger { +func newStructuredLogger(output io.Writer, level *slog.LevelVar, hub *LogHub, redactor *config.SecretRedactor) *slog.Logger { base := slog.NewJSONHandler(output, &slog.HandlerOptions{Level: level, ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr { return sanitizeLogAttr(redactor, attr) }}) return slog.New(&hubHandler{base: base, hub: hub, redactor: redactor}) } -func sanitizeLogAttr(redactor *SecretRedactor, attr slog.Attr) slog.Attr { +func sanitizeLogAttr(redactor *config.SecretRedactor, attr slog.Attr) slog.Attr { attr.Value = attr.Value.Resolve() lower := strings.ToLower(attr.Key) if strings.Contains(lower, "password") || strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "secret") { @@ -285,7 +234,7 @@ func (h *hubHandler) addAttr(fields map[string]any, attr slog.Attr) { fields[key] = value } -func setLogLevel(level *slog.LevelVar, value string) { +func SetLogLevel(level *slog.LevelVar, value string) { switch value { case "debug": level.Set(slog.LevelDebug) diff --git a/metrics.go b/internal/telemetry/metrics.go similarity index 97% rename from metrics.go rename to internal/telemetry/metrics.go index 7e494fb..f280a9f 100644 --- a/metrics.go +++ b/internal/telemetry/metrics.go @@ -1,10 +1,12 @@ -package main +package telemetry import ( "fmt" "sync" "sync/atomic" "time" + + "opencode2api/internal/protocol" ) type metricBucket struct { @@ -246,9 +248,15 @@ func NewMonitor() *Monitor { } } +// BeginStream records a stream entering its response body phase. +func (m *Monitor) BeginStream() { m.activeStreams.Add(1) } + +// EndStream releases a stream recorded by BeginStream. +func (m *Monitor) EndStream() { m.activeStreams.Add(-1) } + var latencyBounds = [...]uint64{50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000, 60000} -func (m *Monitor) Record(endpoint string, status int, duration time.Duration, meta *requestMeta) { +func (m *Monitor) Record(endpoint string, status int, duration time.Duration, meta *RequestMeta) { success := requestSucceeded(status, meta) m.total.Add(1) if success { @@ -326,7 +334,7 @@ func (m *Monitor) Record(endpoint string, status int, duration time.Duration, me // A stream can fail after HTTP headers have been sent. Preserve its HTTP // status while using the terminal result for request success and error counts. -func requestSucceeded(status int, meta *requestMeta) bool { +func requestSucceeded(status int, meta *RequestMeta) bool { return status >= 200 && status < 400 && (meta == nil || meta.Outcome == "") } @@ -490,7 +498,7 @@ func newUsagePeriod() UsagePeriod { return UsagePeriod{Models: make(map[string]TokenCounts), Tiers: make(map[string]TokenCounts)} } -func tokenCounts(usage bridgeUsage) TokenCounts { +func tokenCounts(usage protocol.Usage) TokenCounts { return TokenCounts{ Input: uint64(max(usage.Input, 0)), Output: uint64(max(usage.Output, 0)), Cached: uint64(max(usage.Cached, 0)), Reasoning: uint64(max(usage.Reasoning, 0)), Total: uint64(max(usage.Total, 0)), diff --git a/internal/telemetry/recovery.go b/internal/telemetry/recovery.go new file mode 100644 index 0000000..f6d134a --- /dev/null +++ b/internal/telemetry/recovery.go @@ -0,0 +1,20 @@ +package telemetry + +import ( + "log/slog" + "net/http" + + "opencode2api/internal/protocol" +) + +func Recover(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 handler panicked", "component", "http", "event", "request_panic", "error", value) + protocol.WriteError(w, protocol.Chat, http.StatusInternalServerError, "internal server error", "server_error", "") + } + }() + next.ServeHTTP(w, r) + }) +} diff --git a/selected_key_test.go b/selected_key_test.go deleted file mode 100644 index 3060072..0000000 --- a/selected_key_test.go +++ /dev/null @@ -1,206 +0,0 @@ -package main - -import ( - "bytes" - "context" - "net/http" - "net/http/httptest" - "sync/atomic" - "testing" -) - -// A per-key diagnostic runs the selected key and nothing else: no anonymous -// lane, no other key, no other tier. -func TestSelectedKeyRunsExactlyOneAttempt(t *testing.T) { - var hits int32 - upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - atomic.AddInt32(&hits, 1) - w.WriteHeader(http.StatusBadRequest) - _, _ = w.Write([]byte(`{"error":{"message":"bad request"}}`)) - })) - defer upstream.Close() - - g := newTestGateway(t, &bytes.Buffer{}) - g.cfg.Upstream = UpstreamConfig{Zen: upstream.URL, Go: upstream.URL} - node := g.zenNodes.nodes[0] - - route := modelRoute{ - ID: "example-model", Tier: TierZen, Protocol: ProtocolChat, - Protocols: map[Tier]Protocol{TierZen: ProtocolChat}, KeyTiers: []Tier{TierZen}, - } - bodies := map[Tier][]byte{TierZen: []byte(`{"model":"example-model"}`)} - ids := requestIDs{Session: "ses_test", Request: "req_test", Project: "prj_test"} - - resp, err, attempts := g.doSelectedKeyUpstream(context.Background(), route, bodies, ids, - debugKeyOverride{Tier: TierZen, KeyID: secretFingerprint(node.key)}, 0) - if err != nil { - t.Fatalf("doSelectedKeyUpstream: %v", err) - } - if resp == nil { - t.Fatal("expected the upstream response") - } - defer drainAndClose(resp.Body) - if resp.StatusCode != http.StatusBadRequest { - t.Fatalf("status = %d, want 400", resp.StatusCode) - } - if attempts != 1 { - t.Fatalf("attempts = %d, want 1", attempts) - } - if got := atomic.LoadInt32(&hits); got != 1 { - t.Fatalf("upstream hits = %d, want exactly 1", got) - } -} - -// The diagnostic must never cool a production key or evict a proxy: that is -// what made a bad Playground request degrade live traffic. -func TestSelectedKeyDiagnosticLeavesPoolStateUntouched(t *testing.T) { - upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusUnauthorized) - _, _ = w.Write([]byte(`{"error":{"message":"invalid key"}}`)) - })) - defer upstream.Close() - - g := newTestGateway(t, &bytes.Buffer{}) - g.cfg.Upstream = UpstreamConfig{Zen: upstream.URL, Go: upstream.URL} - node := g.zenNodes.nodes[0] - - route := modelRoute{ - ID: "example-model", Tier: TierZen, Protocol: ProtocolChat, - Protocols: map[Tier]Protocol{TierZen: ProtocolChat}, KeyTiers: []Tier{TierZen}, - } - bodies := map[Tier][]byte{TierZen: []byte(`{"model":"example-model"}`)} - ids := requestIDs{Session: "ses_test", Request: "req_test", Project: "prj_test"} - - for attempt := 0; attempt < 3; attempt++ { - resp, err, _ := g.doSelectedKeyUpstream(context.Background(), route, bodies, ids, - debugKeyOverride{Tier: TierZen, KeyID: secretFingerprint(node.key)}, 0) - if err != nil { - t.Fatalf("doSelectedKeyUpstream: %v", err) - } - drainAndClose(resp.Body) - } - - // Repeated 401s would normally trip the cooldown and mark the proxy failed. - assertPoolUntouched(t, g) -} - -func TestSelectedKeyRejectsUnknownFingerprint(t *testing.T) { - g := newTestGateway(t, &bytes.Buffer{}) - route := modelRoute{ID: "example-model", Tier: TierZen, Protocol: ProtocolChat} - bodies := map[Tier][]byte{TierZen: []byte(`{"model":"example-model"}`)} - - resp, err, attempts := g.doSelectedKeyUpstream(context.Background(), route, bodies, - requestIDs{Request: "req_test"}, debugKeyOverride{Tier: TierZen, KeyID: "deadbeef"}, 0) - if resp != nil || err == nil { - t.Fatalf("response = %v, err = %v; want a lookup failure", resp, err) - } - if attempts != 0 { - t.Fatalf("attempts = %d, want 0", attempts) - } -} - -// The pinned route must describe the selected tier only, and must carry that -// tier's own native protocol so the body is re-encoded for it. -func TestRouteForTierPinsOneTier(t *testing.T) { - catalog := newModelCatalog(TierGo, nil) - catalog.ReplaceWithCapabilities( - []string{"zen-only", "shared"}, []string{"go-only", "shared"}, - map[Tier]map[string]Protocol{ - TierZen: {"zen-only": ProtocolChat, "shared": ProtocolChat}, - TierGo: {"go-only": ProtocolAnthropic, "shared": ProtocolAnthropic}, - }, nil, nil, - ) - - route, err := catalog.RouteForTier("zen-only", TierZen, true, true) - if err != nil { - t.Fatalf("RouteForTier: %v", err) - } - if route.Tier != TierZen || route.Anonymous { - t.Fatalf("route = %+v, want a non-anonymous zen route", route) - } - if len(route.KeyTiers) != 1 || route.KeyTiers[0] != TierZen { - t.Fatalf("key tiers = %v, want exactly [zen]", route.KeyTiers) - } - - shared, err := catalog.RouteForTier("shared", TierGo, true, true) - if err != nil { - t.Fatalf("RouteForTier: %v", err) - } - if shared.Protocol != ProtocolAnthropic { - t.Fatalf("protocol = %q, want the Go tier's own %q", shared.Protocol, ProtocolAnthropic) - } - - if _, err := catalog.RouteForTier("zen-only", TierGo, true, true); err == nil { - t.Fatal("a model missing from the selected tier must be rejected") - } - if _, err := catalog.RouteForTier("shared", TierGo, true, false); err == nil { - t.Fatal("a tier without a configured key must be rejected") - } -} - -func TestClassifyKeyTest(t *testing.T) { - cases := []struct { - name string - status int - outcome string - expected string - }{ - {"success", http.StatusOK, "success", "usable"}, - {"unauthorized", http.StatusUnauthorized, "rejected", "rejected"}, - {"forbidden", http.StatusForbidden, "rejected", "rejected"}, - {"rate limited", http.StatusTooManyRequests, "retryable_failure", "rate_limited"}, - {"transport", 0, "transport_error", "transport_error"}, - {"upstream 500", http.StatusInternalServerError, "retryable_failure", "upstream_error"}, - {"bad request", http.StatusBadRequest, "rejected", "request_error"}, - } - for _, item := range cases { - if got := classifyKeyTest(item.status, item.outcome); got != item.expected { - t.Errorf("%s: classifyKeyTest(%d, %q) = %q, want %q", item.name, item.status, item.outcome, got, item.expected) - } - } -} - -// The selected tier decides where the request goes, even when the preferred -// tier also advertises the model. -func TestSelectedKeyUsesItsOwnTier(t *testing.T) { - var zenHits, goHits int32 - zen := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - atomic.AddInt32(&zenHits, 1) - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"choices":[{"message":{"content":"zen"}}]}`)) - })) - defer zen.Close() - goUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - atomic.AddInt32(&goHits, 1) - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"choices":[{"message":{"content":"go"}}]}`)) - })) - defer goUpstream.Close() - - g := newTestGateway(t, &bytes.Buffer{}) - g.cfg.Upstream = UpstreamConfig{Zen: zen.URL, Go: goUpstream.URL} - node := g.goNodes.nodes[0] - - route := modelRoute{ - ID: "example-model", Tier: TierGo, Protocol: ProtocolChat, - Protocols: map[Tier]Protocol{TierZen: ProtocolChat, TierGo: ProtocolChat}, KeyTiers: []Tier{TierGo}, - } - bodies := map[Tier][]byte{ - TierZen: []byte(`{"model":"example-model"}`), - TierGo: []byte(`{"model":"example-model"}`), - } - - resp, err, _ := g.doSelectedKeyUpstream(context.Background(), route, bodies, - requestIDs{Request: "req_test"}, debugKeyOverride{Tier: TierGo, KeyID: secretFingerprint(node.key)}, 0) - if err != nil { - t.Fatalf("doSelectedKeyUpstream: %v", err) - } - drainAndClose(resp.Body) - - if got := atomic.LoadInt32(&goHits); got != 1 { - t.Fatalf("go tier hits = %d, want 1", got) - } - if got := atomic.LoadInt32(&zenHits); got != 0 { - t.Fatalf("zen tier hits = %d, want 0", got) - } -} diff --git a/stream_test.go b/stream_test.go deleted file mode 100644 index eee7586..0000000 --- a/stream_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package main - -import ( - "testing" -) - -func newResponsesParser() *bridgeStreamParser { - return &bridgeStreamParser{ - protocol: ProtocolResponses, tools: map[string]bool{}, toolIDs: map[string]string{}, - toolNames: map[string]string{}, responseArgs: map[string]bool{}, responseReasoning: map[string]bool{}, - } -} - -func parseAll(t *testing.T, parser *bridgeStreamParser, event string) []bridgeStreamEvent { - t.Helper() - events, err := parser.Parse("", event) - if err != nil { - t.Fatalf("parse %s: %v", event, err) - } - return events -} - -func finishStop(t *testing.T, events []bridgeStreamEvent) string { - t.Helper() - for _, event := range events { - if event.Kind == "finish" { - return event.Stop - } - } - t.Fatalf("no finish event in %v", events) - return "" -} - -// A completed Responses turn that carries function_call items ended waiting for -// tool results. Reporting "stop" made every tool step end the downstream turn -// instead of chaining inside it. -func TestResponsesCompletedWithToolCallFinishesAsToolCalls(t *testing.T) { - parser := newResponsesParser() - parseAll(t, parser, `{"type":"response.output_item.done","output_index":0,"item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}}`) - - events := parseAll(t, parser, `{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`) - if stop := finishStop(t, events); stop != "tool_calls" { - t.Fatalf("stop = %q, want tool_calls", stop) - } -} - -// The completed event is authoritative even when no deltas were observed first. -func TestResponsesCompletedWithToolCallOnlyInOutput(t *testing.T) { - parser := newResponsesParser() - events := parseAll(t, parser, `{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`) - if stop := finishStop(t, events); stop != "tool_calls" { - t.Fatalf("stop = %q, want tool_calls", stop) - } -} - -func TestResponsesCompletedWithoutToolsFinishesAsStop(t *testing.T) { - parser := newResponsesParser() - parseAll(t, parser, `{"type":"response.output_text.delta","delta":"hello"}`) - - events := parseAll(t, parser, `{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[{"id":"msg_1","type":"message","role":"assistant","content":[{"type":"output_text","text":"hello"}]}]}}`) - if stop := finishStop(t, events); stop != "stop" { - t.Fatalf("stop = %q, want stop", stop) - } -} - -// An incomplete turn keeps its mapped reason instead of being reclassified by -// the tool-call scan. -func TestResponsesIncompleteKeepsMappedReason(t *testing.T) { - parser := newResponsesParser() - events := parseAll(t, parser, `{"type":"response.incomplete","response":{"id":"resp_1","status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`) - if stop := finishStop(t, events); stop != "length" { - t.Fatalf("stop = %q, want length", stop) - } -} diff --git a/test_helpers_test.go b/test_helpers_test.go deleted file mode 100644 index 47872b7..0000000 --- a/test_helpers_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package main - -import ( - "context" - "io" - "log/slog" - "net/http" - "net/http/httptest" - "path/filepath" - "strings" - "testing" -) - -const testServerKey = "local-handler-test-key" - -type stubTransport func(*http.Request) (*http.Response, error) - -func (transport stubTransport) RoundTrip(r *http.Request) (*http.Response, error) { - return transport(r) -} - -func stubResponse(status int, body string) *http.Response { - return &http.Response{ - StatusCode: status, - Header: http.Header{"Content-Type": []string{"application/json"}}, - Body: io.NopCloser(strings.NewReader(body)), - } -} - -func handlerTestConfig() Config { - cfg := testConfig() - cfg.Listen = "127.0.0.1:8080" - cfg.ServerKeys = []string{testServerKey} - cfg.ZenKeys = []string{"zen-handler-test-key"} - cfg.Proxies = []string{"direct"} - cfg.Prefer = TierZen - cfg.Retry.MaxAttempts = 1 - cfg.Models.Protocols = map[string]string{ - "example-model": "chat", - "example-free": "chat", - } - return cfg -} - -// The handler harness exercises authentication, routing, conversion, and -// monitoring without starting background refreshes or contacting real services. -func newHandlerTestRuntime(t *testing.T, cfg Config, transport stubTransport) (*RuntimeManager, *Gateway) { - t.Helper() - configPath := filepath.Join(t.TempDir(), "config.json") - cfg, err := NormalizeConfig(configPath, cfg) - if err != nil { - t.Fatal(err) - } - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - monitor := NewMonitor() - gateway, err := NewGateway(cfg, logger, monitor) - if err != nil { - t.Fatal(err) - } - for _, proxy := range gateway.transports.items { - proxy.client = &http.Client{Transport: transport} - } - gateway.catalog.Replace([]string{"example-model", "example-free"}, nil) - redactor := NewSecretRedactor() - redactor.Replace(cfg) - manager := &RuntimeManager{ - configPath: configPath, root: context.Background(), - logger: logger, monitor: monitor, hub: NewLogHub(100), - redactor: redactor, level: new(slog.LevelVar), - effective: effectiveListeners{API: cfg.Listen, WebUI: cfg.WebUI.Listen, WebUIEnabled: cfg.WebUI.Enabled}, - } - manager.current.Store(&gatewayRuntime{ - config: cfg, gateway: gateway, handler: gateway.Handler(), cancel: func() {}, - }) - return manager, gateway -} - -func serveTestRequest(handler http.Handler, method, path, body string) *httptest.ResponseRecorder { - request := httptest.NewRequest(method, path, strings.NewReader(body)) - request.Header.Set("Authorization", "Bearer "+testServerKey) - request.Header.Set("Content-Type", "application/json") - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - return recorder -} diff --git a/webui/embed.go b/webui/embed.go new file mode 100644 index 0000000..bb5c618 --- /dev/null +++ b/webui/embed.go @@ -0,0 +1,11 @@ +// Package webui embeds the static management interface. +package webui + +import ( + "embed" +) + +// Assets contains the static management interface served by the admin listener. +// +//go:embed index.html app.js styles.css +var Assets embed.FS