From ea29a62ecaa727580804b86e0c903361b61b386a Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Tue, 15 Sep 2026 00:43:35 +0800 Subject: [PATCH] fix: harden gateway routing and protocol fidelity Preserve request parameters, tool-call completion reasons and retry session affinity. Bound upstream header waits, stop expired-context scans and add opt-in redacted request-body diagnostics. Isolate Playground diagnostics from production pools, report stream failures accurately, align readiness with discoverable models and honor Docker listen configuration. Split Go and WebUI modules by responsibility, add regression tests and CI, standardize formatting and rewrite the English and Chinese READMEs. Refs: #6, #18, #19, #20, #21, #22, #23, #24, #25 --- .editorconfig | 19 + .gitattributes | 1 + .github/workflows/checks.yml | 66 ++ .github/workflows/release.yml | 2 +- .gitignore | 6 + .prettierignore | 11 + .prettierrc.json | 9 + Dockerfile | 6 +- README.md | 627 +++++++------ README.zh-CN.md | 406 ++++++++ admin.go | 463 +--------- admin_auth.go | 267 ++++++ admin_debug.go | 263 ++++++ admin_debug_test.go | 260 ++++++ admin_test.go | 45 + compose.yaml | 6 +- config.example.json | 6 +- config.go | 31 + config_test.go | 56 ++ convert.go | 1634 ++------------------------------- convert_content.go | 412 +++++++++ convert_request.go | 817 +++++++++++++++++ convert_response.go | 398 ++++++++ convert_test.go | 201 ++++ docker-entrypoint.sh | 30 +- gateway.go | 852 +---------------- gateway_health.go | 153 +++ gateway_health_test.go | 76 ++ gateway_refresh.go | 257 ++++++ gateway_stream_test.go | 181 ++++ gateway_test.go | 148 +++ logging.go | 299 ++++++ metrics.go | 612 ++++++++++++ model_cache.go | 224 +++++ model_discovery.go | 282 ++++++ models.go | 580 ++---------- observability.go | 925 +------------------ package-lock.json | 29 + package.json | 12 + pool.go | 14 + runtime.go | 71 +- selected_key_test.go | 206 +++++ stream.go | 1010 +------------------- stream_emitter.go | 660 +++++++++++++ stream_parser.go | 362 ++++++++ stream_test.go | 74 ++ test_helpers_test.go | 85 ++ upstream.go | 642 +++++++++++++ webui/app.js | 906 ++++++++++++++++++ webui/index.html | 775 +++++++++++++--- webui/styles.css | 833 +++++++++++++++++ 51 files changed, 10622 insertions(+), 5688 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/workflows/checks.yml create mode 100644 .prettierignore create mode 100644 .prettierrc.json create mode 100644 README.zh-CN.md create mode 100644 admin_auth.go create mode 100644 admin_debug.go create mode 100644 admin_debug_test.go create mode 100644 admin_test.go create mode 100644 config_test.go create mode 100644 convert_content.go create mode 100644 convert_request.go create mode 100644 convert_response.go create mode 100644 convert_test.go create mode 100644 gateway_health.go create mode 100644 gateway_health_test.go create mode 100644 gateway_refresh.go create mode 100644 gateway_stream_test.go create mode 100644 gateway_test.go create mode 100644 logging.go create mode 100644 metrics.go create mode 100644 model_cache.go create mode 100644 model_discovery.go create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 selected_key_test.go create mode 100644 stream_emitter.go create mode 100644 stream_parser.go create mode 100644 stream_test.go create mode 100644 test_helpers_test.go create mode 100644 upstream.go create mode 100644 webui/app.js create mode 100644 webui/styles.css diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..15d3740 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,19 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +[*.go] +indent_style = tab +indent_size = 8 + +[*.sh] +indent_size = 4 + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes index 90e4911..ea9424d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ +* text=auto eol=lf docker-entrypoint.sh text eol=lf diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 0000000..3717678 --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,66 @@ +name: Checks + +on: + push: + branches: ["**"] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: checks-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: Go ${{ matrix.go }} / ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + go: ["1.24.x", stable] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: ${{ matrix.go }} + 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 ./... + + format: + name: Formatting and WebUI syntax + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + - uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + - run: npm ci --ignore-scripts + - name: Check Go formatting + shell: bash + run: | + unformatted="$(gofmt -l .)" + if [ -n "$unformatted" ]; then + printf '%s\n' "$unformatted" + exit 1 + fi + - run: npm run format:check + - run: npm run check:web + - name: Check container entrypoint syntax + run: sh -n docker-entrypoint.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c1395be..dc10e30 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -125,7 +125,7 @@ jobs: run: | mkdir -p "dist/$PACKAGE_NAME" go build -trimpath -ldflags="-s -w -X main.version=$RELEASE_TAG" -o "dist/$PACKAGE_NAME/opencode2api$EXTENSION" ./ - cp README.md config.example.json "dist/$PACKAGE_NAME/" + 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") archive="$PACKAGE_NAME.zip" diff --git a/.gitignore b/.gitignore index ba2eec1..cda442d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ .key config.json +config.json.bak +.config-*.tmp *.models.dev.json opencode/ opencode2api @@ -8,3 +10,7 @@ opencode2api.exe .tmp/ .gocache/ *.models.catalog.json +node_modules/ +coverage.out +*.test +*.test.exe diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..e816de9 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,11 @@ +node_modules/ +dist/ +build/ +.tmp/ +.gocache/ +config.json +config.json.bak +*.models.dev.json +*.models.catalog.json +coverage.out +package-lock.json diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..f329927 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,9 @@ +{ + "printWidth": 100, + "tabWidth": 2, + "useTabs": false, + "singleQuote": false, + "trailingComma": "all", + "proseWrap": "preserve", + "endOfLine": "lf" +} diff --git a/Dockerfile b/Dockerfile index 2eb9e6a..8018ce8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,10 +31,12 @@ COPY --from=builder /out/opencode2api /usr/local/bin/opencode2api COPY --chmod=0755 docker-entrypoint.sh /usr/local/bin/docker-entrypoint COPY --chown=opencode2api:opencode2api config.example.json /app/config.example.json +# LISTEN_ADDRESS / WEBUI_LISTEN_ADDRESS are intentionally unset: config.json is +# authoritative. Export them to override the configured listen addresses. ENV CONFIG_PATH=/var/lib/opencode2api/config.json \ CONFIG_SEED_PATH= \ - LISTEN_ADDRESS=0.0.0.0:8080 \ - WEBUI_LISTEN_ADDRESS=0.0.0.0:8081 \ + LISTEN_ADDRESS= \ + WEBUI_LISTEN_ADDRESS= \ STATE_DIR=/var/lib/opencode2api WORKDIR /app diff --git a/README.md b/README.md index 9b749b7..874a59b 100644 --- a/README.md +++ b/README.md @@ -1,387 +1,406 @@ # opencode2api -`opencode2api` 是一个使用 Go 编写的 OpenCode Zen / Zen Go 协议代理。它对外提供标准 OpenAI 与 Anthropic API,并自动添加 OpenCode 客户端请求头。 +[English](README.md) | [简体中文](README.zh-CN.md) -主要功能: +A Go gateway for **OpenCode Zen and Zen Go**. It exposes Chat Completions, Responses, and Anthropic Messages endpoints, translates between their native protocols, and manages upstream keys and proxies. -- 支持 OpenAI Chat Completions、Responses 和 Models API -- 支持 Anthropic Messages API -- 支持普通响应和 SSE 流式响应 -- 支持文本、图片、thinking/reasoning、工具定义、工具调用和工具结果转换 -- 分离配置 Zen key 池与 Zen Go key 池 -- 支持无需上游 key 的 Zen 匿名模式,免费模型先走匿名通道,失败后按 `prefer` 顺序回退 Zen/Go key -- 按配置周期同步 Zen/Go `/v1/models`,并从 OpenCode `models.opencode.ai/api.json` 自动同步每个 Tier 的原生协议与不支持模型;不把模型 ID 硬编码在程序中 -- 每 24 小时从 models.dev 更新 OpenCode 成本与弃用信息;models.dev 零成本或名称含 `free` 任一条件即可判定免费 -- 模型同时存在于两个上游时按 `prefer` 配置排列 Go/Zen key 的首选与回退顺序(默认 Go) -- 支持直连、HTTP、HTTPS、SOCKS5 和 SOCKS5H 代理 -- 支持从文本文件读取代理池,并与配置内的代理合并、去重 -- `config.json` 支持 `//` 和 `/* ... */` 注释 -- 将 key 自动均衡绑定到代理,保持连接亲和性 -- 使用稳定会话哈希保持同一会话的 key/proxy 亲和性,并在节点故障时自动回退 -- 代理失败后自动迁移绑定,key 失败后进行短时冷却 -- 根据真实上游流量识别代理故障,并每 15 分钟通过 Cloudflare trace 并行复查异常代理 -- 为不同会话生成不同的 OpenCode 会话 ID,并支持 `x-opencode-session`、`x-session-id` 和 `conversation-id` 显式指定会话 -- 内置独立端口 Field Manual WebUI,可管理配置、查看 Token/上游指标、诊断路由、运行三协议 Playground 与订阅实时日志 -- WebUI 使用账号密码、服务端 session、HttpOnly Cookie、CSRF 与登录限速保护 -- WebUI 保存后原子写入配置并热切换 Gateway;无效配置不会影响当前流量 -- stdout 输出结构化 JSON 日志;请求、Token、上游尝试与最近一小时滚动指标仅保存在进程内存中 +The executable includes the WebUI. Running the service requires no Node.js runtime or database. -## API 路径 +## Capabilities -| 方法 | 路径 | 协议 | -| --- | --- | --- | -| `GET` | `/v1/models` | OpenAI 模型列表 | -| `POST` | `/v1/chat/completions` | OpenAI Chat Completions | -| `POST` | `/v1/responses` | OpenAI Responses | -| `POST` | `/v1/messages` | Anthropic Messages | -| `GET` | `/healthz` | 健康检查 | +- JSON and SSE responses across all three inference protocols. +- Text, images, reasoning, function tools, tool calls, and tool results; file content where the target protocol can represent it. +- Separate Zen and Go key pools, configurable tier preference, retries, and session affinity. +- Optional anonymous Zen access with the OpenCode `public` credential. +- Direct, HTTP, HTTPS, SOCKS5, and SOCKS5H connections, including a proxy file. +- Dynamic model discovery, native protocol metadata, and disk caches. +- A separate management port with configuration editing, a Playground, diagnostics, token statistics, and live logs. +- Configuration hot reload with validation before switching new requests to a replacement gateway. -`/healthz` 无需 API key,返回服务版本以及模型目录、Zen/Go key、匿名开关和代理池的汇总状态,不会暴露 key 或代理地址。模型目录尚未完成首次刷新、没有可暴露模型或没有健康代理时返回 HTTP `503`;使用过期磁盘快取时仍返回 `200`,但 `models.status` 为 `stale`。 - -模型目录的过期阈值为 `models.refresh_seconds` 的两倍,且不低于 60 秒。刚启动时短暂返回 `503 starting` 属于正常现象,模型列表首次刷新成功后会变为 `200 ok`。 - -健康检查不会计入请求指标。它也不会触发 models.dev 刷新或写入任何监控记录。 - -## WebUI - -示例配置会在独立的 `8081` 端口启动管理界面: - -```text -http://服务器地址:8081 -``` - -首次账号为 `admin`,密码来自 `webui.password`。服务第一次成功启动时会使用 Argon2id 将密码转换为带盐哈希,写入 `webui.password_hash`,并从配置中删除明文密码。请在首次登录后立即修改示例密码。 - -Field Manual WebUI 包含运行桌面、六步首次运行检查、接入手册、Token 用量、三协议 Playground、路由诊断、配置、事件日志和账号安全页面。接入手册会生成 Chat、Responses、Anthropic、Python 和 JavaScript 示例,但始终使用 `YOUR_API_KEY` 占位符,不把真实 Server Key 写入页面。 - -Token 页面展示用量覆盖率、每分钟趋势、模型排行与 Zen/Go Tier 分布。诊断页展示 models.dev 状态、模型原生协议与匿名判断来源、Key/代理状态、逐次上游尝试以及最近一次 Playground 追踪;实时日志通过 SSE 推送。所有动态管理数据都以 DOM 文本节点渲染。 - -监控、上游尝试、最近 Playground 结果和日志仅保存在内存。**进程重启会清空全部监控与诊断历史,包括 lifetime 累计。** stdout 日志仍可由 Docker 或日志平台收集;模型目录快取与 models.dev 价格快取是独立的磁盘兼容资料,不属于监控历史。 - -### 监控字段 - -登录 WebUI 后,`GET /api/monitor` 返回以下顶层字段;该管理 API 只在 `webui.listen` 上提供,并受 Session 保护: - -| 字段 | 内容 | -| --- | --- | -| `version` | 当前程序版本。 | -| `metrics` | 原有请求统计:进程启动时间、活跃请求/流、lifetime 与最近一小时成功率/延迟、端点/模型/Tier/状态码聚合,以及 60 个每分钟序列点。 | -| `usage` | Token 的 `lifetime` 与 `last_hour` 统计。包含 `requests`、`reported`、`coverage`、总 Token 和按模型/Tier 聚合。 | -| `upstream` | 上游请求级路由 `requests`、尝试级 `lifetime`、`last_hour` 与 `recent`。按 Tier、匿名/Key 通道、Key 尾码聚合。 | -| `resources` | 模型目录、Key 冷却、脱敏代理节点、匿名开关和 models.dev metadata 状态。 | - -`usage.*.tokens` 与模型/Tier 项均包含 `input_tokens`、`output_tokens`、`cached_tokens`、`reasoning_tokens`、`total_tokens`。其中 `input_tokens` 统一表示包含缓存读写的总输入,`cached_tokens` 单独表示缓存读取量。`metrics.series` 的每分钟点也包含这些 Token 字段和 `usage_reported`。普通 JSON、同协议 SSE 与跨协议 SSE 响应都会解析上游 usage;`coverage` 是收到 usage 的推理请求数除以已建立上游路由的推理请求数。上游未提供 usage 时不会估算 Token。 - -每个 `upstream.requests` 项对应一个已完成的推理请求,包含最终实际使用的 Tier、通道、Key 尾码(或 `anonymous`)、尝试次数、HTTP 状态、耗时、成功标记和结果分类。每个 `upstream.recent` 项则对应一次上游尝试,包含时间、Request ID、模型、Tier、尝试序号、匿名标记、通道、Key 尾码、`proxy_node`、HTTP 状态、耗时、成功标记和结果分类。真实 Key 在日志和 WebUI 中只显示最后 5 个字符;配置接口的内部 secret ID 仍使用 SHA-256 稳定指纹。代理 URL 的认证信息会被移除,字段名称明确为代理节点而非出口 IP。 - -lifetime 从当前进程启动开始;last hour 使用 60 个一分钟 Bucket。进程内固定保留最近 10,000 个请求路由和 20,000 次上游尝试,管理响应最多返回其中最近 500 个,WebUI 默认各显示最后 100 条。`resources.models` 额外显示模型目录来源(`none`、`disk` 或 `live`)及 `stale` 状态。数据不会写入配置、metadata 快取或其他数据库。 - -### Playground 与诊断 API - -以下接口受管理 Session 保护;POST 还要求当前 CSRF Token,并按客户端每分钟最多 12 次限制: - -| 方法 | 路径 | 用途 | -| --- | --- | --- | -| `GET` | `/api/debug/models` | 模型路由、原生协议、协议来源、Zen/Go 可用性、匿名资格/来源、成本与 metadata 状态。 | -| `POST` | `/api/debug/inference` | 通过真实 Gateway 发起 Chat、Responses 或 Anthropic 非流式诊断请求。 | - -请求格式: - -```json -{ - "protocol": "chat", - "request": { - "model": "example-model", - "messages": [{"role": "user", "content": "Hello"}] - } -} -``` - -`protocol` 可为 `chat`、`responses` 或 `anthropic`。服务端无条件把内层 `stream` 改为 `false`。诊断结果统一包含 `ok`、真实 `http_status`、`duration_ms`、`request_id`、`route` 和原始协议 `response`。一旦诊断调用已执行,管理接口本身返回 HTTP `200`,即使上游结果是 4xx/5xx;因此错误正文、路由和 Request ID 仍可一起查看。外层请求格式、Session、CSRF 或限速错误仍使用相应管理 HTTP 状态。 - -诊断响应不会包含本地 Server Key、上游 Key、Cookie、密码、Authorization 或代理凭据;响应中同名敏感字段及已配置敏感值会在返回浏览器前清除。最近一次结果只保存在当前管理进程内。 - -## 编译 - -需要 Go 1.24 或更高版本。 - -```bash -go build -o opencode2api ./ -``` - -## 下载 - -预编译的 Windows、Linux 和 macOS 可执行文件可从 [GitHub Releases](https://github.com/jasonxu114514/opencode2api/releases) 下载。 - -## GHCR / Docker Compose 部署 - -正式镜像发布在 `ghcr.io/jasonxu114514/opencode2api` +## Quick start +Download a binary from [GitHub Releases](https://github.com/jasonxu114514/opencode2api/releases), or build with **Go 1.24 or newer**: ```bash git clone https://github.com/jasonxu114514/opencode2api.git cd opencode2api cp config.example.json config.json -# 编辑 server_keys、zen_keys/go_keys,并修改 webui.password -docker compose pull -docker compose up -d +go build -o opencode2api . ``` -首次启动会把 `config.json` 导入 `opencode2api-state` 命名卷。之后应通过 WebUI 修改配置;如需再次从宿主机导入配置,可执行: +Before starting, edit `config.json`: + +1. Replace `server_keys` with your own local API key. +2. Supply Zen or Go keys. Alternatively, set `anonymous: true` and empty both upstream key arrays. +3. Replace `webui.password`. The example enables the WebUI with username `admin`. + +```bash +./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`. + +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. + +Command-line options: + +| Option | Default | Purpose | +| ------------- | ------------- | ---------------------------------- | +| `-config` | `config.json` | Configuration file path. | +| `-listen` | Unset | Override the API listen address. | +| `-web-listen` | Unset | Override the WebUI listen address. | + +The configuration directory must be writable for password migration, configuration saves, and model caches. + +## Docker + +The published image is `ghcr.io/jasonxu114514/opencode2api`. + +```bash +cp config.example.json config.json +# Configure keys and replace the WebUI password before starting. +docker compose up -d +docker compose logs -f +``` + +Compose imports the host configuration into the `opencode2api-state` volume **only on first startup**. Subsequent changes should be made through the WebUI. To import an edited host configuration again: ```bash docker compose cp config.json opencode2api:/var/lib/opencode2api/config.json docker compose restart ``` -健康检查、WebUI 和日志: +The container runs the service as an unprivileged user. Compose uses a read-only root filesystem, a writable state volume, and a temporary `/tmp` filesystem. -```bash -curl http://127.0.0.1:8080/healthz -# 浏览器打开 http://127.0.0.1:8081 -docker compose logs -f -``` +| Compose variable | Default | Effect | +| --------------------------- | -------- | ------------------------------------------------- | +| `OPENCODE2API_VERSION` | `latest` | Image tag. Pin a release tag for a fixed version. | +| `OPENCODE2API_PORT` | `8080` | Host port mapped to container port 8080. | +| `OPENCODE2API_WEBUI_PORT` | `8081` | Host port mapped to container port 8081. | +| `OPENCODE2API_LISTEN` | Unset | Explicit container API listen override. | +| `OPENCODE2API_WEBUI_LISTEN` | Unset | Explicit container WebUI listen override. | -可通过环境变量固定镜像版本和修改宿主机端口: +The last two variables become `LISTEN_ADDRESS` and `WEBUI_LISTEN_ADDRESS` inside the container. Empty values defer to the configuration file. While initializing a configuration, the entrypoint changes the example API address `127.0.0.1:8080` to `0.0.0.0:8080` so published ports can reach it. -```bash -OPENCODE2API_VERSION=v1.2.3 OPENCODE2API_PORT=18080 OPENCODE2API_WEBUI_PORT=18081 docker compose up -d -``` +Changing host ports does not change container listeners. If you change the internal API port, also update the port mapping and the image health check, which uses port 8080. -不使用 Compose 时也可直接运行 GHCR 镜像: +For a local image: ```bash +docker build -t opencode2api:local . docker volume create opencode2api-state -docker run -d --name opencode2api --restart unless-stopped \ +docker run -d --name opencode2api \ -p 8080:8080 -p 8081:8081 \ -e CONFIG_SEED_PATH=/run/config/opencode2api.json \ -v "$(pwd)/config.json:/run/config/opencode2api.json:ro" \ -v opencode2api-state:/var/lib/opencode2api \ - ghcr.io/jasonxu114514/opencode2api:latest + opencode2api:local ``` -## 配置 +A `proxyfile` used in Docker must also be available inside the container at the configured path. -复制示例配置: +## API usage + +`server_keys` authenticate clients to this gateway. They are separate from `zen_keys` and `go_keys` and are never used as upstream credentials. + +Send `Authorization: Bearer YOUR_LOCAL_API_KEY` or `x-api-key: YOUR_LOCAL_API_KEY`. Health checks require no authentication. + +| Method | Path | Description | +| ------ | ---------------------- | --------------------------------------------------------- | +| GET | `/v1/models` | Models that can be routed with the current configuration. | +| POST | `/v1/chat/completions` | Chat Completions. | +| POST | `/v1/responses` | Responses. | +| POST | `/v1/messages` | Anthropic Messages. | +| GET | `/healthz` | Readiness and resource summary. | + +Discover an available model first: ```bash -cp config.example.json config.json +curl http://localhost:8080/v1/models \ + -H "Authorization: Bearer YOUR_LOCAL_API_KEY" ``` -然后编辑 `config.json`: +Replace `MODEL_ID` below with an ID from that response. + +**Chat Completions** + +```bash +curl http://localhost:8080/v1/chat/completions \ + -H "Authorization: Bearer YOUR_LOCAL_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"model":"MODEL_ID","messages":[{"role":"user","content":"Hello"}]}' +``` + +**Responses** + +```bash +curl http://localhost:8080/v1/responses \ + -H "Authorization: Bearer YOUR_LOCAL_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"model":"MODEL_ID","input":"Hello"}' +``` + +**Anthropic Messages** + +```bash +curl http://localhost:8080/v1/messages \ + -H "x-api-key: YOUR_LOCAL_API_KEY" \ + -H "anthropic-version: 2023-06-01" \ + -H "Content-Type: application/json" \ + -d '{"model":"MODEL_ID","max_tokens":512,"messages":[{"role":"user","content":"Hello"}]}' +``` + +For streaming, add `"stream": true` to the body and use `curl -N`. Responses include an `x-request-id` for correlation. API request bodies are limited to 32 MiB. + +### Compatibility boundaries + +Requests using the upstream's native protocol retain provider-specific fields. Requests crossing protocols pass through a common representation; not every option has an equivalent. For example, Chat JSON output constraints and `seed` are not forwarded to Anthropic Messages. Unsupported content or tool types may be rejected. + +The gateway exposes the routes listed above. It does not implement embeddings, file uploads, image generation, or Responses retrieval and cancellation. It does not store conversation history; clients must supply the history or use features supported by the actual upstream. + +## Routing and models + +### Model discovery + +The gateway refreshes Zen/Go `/v1/models` and OpenCode's [capability catalog](https://models.opencode.ai/api.json) on the configured interval. Native protocols and model limits are tracked separately for each tier. OpenCode's Zen/Go documentation is a fallback for protocol discovery. + +`models.protocols` overrides discovery: ```json { - "listen": "127.0.0.1:8080", - "server_keys": ["change-this-local-key"], - "zen_keys": ["sk-your-zen-key"], - "go_keys": [], - "anonymous": false, - "prefer": "go", - "proxyfile": "", - "proxies": ["direct"], - "upstream": { - "zen": "https://opencode.ai/zen", - "go": "https://opencode.ai/zen/go" - }, - "retry": { - "max_attempts": 3, - "timeout_seconds": 300 - }, "models": { "refresh_seconds": 300, - "protocols": {} - }, - "performance": { - "max_idle_conns": 2048, - "max_idle_conns_per_host": 256, - "max_conns_per_host": 0, - "idle_conn_timeout_seconds": 120, - "connect_timeout_seconds": 5, - "failure_cooldown_seconds": 15 - }, - "logging": { - "level": "info", - "ring_size": 2000 - }, - "webui": { - "enabled": true, - "listen": "0.0.0.0:8081", - "username": "admin", - "password": "change-this-admin-password", - "session_ttl_minutes": 720 + "protocols": { + "custom-model": "chat" + } } } ``` -### 基础字段 +Allowed protocol values are `chat`, `responses`, and `anthropic`. Models using unsupported native protocols are filtered from discovery unless overridden. -| 字段 | 含义 | -| --- | --- | -| `listen` | 本地监听地址。默认建议使用 `127.0.0.1:8080`,避免服务直接暴露到公网。 | -| `server_keys` | 调用本代理时使用的本地 API key 列表。它们只用于本地鉴权,不会发送给 OpenCode。 | -| `zen_keys` | OpenCode Zen API key 池。允许配置多个 key。 | -| `go_keys` | OpenCode Zen Go API key 池。没有 Go key 时可以使用空数组。 | -| `anonymous` | 是否启用 Zen 匿名模式,默认 `false`。models.dev 判定为零成本,或模型名称包含 `free`,任一条件成立即可进入匿名通道。 | -| `prefer` | 模型同时存在于 Zen 与 Go 时认证 Key 的尝试顺序,值为 `go` 或 `zen`,默认 `go`。首选 Tier 失败后回退另一 Tier;仅存在于某一池时只尝试该池。 | -| `proxyfile` | 可选代理池文件路径。相对路径以 `config.json` 所在目录为基准;内容会追加到 `proxies` 并去重。 | -| `proxies` | 上游代理列表。支持 `direct`、`http://`、`https://`、`socks5://` 和 `socks5h://`。URL 可以包含代理用户名和密码。 | +Cost and deprecation metadata come from [models.dev](https://models.dev/api.json), refreshed every 24 hours. Metadata requests use a 30-second timeout per HTTP client. Refresh failures retain existing data. -`server_keys` 至少需要一个值。`anonymous` 为 `false` 时,`zen_keys` 和 `go_keys` 至少有一个池不能为空;启用匿名模式后两个上游 key 池可以同时为空。 +### Anonymous access and fallback -### Zen 匿名模式 +With `anonymous: true`, either condition makes a model eligible for the anonymous Zen lane: -OpenCode 客户端在没有配置 Zen key 时使用固定的 `public` 凭证;Zen 服务端将它转换为匿名请求,并按出口 IP 对允许匿名访问的模型限流。本项目使用相同协议:OpenAI/Responses 上游请求发送 `Authorization: Bearer public`,Anthropic 上游请求发送 `x-api-key: public`。 +- Its ID contains `free`, case-insensitively. +- models.dev reports zero input and output cost and the model is not deprecated. -启用 `anonymous` 后,以下任一条件成立即视为免费模型: +Eligibility is a routing decision; the upstream can still reject or rate-limit the request. Anonymous requests use `public` in the upstream authentication header. -1. models.dev 已知输入、输出成本都为 `0`,且模型未弃用;不要求名称包含 `free`。 -2. 模型 ID 大小写不敏感地包含 `free`;即使 metadata 尚未就绪、缺少该模型或显示为付费,也仍按名称条件视为免费。 +The routing sequence is: -免费模型先走匿名 Zen,非免费模型完全跳过匿名通道。匿名请求遇到任何错误——包括传输错误、4xx、5xx 或其他非 2xx 响应——都会继续切换下一个当前可用的 proxy;每个可用 proxy 最多尝试一次。anonymous 阶段不受 `retry.max_attempts` 提前截断,只有可用 proxy 全部耗尽后才进入认证 Key 阶段。认证 Tier 按 `prefer` 排序:`prefer: "go"` 为 Go key → Zen key,`prefer: "zen"` 为 Zen key → Go key;首选 Tier 仍不成功时才尝试另一个实际提供该模型且配置了 Key 的 Tier。Zen/Go Key 阶段各自拥有 `retry.max_attempts` 预算。监控中的 `proxy_node` 表示所选代理节点,不代表或推断实际出口 IP。 +1. For an eligible model, try each available anonymous proxy once. +2. Try authenticated tiers in `prefer` order, using only tiers with a configured key and a route for that model. +3. Apply `retry.max_attempts` separately to each authenticated tier. -只有匿名通道、且 `zen_keys` 与 `go_keys` 都为空时,`/v1/models` 只展示按上述规则可匿名使用的模型。只要配置了任一真实上游 Key,模型列表仍展示该 Key 路由可用的完整模型集合。 +Anonymous attempts are not cut short by `retry.max_attempts`, but all attempts share the request timeout. Network errors, authentication failures, rate limits, and server errors can rotate keys. Other 4xx responses end the current tier; another available tier may still be tried. -models.dev 使用固定 30 秒超时,每 24 小时刷新一次。标准地址为 `https://models.dev/api.json`;规范化后的 OpenCode 模型成本缓存在 `config.json.models.dev.json`,以 `0600` 权限和同目录临时文件原子替换。启动会先读取可用快取,再尝试联网更新;更新失败不会丢弃旧资料,错误、更新时间与过期状态可在监控资源和诊断页查看。 +Requests are encoded for each tier's own protocol. Once a stream has started, the gateway does not retry generation on another node. A recognized stale Responses reasoning reference can trigger one repair pass; selected-key diagnostics never use that replay. -### key 与代理分配规则 +When only anonymous access is configured, `/v1/models` exposes only models eligible for that lane. -只需要直连时使用: +### Sessions and proxies -```json -"proxies": ["direct"] +Keys are initially spread across proxies. Real traffic can trigger proxy checks, key rebinding, and cooldowns. Unhealthy proxies are rechecked every 15 minutes against Cloudflare trace. + +A stable session hash selects the preferred key or anonymous proxy. Send an explicit `x-session-id` to separate independent conversations. The gateway also accepts `x-opencode-session`, `x-session-affinity`, `conversation-id`, `conversation_id`, and `metadata.session_id`. + +Without an explicit ID, the first user message is used as a seed. Conversations beginning with the same content can therefore share affinity. Changing pool membership can change the selected node. + +Cooldowns grow exponentially up to eight times `performance.failure_cooldown_seconds`, and a longer `Retry-After` is honored. If every authenticated key is cooling down, routing may try the key whose cooldown ends first. Anonymous nodes still in cooldown are skipped. + +## Configuration reference + +See [config.example.json](config.example.json) for a complete starting configuration. JSON supports `//` and `/* ... */` comments; unknown fields and invalid values are rejected. + +### Keys, listeners, and routing + +| Field | Default / requirement | +| ------------------------ | ------------------------------------------------------------------------- | +| `listen` | `127.0.0.1:8080`. | +| `server_keys` | At least one local key is required. | +| `zen_keys`, `go_keys` | At least one upstream key is required unless anonymous access is enabled. | +| `anonymous` | `false`. | +| `prefer` | `go`; accepts `go` or `zen`. | +| `upstream.zen` | `https://opencode.ai/zen`. | +| `upstream.go` | `https://opencode.ai/zen/go`. | +| `proxies` | Falls back to `["direct"]` when both proxy sources are empty. | +| `proxyfile` | Optional; relative paths resolve beside the configuration file. | +| `models.refresh_seconds` | `300`; minimum 1. | +| `models.protocols` | `{}`; per-model native protocol overrides. | + +Proxy entries accept `direct`, `http://`, `https://`, `socks5://`, and `socks5h://`, including URL credentials. The inline list is merged with `proxyfile` and deduplicated in order. + +A proxy file contains one entry per line and supports blank lines and comments: + +```text +# Primary proxy +http://user:password@127.0.0.1:7890 +socks5://127.0.0.1:1080 # Backup proxy +direct ``` -SOCKS5 代理示例: +Comment markers are `#`, `;`, and `//` at the start of a line or after whitespace. -```json -"proxies": ["socks5://127.0.0.1:1080"] -``` +### Timeouts and connection pools -多个代理示例: +| Field | Default | Meaning | +| --------------------------------------- | ------- | ------------------------------------------------------ | +| `retry.max_attempts` | `3` | Attempts per authenticated tier, including the first. | +| `retry.timeout_seconds` | `300` | Total inference timeout, including stream consumption. | +| `performance.attempt_timeout_seconds` | `0` | Header wait per attempt; 0 uses the request timeout. | +| `performance.connect_timeout_seconds` | `5` | Connection establishment timeout. | +| `performance.failure_cooldown_seconds` | `15` | Base failure cooldown. | +| `performance.max_idle_conns` | `2048` | Idle connection limit per proxy transport. | +| `performance.max_idle_conns_per_host` | `256` | Idle connection limit per host and transport. | +| `performance.max_conns_per_host` | `0` | Connection limit per host; 0 is unlimited. | +| `performance.idle_conn_timeout_seconds` | `120` | Idle connection lifetime. | -```json -"proxies": [ - "http://user:password@127.0.0.1:7890", - "socks5://127.0.0.1:1080" -] -``` +The per-attempt header timeout is capped by the request timeout. Set it below the total timeout if a slow upstream should leave time for fallback. Expired request contexts stop further attempts without penalizing unused keys or proxies. -也可以从文本文件加载代理池: +### Logging and management + +| Field | Default / requirement | +| ----------------------------- | ------------------------------------------------------------- | +| `logging.level` | `info`; accepts `debug`, `info`, `warn`, `error`. | +| `logging.ring_size` | `2000`; range 100–50,000. | +| `logging.dump_request_bodies` | `false`. Requires `debug` logging to emit outbound bodies. | +| `webui.enabled` | `false` when omitted; the example sets it to `true`. | +| `webui.listen` | `0.0.0.0:8081`. | +| `webui.username` | Required when the WebUI is enabled; the example uses `admin`. | +| `webui.password` | Bootstrap password with a minimum length of 10. | +| `webui.password_hash` | Generated Argon2id hash; replaces the plaintext password. | +| `webui.session_ttl_minutes` | `720`; range 5–10,080. | + +On startup, a bootstrap password is hashed and removed from the configuration. The backup containing that bootstrap plaintext is deleted. Keep configuration files and backups private: upstream keys and proxy credentials remain necessary configuration secrets. + +Body dumps are opt-in and capped at 64 KiB per prepared body. Configured secrets are redacted, but conversation content may still be sensitive. + +## WebUI and diagnostics + +The management listener serves the UI and `/api/*` routes. Authentication uses one administrator account, server-side sessions, HttpOnly/SameSite cookies, CSRF checks for writes, and login throttling. + +| Management route | Purpose | +| ------------------------------------------------ | --------------------------------------------------------------------- | +| `POST /api/auth/login` | Log in and obtain a session cookie and CSRF token. | +| `GET /api/auth/session`, `POST /api/auth/logout` | Inspect or end the session. | +| `GET /api/config`, `PUT /api/config` | Read masked configuration or apply changes. | +| `POST /api/config/reload` | Reload the file from disk. | +| `POST /api/config/reveal` | Reveal configured secrets after password verification. | +| `PUT /api/account` | Update credentials after password verification; invalidates sessions. | +| `GET /api/monitor` | Request, token, upstream, and resource statistics. | +| `GET /api/debug/models` | Model routes, key fingerprints, and metadata diagnostics. | +| `POST /api/debug/inference` | Run a Playground request. | +| `GET /api/logs`, `GET /api/logs/stream` | Recent logs or a live SSE subscription. | + +Playground requests require a session and `X-CSRF-Token` and are limited to 12 per minute per client IP: ```json { - "proxyfile": "proxies.txt", - "proxies": ["direct"] + "protocol": "chat", + "key": { "mode": "auto" }, + "request": { + "model": "MODEL_ID", + "messages": [{ "role": "user", "content": "Hello" }] + } } ``` -`proxies.txt` 每行填写一个代理。支持空行、以 `#`、`;` 或 `//` 开头的整行注释,也支持在代理后使用空格加这些标记写行尾注释: +The server forces `stream: false`. Use `{"mode":"selected","tier":"zen","id":"KEY_FINGERPRINT"}` to test a specific key from `/api/debug/models`. A selected request makes at most one upstream attempt, without anonymous access, key rotation, tier fallback, or reasoning replay. -```text -# HTTP 代理 -http://user:password@127.0.0.1:7890 -socks5://127.0.0.1:1080 # 备用代理 +**Both automatic and selected diagnostics preserve production key cooldowns, failure counts, proxy health, and bindings.** They still make real upstream requests, can consume provider quota, and appear in monitoring. + +After execution, the management endpoint returns HTTP 200 with the actual result in `ok`, `http_status`, `request_id`, `route`, and `response`. Selected-key results also include `selected_key` and `key_test`: `usable`, `rejected`, `rate_limited`, `transport_error`, `upstream_error`, `request_error`, or `unavailable`. Invalid management input, authentication, CSRF, and throttling retain their own HTTP error statuses. + +### Saving and reloading + +The server validates a candidate configuration and builds its replacement gateway before saving and switching. Failed validation or persistence leaves the active gateway in place. Requests already running continue on their original gateway. + +Keys, proxies, upstream URLs, retry settings, model settings, logging, and routing preferences apply to new requests immediately. Changes to `listen`, `webui.listen`, or `webui.enabled` require a process restart. Saved JSON is normalized; comments are not retained. + +## Monitoring and persistence + +Request outcomes describe the completed inference. A failed SSE response or truncated stream counts as an error even when HTTP 200 was already sent; its outcome is `stream_error`. Client cancellations are recorded as `client_canceled`. The WebUI displays those outcomes alongside the HTTP status. + +Upstream **attempt** records measure the HTTP exchange through receipt of response headers. Their success and latency are separate from completion of the full JSON body or stream. + +Token statistics use reported usage only. Input tokens include cache reads and writes; cached tokens separately count cache reads. Missing usage is not estimated, and coverage shows how many routed inference requests reported usage. + +| Data | Storage / retention | +| --------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| Sessions, metrics, token totals, latest Playground result | Process memory; cleared on restart. | +| Request and attempt details | Recent hour, capped at 10,000 requests and 20,000 attempts; API returns at most 500 of each. | +| Live log ring | Process memory; size set by `logging.ring_size`. | +| Structured logs | JSON on stdout; collect externally for durable history. | +| Configuration and previous version | `config.json` and `config.json.bak`. | +| Model directory cache | `config.json.models.catalog.json`. | +| Price/deprecation cache | `config.json.models.dev.json`. | + +Cache filenames are based on the actual configuration path. Lifetime counters mean the current process lifetime. Instances do not share sessions or monitoring state. + +### Health checks + +`/healthz` does not increment monitoring counters or trigger network requests. It reports resource counts without keys or proxy addresses. + +- HTTP 503: initial catalog pending, no models routable with the current configuration, or no healthy proxies. +- HTTP 200: ready, including when a usable catalog cache is stale. In that case the model status is `stale` and overall status is `degraded`. + +The staleness threshold is twice `models.refresh_seconds`, with a minimum of 60 seconds. Readiness is a discovery and resource check; it does not verify that an upstream key will accept the next inference. + +## Development + +Source organization: + +| 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 . ``` -配置中的 `proxies` 会先加载,随后加载 `proxyfile`,重复项只保留第一次出现的位置。如果两个来源都为空,则仍使用 `direct`。`config.json` 本身支持 `//` 单行注释和 `/* ... */` 块注释;引号内的 `https://` 等内容不会被当作注释。 +The race detector needs CGO and a supported C compiler. Tests use local servers or stub transports for inference; no production keys are required. -### `upstream` +Node.js is only needed for development formatting and JavaScript syntax checks: -| 字段 | 含义 | -| --- | --- | -| `upstream.zen` | Zen 上游根地址,通常保持为 `https://opencode.ai/zen`。 | -| `upstream.go` | Zen Go 上游根地址,通常保持为 `https://opencode.ai/zen/go`。 | - -### `retry` - -| 字段 | 含义 | -| --- | --- | -| `retry.max_attempts` | 每个认证 Key Tier 的最大尝试次数,包含第一次请求。Tier 内部遇到网络错误、认证失败、限流或 5xx 会切换节点;其他 4xx 会结束当前 Tier。只要还有另一个可用 Tier,当前 Tier 的最终失败会继续按 `prefer` 顺序回退。anonymous 不使用此上限,而是将每个当前可用 proxy 各尝试一次。 | -| `retry.timeout_seconds` | 单个客户端请求的总超时时间,同时用于限制上游响应头等待时间。 | - -流式响应一旦已经向客户端输出数据,就不会切换节点重新生成,避免拼接两个不同的响应。 - -### `models` - -| 字段 | 含义 | -| --- | --- | -| `models.refresh_seconds` | 重新读取 Zen 和 Go 模型列表及 OpenCode 能力目录的间隔秒数。两个模型列表与能力目录会并发刷新。 | -| `models.protocols` | 手动指定模型的原生协议。值只能是 `chat`、`responses` 或 `anthropic`,并覆盖自动同步结果。通常保持为空。 | - - -模型协议覆盖示例: - -```json -"protocols": { - "custom-model": "chat" -} +```bash +npm ci --ignore-scripts +npm run format +npm run format:check +npm run check:web ``` -自动协议来源是 `https://models.opencode.ai/api.json`,并用 OpenCode 官方 Zen/Go endpoint 文档补充具体路径:模型的 `provider.npm`(或 Tier 默认 `npm`)及文档 endpoint 会映射为 OpenAI Responses、Anthropic Messages 或 OpenAI-compatible Chat。模型列表与协议能力会写入 `.models.catalog.json`,使用同目录临时文件原子替换并限制为 `0600`;启动时会先使用有效的旧快取,背景刷新成功后再更新。若能力目录暂时无法更新,服务会保留进程内上一份能力快照;首次启动且没有能力快照时,不会暴露能力未知的模型,避免把不支持的模型误路由到 Chat。手动 `models.protocols` 可用于上游实验模型。 +`.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. -模型同时存在于 Zen 与 Go 时按 `prefer` 配置排列认证 Key 顺序:值为 `go` 时先 Go 后 Zen,值为 `zen` 时先 Zen 后 Go(默认 `go`)。首选 Tier 失败后才回退另一 Tier;仅存在于某一池时只使用该池的 key。免费模型在这条认证顺序之前额外尝试匿名 Zen。 +## Troubleshooting -### Thinking 工具历史兼容 +| Symptom | Check | +| ------------------------------------ | ----------------------------------------------------------------------------------------- | +| API returns 401 | Use a configured local `server_keys` value. | +| Health remains `starting` | Inspect catalog refresh logs and outbound connectivity; add protocol overrides if needed. | +| No models are exposed | Check configured tiers, anonymous eligibility, and native protocol support. | +| Requests return 502/504 | Inspect upstream attempts, credentials, proxies, and total/per-attempt timeouts. | +| HTTP 200 but generation failed | Inspect the SSE error event and request outcome, not only HTTP status. | +| Host edits have no effect in Docker | The active file is in the state volume; import it again or use the WebUI. | +| Container ports are unreachable | Check listener addresses, published ports, and the active volume configuration. | +| Monitoring disappeared after restart | Monitoring is stored only in memory; collect stdout logs externally. | -所有请求都会经过同一个上游请求准备流程,同协议转发和跨协议转换不再使用两套分支。通过 Chat Completions 或 Anthropic Messages API 调用 DeepSeek、Kimi/Moonshot 或 MiMo 模型时,代理会按上游的目标协议规范化 assistant 工具历史:Chat 补全缺失或空的 `reasoning_content`;Anthropic 保留有效 thinking 文本、为缺失或空的 thinking 补充兼容占位内容、将 `redacted_thinking` 转为普通 thinking,并移除这些兼容端点不接受的 `signature`。显式启用 reasoning/thinking 的别名模型也会启用该处理,普通非 reasoning 请求不会被修改。 +## Acknowledgements -跨协议桥接会区分 Chat/Responses 的 system 与 developer 指令,在 Anthropic 目标中按顺序合并为 system 内容;reasoning effort 会转换为兼容 thinking 预算。工具选择、空参数 `{}`、停止原因,以及 SSE 中延迟到达的工具名称、参数分片和完成事件也会转换到目标协议的对应形态。 - -流式响应会兼容 Chat 上游的 `delta.reasoning_content` 与 `delta.reasoning`。Anthropic 上游的 `event: error`、Responses 上游的 `response.failed` 以及 Chat 的错误类 `finish_reason` 会转换为目标协议的结构化错误事件,不会伪装成正常结束或静默断流。`redacted_thinking` 在支持加密 reasoning 的 Responses 目标中保留 `encrypted_content`,在无法表达加密块的 Chat/Anthropic 目标中使用 `[redacted thinking]` 明确占位。 - -协议文档未定义或当前 bridge 无法无损表达的输入 content block(例如未实现的音频/文件类型)会返回明确的转换错误,不再静默丢弃内容。 - -### `performance` - -| 字段 | 含义 | -| --- | --- | -| `performance.max_idle_conns` | 所有上游连接池允许保留的最大空闲连接数。 | -| `performance.max_idle_conns_per_host` | 每个上游主机允许保留的最大空闲连接数。 | -| `performance.max_conns_per_host` | 每个主机的最大并发连接数。`0` 表示不设置上限。 | -| `performance.idle_conn_timeout_seconds` | 空闲连接在连接池中保留的时间。 | -| `performance.connect_timeout_seconds` | 与上游或代理建立 TCP 连接的超时时间。 | -| `performance.failure_cooldown_seconds` | 连接失败、认证失败、限流或 5xx 后节点的基础冷却时间。连续失败会指数增加冷却时间。 | - -### `logging` - -| 字段 | 含义 | -| --- | --- | -| `logging.level` | 日志级别,支持 `debug`、`info`、`warn` 和 `error`,可通过 WebUI 热切换。 | -| `logging.ring_size` | WebUI 最近日志环容量,范围 100–50000,默认 2000。stdout 不受此容量限制。 | - -每条 stdout 日志都是单行 JSON,包含时间、级别、组件、事件以及适用的 request ID、模型、tier、状态码、耗时、重试次数和实际使用的 Key 尾码。已建立上游路由的请求会以 `info` 级别记录 `request_routed` 事件;真实 Key 只显示最后 5 个字符,anonymous 请求显示为 `anonymous`。普通“请求完成”事件仍使用 `debug` 级别;警告和错误按原级别输出。日志不会输出完整上游 key、本地 key、Authorization、Cookie、代理认证信息或请求消息正文。 - -### `webui` - -| 字段 | 含义 | -| --- | --- | -| `webui.enabled` | 是否在独立端口启动管理服务。旧配置未包含该段时默认关闭。 | -| `webui.listen` | 管理服务监听地址,示例为 `0.0.0.0:8081`。 | -| `webui.username` | 单一管理员账号。 | -| `webui.password` | 仅用于首次初始化的明文密码,至少 10 个字符;启动后自动删除。 | -| `webui.password_hash` | 自动生成的 Argon2id 哈希,不应手动编辑,也不会由 WebUI API 返回。 | -| `webui.session_ttl_minutes` | 登录 session 有效时间,范围 5–10080 分钟。 | - -WebUI 中普通配置响应只包含 key 尾码/指纹及脱敏 proxy;运行桌面和路由诊断会显示每个请求最终使用的 Key 最后 5 个字符或 `anonymous`。需要查看完整值时必须再次输入管理密码,敏感响应禁止浏览器缓存。 - -### 配置保存与热重载 - -WebUI 保存时先解析并验证完整候选配置、创建新的连接池和 Gateway,然后写入临时文件、保留 `config.json.bak` 并替换 `config.json`,最后原子切换新请求使用的运行实例。写入或初始化失败时旧实例继续工作;切换前已开始的请求不会中断。 - -keys、proxy、上游、重试、模型、性能、优先 tier 和日志级别会立即生效。`listen`、`webui.listen` 与 `webui.enabled` 会保存但需要重启进程。WebUI 也提供“从磁盘重载”,外部编辑后的配置仍会经过相同的验证与回滚流程。保存后的 JSON 会被规范化,原有注释不会保留。 - - -## 会话 ID - -代理会为上游添加 OpenCode 使用的 `User-Agent`、`x-opencode-client`、`x-opencode-session`、`x-opencode-request` 和 `x-opencode-project` 请求头。 - -- 每个请求使用不同的 `x-opencode-request`,同一次请求的重试保持不变。 -- 优先使用客户端提供的 `x-opencode-session`、`x-session-affinity`、`X-Session-Id`、`x-session-id`、`conversation-id`、`conversation_id` 或 `metadata.session_id` 生成会话 ID。 -- 没有显式会话标识时,使用第一条用户消息生成稳定会话 ID,使同一段多轮对话保持一致。 -- 如果两个独立会话的第一条消息完全相同,建议由客户端发送不同的 `x-session-id`,以确保两个会话严格分离。 -- 上游请求同时发送 `x-session-affinity`、`X-Session-Id` 和可选的 `x-parent-session-id`,以兼容 OpenCode 近期的会话关联要求。 - -## 致谢 - -感谢 [LINUX DO](https://linux.do) 社区一直以来的支持。 +Thanks to the [LINUX DO](https://linux.do) community for its support. diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..2c06818 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,406 @@ +# opencode2api + +[English](README.md) | [简体中文](README.zh-CN.md) + +使用 Go 编写的 **OpenCode Zen / Zen Go API 网关**。对外提供 Chat Completions、Responses 和 Anthropic Messages 接口,按上游原生协议转换请求,并统一管理上游 Key 与代理。 + +WebUI 内嵌在可执行文件中,运行服务无需 Node.js 或数据库。 + +## 功能 + +- 三种推理协议之间的普通 JSON 响应与 SSE 流式转换。 +- 文本、图片、reasoning、函数工具、工具调用和工具结果;目标协议允许时支持文件内容转换。 +- 独立的 Zen / Go Key 池,可配置优先级、重试和会话亲和性。 +- 使用 OpenCode `public` 凭证的可选 Zen 匿名通道。 +- 直连、HTTP、HTTPS、SOCKS5、SOCKS5H 连接,以及代理文件。 +- 动态模型发现、原生协议与能力信息、磁盘缓存。 +- 独立管理端口,支持配置编辑、Playground、路由诊断、Token 统计和实时日志。 +- 配置热重载:先验证新配置,再切换新请求使用的 Gateway。 + +## 快速开始 + +从 [GitHub Releases](https://github.com/jasonxu114514/opencode2api/releases) 下载可执行文件,或使用 **Go 1.24 及以上版本**编译: + +```bash +git clone https://github.com/jasonxu114514/opencode2api.git +cd opencode2api +cp config.example.json config.json +go build -o opencode2api . +``` + +启动前编辑 `config.json`: + +1. 将 `server_keys` 替换为自己的本地 API Key。 +2. 填入 Zen 或 Go Key;也可以设置 `anonymous: true`,并清空两个上游 Key 数组。 +3. 替换 `webui.password`。示例配置启用了 WebUI,用户名为 `admin`。 + +```bash +./opencode2api -config config.json +``` + +Windows 下使用 `Copy-Item config.example.json config.json` 复制配置,执行 `go build -o opencode2api.exe .` 编译,再运行 `.\opencode2api.exe -config config.json`。 + +示例配置的 API 监听 `127.0.0.1:8080`,WebUI 监听 `0.0.0.0:8081`。本机可访问 `http://localhost:8081`。通过网络访问管理界面时,请限制访问范围,并使用 HTTPS 反向代理。 + +命令行参数: + +| 参数 | 默认值 | 用途 | +| ------------- | ------------- | --------------------- | +| `-config` | `config.json` | 配置文件路径。 | +| `-listen` | 未设置 | 覆盖 API 监听地址。 | +| `-web-listen` | 未设置 | 覆盖 WebUI 监听地址。 | + +配置所在目录需要可写,以便迁移密码、保存配置和写入模型缓存。 + +## Docker 部署 + +已发布镜像:`ghcr.io/jasonxu114514/opencode2api`。 + +```bash +cp config.example.json config.json +# 启动前填写 Key,并替换 WebUI 密码。 +docker compose up -d +docker compose logs -f +``` + +Compose **仅在首次启动时**将宿主机配置导入 `opencode2api-state` 命名卷。后续建议通过 WebUI 修改配置。需要重新导入宿主机文件时: + +```bash +docker compose cp config.json opencode2api:/var/lib/opencode2api/config.json +docker compose restart +``` + +容器内的服务进程使用普通用户运行。Compose 启用只读根文件系统,并提供可写状态卷和临时 `/tmp` 文件系统。 + +| Compose 环境变量 | 默认值 | 作用 | +| --------------------------- | -------- | ------------------------------------ | +| `OPENCODE2API_VERSION` | `latest` | 镜像标签;可指定发行标签来固定版本。 | +| `OPENCODE2API_PORT` | `8080` | 映射到容器 8080 的宿主机端口。 | +| `OPENCODE2API_WEBUI_PORT` | `8081` | 映射到容器 8081 的宿主机端口。 | +| `OPENCODE2API_LISTEN` | 未设置 | 显式覆盖容器内 API 监听地址。 | +| `OPENCODE2API_WEBUI_LISTEN` | 未设置 | 显式覆盖容器内 WebUI 监听地址。 | + +后两项在容器内对应 `LISTEN_ADDRESS` 与 `WEBUI_LISTEN_ADDRESS`。值为空时使用配置文件中的地址。首次初始化配置时,入口脚本会将示例 API 地址 `127.0.0.1:8080` 改为 `0.0.0.0:8080`,使其能够通过发布端口访问。 + +修改宿主机端口不会改变容器内监听地址。如果修改容器内 API 端口,还需要同步调整端口映射和镜像健康检查;默认健康检查使用 8080 端口。 + +构建并运行本地镜像: + +```bash +docker build -t opencode2api:local . +docker volume create opencode2api-state +docker run -d --name opencode2api \ + -p 8080:8080 -p 8081:8081 \ + -e CONFIG_SEED_PATH=/run/config/opencode2api.json \ + -v "$(pwd)/config.json:/run/config/opencode2api.json:ro" \ + -v opencode2api-state:/var/lib/opencode2api \ + opencode2api:local +``` + +在 Docker 中使用 `proxyfile` 时,代理文件也需要挂载到容器内配置指定的位置。 + +## API 调用 + +`server_keys` 用于客户端调用本地网关,与 `zen_keys`、`go_keys` 相互独立,不会作为上游认证凭证发送。 + +请求可以使用 `Authorization: Bearer YOUR_LOCAL_API_KEY` 或 `x-api-key: YOUR_LOCAL_API_KEY`。健康检查无需认证。 + +| 方法 | 路径 | 用途 | +| ---- | ---------------------- | -------------------------- | +| GET | `/v1/models` | 当前配置下可以路由的模型。 | +| POST | `/v1/chat/completions` | Chat Completions。 | +| POST | `/v1/responses` | Responses。 | +| POST | `/v1/messages` | Anthropic Messages。 | +| GET | `/healthz` | 就绪状态与资源汇总。 | + +先获取可用模型: + +```bash +curl http://localhost:8080/v1/models \ + -H "Authorization: Bearer YOUR_LOCAL_API_KEY" +``` + +将以下示例中的 `MODEL_ID` 替换为模型列表返回的 ID。 + +**Chat Completions** + +```bash +curl http://localhost:8080/v1/chat/completions \ + -H "Authorization: Bearer YOUR_LOCAL_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"model":"MODEL_ID","messages":[{"role":"user","content":"Hello"}]}' +``` + +**Responses** + +```bash +curl http://localhost:8080/v1/responses \ + -H "Authorization: Bearer YOUR_LOCAL_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"model":"MODEL_ID","input":"Hello"}' +``` + +**Anthropic Messages** + +```bash +curl http://localhost:8080/v1/messages \ + -H "x-api-key: YOUR_LOCAL_API_KEY" \ + -H "anthropic-version: 2023-06-01" \ + -H "Content-Type: application/json" \ + -d '{"model":"MODEL_ID","max_tokens":512,"messages":[{"role":"user","content":"Hello"}]}' +``` + +需要流式响应时,在请求体中加入 `"stream": true`,并使用 `curl -N`。响应通过 `x-request-id` 提供请求关联标识。API 请求体上限为 32 MiB。 + +### 协议兼容边界 + +客户端协议与上游原生协议相同时,会保留供应商特有字段。跨协议请求经过统一中间结构转换,部分参数没有等价表达。例如,Chat 的 JSON 输出约束与 `seed` 不会被转发到 Anthropic Messages。不支持的内容块或工具类型可能被拒绝。 + +网关仅实现上表中的接口,不提供 embeddings、文件上传、图像生成、Responses 查询或取消接口。网关不保存会话历史;客户端需要提交历史,或使用实际上游支持的相关能力。 + +## 路由与模型 + +### 模型发现 + +服务按配置周期刷新 Zen / Go 的 `/v1/models` 和 OpenCode [能力目录](https://models.opencode.ai/api.json),分别记录两个 Tier 的原生协议与模型限制。OpenCode 的 Zen / Go 文档作为协议发现的回退来源。 + +可通过 `models.protocols` 覆盖自动发现结果: + +```json +{ + "models": { + "refresh_seconds": 300, + "protocols": { + "custom-model": "chat" + } + } +} +``` + +协议值仅允许 `chat`、`responses`、`anthropic`。使用不支持的原生协议的模型会从模型列表中隐藏,除非配置了覆盖值。 + +成本和弃用信息来自 [models.dev](https://models.dev/api.json),每 24 小时刷新一次;每个 HTTP 客户端的拉取超时为 30 秒。刷新失败时保留已有数据。 + +### 匿名通道与回退 + +启用 `anonymous: true` 后,满足以下任一条件的模型可以进入 Zen 匿名通道: + +- 模型 ID 包含 `free`,不区分大小写。 +- models.dev 中的输入、输出成本均为零,且模型未弃用。 + +这只是网关的路由判断,上游仍可能拒绝或限制请求。匿名请求在上游认证头中使用 `public` 凭证。 + +路由顺序: + +1. 符合条件的模型先尝试匿名通道,每个可用代理最多一次。 +2. 按 `prefer` 顺序尝试认证通道,仅包含已配置 Key 且可以提供该模型的 Tier。 +3. 每个认证 Tier 分别使用 `retry.max_attempts` 预算。 + +匿名阶段不受 `retry.max_attempts` 截断,但所有阶段共享请求总超时。网络错误、认证失败、限流和服务端错误可以触发 Key 轮换;其他 4xx 会结束当前 Tier,仍可继续尝试另一个可用 Tier。 + +每个 Tier 使用自己的原生协议编码请求。流开始后不再切换节点重新生成。识别到过期的 Responses reasoning 引用时,可执行一次修复重试;指定 Key 的诊断不会执行该重试。 + +只有匿名通道可用时,`/v1/models` 仅展示符合匿名条件的模型。 + +### 会话与代理 + +Key 初始化时均衡分配到代理。真实流量可以触发代理检查、Key 重新绑定和失败冷却。已经标记异常的代理,每 15 分钟通过 Cloudflare trace 复查一次。 + +服务使用稳定会话哈希选择首选 Key 或匿名代理。建议通过 `x-session-id` 区分独立会话,同时支持 `x-opencode-session`、`x-session-affinity`、`conversation-id`、`conversation_id` 与 `metadata.session_id`。 + +没有显式会话 ID 时,使用第一条用户消息生成会话标识,因此开场内容相同的会话可能共享亲和性。调整 Key 或代理池成员后,原有会话选择的节点可能变化。 + +失败冷却按指数增长,最高为 `performance.failure_cooldown_seconds` 的八倍;如果上游的 `Retry-After` 更长,则使用更长时间。所有认证 Key 都处于冷却时,路由仍可能尝试最早结束冷却的 Key;仍在冷却的匿名节点会被跳过。 + +## 配置参考 + +完整起始配置见 [config.example.json](config.example.json)。配置支持 `//` 和 `/* ... */` 注释,未知字段和无效取值会被拒绝。 + +### Key、监听地址与路由 + +| 字段 | 默认值或要求 | +| ------------------------ | ----------------------------------------- | +| `listen` | `127.0.0.1:8080`。 | +| `server_keys` | 至少一个本地 Key。 | +| `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 | +| `anonymous` | `false`。 | +| `prefer` | `go`;可选 `go`、`zen`。 | +| `upstream.zen` | `https://opencode.ai/zen`。 | +| `upstream.go` | `https://opencode.ai/zen/go`。 | +| `proxies` | 两个代理来源都为空时,使用 `["direct"]`。 | +| `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 | +| `models.refresh_seconds` | `300`;最小为 1。 | +| `models.protocols` | `{}`;按模型 ID 覆盖原生协议。 | + +代理支持 `direct`、`http://`、`https://`、`socks5://` 和 `socks5h://`,URL 可包含认证信息。配置内代理先加载,再追加 `proxyfile` 内容,并按首次出现的顺序去重。 + +代理文件每行一个地址,允许空行和注释: + +```text +# 首选代理 +http://user:password@127.0.0.1:7890 +socks5://127.0.0.1:1080 # 备用代理 +direct +``` + +支持 `#`、`;`、`//` 注释标记,标记需要位于行首或空白字符之后。 + +### 超时与连接池 + +| 字段 | 默认值 | 含义 | +| --------------------------------------- | ------ | ------------------------------------------------ | +| `retry.max_attempts` | `3` | 每个认证 Tier 的尝试次数,包含首次请求。 | +| `retry.timeout_seconds` | `300` | 推理请求总超时,包含流式响应读取。 | +| `performance.attempt_timeout_seconds` | `0` | 每次尝试等待响应头的超时;0 表示使用请求总超时。 | +| `performance.connect_timeout_seconds` | `5` | 建立连接的超时。 | +| `performance.failure_cooldown_seconds` | `15` | 失败冷却基数。 | +| `performance.max_idle_conns` | `2048` | 每个代理 Transport 的空闲连接上限。 | +| `performance.max_idle_conns_per_host` | `256` | 每个 Transport 对单个主机的空闲连接上限。 | +| `performance.max_conns_per_host` | `0` | 单个主机的连接上限;0 表示不限制。 | +| `performance.idle_conn_timeout_seconds` | `120` | 空闲连接保留时间。 | + +单次响应头超时不会超过请求总超时。希望慢节点仍能留出回退时间时,可以将它设为小于总超时的值。请求上下文过期后会停止后续尝试,不会惩罚尚未实际使用的 Key 或代理。 + +### 日志与管理端 + +| 字段 | 默认值或要求 | +| ----------------------------- | ----------------------------------------------- | +| `logging.level` | `info`;可选 `debug`、`info`、`warn`、`error`。 | +| `logging.ring_size` | `2000`;范围为 100–50,000。 | +| `logging.dump_request_bodies` | `false`;配合 `debug` 日志级别输出上游请求体。 | +| `webui.enabled` | 省略时为 `false`;示例配置设置为 `true`。 | +| `webui.listen` | `0.0.0.0:8081`。 | +| `webui.username` | 启用 WebUI 时必填;示例为 `admin`。 | +| `webui.password` | 首次初始化密码,最小长度为 10。 | +| `webui.password_hash` | 自动生成的 Argon2id 哈希,用于替代明文密码。 | +| `webui.session_ttl_minutes` | `720`;范围为 5–10,080。 | + +启动时会将初始密码哈希化,并从配置中删除明文;包含初始明文密码的备份也会删除。配置和备份仍包含运行所需的上游 Key、代理凭据,应限制文件访问权限。 + +请求体日志默认关闭,每份准备好的上游请求体最多输出 64 KiB。已配置的敏感值会脱敏,但对话内容本身仍可能包含敏感信息。 + +## WebUI 与诊断 + +管理监听端口提供 WebUI 和 `/api/*` 接口。认证使用单一管理员账号、服务端 Session、HttpOnly / SameSite Cookie、写操作 CSRF 校验及登录限速。 + +| 管理接口 | 用途 | +| ------------------------------------------------ | ----------------------------------------------- | +| `POST /api/auth/login` | 登录,获取 Session Cookie 和 CSRF Token。 | +| `GET /api/auth/session`、`POST /api/auth/logout` | 查看或结束当前 Session。 | +| `GET /api/config`、`PUT /api/config` | 读取脱敏配置或应用修改。 | +| `POST /api/config/reload` | 从磁盘重载配置。 | +| `POST /api/config/reveal` | 验证密码后查看配置中的敏感值。 | +| `PUT /api/account` | 验证密码后修改账号,修改后使已有 Session 失效。 | +| `GET /api/monitor` | 请求、Token、上游和资源统计。 | +| `GET /api/debug/models` | 模型路由、Key 指纹和 metadata 诊断。 | +| `POST /api/debug/inference` | 执行 Playground 请求。 | +| `GET /api/logs`、`GET /api/logs/stream` | 最近日志或 SSE 实时订阅。 | + +Playground 需要已登录的 Session 和 `X-CSRF-Token`,每个客户端 IP 每分钟最多 12 次: + +```json +{ + "protocol": "chat", + "key": { "mode": "auto" }, + "request": { + "model": "MODEL_ID", + "messages": [{ "role": "user", "content": "Hello" }] + } +} +``` + +服务端强制设置 `stream: false`。需要指定 Key 时,使用 `{"mode":"selected","tier":"zen","id":"KEY_FINGERPRINT"}`,其中指纹来自 `/api/debug/models`。指定 Key 的诊断最多执行一次上游尝试,不进入匿名通道,不轮换 Key,不切换 Tier,也不重放 reasoning 请求。 + +**自动模式和指定 Key 模式都不会改变生产 Key 的冷却、失败次数,以及代理的健康状态和绑定关系。** 诊断仍会真实访问上游,可能消耗供应商配额,并会计入监控。 + +执行后,管理接口返回 HTTP 200,实际结果位于 `ok`、`http_status`、`request_id`、`route` 和 `response`。指定 Key 时还返回 `selected_key` 与 `key_test`,其值包括 `usable`、`rejected`、`rate_limited`、`transport_error`、`upstream_error`、`request_error`、`unavailable`。管理请求格式、认证、CSRF 和限速错误仍返回各自对应的 HTTP 状态。 + +### 保存与重载 + +服务先验证候选配置并创建新的 Gateway,然后保存配置并切换实例。验证或保存失败时,当前 Gateway 继续处理请求;已经开始的请求继续使用原有实例。 + +Key、代理、上游地址、重试、模型、日志和路由偏好立即对新请求生效。`listen`、`webui.listen`、`webui.enabled` 的修改需要重启进程。保存后的 JSON 会规范化,不保留原有注释。 + +## 监控与持久化 + +请求结果以完整推理过程为准。即使 HTTP 200 已经发出,SSE 错误事件或异常断流仍会计为失败,并标记 `stream_error`;客户端取消标记为 `client_canceled`。WebUI 会将这些结果与 HTTP 状态一起显示。 + +上游**尝试记录**统计的是收到响应头为止的 HTTP 交互,其成功状态和耗时与完整 JSON 响应或流的最终完成情况分开计算。 + +Token 统计仅使用上游报告的 usage。输入 Token 包含缓存读取和写入,缓存 Token 单独统计缓存读取量。缺失 usage 时不估算 Token,覆盖率表示已经建立路由的推理请求中有多少报告了 usage。 + +| 数据 | 保存位置或保留规则 | +| ----------------------------------------------- | ------------------------------------------------------------------------- | +| Session、指标、Token 累计、最近 Playground 结果 | 进程内存;重启清空。 | +| 请求与尝试明细 | 最近一小时,最多 10,000 个请求和 20,000 次尝试;API 分别最多返回 500 条。 | +| 实时日志环形缓冲 | 进程内存,大小由 `logging.ring_size` 指定。 | +| 结构化日志 | stdout JSON;需要长期保留时由外部系统收集。 | +| 当前配置与上一版本 | `config.json`、`config.json.bak`。 | +| 模型目录缓存 | `config.json.models.catalog.json`。 | +| 成本与弃用信息缓存 | `config.json.models.dev.json`。 | + +缓存文件名基于实际配置路径生成。lifetime 仅表示当前进程运行期间的累计,各实例之间不共享 Session 或监控状态。 + +### 健康检查 + +`/healthz` 不增加监控计数,也不触发网络请求;返回资源数量,不包含 Key 或代理地址。 + +- HTTP 503:模型目录尚未就绪、当前配置下没有可路由模型,或没有健康代理。 +- HTTP 200:服务就绪。可用目录缓存过期时仍返回 200,同时模型状态为 `stale`,整体状态为 `degraded`。 + +过期阈值为 `models.refresh_seconds` 的两倍,且不低于 60 秒。就绪状态检查目录和资源,不会实际验证某个上游 Key 能否完成下一次推理。 + +## 开发 + +代码按职责组织: + +| 文件 | 职责 | +| ------------------------------------------------------ | --------------------------------------------------- | +| `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 . +``` + +竞态检测需要启用 CGO 并安装受支持的 C 编译器。推理测试使用本地服务器或模拟 Transport,不需要生产 Key。 + +Node.js 仅用于开发时的格式化和 JavaScript 语法检查: + +```bash +npm ci --ignore-scripts +npm run format +npm run format:check +npm run check:web +``` + +项目通过 `.editorconfig`、`.gitattributes`、Go 格式化和固定版本的 Prettier 统一格式。PR 检查覆盖 Linux / Windows 上的 Go 1.24 与稳定版 Go、Linux 竞态检测、格式、WebUI 语法和容器入口脚本语法。发布压缩包包含中英文两份 README。 + +## 常见问题 + +| 现象 | 排查方向 | +| ----------------------------- | -------------------------------------------------- | +| API 返回 401 | 使用配置中的本地 `server_keys`。 | +| 健康检查一直为 `starting` | 查看目录刷新日志和网络连通性,必要时补充协议覆盖。 | +| 模型列表为空 | 检查配置的 Tier、匿名资格和原生协议是否受支持。 | +| 请求返回 502 / 504 | 查看上游尝试、凭据、代理以及请求总超时和单次超时。 | +| HTTP 200 但生成失败 | 查看 SSE 错误事件和请求结果,不能只看 HTTP 状态。 | +| Docker 中宿主机配置修改不生效 | 当前配置在状态卷中;重新导入,或通过 WebUI 修改。 | +| 无法通过容器端口访问 | 检查监听地址、端口映射和状态卷中的实际配置。 | +| 重启后监控消失 | 监控仅保存在内存,需要外部收集 stdout 日志。 | + +## 致谢 + +感谢 [LINUX DO](https://linux.do) 社区的支持。 diff --git a/admin.go b/admin.go index a62b8dd..365588b 100644 --- a/admin.go +++ b/admin.go @@ -1,46 +1,23 @@ package main import ( - "bytes" - "context" - "crypto/rand" - "crypto/sha256" - "crypto/subtle" "embed" - "encoding/base64" - "encoding/hex" "encoding/json" "errors" "fmt" "io" "io/fs" "log/slog" - "net" "net/http" - "net/url" "strconv" "strings" "sync" "time" ) -const adminCookieName = "opencode2api_session" - //go:embed webui/* var webAssets embed.FS -type adminSession struct { - Username string - AuthVersion string - CSRF string - Expires time.Time -} - -type loginWindow struct { - Started time.Time - Count int -} - type AdminServer struct { manager *RuntimeManager monitor *Monitor @@ -101,7 +78,7 @@ func (a *AdminServer) staticHandler() http.Handler { func (a *AdminServer) 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' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:") + 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") w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Frame-Options", "DENY") @@ -111,129 +88,6 @@ func (a *AdminServer) securityHeaders(next http.Handler) http.Handler { }) } -func (a *AdminServer) 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") - return - } - var input struct { - Username string `json:"username"` - Password string `json:"password"` - } - if err := decodeAdminJSON(w, r, &input); err != nil { - writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) - return - } - 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) - if !usernameMatch || !passwordMatch { - a.recordLoginFailure(client) - a.logger.Warn("admin login failed", "component", "auth", "event", "login_failed", "client_ip", client) - writeAdminError(w, http.StatusUnauthorized, "invalid_credentials", "invalid username or password") - return - } - token, err := randomToken(32) - if err != nil { - writeAdminError(w, http.StatusInternalServerError, "internal_error", "could not create session") - return - } - csrf, err := randomToken(24) - if err != nil { - writeAdminError(w, http.StatusInternalServerError, "internal_error", "could not create session") - return - } - expires := time.Now().Add(time.Duration(cfg.WebUI.SessionTTLMinutes) * time.Minute) - a.mu.Lock() - delete(a.attempts, client) - a.cleanupSessionsLocked(time.Now()) - 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.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()}) -} - -func (a *AdminServer) 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()}) -} - -func (a *AdminServer) handleLogout(w http.ResponseWriter, r *http.Request) { - cookie, _ := r.Cookie(adminCookieName) - if cookie != nil { - a.mu.Lock() - delete(a.sessions, tokenDigest(cookie.Value)) - a.mu.Unlock() - } - http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1, Secure: requestIsSecure(r)}) - w.WriteHeader(http.StatusNoContent) -} - -type sessionContextKey struct{} - -func (a *AdminServer) 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 == "" { - writeAdminError(w, http.StatusUnauthorized, "authentication_required", "login required") - return - } - now := time.Now() - a.mu.Lock() - session, ok := a.sessions[tokenDigest(cookie.Value)] - if ok && now.After(session.Expires) { - delete(a.sessions, tokenDigest(cookie.Value)) - ok = false - } - a.mu.Unlock() - if !ok { - writeAdminError(w, http.StatusUnauthorized, "authentication_required", "session expired or invalid") - return - } - cfg := a.manager.Config() - if session.Username != cfg.WebUI.Username || session.AuthVersion != secretFingerprint(cfg.WebUI.PasswordHash) { - writeAdminError(w, http.StatusUnauthorized, "authentication_required", "session is no longer valid") - return - } - r = r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, session)) - next.ServeHTTP(w, r) - }) -} - -func sessionFromContext(r *http.Request) (adminSession, bool) { - session, ok := r.Context().Value(sessionContextKey{}).(adminSession) - return session, ok -} - -func (a *AdminServer) 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 { - writeAdminError(w, http.StatusForbidden, "csrf_failed", "invalid CSRF token") - return - } - if origin := r.Header.Get("Origin"); origin != "" { - parsed, err := url.Parse(origin) - expectedScheme := "http" - if requestIsSecure(r) { - expectedScheme = "https" - } - if err != nil || !strings.EqualFold(parsed.Host, r.Host) || !strings.EqualFold(parsed.Scheme, expectedScheme) { - writeAdminError(w, http.StatusForbidden, "origin_failed", "request origin does not match this server") - return - } - } - next.ServeHTTP(w, r) - }) -} - type SecretView struct { ID string `json:"id"` Display string `json:"display"` @@ -366,39 +220,6 @@ func (a *AdminServer) handleReveal(w http.ResponseWriter, r *http.Request) { 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) handleAccount(w http.ResponseWriter, r *http.Request) { - var input struct { - CurrentPassword string `json:"current_password"` - Username string `json:"username"` - NewPassword string `json:"new_password"` - } - if err := decodeAdminJSON(w, r, &input); err != nil { - writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) - return - } - cfg := a.manager.Config() - if !verifyPassword(cfg.WebUI.PasswordHash, input.CurrentPassword) { - writeAdminError(w, http.StatusForbidden, "verification_failed", "current password is incorrect") - return - } - if username := strings.TrimSpace(input.Username); username != "" { - cfg.WebUI.Username = username - } - if input.NewPassword != "" { - cfg.WebUI.Password = input.NewPassword - } - if _, err := a.manager.Apply(cfg, true); err != nil { - writeAdminError(w, http.StatusBadRequest, "account_update_failed", err.Error()) - return - } - a.mu.Lock() - a.sessions = make(map[string]adminSession) - 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}) -} - func (a *AdminServer) handleMonitor(w http.ResponseWriter, _ *http.Request) { metrics := a.monitor.Snapshot() writeJSON(w, http.StatusOK, map[string]any{ @@ -406,171 +227,6 @@ func (a *AdminServer) handleMonitor(w http.ResponseWriter, _ *http.Request) { }) } -type DebugInferenceRequest struct { - Protocol Protocol `json:"protocol"` - 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"` - Response any `json:"response"` -} - -func (a *AdminServer) handleDebugModels(w http.ResponseWriter, _ *http.Request) { - models, metadata := a.manager.DebugModels() - catalog := a.manager.Resources().Models - a.mu.Lock() - last := a.lastInference - a.mu.Unlock() - w.Header().Set("Cache-Control", "no-store") - writeJSON(w, http.StatusOK, map[string]any{"models": models, "metadata": metadata, "catalog": catalog, "last_inference": last}) -} - -func (a *AdminServer) 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 - } - var input DebugInferenceRequest - if err := decodeAdminJSON(w, r, &input); err != nil { - writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) - return - } - if !validProtocol(input.Protocol) { - writeAdminError(w, http.StatusBadRequest, "invalid_protocol", "protocol must be chat, responses, or anthropic") - return - } - if input.Request == nil { - writeAdminError(w, http.StatusBadRequest, "invalid_request", "request must be a JSON object") - return - } - payload := cloneMap(input.Request) - payload["stream"] = false - model := stringAt(payload, "model") - if model == "" { - writeAdminError(w, http.StatusBadRequest, "invalid_request", "request.model is required") - return - } - route := a.manager.DebugRoute(model, input.Protocol) - encoded, err := json.Marshal(payload) - if err != nil { - writeAdminError(w, http.StatusBadRequest, "invalid_request", "request contains unsupported JSON values") - return - } - path := protocolPath(input.Protocol) - request, err := http.NewRequestWithContext(r.Context(), http.MethodPost, "http://gateway.local"+path, bytes.NewReader(encoded)) - if err != nil { - writeAdminError(w, http.StatusInternalServerError, "debug_request_failed", "could not construct Gateway request") - return - } - cfg := a.manager.Config() - if len(cfg.ServerKeys) == 0 { - writeAdminError(w, http.StatusServiceUnavailable, "debug_unavailable", "no local server key is configured") - return - } - request.Header.Set("Authorization", "Bearer "+cfg.ServerKeys[0]) - request.Header.Set("Content-Type", "application/json") - request.Header.Set("Accept", "application/json") - recorder := newDebugResponseRecorder() - started := time.Now() - a.manager.Handler().ServeHTTP(recorder, request) - duration := time.Since(started) - requestID := recorder.Header().Get("x-request-id") - if requestID != "" { - snapshot := a.monitor.Snapshot().Upstream - for index := len(snapshot.Requests) - 1; index >= 0; index-- { - if snapshot.Requests[index].RequestID == requestID { - requestRoute := snapshot.Requests[index] - route.Anonymous = requestRoute.Anonymous - route.Tier = Tier(requestRoute.Tier) - route.KeyID = requestRoute.KeyID - route.Channel = requestRoute.Channel - route.Attempts = requestRoute.Attempts - break - } - } - if route.KeyID == "" { - for index := len(snapshot.Recent) - 1; index >= 0; index-- { - if snapshot.Recent[index].RequestID == requestID { - attempt := snapshot.Recent[index] - route.Anonymous = attempt.Anonymous - route.Tier = Tier(attempt.Tier) - route.KeyID = attempt.KeyID - route.Channel = attempt.Channel - break - } - } - } - } - var raw any - if json.Unmarshal(recorder.body.Bytes(), &raw) != nil { - raw = recorder.body.String() - } - raw = sanitizeDebugValue(raw, a.manager.redactor) - result := DebugInferenceResult{ - OK: recorder.status >= 200 && recorder.status < 300, HTTPStatus: recorder.status, - DurationMS: max(duration.Milliseconds(), 0), RequestID: requestID, Route: route, Response: raw, - } - a.mu.Lock() - a.lastInference = &result - a.mu.Unlock() - w.Header().Set("Cache-Control", "no-store") - writeJSON(w, http.StatusOK, result) -} - -type debugResponseRecorder struct { - header http.Header - body bytes.Buffer - status int -} - -func newDebugResponseRecorder() *debugResponseRecorder { - return &debugResponseRecorder{header: make(http.Header), status: http.StatusOK} -} - -func (recorder *debugResponseRecorder) Header() http.Header { return recorder.header } - -func (recorder *debugResponseRecorder) WriteHeader(status int) { - if recorder.status != http.StatusOK || status == http.StatusOK { - return - } - recorder.status = status -} - -func (recorder *debugResponseRecorder) Write(data []byte) (int, error) { - return recorder.body.Write(data) -} - -func sanitizeDebugValue(value any, redactor *SecretRedactor) any { - switch current := value.(type) { - case map[string]any: - result := make(map[string]any, len(current)) - for key, item := range current { - lower := strings.ToLower(key) - if sensitiveDebugKey(lower) { - result[key] = "***" - continue - } - result[key] = sanitizeDebugValue(item, redactor) - } - return result - case []any: - result := make([]any, len(current)) - for index, item := range current { - result[index] = sanitizeDebugValue(item, redactor) - } - return result - case string: - return redactor.String(current) - default: - return value - } -} - func (a *AdminServer) 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")) @@ -701,123 +357,6 @@ func resolveSecrets(inputs []SecretInput, existing []string) ([]string, error) { return result, nil } -func (a *AdminServer) allowLogin(client string) bool { - a.mu.Lock() - defer a.mu.Unlock() - now := time.Now() - if len(a.attempts) > 1024 { - for address, candidate := range a.attempts { - if now.Sub(candidate.Started) > 5*time.Minute { - delete(a.attempts, address) - } - } - } - if _, exists := a.attempts[client]; !exists && len(a.attempts) >= 4096 { - return false - } - window := a.attempts[client] - if window.Started.IsZero() || now.Sub(window.Started) > 5*time.Minute { - return true - } - return window.Count < 5 -} - -func (a *AdminServer) recordLoginFailure(client string) { - a.mu.Lock() - defer a.mu.Unlock() - now := time.Now() - window := a.attempts[client] - if window.Started.IsZero() || now.Sub(window.Started) > 5*time.Minute { - window = loginWindow{Started: now} - } - window.Count++ - a.attempts[client] = window -} - -func (a *AdminServer) allowDebug(client string) bool { - a.mu.Lock() - defer a.mu.Unlock() - now := time.Now() - window := a.debugAttempts[client] - if window.Started.IsZero() || now.Sub(window.Started) >= time.Minute { - window = loginWindow{Started: now} - } - if window.Count >= 12 { - return false - } - window.Count++ - a.debugAttempts[client] = window - if len(a.debugAttempts) > 4096 { - for key, candidate := range a.debugAttempts { - if now.Sub(candidate.Started) >= time.Minute { - delete(a.debugAttempts, key) - } - } - } - return true -} - -func (a *AdminServer) cleanupSessionsLocked(now time.Time) { - for token, session := range a.sessions { - if now.After(session.Expires) { - delete(a.sessions, token) - } - } -} - -func (a *AdminServer) removeEarliestSessionLocked() { - var earliestToken string - var earliest time.Time - for token, session := range a.sessions { - if earliestToken == "" || session.Expires.Before(earliest) { - earliestToken, earliest = token, session.Expires - } - } - if earliestToken != "" { - delete(a.sessions, earliestToken) - } -} - -func randomToken(length int) (string, error) { - data := make([]byte, length) - if _, err := rand.Read(data); err != nil { - return "", err - } - return base64.RawURLEncoding.EncodeToString(data), nil -} - -func tokenDigest(token string) string { - sum := sha256.Sum256([]byte(token)) - return hex.EncodeToString(sum[:]) -} - -func clientIP(r *http.Request) string { - host, _, err := net.SplitHostPort(r.RemoteAddr) - if err == nil { - return host - } - return r.RemoteAddr -} - -func requestIsSecure(r *http.Request) bool { - if r == nil { - return false - } - return r.TLS != nil || strings.EqualFold(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")), "https") -} - -func sensitiveDebugKey(key string) bool { - for _, hint := range []string{ - "authorization", "cookie", "password", "secret", "api_key", "api-key", "x-api-key", - "access_token", "refresh_token", "set-cookie", "credential", - } { - if strings.Contains(key, hint) { - return true - } - } - return false -} - func decodeAdminJSON(w http.ResponseWriter, r *http.Request, target any) error { decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2<<20)) decoder.DisallowUnknownFields() diff --git a/admin_auth.go b/admin_auth.go new file mode 100644 index 0000000..560775c --- /dev/null +++ b/admin_auth.go @@ -0,0 +1,267 @@ +package main + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "net" + "net/http" + "net/url" + "strings" + "time" +) + +const adminCookieName = "opencode2api_session" + +type adminSession struct { + Username string + AuthVersion string + CSRF string + Expires time.Time +} + +type loginWindow struct { + Started time.Time + Count int +} + +func (a *AdminServer) 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") + return + } + var input struct { + Username string `json:"username"` + Password string `json:"password"` + } + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + 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) + if !usernameMatch || !passwordMatch { + a.recordLoginFailure(client) + a.logger.Warn("admin login failed", "component", "auth", "event", "login_failed", "client_ip", client) + writeAdminError(w, http.StatusUnauthorized, "invalid_credentials", "invalid username or password") + return + } + token, err := randomToken(32) + if err != nil { + writeAdminError(w, http.StatusInternalServerError, "internal_error", "could not create session") + return + } + csrf, err := randomToken(24) + if err != nil { + writeAdminError(w, http.StatusInternalServerError, "internal_error", "could not create session") + return + } + expires := time.Now().Add(time.Duration(cfg.WebUI.SessionTTLMinutes) * time.Minute) + a.mu.Lock() + delete(a.attempts, client) + a.cleanupSessionsLocked(time.Now()) + 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.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()}) +} + +func (a *AdminServer) 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()}) +} + +func (a *AdminServer) handleLogout(w http.ResponseWriter, r *http.Request) { + cookie, _ := r.Cookie(adminCookieName) + if cookie != nil { + a.mu.Lock() + delete(a.sessions, tokenDigest(cookie.Value)) + a.mu.Unlock() + } + http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1, Secure: requestIsSecure(r)}) + w.WriteHeader(http.StatusNoContent) +} + +type sessionContextKey struct{} + +func (a *AdminServer) 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 == "" { + writeAdminError(w, http.StatusUnauthorized, "authentication_required", "login required") + return + } + now := time.Now() + a.mu.Lock() + session, ok := a.sessions[tokenDigest(cookie.Value)] + if ok && now.After(session.Expires) { + delete(a.sessions, tokenDigest(cookie.Value)) + ok = false + } + a.mu.Unlock() + if !ok { + writeAdminError(w, http.StatusUnauthorized, "authentication_required", "session expired or invalid") + return + } + cfg := a.manager.Config() + if session.Username != cfg.WebUI.Username || session.AuthVersion != secretFingerprint(cfg.WebUI.PasswordHash) { + writeAdminError(w, http.StatusUnauthorized, "authentication_required", "session is no longer valid") + return + } + r = r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, session)) + next.ServeHTTP(w, r) + }) +} + +func sessionFromContext(r *http.Request) (adminSession, bool) { + session, ok := r.Context().Value(sessionContextKey{}).(adminSession) + return session, ok +} + +func (a *AdminServer) 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 { + writeAdminError(w, http.StatusForbidden, "csrf_failed", "invalid CSRF token") + return + } + if origin := r.Header.Get("Origin"); origin != "" { + parsed, err := url.Parse(origin) + expectedScheme := "http" + if requestIsSecure(r) { + expectedScheme = "https" + } + if err != nil || !strings.EqualFold(parsed.Host, r.Host) || !strings.EqualFold(parsed.Scheme, expectedScheme) { + writeAdminError(w, http.StatusForbidden, "origin_failed", "request origin does not match this server") + return + } + } + next.ServeHTTP(w, r) + }) +} + +func (a *AdminServer) handleAccount(w http.ResponseWriter, r *http.Request) { + var input struct { + CurrentPassword string `json:"current_password"` + Username string `json:"username"` + NewPassword string `json:"new_password"` + } + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + cfg := a.manager.Config() + if !verifyPassword(cfg.WebUI.PasswordHash, input.CurrentPassword) { + writeAdminError(w, http.StatusForbidden, "verification_failed", "current password is incorrect") + return + } + if username := strings.TrimSpace(input.Username); username != "" { + cfg.WebUI.Username = username + } + if input.NewPassword != "" { + cfg.WebUI.Password = input.NewPassword + } + if _, err := a.manager.Apply(cfg, true); err != nil { + writeAdminError(w, http.StatusBadRequest, "account_update_failed", err.Error()) + return + } + a.mu.Lock() + a.sessions = make(map[string]adminSession) + 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}) +} + +func (a *AdminServer) allowLogin(client string) bool { + a.mu.Lock() + defer a.mu.Unlock() + now := time.Now() + if len(a.attempts) > 1024 { + for address, candidate := range a.attempts { + if now.Sub(candidate.Started) > 5*time.Minute { + delete(a.attempts, address) + } + } + } + if _, exists := a.attempts[client]; !exists && len(a.attempts) >= 4096 { + return false + } + window := a.attempts[client] + if window.Started.IsZero() || now.Sub(window.Started) > 5*time.Minute { + return true + } + return window.Count < 5 +} + +func (a *AdminServer) recordLoginFailure(client string) { + a.mu.Lock() + defer a.mu.Unlock() + now := time.Now() + window := a.attempts[client] + if window.Started.IsZero() || now.Sub(window.Started) > 5*time.Minute { + window = loginWindow{Started: now} + } + window.Count++ + a.attempts[client] = window +} + +func (a *AdminServer) cleanupSessionsLocked(now time.Time) { + for token, session := range a.sessions { + if now.After(session.Expires) { + delete(a.sessions, token) + } + } +} + +func (a *AdminServer) removeEarliestSessionLocked() { + var earliestToken string + var earliest time.Time + for token, session := range a.sessions { + if earliestToken == "" || session.Expires.Before(earliest) { + earliestToken, earliest = token, session.Expires + } + } + if earliestToken != "" { + delete(a.sessions, earliestToken) + } +} + +func randomToken(length int) (string, error) { + data := make([]byte, length) + if _, err := rand.Read(data); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(data), nil +} + +func tokenDigest(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +func clientIP(r *http.Request) string { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err == nil { + return host + } + return r.RemoteAddr +} + +func requestIsSecure(r *http.Request) bool { + if r == nil { + return false + } + return r.TLS != nil || strings.EqualFold(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")), "https") +} diff --git a/admin_debug.go b/admin_debug.go new file mode 100644 index 0000000..2e7eb69 --- /dev/null +++ b/admin_debug.go @@ -0,0 +1,263 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "strings" + "time" +) + +// 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"` +} + +type DebugInferenceRequest struct { + 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"` +} + +func (a *AdminServer) handleDebugModels(w http.ResponseWriter, _ *http.Request) { + models, metadata := a.manager.DebugModels() + catalog := a.manager.Resources().Models + keys := a.manager.DebugKeys() + a.mu.Lock() + 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}) +} + +func (a *AdminServer) 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 + } + var input DebugInferenceRequest + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + if !validProtocol(input.Protocol) { + writeAdminError(w, http.StatusBadRequest, "invalid_protocol", "protocol must be chat, responses, or anthropic") + return + } + if input.Request == nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", "request must be a JSON object") + return + } + payload := cloneMap(input.Request) + payload["stream"] = false + model := stringAt(payload, "model") + if model == "" { + writeAdminError(w, http.StatusBadRequest, "invalid_request", "request.model is required") + return + } + if input.Key.Mode == "" { + input.Key.Mode = "auto" + } + if input.Key.Mode != "auto" && input.Key.Mode != "selected" { + writeAdminError(w, http.StatusBadRequest, "invalid_key_mode", "key.mode must be auto or selected") + return + } + var selectedKey *DebugKeyView + if input.Key.Mode == "selected" { + selectedKey = a.manager.DebugKey(input.Key.Tier, input.Key.ID) + if selectedKey == nil { + writeAdminError(w, http.StatusBadRequest, "unknown_key_id", "selected key is not configured") + return + } + } + route := a.manager.DebugRoute(model, input.Protocol) + if selectedKey != nil { + selected, routeErr := a.manager.DebugRouteForTier(model, selectedKey.Tier) + if routeErr != nil { + writeAdminError(w, http.StatusBadRequest, "model_unavailable_for_key_tier", routeErr.Error()) + return + } + route = selected + } + encoded, err := json.Marshal(payload) + if err != nil { + 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) + 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") + return + } + cfg := a.manager.Config() + if len(cfg.ServerKeys) == 0 { + writeAdminError(w, http.StatusServiceUnavailable, "debug_unavailable", "no local server key is configured") + return + } + 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.Header.Set("Content-Type", "application/json") + request.Header.Set("Accept", "application/json") + recorder := newDebugResponseRecorder() + started := time.Now() + a.manager.Handler().ServeHTTP(recorder, request) + duration := time.Since(started) + requestID := recorder.Header().Get("x-request-id") + if trace.Channel != "" { + route.Anonymous = trace.Anonymous + route.Tier = Tier(trace.Tier) + route.KeyID = trace.KeyID + route.Channel = trace.Channel + route.Attempts = trace.Attempts + route.NativeProtocol = trace.Protocol + } + var raw any + if json.Unmarshal(recorder.body.Bytes(), &raw) != nil { + raw = recorder.body.String() + } + raw = sanitizeDebugValue(raw, a.manager.redactor) + keyTest := "" + if selectedKey != nil { + if current := a.manager.DebugKey(selectedKey.Tier, selectedKey.ID); current != nil { + selectedKey = current + } + keyTest = classifyKeyTest(recorder.status, trace.AttemptOutcome) + } + result := DebugInferenceResult{ + OK: recorder.status >= 200 && recorder.status < 300, HTTPStatus: recorder.status, + DurationMS: max(duration.Milliseconds(), 0), RequestID: requestID, Route: route, + SelectedKey: selectedKey, KeyTest: keyTest, Response: raw, + } + a.mu.Lock() + a.lastInference = &result + a.mu.Unlock() + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, http.StatusOK, result) +} + +type debugResponseRecorder struct { + header http.Header + body bytes.Buffer + status int +} + +func newDebugResponseRecorder() *debugResponseRecorder { + return &debugResponseRecorder{header: make(http.Header), status: http.StatusOK} +} + +func (recorder *debugResponseRecorder) Header() http.Header { return recorder.header } + +func (recorder *debugResponseRecorder) WriteHeader(status int) { + if recorder.status != http.StatusOK || status == http.StatusOK { + return + } + recorder.status = status +} + +func (recorder *debugResponseRecorder) Write(data []byte) (int, error) { + return recorder.body.Write(data) +} + +func sanitizeDebugValue(value any, redactor *SecretRedactor) any { + switch current := value.(type) { + case map[string]any: + result := make(map[string]any, len(current)) + for key, item := range current { + lower := strings.ToLower(key) + if sensitiveDebugKey(lower) { + result[key] = "***" + continue + } + result[key] = sanitizeDebugValue(item, redactor) + } + return result + case []any: + result := make([]any, len(current)) + for index, item := range current { + result[index] = sanitizeDebugValue(item, redactor) + } + return result + case string: + return redactor.String(current) + default: + return value + } +} + +func (a *AdminServer) allowDebug(client string) bool { + a.mu.Lock() + defer a.mu.Unlock() + now := time.Now() + window := a.debugAttempts[client] + if window.Started.IsZero() || now.Sub(window.Started) >= time.Minute { + window = loginWindow{Started: now} + } + if window.Count >= 12 { + return false + } + window.Count++ + a.debugAttempts[client] = window + if len(a.debugAttempts) > 4096 { + for key, candidate := range a.debugAttempts { + if now.Sub(candidate.Started) >= time.Minute { + delete(a.debugAttempts, key) + } + } + } + return true +} + +// classifyKeyTest turns a per-key diagnostic into a verdict about that key. +// Only statuses that are unambiguous about the credential are reported as key +// problems: a 4xx request-shape error says nothing about the key, and a 5xx may +// be entirely unrelated to it. +func classifyKeyTest(status int, attemptOutcome string) string { + switch { + case attemptOutcome == "transport_error": + return "transport_error" + case status >= 200 && status < 300: + return "usable" + case status == http.StatusUnauthorized || status == http.StatusForbidden: + return "rejected" + case status == http.StatusTooManyRequests: + return "rate_limited" + case status == 0: + return "unavailable" + case status >= 500: + return "upstream_error" + default: + return "request_error" + } +} + +func sensitiveDebugKey(key string) bool { + for _, hint := range []string{ + "authorization", "cookie", "password", "secret", "api_key", "api-key", "x-api-key", + "access_token", "refresh_token", "set-cookie", "credential", + } { + if strings.Contains(key, hint) { + return true + } + } + return false +} diff --git a/admin_debug_test.go b/admin_debug_test.go new file mode 100644 index 0000000..f6faea6 --- /dev/null +++ b/admin_debug_test.go @@ -0,0 +1,260 @@ +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 new file mode 100644 index 0000000..dac62e5 --- /dev/null +++ b/admin_test.go @@ -0,0 +1,45 @@ +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/compose.yaml b/compose.yaml index b0d0091..815cbb6 100644 --- a/compose.yaml +++ b/compose.yaml @@ -9,8 +9,10 @@ services: environment: CONFIG_PATH: /var/lib/opencode2api/config.json CONFIG_SEED_PATH: /run/config/opencode2api.json - LISTEN_ADDRESS: 0.0.0.0:8080 - WEBUI_LISTEN_ADDRESS: 0.0.0.0:8081 + # Empty defers to the listen addresses in config.json. Export + # OPENCODE2API_LISTEN / OPENCODE2API_WEBUI_LISTEN to override them. + LISTEN_ADDRESS: ${OPENCODE2API_LISTEN:-} + WEBUI_LISTEN_ADDRESS: ${OPENCODE2API_WEBUI_LISTEN:-} ports: - "${OPENCODE2API_PORT:-8080}:8080" - "${OPENCODE2API_WEBUI_PORT:-8081}:8081" diff --git a/config.example.json b/config.example.json index 5ef3f51..19d40d7 100644 --- a/config.example.json +++ b/config.example.json @@ -25,11 +25,13 @@ "max_conns_per_host": 0, "idle_conn_timeout_seconds": 120, "connect_timeout_seconds": 5, - "failure_cooldown_seconds": 15 + "failure_cooldown_seconds": 15, + "attempt_timeout_seconds": 0 }, "logging": { "level": "info", - "ring_size": 2000 + "ring_size": 2000, + "dump_request_bodies": false }, "webui": { "enabled": true, diff --git a/config.go b/config.go index 6cca957..64fe648 100644 --- a/config.go +++ b/config.go @@ -12,6 +12,7 @@ import ( "path/filepath" "runtime" "strings" + "time" ) type Config struct { @@ -51,6 +52,10 @@ type ModelsConfig struct { type LoggingConfig struct { Level string `json:"level"` RingSize int `json:"ring_size"` + // DumpRequestBodies logs the exact bytes sent upstream (redacted, capped) + // so retry and translation problems can be diagnosed without patching the + // binary. Off by default: the bodies contain conversation content. + DumpRequestBodies bool `json:"dump_request_bodies"` } type WebUIConfig struct { @@ -69,6 +74,29 @@ type PerformanceConfig struct { IdleConnTimeoutSeconds int `json:"idle_conn_timeout_seconds"` ConnectTimeoutSeconds int `json:"connect_timeout_seconds"` FailureCooldownSeconds int `json:"failure_cooldown_seconds"` + AttemptTimeoutSeconds int `json:"attempt_timeout_seconds"` +} + +// AttemptTimeout bounds how long a single upstream attempt may wait for +// response headers before it is abandoned and the next node is tried. Values +// <= 0 keep the historical behavior of using the request-level retry timeout, +// so existing configs are unaffected. The result never exceeds requestTimeout, +// and only the header wait is bounded: an established stream keeps flowing +// under the request-level timeout. +// +// The bound is installed on the shared transports, so it covers every attempt +// in both the anonymous and the authenticated loops. Without it, one hung exit +// can consume the entire request budget by itself, and the attempts that follow +// are fired against an already-expired context. +func (cfg PerformanceConfig) AttemptTimeout(requestTimeout time.Duration) time.Duration { + if cfg.AttemptTimeoutSeconds > 0 { + attempt := time.Duration(cfg.AttemptTimeoutSeconds) * time.Second + if requestTimeout > 0 && attempt > requestTimeout { + return requestTimeout + } + return attempt + } + return requestTimeout } func LoadConfig(path string) (Config, error) { @@ -143,6 +171,9 @@ func NormalizeConfig(path string, cfg Config) (Config, error) { if cfg.Performance.MaxIdleConns < 1 || cfg.Performance.MaxIdleConnsPerHost < 1 || cfg.Performance.MaxConnsPerHost < 0 || cfg.Performance.IdleConnTimeoutSeconds < 1 || cfg.Performance.ConnectTimeoutSeconds < 1 || cfg.Performance.FailureCooldownSeconds < 1 { return Config{}, errors.New("performance values must be positive (max_conns_per_host may be zero for unlimited)") } + if cfg.Performance.AttemptTimeoutSeconds < 0 { + return Config{}, errors.New("performance.attempt_timeout_seconds must not be negative (0 keeps the retry timeout)") + } if cfg.Logging.Level != "debug" && cfg.Logging.Level != "info" && cfg.Logging.Level != "warn" && cfg.Logging.Level != "error" { return Config{}, errors.New("logging.level must be debug, info, warn, or error") } diff --git a/config_test.go b/config_test.go new file mode 100644 index 0000000..2706ef7 --- /dev/null +++ b/config_test.go @@ -0,0 +1,56 @@ +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.go b/convert.go index a6a84d5..86e7e3b 100644 --- a/convert.go +++ b/convert.go @@ -2,11 +2,7 @@ package main import ( "encoding/json" - "errors" - "fmt" - "sort" "strings" - "time" ) const ( @@ -66,6 +62,16 @@ type bridgeRequest struct { Stop any Reasoning any Metadata any + // Sampling and response-shape knobs are carried across the bridge as + // opaque values. Each protocol accepts a different shape, so a value that + // cannot be expressed natively is omitted rather than rejected: dropping a + // knob silently was the old behavior and it made clients believe (for + // example) that JSON mode had been honored. + ResponseFormat any + ParallelToolCalls any + FrequencyPenalty any + PresencePenalty any + Seed any } type bridgeUsage struct { @@ -103,1487 +109,6 @@ func convertRequest(from, to Protocol, input map[string]any) (map[string]any, er return encodeBridgeRequest(to, request) } -// prepareUpstreamRequest 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) - if err != nil { - return nil, err - } - normalizeToolReasoningHistory(to, stringAt(output, "model"), upstreamURL, output) - return output, nil -} - -// normalizeToolReasoningHistory applies only to endpoints that are known to -// require reasoning replay, or to requests that explicitly enable reasoning. -// Normalizing the target shape makes the behavior independent of the client -// protocol used to reach the gateway. -func normalizeToolReasoningHistory(protocol Protocol, model, upstreamURL string, input map[string]any) bool { - if !shouldNormalizeToolReasoningHistory(model, upstreamURL, input) { - return false - } - switch protocol { - case ProtocolChat: - return normalizeChatToolReasoningHistory(input) - case ProtocolAnthropic: - return normalizeAnthropicToolThinkingHistory(input) - default: - return false - } -} - -// shouldNormalizeToolReasoningHistory identifies providers whose compatible -// endpoints require thinking/reasoning to be replayed with assistant tool -// calls. Explicit reasoning settings also cover aliased model names. -func shouldNormalizeToolReasoningHistory(model, upstreamURL string, input map[string]any) bool { - return isReasoningVendorIdentifier(model) || isReasoningVendorIdentifier(upstreamURL) || requestEnablesReasoning(input) -} - -func isReasoningVendorIdentifier(value string) bool { - value = strings.ToLower(value) - for _, hint := range reasoningVendorHints { - if strings.Contains(value, hint) { - return true - } - } - return false -} - -func requestEnablesReasoning(input map[string]any) bool { - for _, key := range []string{"reasoning_effort", "reasoning", "thinking", "effort"} { - value, exists := input[key] - if !exists || value == nil { - continue - } - switch typed := value.(type) { - case string: - mode := strings.ToLower(strings.TrimSpace(typed)) - if mode != "" && mode != "none" && mode != "disabled" { - return true - } - case bool: - if typed { - return true - } - case map[string]any: - mode := strings.ToLower(strings.TrimSpace(firstString(stringAt(typed, "type"), stringAt(typed, "effort")))) - if mode == "none" || mode == "disabled" { - continue - } - return true - default: - return true - } - } - return false -} - -// normalizeChatToolReasoningHistory ensures every assistant tool-call turn -// carries reasoning_content. Some clients discard this non-standard field -// while retaining tool_calls, which otherwise makes the next thinking-mode -// request invalid. A legacy reasoning string is promoted when available. -func normalizeChatToolReasoningHistory(input map[string]any) bool { - messages, ok := input["messages"].([]any) - if !ok { - return false - } - - changed := false - for _, rawMessage := range messages { - message, ok := rawMessage.(map[string]any) - if !ok || stringAt(message, "role") != "assistant" || len(sliceAt(message, "tool_calls")) == 0 { - continue - } - if reasoning, ok := message["reasoning_content"].(string); ok && strings.TrimSpace(reasoning) != "" { - continue - } - reasoning, _ := message["reasoning"].(string) - if strings.TrimSpace(reasoning) == "" { - reasoning = toolReasoningPlaceholder - } - message["reasoning_content"] = reasoning - changed = true - } - return changed -} - -// normalizeAnthropicToolThinkingHistory repairs only assistant turns that -// contain tool_use. DeepSeek, Kimi/Moonshot and MiMo reject signed, redacted, -// empty or missing thinking history on those turns even though Anthropic -// clients can legitimately send each of those shapes. -func normalizeAnthropicToolThinkingHistory(input map[string]any) bool { - messages, ok := input["messages"].([]any) - if !ok { - return false - } - - changed := false - for _, rawMessage := range messages { - message, ok := rawMessage.(map[string]any) - if !ok || stringAt(message, "role") != "assistant" { - continue - } - content, ok := message["content"].([]any) - if !ok || !anthropicContentHasType(content, "tool_use") { - continue - } - - hasThinking := false - for i, rawBlock := range content { - block, ok := rawBlock.(map[string]any) - if !ok { - continue - } - switch stringAt(block, "type") { - case "thinking": - hasThinking = true - if _, exists := block["signature"]; exists { - delete(block, "signature") - changed = true - } - thinking, ok := block["thinking"].(string) - if !ok || strings.TrimSpace(thinking) == "" { - block["thinking"] = toolReasoningPlaceholder - changed = true - } - case "redacted_thinking": - hasThinking = true - content[i] = map[string]any{ - "type": "thinking", - "thinking": anthropicRedactedThinkingPlaceholder, - } - changed = true - } - } - if !hasThinking { - content = append([]any{map[string]any{ - "type": "thinking", - "thinking": toolReasoningPlaceholder, - }}, content...) - message["content"] = content - changed = true - } - } - return changed -} - -func anthropicContentHasType(content []any, kind string) bool { - for _, rawBlock := range content { - block, _ := rawBlock.(map[string]any) - if stringAt(block, "type") == kind { - return true - } - } - return false -} - -func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest, error) { - request := bridgeRequest{ - Model: stringAt(input, "model"), - Stream: boolAt(input, "stream"), - Temperature: input["temperature"], - TopP: input["top_p"], - Metadata: input["metadata"], - } - switch protocol { - case ProtocolChat: - request.MaxTokens = firstAny(input["max_completion_tokens"], input["max_tokens"]) - request.Stop = input["stop"] - request.Reasoning = firstAny(input["reasoning_effort"], input["reasoning"]) - for i, raw := range 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") - blocks, err := decodeOpenAIBlocksChecked(message["content"]) - if err != nil { - return request, fmt.Errorf("messages[%d]: %w", i, err) - } - if role == "assistant" { - blocks = append(decodeChatReasoning(message), blocks...) - } - for j, rawCall := range 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") - blocks = append(blocks, bridgeBlock{ - Kind: "tool_call", - ID: stringAt(call, "id"), - Name: stringAt(function, "name"), - ArgumentsJSON: stringAt(function, "arguments"), - }) - } - switch role { - case "system": - request.System = append(request.System, blocks...) - case "developer": - request.Developer = append(request.Developer, blocks...) - case "tool": - request.Messages = append(request.Messages, bridgeMessage{Role: "user", Blocks: []bridgeBlock{{ - Kind: "tool_result", - CallID: stringAt(message, "tool_call_id"), - Result: message["content"], - }}}) - case "user", "assistant": - request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks}) - default: - return request, fmt.Errorf("messages[%d] has unsupported role %q", i, role) - } - } - for i, raw := range sliceAt(input, "tools") { - tool, ok := raw.(map[string]any) - if !ok || stringAt(tool, "type") != "function" { - return request, fmt.Errorf("tools[%d] must be a function tool", i) - } - function := mapAt(tool, "function") - request.Tools = append(request.Tools, bridgeTool{ - Name: stringAt(function, "name"), - Description: stringAt(function, "description"), - Schema: function["parameters"], - Strict: boolAt(function, "strict"), - }) - } - request.ToolChoice = decodeChatToolChoice(input["tool_choice"]) - - case ProtocolResponses: - request.MaxTokens = input["max_output_tokens"] - request.Stop = input["stop"] - request.Reasoning = firstAny(input["reasoning"], input["reasoning_effort"]) - instructions, err := decodeOpenAIBlocksChecked(input["instructions"]) - if err != nil { - return request, fmt.Errorf("instructions: %w", err) - } - request.System = append(request.System, instructions...) - switch value := input["input"].(type) { - case string: - request.Messages = append(request.Messages, bridgeMessage{Role: "user", Blocks: []bridgeBlock{{Kind: "text", Text: value}}}) - case []any: - for i, raw := range value { - item, ok := raw.(map[string]any) - if !ok { - return request, fmt.Errorf("input[%d] must be an object", i) - } - switch stringAt(item, "type") { - case "reasoning": - for _, block := range decodeResponsesReasoning(item) { - appendBridgeBlock(&request.Messages, "assistant", block) - } - 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"), - }) - case "function_call_output": - appendBridgeBlock(&request.Messages, "user", bridgeBlock{ - Kind: "tool_result", - CallID: stringAt(item, "call_id"), - Result: item["output"], - }) - case "message", "": - role := stringAt(item, "role") - blocks, err := decodeOpenAIBlocksChecked(item["content"]) - if err != nil { - return request, fmt.Errorf("input[%d]: %w", i, err) - } - if role == "system" { - request.System = append(request.System, blocks...) - } else if role == "developer" { - request.Developer = append(request.Developer, blocks...) - } else if role == "user" || role == "assistant" { - 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")) - } - } - default: - return request, fmt.Errorf("input must be a string or array") - } - for i, raw := range sliceAt(input, "tools") { - tool, ok := raw.(map[string]any) - if !ok || 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"), - Schema: tool["parameters"], - Strict: boolAt(tool, "strict"), - }) - } - request.ToolChoice = decodeResponsesToolChoice(input["tool_choice"]) - - case ProtocolAnthropic: - request.MaxTokens = input["max_tokens"] - request.Stop = input["stop_sequences"] - request.Reasoning = firstAny(input["thinking"], 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") { - message, ok := raw.(map[string]any) - if !ok { - return request, fmt.Errorf("messages[%d] must be an object", i) - } - role := 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. - if role == "system" { - blocks, err := decodeAnthropicBlocksChecked(message["content"]) - if err != nil { - return request, fmt.Errorf("messages[%d]: %w", i, err) - } - request.System = append(request.System, blocks...) - continue - } - if role == "developer" { - blocks, err := decodeAnthropicBlocksChecked(message["content"]) - if err != nil { - return request, fmt.Errorf("messages[%d]: %w", i, err) - } - request.Developer = append(request.Developer, blocks...) - continue - } - if role != "user" && role != "assistant" { - return request, fmt.Errorf("messages[%d] has unsupported role %q", i, role) - } - blocks, err := decodeAnthropicBlocksChecked(message["content"]) - if err != nil { - return request, fmt.Errorf("messages[%d]: %w", i, err) - } - request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks}) - } - for i, raw := range 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"), - Schema: tool["input_schema"], - }) - } - request.ToolChoice = decodeAnthropicToolChoice(input["tool_choice"]) - - default: - return request, fmt.Errorf("unsupported input protocol %q", protocol) - } - return request, nil -} - -func appendBridgeBlock(messages *[]bridgeMessage, role string, block bridgeBlock) { - if len(*messages) > 0 { - last := &(*messages)[len(*messages)-1] - if last.Role == role && bridgeBlocksOnlyTools(last.Blocks) { - last.Blocks = append(last.Blocks, block) - return - } - } - *messages = append(*messages, bridgeMessage{Role: role, Blocks: []bridgeBlock{block}}) -} - -func bridgeBlocksOnlyTools(blocks []bridgeBlock) bool { - if len(blocks) == 0 { - return false - } - for _, block := range blocks { - if block.Kind != "tool_call" && block.Kind != "tool_result" { - return false - } - } - return true -} - -func encodeBridgeRequest(protocol Protocol, request bridgeRequest) (map[string]any, error) { - if err := validateBridgeRequest(protocol, request); err != nil { - return nil, err - } - switch protocol { - case ProtocolChat: - return encodeChatRequest(request) - case ProtocolResponses: - return encodeResponsesRequest(request), nil - case ProtocolAnthropic: - return encodeAnthropicRequest(request), nil - default: - return nil, fmt.Errorf("unsupported output protocol %q", protocol) - } -} - -func validateBridgeRequest(protocol Protocol, request bridgeRequest) error { - if protocol == ProtocolResponses { - 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") - } - } - } - blocks := make([]bridgeBlock, 0, len(request.System)+len(request.Developer)) - blocks = append(blocks, request.System...) - blocks = append(blocks, request.Developer...) - for _, message := range request.Messages { - blocks = append(blocks, message.Blocks...) - } - for _, block := range blocks { - if block.Kind == "file" && protocol == ProtocolAnthropic && 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) - } - } - return nil -} - -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) - if effort := reasoningEffort(request.Reasoning); effort != nil { - output["reasoning_effort"] = effort - } - if request.Stream { - output["stream_options"] = map[string]any{"include_usage": true} - } - - messages := make([]any, 0, len(request.Messages)+1) - if len(request.System) > 0 { - messages = append(messages, map[string]any{"role": "system", "content": encodeChatBlocks(request.System)}) - } - if len(request.Developer) > 0 { - messages = append(messages, map[string]any{"role": "developer", "content": encodeChatBlocks(request.Developer)}) - } - pending := make(map[string]bool) - pendingResults := make(map[string]bridgeBlock) - var pendingOrder []string - var deferred [][]bridgeBlock - flushDeferred := func() { - for _, blocks := range deferred { - if len(blocks) > 0 { - messages = append(messages, map[string]any{"role": "user", "content": encodeChatBlocks(blocks)}) - } - } - deferred = nil - } - - for i, message := range request.Messages { - var content, reasoning, calls, results []bridgeBlock - for _, block := range message.Blocks { - switch block.Kind { - case "reasoning": - reasoning = append(reasoning, block) - case "tool_call": - calls = append(calls, block) - case "tool_result": - results = append(results, block) - default: - content = append(content, block) - } - } - if message.Role == "assistant" { - if len(pending) > 0 { - return nil, fmt.Errorf("messages[%d]: assistant message appears before tool results for %s", i, strings.Join(missingToolIDs(pendingOrder, pending), ", ")) - } - if len(results) > 0 { - return nil, fmt.Errorf("messages[%d]: assistant message contains tool results", i) - } - encoded := map[string]any{"role": "assistant", "content": nil} - if value, ok := bridgeReasoningText(reasoning); ok { - encoded["reasoning_content"] = value - } - if len(content) > 0 { - encoded["content"] = encodeChatBlocks(content) - } - if len(calls) > 0 { - toolCalls := make([]any, 0, len(calls)) - for _, call := range calls { - if call.ID == "" || call.Name == "" { - return nil, fmt.Errorf("messages[%d]: tool call must contain id and name", i) - } - if pending[call.ID] { - return nil, fmt.Errorf("messages[%d]: duplicate tool call id %q", i, call.ID) - } - pending[call.ID] = true - pendingOrder = append(pendingOrder, call.ID) - toolCalls = append(toolCalls, map[string]any{ - "id": call.ID, - "type": "function", - "function": map[string]any{ - "name": call.Name, - "arguments": bridgeArgumentsJSON(call), - }, - }) - } - encoded["tool_calls"] = toolCalls - } - if len(content) > 0 || len(reasoning) > 0 || len(calls) > 0 { - messages = append(messages, encoded) - } - continue - } - - if len(calls) > 0 { - return nil, fmt.Errorf("messages[%d]: user message contains tool calls", i) - } - for _, result := range results { - if _, duplicate := pendingResults[result.CallID]; duplicate { - return nil, fmt.Errorf("messages[%d]: duplicate tool result %q", i, result.CallID) - } - if !pending[result.CallID] { - return nil, fmt.Errorf("messages[%d]: tool result %q has no pending tool call", i, result.CallID) - } - pendingResults[result.CallID] = result - delete(pending, result.CallID) - } - if len(content) > 0 { - if len(pendingOrder) > 0 || len(deferred) > 0 { - deferred = append(deferred, content) - } else { - messages = append(messages, map[string]any{"role": "user", "content": encodeChatBlocks(content)}) - } - } - if len(pending) == 0 && len(pendingOrder) > 0 { - for _, id := range pendingOrder { - result := pendingResults[id] - messages = append(messages, map[string]any{ - "role": "tool", - "tool_call_id": id, - "content": bridgeToolResultContent(result.Result), - }) - } - flushDeferred() - pendingOrder = nil - clear(pendingResults) - } - } - if len(pending) > 0 { - return nil, fmt.Errorf("tool calls are missing results for %s", strings.Join(missingToolIDs(pendingOrder, pending), ", ")) - } - flushDeferred() - output["messages"] = messages - - if len(request.Tools) > 0 { - tools := make([]any, 0, len(request.Tools)) - for _, tool := range request.Tools { - function := map[string]any{ - "name": tool.Name, - "description": tool.Description, - "parameters": schemaOrDefault(tool.Schema), - } - if tool.Strict { - function["strict"] = true - } - tools = append(tools, map[string]any{"type": "function", "function": function}) - } - output["tools"] = tools - if choice := encodeChatToolChoice(request.ToolChoice); choice != nil { - output["tool_choice"] = choice - } - } - return output, nil -} - -func missingToolIDs(order []string, pending map[string]bool) []string { - missing := make([]string, 0, len(pending)) - for _, id := range order { - if pending[id] { - missing = append(missing, id) - } - } - if len(missing) == len(pending) { - return missing - } - for id := range pending { - found := false - for _, current := range missing { - if current == id { - found = true - break - } - } - if !found { - missing = append(missing, id) - } - } - sort.Strings(missing) - return missing -} - -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) - if len(request.System) > 0 { - output["instructions"] = bridgeBlocksText(request.System) - } - if request.Reasoning != nil { - switch value := request.Reasoning.(type) { - case string: - output["reasoning"] = map[string]any{"effort": value} - default: - output["reasoning"] = value - } - } - - items := make([]any, 0, len(request.Messages)+1) - if len(request.Developer) > 0 { - items = append(items, map[string]any{ - "type": "message", "role": "developer", - "content": []any{map[string]any{"type": "input_text", "text": bridgeBlocksText(request.Developer)}}, - }) - } - for _, message := range request.Messages { - var content []any - flushContent := func() { - if len(content) == 0 { - return - } - items = append(items, map[string]any{ - "type": "message", - "role": normalizeResponsesRole(message.Role), - "content": content, - }) - content = nil - } - for _, block := range message.Blocks { - switch block.Kind { - case "reasoning": - flushContent() - items = append(items, encodeResponsesReasoning(block, false)) - case "text": - kind := "input_text" - if message.Role == "assistant" { - kind = "output_text" - } - content = append(content, map[string]any{"type": kind, "text": block.Text}) - case "image": - url := block.URL - if url == "" && block.Data != "" { - url = "data:" + block.MediaType + ";base64," + block.Data - } - 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) - content = append(content, item) - case "tool_call": - flushContent() - items = append(items, map[string]any{ - "type": "function_call", - "call_id": block.ID, - "name": block.Name, - "arguments": bridgeArgumentsJSON(block), - }) - case "tool_result": - flushContent() - items = append(items, map[string]any{ - "type": "function_call_output", - "call_id": block.CallID, - "output": bridgeToolResultContent(block.Result), - }) - } - } - flushContent() - } - output["input"] = items - if len(request.Tools) > 0 { - tools := make([]any, 0, len(request.Tools)) - for _, tool := range request.Tools { - tools = append(tools, map[string]any{ - "type": "function", - "name": tool.Name, - "description": tool.Description, - "parameters": schemaOrDefault(tool.Schema), - "strict": tool.Strict, - }) - } - output["tools"] = tools - if choice := encodeResponsesToolChoice(request.ToolChoice); choice != nil { - output["tool_choice"] = choice - } - } - return output -} - -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) - if request.MaxTokens == nil { - output["max_tokens"] = 4096 - } else { - output["max_tokens"] = request.MaxTokens - } - if thinking, outputConfig := anthropicThinking(request.Reasoning); thinking != nil { - output["thinking"] = thinking - if outputConfig != nil { - output["output_config"] = outputConfig - } - } - if len(request.System) > 0 || len(request.Developer) > 0 { - instructions := append([]bridgeBlock(nil), request.System...) - instructions = append(instructions, request.Developer...) - output["system"] = encodeAnthropicBlocks(instructions) - } - - messages := make([]any, 0, len(request.Messages)) - for _, message := range request.Messages { - content := encodeAnthropicBlocks(message.Blocks) - if len(content) == 0 { - continue - } - role := "user" - if message.Role == "assistant" { - role = "assistant" - } - if len(messages) > 0 { - last, _ := messages[len(messages)-1].(map[string]any) - if stringAt(last, "role") == role { - last["content"] = append(asSlice(last["content"]), content...) - continue - } - } - messages = append(messages, map[string]any{"role": role, "content": content}) - } - output["messages"] = messages - // Anthropic has no tool_choice "none" value. Omitting the tools is the - // protocol-compatible representation of an explicitly disabled tool set. - if len(request.Tools) > 0 && request.ToolChoice.Mode != "none" { - tools := make([]any, 0, len(request.Tools)) - for _, tool := range request.Tools { - tools = append(tools, map[string]any{ - "name": tool.Name, - "description": tool.Description, - "input_schema": schemaOrDefault(tool.Schema), - }) - } - output["tools"] = tools - if choice := encodeAnthropicToolChoice(request.ToolChoice); choice != nil { - output["tool_choice"] = choice - } - } - return output -} - -func decodeOpenAIBlocks(value any) []bridgeBlock { - blocks, _ := decodeOpenAIBlocksChecked(value) - return blocks -} - -func decodeOpenAIBlocksChecked(value any) ([]bridgeBlock, error) { - switch value := value.(type) { - case string: - if value == "" { - return nil, nil - } - return []bridgeBlock{{Kind: "text", Text: value}}, nil - case map[string]any: - return decodeOpenAIBlocksChecked([]any{value}) - case []any: - blocks := make([]bridgeBlock, 0, len(value)) - for _, raw := range value { - part, ok := raw.(map[string]any) - if !ok { - return nil, errors.New("OpenAI content block must be an object") - } - switch stringAt(part, "type") { - case "text", "input_text", "output_text": - blocks = append(blocks, bridgeBlock{Kind: "text", Text: stringAt(part, "text")}) - case "image_url": - blocks = append(blocks, bridgeBlock{Kind: "image", URL: firstString(stringAt(part, "image_url", "url"), stringAt(part, "image_url"))}) - case "input_image": - blocks = append(blocks, bridgeBlock{Kind: "image", URL: stringAt(part, "image_url")}) - case "file", "input_file": - file := 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")), - }) - default: - return nil, fmt.Errorf("unsupported OpenAI content block type %q", stringAt(part, "type")) - } - } - return blocks, nil - default: - if value == nil { - return nil, nil - } - return nil, errors.New("unsupported OpenAI content value") - } -} - -func decodeAnthropicBlocks(value any) []bridgeBlock { - blocks, _ := decodeAnthropicBlocksChecked(value) - return blocks -} - -func decodeAnthropicBlocksChecked(value any) ([]bridgeBlock, error) { - if text, ok := value.(string); ok { - if text == "" { - return nil, nil - } - return []bridgeBlock{{Kind: "text", Text: text}}, nil - } - var blocks []bridgeBlock - for _, raw := range 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") { - case "thinking": - blocks = append(blocks, bridgeBlock{ - Kind: "reasoning", - Text: stringAt(part, "thinking"), - Signature: stringAt(part, "signature"), - }) - case "redacted_thinking": - blocks = append(blocks, bridgeBlock{Kind: "reasoning", Encrypted: stringAt(part, "data")}) - case "text": - blocks = append(blocks, bridgeBlock{Kind: "text", Text: stringAt(part, "text")}) - case "image": - source := mapAt(part, "source") - if stringAt(source, "type") == "url" { - blocks = append(blocks, bridgeBlock{Kind: "image", URL: stringAt(source, "url")}) - } else { - blocks = append(blocks, bridgeBlock{Kind: "image", MediaType: stringAt(source, "media_type"), Data: 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"))}) - 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"), - }) - case "tool_use": - blocks = append(blocks, bridgeBlock{ - Kind: "tool_call", - ID: stringAt(part, "id"), - Name: stringAt(part, "name"), - Arguments: part["input"], - }) - case "tool_result": - blocks = append(blocks, bridgeBlock{ - Kind: "tool_result", - CallID: stringAt(part, "tool_use_id"), - Result: part["content"], - IsError: boolAt(part, "is_error"), - }) - default: - return nil, fmt.Errorf("unsupported Anthropic content block type %q", stringAt(part, "type")) - } - } - return blocks, nil -} - -func decodeChatReasoning(message map[string]any) []bridgeBlock { - value, exists := message["reasoning_content"] - if !exists { - value, exists = message["reasoning"] - } - text, ok := value.(string) - if !exists || !ok { - return nil - } - return []bridgeBlock{{ - Kind: "reasoning", - Text: text, - Signature: stringAt(message, "reasoning_signature"), - }} -} - -func decodeResponsesReasoning(item map[string]any) []bridgeBlock { - var text strings.Builder - for _, raw := range asSlice(item["summary"]) { - part, _ := raw.(map[string]any) - text.WriteString(stringAt(part, "text")) - } - if content := item["content"]; content != nil { - for _, raw := range asSlice(content) { - part, _ := raw.(map[string]any) - text.WriteString(stringAt(part, "text")) - } - } - encrypted := stringAt(item, "encrypted_content") - if text.Len() == 0 && encrypted == "" { - return nil - } - return []bridgeBlock{{ - Kind: "reasoning", - ID: stringAt(item, "id"), - Text: text.String(), - Encrypted: encrypted, - }} -} - -func encodeResponsesReasoning(block bridgeBlock, completed bool) map[string]any { - id := block.ID - if id == "" { - id = randomID("rs", 12) - } - summary := []any{} - if block.Text != "" { - summary = append(summary, map[string]any{"type": "summary_text", "text": block.Text}) - } - item := map[string]any{"id": id, "type": "reasoning", "summary": summary} - if block.Encrypted != "" { - item["encrypted_content"] = block.Encrypted - } - if completed { - item["status"] = "completed" - } - return item -} - -func bridgeReasoningText(blocks []bridgeBlock) (string, bool) { - if len(blocks) == 0 { - return "", false - } - var text strings.Builder - for _, block := range blocks { - if block.Text != "" { - text.WriteString(block.Text) - } else if block.Encrypted != "" { - text.WriteString(anthropicRedactedThinkingPlaceholder) - } - } - return text.String(), true -} - -func bridgeReasoningSignature(blocks []bridgeBlock) string { - for i := len(blocks) - 1; i >= 0; i-- { - if blocks[i].Signature != "" { - return blocks[i].Signature - } - } - return "" -} - -func encodeChatBlocks(blocks []bridgeBlock) any { - if len(blocks) == 1 && blocks[0].Kind == "text" { - return blocks[0].Text - } - parts := make([]any, 0, len(blocks)) - for _, block := range blocks { - switch block.Kind { - case "text": - parts = append(parts, map[string]any{"type": "text", "text": block.Text}) - case "image": - url := block.URL - if url == "" && block.Data != "" { - url = "data:" + block.MediaType + ";base64," + block.Data - } - 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) - parts = append(parts, map[string]any{"type": "file", "file": file}) - } - } - return parts -} - -func encodeAnthropicBlocks(blocks []bridgeBlock) []any { - parts := make([]any, 0, len(blocks)) - for _, block := range blocks { - switch block.Kind { - case "text": - parts = append(parts, map[string]any{"type": "text", "text": block.Text}) - case "image": - if block.URL != "" { - parts = append(parts, map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": block.URL}}) - } else { - parts = append(parts, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": block.MediaType, "data": block.Data}}) - } - case "file": - var source map[string]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} - } - if source != nil { - part := map[string]any{"type": "document", "source": source} - put(part, "title", block.Filename) - parts = append(parts, part) - } - case "tool_call": - input := block.Arguments - if input == nil { - input = parseJSONOrString(block.ArgumentsJSON) - } - parts = append(parts, map[string]any{"type": "tool_use", "id": block.ID, "name": block.Name, "input": input}) - case "tool_result": - parts = append(parts, map[string]any{"type": "tool_result", "tool_use_id": block.CallID, "content": block.Result, "is_error": block.IsError}) - case "reasoning": - if block.Encrypted != "" { - parts = append(parts, map[string]any{"type": "redacted_thinking", "data": block.Encrypted}) - continue - } - part := map[string]any{"type": "thinking", "thinking": block.Text, "signature": block.Signature} - parts = append(parts, part) - } - } - return parts -} - -func bridgeArgumentsJSON(block bridgeBlock) string { - if block.ArgumentsJSON != "" { - return block.ArgumentsJSON - } - if block.Arguments == nil { - return "{}" - } - data, err := json.Marshal(block.Arguments) - if err != nil { - return "{}" - } - return string(data) -} - -func bridgeToolResultContent(value any) string { - if text, ok := value.(string); ok { - return text - } - if parts, ok := value.([]any); ok { - var text strings.Builder - allText := true - for _, raw := range parts { - part, ok := raw.(map[string]any) - if !ok || stringAt(part, "type") != "text" { - allText = false - break - } - text.WriteString(stringAt(part, "text")) - } - if allText { - return text.String() - } - } - data, err := json.Marshal(value) - if err != nil { - return "" - } - return string(data) -} - -func decodeChatToolChoice(value any) bridgeToolChoice { - if mode, ok := value.(string); ok { - return bridgeToolChoice{Mode: mode} - } - choice, _ := value.(map[string]any) - if stringAt(choice, "type") == "function" { - return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "function", "name")} - } - return bridgeToolChoice{} -} - -func decodeResponsesToolChoice(value any) bridgeToolChoice { - if mode, ok := value.(string); ok { - return bridgeToolChoice{Mode: mode} - } - choice, _ := value.(map[string]any) - if stringAt(choice, "type") == "function" { - return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "name")} - } - return bridgeToolChoice{} -} - -func decodeAnthropicToolChoice(value any) bridgeToolChoice { - if mode, ok := value.(string); ok { - if mode == "required" { - mode = "any" - } - return decodeAnthropicToolChoice(map[string]any{"type": mode}) - } - choice, _ := value.(map[string]any) - switch stringAt(choice, "type") { - case "auto": - return bridgeToolChoice{Mode: "auto"} - case "none": - return bridgeToolChoice{Mode: "none"} - case "any": - return bridgeToolChoice{Mode: "required"} - case "tool": - return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "name")} - default: - return bridgeToolChoice{} - } -} - -func encodeChatToolChoice(choice bridgeToolChoice) any { - switch choice.Mode { - case "named": - return map[string]any{"type": "function", "function": map[string]any{"name": choice.Name}} - case "auto", "none", "required": - return choice.Mode - default: - return nil - } -} - -func encodeResponsesToolChoice(choice bridgeToolChoice) any { - switch choice.Mode { - case "named": - return map[string]any{"type": "function", "name": choice.Name} - case "auto", "none", "required": - return choice.Mode - default: - return nil - } -} - -func encodeAnthropicToolChoice(choice bridgeToolChoice) any { - switch choice.Mode { - case "named": - return map[string]any{"type": "tool", "name": choice.Name} - case "required": - return map[string]any{"type": "any"} - case "auto": - return map[string]any{"type": choice.Mode} - default: - return nil - } -} - -func convertResponse(from, to Protocol, body []byte) ([]byte, error) { - if from == to { - return append([]byte(nil), body...), nil - } - var input map[string]any - if err := json.Unmarshal(body, &input); err != nil { - return nil, err - } - response, err := decodeBridgeResponse(from, input) - if err != nil { - return nil, err - } - if response.Error != "" || response.Stop == "error" { - return nil, fmt.Errorf("upstream response failed: %s", 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"), - } - if response.Created == 0 { - response.Created = int64At(input, "created_at") - } - if response.Created == 0 { - response.Created = time.Now().Unix() - } - switch protocol { - case ProtocolChat: - if message := stringAt(input, "error", "message"); message != "" { - response.Error = message - } - if response.Error != "" { - return response, nil - } - choices := 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") - response.Reasoning = decodeChatReasoning(message) - blocks, err := decodeOpenAIBlocksChecked(message["content"]) - if err != nil { - return response, fmt.Errorf("chat response content: %w", err) - } - response.Text, err = responseTextBlocks(blocks, "Chat") - if err != nil { - return response, err - } - for _, raw := range sliceAt(message, "tool_calls") { - call, _ := raw.(map[string]any) - function := mapAt(call, "function") - response.Tools = append(response.Tools, bridgeBlock{ - Kind: "tool_call", - ID: stringAt(call, "id"), - Name: stringAt(function, "name"), - ArgumentsJSON: stringAt(function, "arguments"), - }) - } - response.Stop = canonicalChatStop(stringAt(choice, "finish_reason")) - response.Usage = decodeOpenAIUsage(mapAt(input, "usage")) - case ProtocolResponses: - for _, raw := range sliceAt(input, "output") { - item, _ := raw.(map[string]any) - switch stringAt(item, "type") { - case "reasoning": - response.Reasoning = append(response.Reasoning, decodeResponsesReasoning(item)...) - case "message": - blocks, err := decodeOpenAIBlocksChecked(item["content"]) - if err != nil { - return response, fmt.Errorf("Responses response content: %w", err) - } - text, err := responseTextBlocks(blocks, "Responses") - if err != nil { - return response, err - } - response.Text += text - 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"), - }) - default: - return response, fmt.Errorf("Responses response has unsupported output item type %q", 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" { - response.Stop = "error" - response.Error = firstString(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") - } - blocks, err := decodeAnthropicBlocksChecked(input["content"]) - if err != nil { - return response, fmt.Errorf("Anthropic response content: %w", err) - } - for _, block := range blocks { - if block.Kind == "reasoning" { - response.Reasoning = append(response.Reasoning, block) - } else if block.Kind == "text" { - response.Text += block.Text - } else if block.Kind == "tool_call" { - response.Tools = append(response.Tools, block) - } else if block.Kind != "text" { - 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")) - default: - return response, fmt.Errorf("unsupported response protocol %q", protocol) - } - return response, nil -} - -func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string]any { - if response.ID == "" { - response.ID = randomID("resp", 12) - } - switch protocol { - case ProtocolChat: - message := map[string]any{"role": "assistant", "content": response.Text} - if value, ok := bridgeReasoningText(response.Reasoning); ok { - message["reasoning_content"] = value - } - if signature := bridgeReasoningSignature(response.Reasoning); signature != "" { - message["reasoning_signature"] = signature - } - if len(response.Tools) > 0 { - calls := make([]any, 0, len(response.Tools)) - for _, tool := range response.Tools { - calls = append(calls, map[string]any{ - "id": tool.ID, - "type": "function", - "function": map[string]any{ - "name": tool.Name, - "arguments": bridgeArgumentsJSON(tool), - }, - }) - } - message["tool_calls"] = calls - } - return map[string]any{ - "id": asPrefix(response.ID, "chatcmpl"), - "object": "chat.completion", - "created": response.Created, - "model": response.Model, - "choices": []any{map[string]any{ - "index": 0, - "message": message, - "finish_reason": chatStop(response.Stop), - }}, - "usage": openAIUsage(response.Usage), - } - case ProtocolResponses: - output := make([]any, 0, len(response.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), - "type": "message", - "status": "completed", - "role": "assistant", - "content": []any{map[string]any{ - "type": "output_text", - "text": response.Text, - "annotations": []any{}, - }}, - }) - } - for _, tool := range response.Tools { - output = append(output, map[string]any{ - "id": randomID("fc", 12), - "type": "function_call", - "status": "completed", - "call_id": tool.ID, - "name": tool.Name, - "arguments": bridgeArgumentsJSON(tool), - }) - } - status := "completed" - var incomplete any - if response.Stop == "length" || response.Stop == "content_filter" { - status = "incomplete" - incomplete = map[string]any{"reason": responsesIncompleteReason(response.Stop)} - } else if response.Stop == "error" { - status = "failed" - } - return map[string]any{ - "id": asPrefix(response.ID, "resp"), - "object": "response", - "created_at": response.Created, - "status": status, - "model": response.Model, - "output": output, - "error": nil, - "incomplete_details": incomplete, - "usage": map[string]any{ - "input_tokens": response.Usage.Input, - "output_tokens": response.Usage.Output, - "total_tokens": response.Usage.Total, - "input_tokens_details": map[string]any{ - "cached_tokens": response.Usage.Cached, - }, - "output_tokens_details": map[string]any{ - "reasoning_tokens": response.Usage.Reasoning, - }, - }, - } - case ProtocolAnthropic: - content := make([]any, 0, len(response.Reasoning)+len(response.Tools)+1) - content = append(content, encodeAnthropicBlocks(response.Reasoning)...) - if response.Text != "" { - content = append(content, map[string]any{"type": "text", "text": response.Text}) - } - for _, tool := range response.Tools { - input := tool.Arguments - if input == nil { - input = parseJSONOrString(tool.ArgumentsJSON) - } - content = append(content, map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": input}) - } - return map[string]any{ - "id": asPrefix(response.ID, "msg"), - "type": "message", - "role": "assistant", - "model": response.Model, - "content": content, - "stop_reason": anthropicStop(response.Stop), - "stop_sequence": nil, - "usage": anthropicUsage(response.Usage), - } - default: - return map[string]any{} - } -} - -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") - 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"), - ) - 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} -} - -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") - input += cached + cacheCreation - return bridgeUsage{ - Input: input, - Output: output, - Total: input + output, - Cached: cached, - CacheCreation: cacheCreation, - } -} - -func openAIUsage(usage bridgeUsage) map[string]any { - return map[string]any{ - "prompt_tokens": usage.Input, - "completion_tokens": usage.Output, - "total_tokens": usage.Total, - "prompt_tokens_details": map[string]any{ - "cached_tokens": usage.Cached, - }, - "completion_tokens_details": map[string]any{ - "reasoning_tokens": usage.Reasoning, - }, - } -} - -func anthropicUsage(usage bridgeUsage) map[string]any { - return map[string]any{ - "input_tokens": max(usage.Input-usage.Cached-usage.CacheCreation, 0), - "output_tokens": usage.Output, - "cache_creation_input_tokens": usage.CacheCreation, - "cache_read_input_tokens": usage.Cached, - } -} - func firstNonZero(values ...int) int { for _, value := range values { if value != 0 { @@ -1600,32 +125,6 @@ func normalizeResponsesRole(role string) string { return "user" } -func chatStop(stop string) string { - switch stop { - case "tool_use", "tool_calls": - return "tool_calls" - case "max_tokens", "length": - return "length" - case "content_filter", "error": - return stop - default: - return "stop" - } -} - -func anthropicStop(stop string) string { - switch stop { - case "tool_use", "tool_calls": - return "tool_use" - case "max_tokens", "length": - return "max_tokens" - case "stop_sequence", "pause_turn", "refusal": - return stop - default: - return "end_turn" - } -} - func schemaOrDefault(value any) any { if value == nil { return map[string]any{"type": "object", "properties": map[string]any{}} @@ -1633,6 +132,64 @@ func schemaOrDefault(value any) any { return value } +// chatResponseFormat converts a bridge-level response format into the OpenAI +// Chat Completions shape. Chat and Responses agree on the format type names but +// not on the json_schema nesting: Responses carries name/schema/strict inline, +// while Chat nests them under "json_schema". A value that has no Chat +// equivalent (the "text" type) is omitted instead of failing the request. +func chatResponseFormat(format any) any { + object, ok := format.(map[string]any) + if !ok { + return nil + } + switch stringAt(object, "type") { + case "json_object": + return map[string]any{"type": "json_object"} + case "json_schema": + if nested, ok := object["json_schema"].(map[string]any); ok { + return map[string]any{"type": "json_schema", "json_schema": nested} + } + nested := make(map[string]any, 4) + for _, key := range []string{"name", "description", "schema", "strict"} { + if value, exists := object[key]; exists { + nested[key] = value + } + } + if len(nested) == 0 { + return nil + } + return map[string]any{"type": "json_schema", "json_schema": nested} + default: + return nil + } +} + +// responsesTextFormat converts a bridge-level response format into the object +// accepted by the Responses "text.format" field. A Chat-style nested +// json_schema is flattened into the inline shape Responses expects. +func responsesTextFormat(format any) any { + object, ok := format.(map[string]any) + if !ok { + return nil + } + switch stringAt(object, "type") { + case "text", "json_object": + return object + case "json_schema": + if nested, ok := object["json_schema"].(map[string]any); ok { + flattened := make(map[string]any, len(nested)+1) + for key, value := range nested { + flattened[key] = value + } + flattened["type"] = "json_schema" + return flattened + } + return object + default: + return nil + } +} + func reasoningEffort(value any) any { if object, ok := value.(map[string]any); ok { if effort := object["effort"]; effort != nil { @@ -1688,52 +245,6 @@ func effortForThinkingBudget(budget int) string { return "medium" } -func canonicalChatStop(stop string) string { - switch stop { - case "tool_calls", "function_call": - return "tool_calls" - case "length": - return "length" - case "content_filter": - return "content_filter" - case "error", "network_error", "server_error": - return "error" - default: - return "stop" - } -} - -func canonicalAnthropicStop(stop string) string { - switch stop { - case "tool_use": - return "tool_calls" - case "max_tokens": - return "length" - case "stop_sequence", "pause_turn", "refusal": - return stop - case "error", "network_error", "server_error": - return "error" - default: - return "stop" - } -} - -func canonicalResponsesIncomplete(reason string) string { - switch reason { - case "content_filter": - return "content_filter" - default: - return "length" - } -} - -func responsesIncompleteReason(stop string) string { - if stop == "content_filter" { - return "content_filter" - } - return "max_output_tokens" -} - func bridgeBlocksText(blocks []bridgeBlock) string { var text strings.Builder for _, block := range blocks { @@ -1744,15 +255,6 @@ func bridgeBlocksText(blocks []bridgeBlock) string { return text.String() } -func responseTextBlocks(blocks []bridgeBlock, protocol string) (string, error) { - for _, block := range blocks { - if block.Kind != "text" { - return "", fmt.Errorf("%s response contains unsupported %s content block", protocol, block.Kind) - } - } - return bridgeBlocksText(blocks), nil -} - func parseJSONOrString(value string) any { if value == "" { return map[string]any{} diff --git a/convert_content.go b/convert_content.go new file mode 100644 index 0000000..f40cd7e --- /dev/null +++ b/convert_content.go @@ -0,0 +1,412 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "strings" +) + +func decodeOpenAIBlocks(value any) []bridgeBlock { + blocks, _ := decodeOpenAIBlocksChecked(value) + return blocks +} + +func decodeOpenAIBlocksChecked(value any) ([]bridgeBlock, error) { + switch value := value.(type) { + case string: + if value == "" { + return nil, nil + } + return []bridgeBlock{{Kind: "text", Text: value}}, nil + case map[string]any: + return decodeOpenAIBlocksChecked([]any{value}) + case []any: + blocks := make([]bridgeBlock, 0, len(value)) + for _, raw := range value { + part, ok := raw.(map[string]any) + if !ok { + return nil, errors.New("OpenAI content block must be an object") + } + switch stringAt(part, "type") { + case "text", "input_text", "output_text": + blocks = append(blocks, bridgeBlock{Kind: "text", Text: stringAt(part, "text")}) + case "image_url": + blocks = append(blocks, bridgeBlock{Kind: "image", URL: firstString(stringAt(part, "image_url", "url"), stringAt(part, "image_url"))}) + case "input_image": + blocks = append(blocks, bridgeBlock{Kind: "image", URL: stringAt(part, "image_url")}) + case "file", "input_file": + file := 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")), + }) + default: + return nil, fmt.Errorf("unsupported OpenAI content block type %q", stringAt(part, "type")) + } + } + return blocks, nil + default: + if value == nil { + return nil, nil + } + return nil, errors.New("unsupported OpenAI content value") + } +} + +func decodeAnthropicBlocks(value any) []bridgeBlock { + blocks, _ := decodeAnthropicBlocksChecked(value) + return blocks +} + +func decodeAnthropicBlocksChecked(value any) ([]bridgeBlock, error) { + if text, ok := value.(string); ok { + if text == "" { + return nil, nil + } + return []bridgeBlock{{Kind: "text", Text: text}}, nil + } + var blocks []bridgeBlock + for _, raw := range 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") { + case "thinking": + blocks = append(blocks, bridgeBlock{ + Kind: "reasoning", + Text: stringAt(part, "thinking"), + Signature: stringAt(part, "signature"), + }) + case "redacted_thinking": + blocks = append(blocks, bridgeBlock{Kind: "reasoning", Encrypted: stringAt(part, "data")}) + case "text": + blocks = append(blocks, bridgeBlock{Kind: "text", Text: stringAt(part, "text")}) + case "image": + source := mapAt(part, "source") + if stringAt(source, "type") == "url" { + blocks = append(blocks, bridgeBlock{Kind: "image", URL: stringAt(source, "url")}) + } else { + blocks = append(blocks, bridgeBlock{Kind: "image", MediaType: stringAt(source, "media_type"), Data: 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"))}) + 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"), + }) + case "tool_use": + blocks = append(blocks, bridgeBlock{ + Kind: "tool_call", + ID: stringAt(part, "id"), + Name: stringAt(part, "name"), + Arguments: part["input"], + }) + case "tool_result": + blocks = append(blocks, bridgeBlock{ + Kind: "tool_result", + CallID: stringAt(part, "tool_use_id"), + Result: part["content"], + IsError: boolAt(part, "is_error"), + }) + default: + return nil, fmt.Errorf("unsupported Anthropic content block type %q", stringAt(part, "type")) + } + } + return blocks, nil +} + +func decodeChatReasoning(message map[string]any) []bridgeBlock { + value, exists := message["reasoning_content"] + if !exists { + value, exists = message["reasoning"] + } + text, ok := value.(string) + if !exists || !ok { + return nil + } + return []bridgeBlock{{ + Kind: "reasoning", + Text: text, + Signature: stringAt(message, "reasoning_signature"), + }} +} + +func decodeResponsesReasoning(item map[string]any) []bridgeBlock { + var text strings.Builder + for _, raw := range asSlice(item["summary"]) { + part, _ := raw.(map[string]any) + text.WriteString(stringAt(part, "text")) + } + if content := item["content"]; content != nil { + for _, raw := range asSlice(content) { + part, _ := raw.(map[string]any) + text.WriteString(stringAt(part, "text")) + } + } + encrypted := stringAt(item, "encrypted_content") + if text.Len() == 0 && encrypted == "" { + return nil + } + return []bridgeBlock{{ + Kind: "reasoning", + ID: stringAt(item, "id"), + Text: text.String(), + Encrypted: encrypted, + }} +} + +// encodeResponsesReasoningInput renders a reasoning block for a Responses +// request body. It reports false for blocks that carry neither a server-issued +// id nor encrypted content: those came from a protocol whose wire format has no +// reasoning reference (Chat text or Anthropic thinking), so replaying them +// under a synthesized id can only be rejected as a stale reference. +func encodeResponsesReasoningInput(block bridgeBlock) (map[string]any, bool) { + if block.ID == "" && block.Encrypted == "" { + return nil, false + } + return encodeResponsesReasoning(block, false), true +} + +func encodeResponsesReasoning(block bridgeBlock, completed bool) map[string]any { + id := block.ID + if id == "" { + id = randomID("rs", 12) + } + summary := []any{} + if block.Text != "" { + summary = append(summary, map[string]any{"type": "summary_text", "text": block.Text}) + } + item := map[string]any{"id": id, "type": "reasoning", "summary": summary} + if block.Encrypted != "" { + item["encrypted_content"] = block.Encrypted + } + if completed { + item["status"] = "completed" + } + return item +} + +func bridgeReasoningText(blocks []bridgeBlock) (string, bool) { + if len(blocks) == 0 { + return "", false + } + var text strings.Builder + for _, block := range blocks { + if block.Text != "" { + text.WriteString(block.Text) + } else if block.Encrypted != "" { + text.WriteString(anthropicRedactedThinkingPlaceholder) + } + } + return text.String(), true +} + +func bridgeReasoningSignature(blocks []bridgeBlock) string { + for i := len(blocks) - 1; i >= 0; i-- { + if blocks[i].Signature != "" { + return blocks[i].Signature + } + } + return "" +} + +func encodeChatBlocks(blocks []bridgeBlock) any { + if len(blocks) == 1 && blocks[0].Kind == "text" { + return blocks[0].Text + } + parts := make([]any, 0, len(blocks)) + for _, block := range blocks { + switch block.Kind { + case "text": + parts = append(parts, map[string]any{"type": "text", "text": block.Text}) + case "image": + url := block.URL + if url == "" && block.Data != "" { + url = "data:" + block.MediaType + ";base64," + block.Data + } + 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) + parts = append(parts, map[string]any{"type": "file", "file": file}) + } + } + return parts +} + +func encodeAnthropicBlocks(blocks []bridgeBlock) []any { + parts := make([]any, 0, len(blocks)) + for _, block := range blocks { + switch block.Kind { + case "text": + parts = append(parts, map[string]any{"type": "text", "text": block.Text}) + case "image": + if block.URL != "" { + parts = append(parts, map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": block.URL}}) + } else { + parts = append(parts, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": block.MediaType, "data": block.Data}}) + } + case "file": + var source map[string]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} + } + if source != nil { + part := map[string]any{"type": "document", "source": source} + put(part, "title", block.Filename) + parts = append(parts, part) + } + case "tool_call": + input := block.Arguments + if input == nil { + input = parseJSONOrString(block.ArgumentsJSON) + } + parts = append(parts, map[string]any{"type": "tool_use", "id": block.ID, "name": block.Name, "input": input}) + case "tool_result": + parts = append(parts, map[string]any{"type": "tool_result", "tool_use_id": block.CallID, "content": block.Result, "is_error": block.IsError}) + case "reasoning": + if block.Encrypted != "" { + parts = append(parts, map[string]any{"type": "redacted_thinking", "data": block.Encrypted}) + continue + } + part := map[string]any{"type": "thinking", "thinking": block.Text, "signature": block.Signature} + parts = append(parts, part) + } + } + return parts +} + +func bridgeArgumentsJSON(block bridgeBlock) string { + if block.ArgumentsJSON != "" { + return block.ArgumentsJSON + } + if block.Arguments == nil { + return "{}" + } + data, err := json.Marshal(block.Arguments) + if err != nil { + return "{}" + } + return string(data) +} + +func bridgeToolResultContent(value any) string { + if text, ok := value.(string); ok { + return text + } + if parts, ok := value.([]any); ok { + var text strings.Builder + allText := true + for _, raw := range parts { + part, ok := raw.(map[string]any) + if !ok || stringAt(part, "type") != "text" { + allText = false + break + } + text.WriteString(stringAt(part, "text")) + } + if allText { + return text.String() + } + } + data, err := json.Marshal(value) + if err != nil { + return "" + } + return string(data) +} + +func decodeChatToolChoice(value any) bridgeToolChoice { + if mode, ok := value.(string); ok { + return bridgeToolChoice{Mode: mode} + } + choice, _ := value.(map[string]any) + if stringAt(choice, "type") == "function" { + return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "function", "name")} + } + return bridgeToolChoice{} +} + +func decodeResponsesToolChoice(value any) bridgeToolChoice { + if mode, ok := value.(string); ok { + return bridgeToolChoice{Mode: mode} + } + choice, _ := value.(map[string]any) + if stringAt(choice, "type") == "function" { + return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "name")} + } + return bridgeToolChoice{} +} + +func decodeAnthropicToolChoice(value any) bridgeToolChoice { + if mode, ok := value.(string); ok { + if mode == "required" { + mode = "any" + } + return decodeAnthropicToolChoice(map[string]any{"type": mode}) + } + choice, _ := value.(map[string]any) + switch stringAt(choice, "type") { + case "auto": + return bridgeToolChoice{Mode: "auto"} + case "none": + return bridgeToolChoice{Mode: "none"} + case "any": + return bridgeToolChoice{Mode: "required"} + case "tool": + return bridgeToolChoice{Mode: "named", Name: stringAt(choice, "name")} + default: + return bridgeToolChoice{} + } +} + +func encodeChatToolChoice(choice bridgeToolChoice) any { + switch choice.Mode { + case "named": + return map[string]any{"type": "function", "function": map[string]any{"name": choice.Name}} + case "auto", "none", "required": + return choice.Mode + default: + return nil + } +} + +func encodeResponsesToolChoice(choice bridgeToolChoice) any { + switch choice.Mode { + case "named": + return map[string]any{"type": "function", "name": choice.Name} + case "auto", "none", "required": + return choice.Mode + default: + return nil + } +} + +func encodeAnthropicToolChoice(choice bridgeToolChoice) any { + switch choice.Mode { + case "named": + return map[string]any{"type": "tool", "name": choice.Name} + case "required": + return map[string]any{"type": "any"} + case "auto": + return map[string]any{"type": choice.Mode} + default: + return nil + } +} diff --git a/convert_request.go b/convert_request.go new file mode 100644 index 0000000..425e3e5 --- /dev/null +++ b/convert_request.go @@ -0,0 +1,817 @@ +package main + +import ( + "errors" + "fmt" + "sort" + "strings" +) + +// prepareUpstreamRequest 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) + if err != nil { + return nil, err + } + normalizeToolReasoningHistory(to, stringAt(output, "model"), upstreamURL, output) + return output, nil +} + +// normalizeToolReasoningHistory applies only to endpoints that are known to +// require reasoning replay, or to requests that explicitly enable reasoning. +// Normalizing the target shape makes the behavior independent of the client +// protocol used to reach the gateway. +func normalizeToolReasoningHistory(protocol Protocol, model, upstreamURL string, input map[string]any) bool { + vendor := isReasoningVendorIdentifier(model) || isReasoningVendorIdentifier(upstreamURL) + widened := vendor || requestEnablesReasoning(input) + switch protocol { + case ProtocolChat: + // 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. + if !widened { + return false + } + return normalizeChatToolReasoningHistory(input) + case ProtocolAnthropic: + // 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 + // native endpoint re-validates and replays verbatim, and rewriting them + // also shifts the cached prompt prefix mid-history. Only endpoints + // identified as reasoning vendors get the rewrite. + if !vendor { + return false + } + return normalizeAnthropicToolThinkingHistory(input) + default: + return false + } +} + +func isReasoningVendorIdentifier(value string) bool { + value = strings.ToLower(value) + for _, hint := range reasoningVendorHints { + if strings.Contains(value, hint) { + return true + } + } + return false +} + +func requestEnablesReasoning(input map[string]any) bool { + for _, key := range []string{"reasoning_effort", "reasoning", "thinking", "effort"} { + value, exists := input[key] + if !exists || value == nil { + continue + } + switch typed := value.(type) { + case string: + mode := strings.ToLower(strings.TrimSpace(typed)) + if mode != "" && mode != "none" && mode != "disabled" { + return true + } + case bool: + if typed { + return true + } + case map[string]any: + mode := strings.ToLower(strings.TrimSpace(firstString(stringAt(typed, "type"), stringAt(typed, "effort")))) + if mode == "none" || mode == "disabled" { + continue + } + return true + default: + return true + } + } + return false +} + +// normalizeChatToolReasoningHistory ensures every assistant tool-call turn +// carries reasoning_content. Some clients discard this non-standard field +// while retaining tool_calls, which otherwise makes the next thinking-mode +// request invalid. A legacy reasoning string is promoted when available. +func normalizeChatToolReasoningHistory(input map[string]any) bool { + messages, ok := input["messages"].([]any) + if !ok { + return false + } + + changed := false + for _, rawMessage := range messages { + message, ok := rawMessage.(map[string]any) + if !ok || stringAt(message, "role") != "assistant" || len(sliceAt(message, "tool_calls")) == 0 { + continue + } + if reasoning, ok := message["reasoning_content"].(string); ok && strings.TrimSpace(reasoning) != "" { + continue + } + reasoning, _ := message["reasoning"].(string) + if strings.TrimSpace(reasoning) == "" { + reasoning = toolReasoningPlaceholder + } + message["reasoning_content"] = reasoning + changed = true + } + return changed +} + +// normalizeAnthropicToolThinkingHistory repairs only assistant turns that +// contain tool_use. DeepSeek, Kimi/Moonshot and MiMo reject signed, redacted, +// empty or missing thinking history on those turns even though Anthropic +// clients can legitimately send each of those shapes. +func normalizeAnthropicToolThinkingHistory(input map[string]any) bool { + messages, ok := input["messages"].([]any) + if !ok { + return false + } + + changed := false + for _, rawMessage := range messages { + message, ok := rawMessage.(map[string]any) + if !ok || stringAt(message, "role") != "assistant" { + continue + } + content, ok := message["content"].([]any) + if !ok || !anthropicContentHasType(content, "tool_use") { + continue + } + + hasThinking := false + for i, rawBlock := range content { + block, ok := rawBlock.(map[string]any) + if !ok { + continue + } + switch stringAt(block, "type") { + case "thinking": + hasThinking = true + if _, exists := block["signature"]; exists { + delete(block, "signature") + changed = true + } + thinking, ok := block["thinking"].(string) + if !ok || strings.TrimSpace(thinking) == "" { + block["thinking"] = toolReasoningPlaceholder + changed = true + } + case "redacted_thinking": + hasThinking = true + content[i] = map[string]any{ + "type": "thinking", + "thinking": anthropicRedactedThinkingPlaceholder, + } + changed = true + } + } + if !hasThinking { + content = append([]any{map[string]any{ + "type": "thinking", + "thinking": toolReasoningPlaceholder, + }}, content...) + message["content"] = content + changed = true + } + } + return changed +} + +func anthropicContentHasType(content []any, kind string) bool { + for _, rawBlock := range content { + block, _ := rawBlock.(map[string]any) + if stringAt(block, "type") == kind { + return true + } + } + return false +} + +func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest, error) { + request := bridgeRequest{ + Model: stringAt(input, "model"), + Stream: boolAt(input, "stream"), + Temperature: input["temperature"], + TopP: input["top_p"], + Metadata: input["metadata"], + } + switch protocol { + case ProtocolChat: + request.MaxTokens = firstAny(input["max_completion_tokens"], input["max_tokens"]) + request.Stop = input["stop"] + request.Reasoning = firstAny(input["reasoning_effort"], input["reasoning"]) + for i, raw := range 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") + blocks, err := decodeOpenAIBlocksChecked(message["content"]) + if err != nil { + return request, fmt.Errorf("messages[%d]: %w", i, err) + } + if role == "assistant" { + blocks = append(decodeChatReasoning(message), blocks...) + } + for j, rawCall := range 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") + blocks = append(blocks, bridgeBlock{ + Kind: "tool_call", + ID: stringAt(call, "id"), + Name: stringAt(function, "name"), + ArgumentsJSON: stringAt(function, "arguments"), + }) + } + switch role { + case "system": + request.System = append(request.System, blocks...) + case "developer": + request.Developer = append(request.Developer, blocks...) + case "tool": + request.Messages = append(request.Messages, bridgeMessage{Role: "user", Blocks: []bridgeBlock{{ + Kind: "tool_result", + CallID: stringAt(message, "tool_call_id"), + Result: message["content"], + }}}) + case "user", "assistant": + request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks}) + default: + return request, fmt.Errorf("messages[%d] has unsupported role %q", i, role) + } + } + for i, raw := range sliceAt(input, "tools") { + tool, ok := raw.(map[string]any) + if !ok || stringAt(tool, "type") != "function" { + return request, fmt.Errorf("tools[%d] must be a function tool", i) + } + function := mapAt(tool, "function") + request.Tools = append(request.Tools, bridgeTool{ + Name: stringAt(function, "name"), + Description: stringAt(function, "description"), + Schema: function["parameters"], + Strict: boolAt(function, "strict"), + }) + } + request.ToolChoice = decodeChatToolChoice(input["tool_choice"]) + request.ResponseFormat = input["response_format"] + request.ParallelToolCalls = input["parallel_tool_calls"] + request.FrequencyPenalty = input["frequency_penalty"] + request.PresencePenalty = input["presence_penalty"] + request.Seed = input["seed"] + + case ProtocolResponses: + request.MaxTokens = input["max_output_tokens"] + request.Stop = input["stop"] + request.Reasoning = firstAny(input["reasoning"], input["reasoning_effort"]) + instructions, err := decodeOpenAIBlocksChecked(input["instructions"]) + if err != nil { + return request, fmt.Errorf("instructions: %w", err) + } + request.System = append(request.System, instructions...) + switch value := input["input"].(type) { + case string: + request.Messages = append(request.Messages, bridgeMessage{Role: "user", Blocks: []bridgeBlock{{Kind: "text", Text: value}}}) + case []any: + for i, raw := range value { + item, ok := raw.(map[string]any) + if !ok { + return request, fmt.Errorf("input[%d] must be an object", i) + } + switch stringAt(item, "type") { + case "reasoning": + for _, block := range decodeResponsesReasoning(item) { + appendBridgeBlock(&request.Messages, "assistant", block) + } + 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"), + }) + case "function_call_output": + appendBridgeBlock(&request.Messages, "user", bridgeBlock{ + Kind: "tool_result", + CallID: stringAt(item, "call_id"), + Result: item["output"], + }) + case "message", "": + role := stringAt(item, "role") + blocks, err := decodeOpenAIBlocksChecked(item["content"]) + if err != nil { + return request, fmt.Errorf("input[%d]: %w", i, err) + } + if role == "system" { + request.System = append(request.System, blocks...) + } else if role == "developer" { + request.Developer = append(request.Developer, blocks...) + } else if role == "user" || role == "assistant" { + 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")) + } + } + default: + return request, fmt.Errorf("input must be a string or array") + } + for i, raw := range sliceAt(input, "tools") { + tool, ok := raw.(map[string]any) + if !ok || 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"), + Schema: tool["parameters"], + Strict: boolAt(tool, "strict"), + }) + } + request.ToolChoice = decodeResponsesToolChoice(input["tool_choice"]) + request.ResponseFormat = mapAt(input, "text", "format") + request.ParallelToolCalls = input["parallel_tool_calls"] + + case ProtocolAnthropic: + request.MaxTokens = input["max_tokens"] + request.Stop = input["stop_sequences"] + request.Reasoning = firstAny(input["thinking"], 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") { + message, ok := raw.(map[string]any) + if !ok { + return request, fmt.Errorf("messages[%d] must be an object", i) + } + role := 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. + if role == "system" { + blocks, err := decodeAnthropicBlocksChecked(message["content"]) + if err != nil { + return request, fmt.Errorf("messages[%d]: %w", i, err) + } + request.System = append(request.System, blocks...) + continue + } + if role == "developer" { + blocks, err := decodeAnthropicBlocksChecked(message["content"]) + if err != nil { + return request, fmt.Errorf("messages[%d]: %w", i, err) + } + request.Developer = append(request.Developer, blocks...) + continue + } + if role != "user" && role != "assistant" { + return request, fmt.Errorf("messages[%d] has unsupported role %q", i, role) + } + blocks, err := decodeAnthropicBlocksChecked(message["content"]) + if err != nil { + return request, fmt.Errorf("messages[%d]: %w", i, err) + } + request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks}) + } + for i, raw := range 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"), + Schema: tool["input_schema"], + }) + } + request.ToolChoice = decodeAnthropicToolChoice(input["tool_choice"]) + + default: + return request, fmt.Errorf("unsupported input protocol %q", protocol) + } + return request, nil +} + +func appendBridgeBlock(messages *[]bridgeMessage, role string, block bridgeBlock) { + if len(*messages) > 0 { + last := &(*messages)[len(*messages)-1] + if last.Role == role && bridgeBlocksOnlyTools(last.Blocks) { + last.Blocks = append(last.Blocks, block) + return + } + } + *messages = append(*messages, bridgeMessage{Role: role, Blocks: []bridgeBlock{block}}) +} + +func bridgeBlocksOnlyTools(blocks []bridgeBlock) bool { + if len(blocks) == 0 { + return false + } + for _, block := range blocks { + if block.Kind != "tool_call" && block.Kind != "tool_result" { + return false + } + } + return true +} + +func encodeBridgeRequest(protocol Protocol, request bridgeRequest) (map[string]any, error) { + if err := validateBridgeRequest(protocol, request); err != nil { + return nil, err + } + switch protocol { + case ProtocolChat: + return encodeChatRequest(request) + case ProtocolResponses: + return encodeResponsesRequest(request), nil + case ProtocolAnthropic: + return encodeAnthropicRequest(request), nil + default: + return nil, fmt.Errorf("unsupported output protocol %q", protocol) + } +} + +func validateBridgeRequest(protocol Protocol, request bridgeRequest) error { + if protocol == ProtocolResponses { + 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") + } + } + } + blocks := make([]bridgeBlock, 0, len(request.System)+len(request.Developer)) + blocks = append(blocks, request.System...) + blocks = append(blocks, request.Developer...) + for _, message := range request.Messages { + blocks = append(blocks, message.Blocks...) + } + for _, block := range blocks { + if block.Kind == "file" && protocol == ProtocolAnthropic && 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) + } + } + return nil +} + +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) + 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) + if request.Stream { + output["stream_options"] = map[string]any{"include_usage": true} + } + + messages := make([]any, 0, len(request.Messages)+1) + if len(request.System) > 0 { + messages = append(messages, map[string]any{"role": "system", "content": encodeChatBlocks(request.System)}) + } + if len(request.Developer) > 0 { + messages = append(messages, map[string]any{"role": "developer", "content": encodeChatBlocks(request.Developer)}) + } + pending := make(map[string]bool) + pendingResults := make(map[string]bridgeBlock) + var pendingOrder []string + var deferred [][]bridgeBlock + flushDeferred := func() { + for _, blocks := range deferred { + if len(blocks) > 0 { + messages = append(messages, map[string]any{"role": "user", "content": encodeChatBlocks(blocks)}) + } + } + deferred = nil + } + + for i, message := range request.Messages { + var content, reasoning, calls, results []bridgeBlock + for _, block := range message.Blocks { + switch block.Kind { + case "reasoning": + reasoning = append(reasoning, block) + case "tool_call": + calls = append(calls, block) + case "tool_result": + results = append(results, block) + default: + content = append(content, block) + } + } + if message.Role == "assistant" { + if len(pending) > 0 { + return nil, fmt.Errorf("messages[%d]: assistant message appears before tool results for %s", i, strings.Join(missingToolIDs(pendingOrder, pending), ", ")) + } + if len(results) > 0 { + return nil, fmt.Errorf("messages[%d]: assistant message contains tool results", i) + } + encoded := map[string]any{"role": "assistant", "content": nil} + if value, ok := bridgeReasoningText(reasoning); ok { + encoded["reasoning_content"] = value + } + if len(content) > 0 { + encoded["content"] = encodeChatBlocks(content) + } + if len(calls) > 0 { + toolCalls := make([]any, 0, len(calls)) + for _, call := range calls { + if call.ID == "" || call.Name == "" { + return nil, fmt.Errorf("messages[%d]: tool call must contain id and name", i) + } + if pending[call.ID] { + return nil, fmt.Errorf("messages[%d]: duplicate tool call id %q", i, call.ID) + } + pending[call.ID] = true + pendingOrder = append(pendingOrder, call.ID) + toolCalls = append(toolCalls, map[string]any{ + "id": call.ID, + "type": "function", + "function": map[string]any{ + "name": call.Name, + "arguments": bridgeArgumentsJSON(call), + }, + }) + } + encoded["tool_calls"] = toolCalls + } + if len(content) > 0 || len(reasoning) > 0 || len(calls) > 0 { + messages = append(messages, encoded) + } + continue + } + + if len(calls) > 0 { + return nil, fmt.Errorf("messages[%d]: user message contains tool calls", i) + } + for _, result := range results { + if _, duplicate := pendingResults[result.CallID]; duplicate { + return nil, fmt.Errorf("messages[%d]: duplicate tool result %q", i, result.CallID) + } + if !pending[result.CallID] { + return nil, fmt.Errorf("messages[%d]: tool result %q has no pending tool call", i, result.CallID) + } + pendingResults[result.CallID] = result + delete(pending, result.CallID) + } + if len(content) > 0 { + if len(pendingOrder) > 0 || len(deferred) > 0 { + deferred = append(deferred, content) + } else { + messages = append(messages, map[string]any{"role": "user", "content": encodeChatBlocks(content)}) + } + } + if len(pending) == 0 && len(pendingOrder) > 0 { + for _, id := range pendingOrder { + result := pendingResults[id] + messages = append(messages, map[string]any{ + "role": "tool", + "tool_call_id": id, + "content": bridgeToolResultContent(result.Result), + }) + } + flushDeferred() + pendingOrder = nil + clear(pendingResults) + } + } + if len(pending) > 0 { + return nil, fmt.Errorf("tool calls are missing results for %s", strings.Join(missingToolIDs(pendingOrder, pending), ", ")) + } + flushDeferred() + output["messages"] = messages + + if len(request.Tools) > 0 { + tools := make([]any, 0, len(request.Tools)) + for _, tool := range request.Tools { + function := map[string]any{ + "name": tool.Name, + "description": tool.Description, + "parameters": schemaOrDefault(tool.Schema), + } + if tool.Strict { + function["strict"] = true + } + tools = append(tools, map[string]any{"type": "function", "function": function}) + } + output["tools"] = tools + if choice := encodeChatToolChoice(request.ToolChoice); choice != nil { + output["tool_choice"] = choice + } + } + return output, nil +} + +func missingToolIDs(order []string, pending map[string]bool) []string { + missing := make([]string, 0, len(pending)) + for _, id := range order { + if pending[id] { + missing = append(missing, id) + } + } + if len(missing) == len(pending) { + return missing + } + for id := range pending { + found := false + for _, current := range missing { + if current == id { + found = true + break + } + } + if !found { + missing = append(missing, id) + } + } + sort.Strings(missing) + return missing +} + +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) + if len(request.System) > 0 { + output["instructions"] = bridgeBlocksText(request.System) + } + if request.Reasoning != nil { + switch value := request.Reasoning.(type) { + case string: + output["reasoning"] = map[string]any{"effort": value} + default: + output["reasoning"] = value + } + } + if format := responsesTextFormat(request.ResponseFormat); format != nil { + output["text"] = map[string]any{"format": format} + } + put(output, "parallel_tool_calls", request.ParallelToolCalls) + + items := make([]any, 0, len(request.Messages)+1) + if len(request.Developer) > 0 { + items = append(items, map[string]any{ + "type": "message", "role": "developer", + "content": []any{map[string]any{"type": "input_text", "text": bridgeBlocksText(request.Developer)}}, + }) + } + for _, message := range request.Messages { + var content []any + flushContent := func() { + if len(content) == 0 { + return + } + items = append(items, map[string]any{ + "type": "message", + "role": normalizeResponsesRole(message.Role), + "content": content, + }) + content = nil + } + for _, block := range message.Blocks { + switch block.Kind { + case "reasoning": + flushContent() + // Only replay reasoning the upstream actually issued. A block + // that arrived as plain text (Chat/Anthropic history) has no + // server-side id, and synthesizing one guarantees a stale + // reasoning-reference rejection, which previously forced every + // such turn through the strip-and-retry path. + if item, ok := encodeResponsesReasoningInput(block); ok { + items = append(items, item) + } + case "text": + kind := "input_text" + if message.Role == "assistant" { + kind = "output_text" + } + content = append(content, map[string]any{"type": kind, "text": block.Text}) + case "image": + url := block.URL + if url == "" && block.Data != "" { + url = "data:" + block.MediaType + ";base64," + block.Data + } + 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) + content = append(content, item) + case "tool_call": + flushContent() + items = append(items, map[string]any{ + "type": "function_call", + "call_id": block.ID, + "name": block.Name, + "arguments": bridgeArgumentsJSON(block), + }) + case "tool_result": + flushContent() + items = append(items, map[string]any{ + "type": "function_call_output", + "call_id": block.CallID, + "output": bridgeToolResultContent(block.Result), + }) + } + } + flushContent() + } + output["input"] = items + if len(request.Tools) > 0 { + tools := make([]any, 0, len(request.Tools)) + for _, tool := range request.Tools { + tools = append(tools, map[string]any{ + "type": "function", + "name": tool.Name, + "description": tool.Description, + "parameters": schemaOrDefault(tool.Schema), + "strict": tool.Strict, + }) + } + output["tools"] = tools + if choice := encodeResponsesToolChoice(request.ToolChoice); choice != nil { + output["tool_choice"] = choice + } + } + return output +} + +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) + if request.MaxTokens == nil { + output["max_tokens"] = 4096 + } else { + output["max_tokens"] = request.MaxTokens + } + if thinking, outputConfig := anthropicThinking(request.Reasoning); thinking != nil { + output["thinking"] = thinking + if outputConfig != nil { + output["output_config"] = outputConfig + } + } + if len(request.System) > 0 || len(request.Developer) > 0 { + instructions := append([]bridgeBlock(nil), request.System...) + instructions = append(instructions, request.Developer...) + output["system"] = encodeAnthropicBlocks(instructions) + } + + messages := make([]any, 0, len(request.Messages)) + for _, message := range request.Messages { + content := encodeAnthropicBlocks(message.Blocks) + if len(content) == 0 { + continue + } + role := "user" + if message.Role == "assistant" { + role = "assistant" + } + if len(messages) > 0 { + last, _ := messages[len(messages)-1].(map[string]any) + if stringAt(last, "role") == role { + last["content"] = append(asSlice(last["content"]), content...) + continue + } + } + messages = append(messages, map[string]any{"role": role, "content": content}) + } + output["messages"] = messages + // Anthropic has no tool_choice "none" value. Omitting the tools is the + // protocol-compatible representation of an explicitly disabled tool set. + if len(request.Tools) > 0 && request.ToolChoice.Mode != "none" { + tools := make([]any, 0, len(request.Tools)) + for _, tool := range request.Tools { + tools = append(tools, map[string]any{ + "name": tool.Name, + "description": tool.Description, + "input_schema": schemaOrDefault(tool.Schema), + }) + } + output["tools"] = tools + if choice := encodeAnthropicToolChoice(request.ToolChoice); choice != nil { + output["tool_choice"] = choice + } + } + return output +} diff --git a/convert_response.go b/convert_response.go new file mode 100644 index 0000000..a82829b --- /dev/null +++ b/convert_response.go @@ -0,0 +1,398 @@ +package main + +import ( + "encoding/json" + "fmt" + "time" +) + +func convertResponse(from, to Protocol, body []byte) ([]byte, error) { + if from == to { + return append([]byte(nil), body...), nil + } + var input map[string]any + if err := json.Unmarshal(body, &input); err != nil { + return nil, err + } + response, err := decodeBridgeResponse(from, input) + if err != nil { + return nil, err + } + if response.Error != "" || response.Stop == "error" { + return nil, fmt.Errorf("upstream response failed: %s", 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"), + } + if response.Created == 0 { + response.Created = int64At(input, "created_at") + } + if response.Created == 0 { + response.Created = time.Now().Unix() + } + switch protocol { + case ProtocolChat: + if message := stringAt(input, "error", "message"); message != "" { + response.Error = message + } + if response.Error != "" { + return response, nil + } + choices := 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") + response.Reasoning = decodeChatReasoning(message) + blocks, err := decodeOpenAIBlocksChecked(message["content"]) + if err != nil { + return response, fmt.Errorf("chat response content: %w", err) + } + response.Text, err = responseTextBlocks(blocks, "Chat") + if err != nil { + return response, err + } + for _, raw := range sliceAt(message, "tool_calls") { + call, _ := raw.(map[string]any) + function := mapAt(call, "function") + response.Tools = append(response.Tools, bridgeBlock{ + Kind: "tool_call", + ID: stringAt(call, "id"), + Name: stringAt(function, "name"), + ArgumentsJSON: stringAt(function, "arguments"), + }) + } + response.Stop = canonicalChatStop(stringAt(choice, "finish_reason")) + response.Usage = decodeOpenAIUsage(mapAt(input, "usage")) + case ProtocolResponses: + for _, raw := range sliceAt(input, "output") { + item, _ := raw.(map[string]any) + switch stringAt(item, "type") { + case "reasoning": + response.Reasoning = append(response.Reasoning, decodeResponsesReasoning(item)...) + case "message": + blocks, err := decodeOpenAIBlocksChecked(item["content"]) + if err != nil { + return response, fmt.Errorf("Responses response content: %w", err) + } + text, err := responseTextBlocks(blocks, "Responses") + if err != nil { + return response, err + } + response.Text += text + 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"), + }) + default: + return response, fmt.Errorf("Responses response has unsupported output item type %q", 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" { + response.Stop = "error" + response.Error = firstString(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") + } + blocks, err := decodeAnthropicBlocksChecked(input["content"]) + if err != nil { + return response, fmt.Errorf("Anthropic response content: %w", err) + } + for _, block := range blocks { + if block.Kind == "reasoning" { + response.Reasoning = append(response.Reasoning, block) + } else if block.Kind == "text" { + response.Text += block.Text + } else if block.Kind == "tool_call" { + response.Tools = append(response.Tools, block) + } else if block.Kind != "text" { + 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")) + default: + return response, fmt.Errorf("unsupported response protocol %q", protocol) + } + return response, nil +} + +func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string]any { + if response.ID == "" { + response.ID = randomID("resp", 12) + } + switch protocol { + case ProtocolChat: + message := map[string]any{"role": "assistant", "content": response.Text} + if value, ok := bridgeReasoningText(response.Reasoning); ok { + message["reasoning_content"] = value + } + if signature := bridgeReasoningSignature(response.Reasoning); signature != "" { + message["reasoning_signature"] = signature + } + if len(response.Tools) > 0 { + calls := make([]any, 0, len(response.Tools)) + for _, tool := range response.Tools { + calls = append(calls, map[string]any{ + "id": tool.ID, + "type": "function", + "function": map[string]any{ + "name": tool.Name, + "arguments": bridgeArgumentsJSON(tool), + }, + }) + } + message["tool_calls"] = calls + } + return map[string]any{ + "id": asPrefix(response.ID, "chatcmpl"), + "object": "chat.completion", + "created": response.Created, + "model": response.Model, + "choices": []any{map[string]any{ + "index": 0, + "message": message, + "finish_reason": chatStop(response.Stop), + }}, + "usage": openAIUsage(response.Usage), + } + case ProtocolResponses: + output := make([]any, 0, len(response.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), + "type": "message", + "status": "completed", + "role": "assistant", + "content": []any{map[string]any{ + "type": "output_text", + "text": response.Text, + "annotations": []any{}, + }}, + }) + } + for _, tool := range response.Tools { + output = append(output, map[string]any{ + "id": randomID("fc", 12), + "type": "function_call", + "status": "completed", + "call_id": tool.ID, + "name": tool.Name, + "arguments": bridgeArgumentsJSON(tool), + }) + } + status := "completed" + var incomplete any + if response.Stop == "length" || response.Stop == "content_filter" { + status = "incomplete" + incomplete = map[string]any{"reason": responsesIncompleteReason(response.Stop)} + } else if response.Stop == "error" { + status = "failed" + } + return map[string]any{ + "id": asPrefix(response.ID, "resp"), + "object": "response", + "created_at": response.Created, + "status": status, + "model": response.Model, + "output": output, + "error": nil, + "incomplete_details": incomplete, + "usage": map[string]any{ + "input_tokens": response.Usage.Input, + "output_tokens": response.Usage.Output, + "total_tokens": response.Usage.Total, + "input_tokens_details": map[string]any{ + "cached_tokens": response.Usage.Cached, + }, + "output_tokens_details": map[string]any{ + "reasoning_tokens": response.Usage.Reasoning, + }, + }, + } + case ProtocolAnthropic: + content := make([]any, 0, len(response.Reasoning)+len(response.Tools)+1) + content = append(content, encodeAnthropicBlocks(response.Reasoning)...) + if response.Text != "" { + content = append(content, map[string]any{"type": "text", "text": response.Text}) + } + for _, tool := range response.Tools { + input := tool.Arguments + if input == nil { + input = parseJSONOrString(tool.ArgumentsJSON) + } + content = append(content, map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": input}) + } + return map[string]any{ + "id": asPrefix(response.ID, "msg"), + "type": "message", + "role": "assistant", + "model": response.Model, + "content": content, + "stop_reason": anthropicStop(response.Stop), + "stop_sequence": nil, + "usage": anthropicUsage(response.Usage), + } + default: + return map[string]any{} + } +} + +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") + 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"), + ) + 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} +} + +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") + input += cached + cacheCreation + return bridgeUsage{ + Input: input, + Output: output, + Total: input + output, + Cached: cached, + CacheCreation: cacheCreation, + } +} + +func openAIUsage(usage bridgeUsage) map[string]any { + return map[string]any{ + "prompt_tokens": usage.Input, + "completion_tokens": usage.Output, + "total_tokens": usage.Total, + "prompt_tokens_details": map[string]any{ + "cached_tokens": usage.Cached, + }, + "completion_tokens_details": map[string]any{ + "reasoning_tokens": usage.Reasoning, + }, + } +} + +func anthropicUsage(usage bridgeUsage) map[string]any { + return map[string]any{ + "input_tokens": max(usage.Input-usage.Cached-usage.CacheCreation, 0), + "output_tokens": usage.Output, + "cache_creation_input_tokens": usage.CacheCreation, + "cache_read_input_tokens": usage.Cached, + } +} + +func chatStop(stop string) string { + switch stop { + case "tool_use", "tool_calls": + return "tool_calls" + case "max_tokens", "length": + return "length" + case "content_filter", "error": + return stop + default: + return "stop" + } +} + +func anthropicStop(stop string) string { + switch stop { + case "tool_use", "tool_calls": + return "tool_use" + case "max_tokens", "length": + return "max_tokens" + case "stop_sequence", "pause_turn", "refusal": + return stop + default: + return "end_turn" + } +} + +func canonicalChatStop(stop string) string { + switch stop { + case "tool_calls", "function_call": + return "tool_calls" + case "length": + return "length" + case "content_filter": + return "content_filter" + case "error", "network_error", "server_error": + return "error" + default: + return "stop" + } +} + +func canonicalAnthropicStop(stop string) string { + switch stop { + case "tool_use": + return "tool_calls" + case "max_tokens": + return "length" + case "stop_sequence", "pause_turn", "refusal": + return stop + case "error", "network_error", "server_error": + return "error" + default: + return "stop" + } +} + +func canonicalResponsesIncomplete(reason string) string { + switch reason { + case "content_filter": + return "content_filter" + default: + return "length" + } +} + +func responsesIncompleteReason(stop string) string { + if stop == "content_filter" { + return "content_filter" + } + return "max_output_tokens" +} + +func responseTextBlocks(blocks []bridgeBlock, protocol string) (string, error) { + for _, block := range blocks { + if block.Kind != "text" { + return "", fmt.Errorf("%s response contains unsupported %s content block", protocol, block.Kind) + } + } + return bridgeBlocksText(blocks), nil +} diff --git a/convert_test.go b/convert_test.go new file mode 100644 index 0000000..12aff1c --- /dev/null +++ b/convert_test.go @@ -0,0 +1,201 @@ +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/docker-entrypoint.sh b/docker-entrypoint.sh index b771208..12f1abe 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -4,8 +4,10 @@ set -eu state_dir=${STATE_DIR:-/var/lib/opencode2api} config_path=${CONFIG_PATH:-$state_dir/config.json} config_seed_path=${CONFIG_SEED_PATH:-} -listen_address=${LISTEN_ADDRESS:-0.0.0.0:8080} -webui_listen_address=${WEBUI_LISTEN_ADDRESS:-0.0.0.0:8081} +# Empty means "defer to config.json". Only an explicitly provided value becomes +# a command-line override, so the file stays authoritative as documented. +listen_address=${LISTEN_ADDRESS:-} +webui_listen_address=${WEBUI_LISTEN_ADDRESS:-} if [ "$(id -u)" = "0" ]; then mkdir -p "$state_dir" @@ -17,19 +19,35 @@ if [ "$#" -gt 0 ]; then exec "$@" fi +# The example config binds the API to loopback, which is unreachable from +# outside a container through published ports. Rewrite only that exact default +# while seeding; any other address is left exactly as the operator wrote it. +seed_container_listen() { + if grep -q '"listen"[[:space:]]*:[[:space:]]*"127.0.0.1:8080"' "$1"; then + sed -i 's|"listen"[[:space:]]*:[[:space:]]*"127.0.0.1:8080"|"listen": "0.0.0.0:8080"|' "$1" + printf '%s\n' "Seeded $1 with listen 0.0.0.0:8080 so it is reachable through published ports." + fi +} + if [ ! -f "$config_path" ]; then mkdir -p "$(dirname "$config_path")" if [ -n "$config_seed_path" ] && [ -f "$config_seed_path" ]; then cp "$config_seed_path" "$config_path" + seed_container_listen "$config_path" printf '%s\n' "Initialized $config_path from $config_seed_path." else cp /app/config.example.json "$config_path" + seed_container_listen "$config_path" printf '%s\n' \ "config.json not found; created $config_path. Set API keys or enable anonymous mode, and change the WebUI password before use." fi fi -exec /usr/local/bin/opencode2api \ - -config "$config_path" \ - -listen "$listen_address" \ - -web-listen "$webui_listen_address" +set -- /usr/local/bin/opencode2api -config "$config_path" +if [ -n "$listen_address" ]; then + set -- "$@" -listen "$listen_address" +fi +if [ -n "$webui_listen_address" ]; then + set -- "$@" -web-listen "$webui_listen_address" +fi +exec "$@" diff --git a/gateway.go b/gateway.go index 96a6653..3564ac7 100644 --- a/gateway.go +++ b/gateway.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "context" "crypto/subtle" "encoding/json" @@ -11,7 +10,6 @@ import ( "log/slog" "net/http" "strings" - "sync" "time" ) @@ -19,12 +17,6 @@ const maxRequestBody = 32 << 20 const anonymousZenKey = "public" -const ( - proxyHealthCheckURL = "https://cloudflare.com/cdn-cgi/trace" - proxyHealthCheckInterval = 15 * time.Minute - proxyHealthCheckTimeout = 10 * time.Second -) - type Gateway struct { cfg Config logger *slog.Logger @@ -36,43 +28,8 @@ type Gateway struct { monitor *Monitor } -type healthResponse struct { - Status string `json:"status"` - Ready bool `json:"ready"` - Version string `json:"version"` - Models healthModels `json:"models"` - Keys healthKeys `json:"keys"` - Proxies healthProxies `json:"proxies"` - Issues []string `json:"issues,omitempty"` -} - -type healthModels struct { - Status string `json:"status"` - Total int `json:"total"` - Exposed int `json:"exposed"` - Zen int `json:"zen"` - Go int `json:"go"` - LastRefresh *time.Time `json:"last_refresh,omitempty"` - StaleAfterSeconds int `json:"stale_after_seconds"` - CacheSource string `json:"cache_source,omitempty"` - Stale bool `json:"stale"` -} - -type healthKeys struct { - Zen int `json:"zen"` - Go int `json:"go"` - Total int `json:"total"` - Anonymous bool `json:"anonymous"` -} - -type healthProxies struct { - Total int `json:"total"` - Healthy int `json:"healthy"` - Unhealthy int `json:"unhealthy"` -} - func NewGateway(cfg Config, logger *slog.Logger, monitor *Monitor) (*Gateway, error) { - transports, err := newTransportPool(cfg.RuntimeProxies(), cfg.Performance, time.Duration(cfg.Retry.TimeoutSeconds)*time.Second) + transports, err := newTransportPool(cfg.RuntimeProxies(), cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second)) if err != nil { return nil, err } @@ -109,74 +66,6 @@ func (g *Gateway) Handler() http.Handler { return recoveryMiddleware(g.logger, mux) } -func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { - models := g.catalog.Snapshot() - proxyTotal, proxyHealthy := g.transports.healthCounts() - zenKeys, goKeys := g.zenNodes.Len(), g.goNodes.Len() - staleAfter := max(2*time.Duration(g.cfg.Models.RefreshSeconds)*time.Second, time.Minute) - - modelStatus := "ready" - var lastRefresh *time.Time - issues := make([]string, 0, 3) - if models.UpdatedAt.IsZero() { - modelStatus = "pending" - issues = append(issues, "model_catalog_pending") - } else { - updatedAt := models.UpdatedAt.UTC() - lastRefresh = &updatedAt - if models.Exposed == 0 { - modelStatus = "empty" - issues = append(issues, "model_catalog_empty") - } else if models.Stale || time.Since(models.UpdatedAt) > staleAfter { - modelStatus = "stale" - issues = append(issues, "model_catalog_stale") - } - } - if zenKeys+goKeys == 0 && !g.cfg.Anonymous { - issues = append(issues, "no_upstream_keys") - } - if proxyHealthy == 0 { - issues = append(issues, "no_healthy_proxies") - } - - status := "ok" - if len(issues) > 0 { - status = "degraded" - } - blocking := modelStatus == "pending" || modelStatus == "empty" || proxyHealthy == 0 - httpStatus := http.StatusOK - ready := !blocking - if blocking { - httpStatus = http.StatusServiceUnavailable - if modelStatus == "pending" { - status = "starting" - } - } - writeJSON(w, httpStatus, healthResponse{ - Status: status, - Ready: ready, - Version: version, - Models: healthModels{ - Status: modelStatus, - Total: models.Total, - Exposed: models.Exposed, - Zen: models.Zen, - Go: models.Go, - LastRefresh: lastRefresh, - StaleAfterSeconds: int(staleAfter / time.Second), - CacheSource: models.CacheSource, - Stale: models.Stale, - }, - Keys: healthKeys{Zen: zenKeys, Go: goKeys, Total: zenKeys + goKeys, Anonymous: g.cfg.Anonymous}, - Proxies: healthProxies{ - Total: proxyTotal, - Healthy: proxyHealthy, - Unhealthy: proxyTotal - proxyHealthy, - }, - Issues: issues, - }) -} - func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { candidates := []string{strings.TrimSpace(r.Header.Get("x-api-key"))} @@ -203,52 +92,6 @@ func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc { } } -func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { - now := time.Now().Unix() - models := g.catalog.List() - data := make([]map[string]any, 0, len(models)) - for _, model := range models { - if g.cfg.Anonymous && len(g.cfg.ZenKeys) == 0 && len(g.cfg.GoKeys) == 0 && !g.catalog.anonymousDecision(model).Allowed { - continue - } - route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous) - if err != nil { - continue - } - // Tier-scoped metadata: the advertised context window must match - // the tier that will serve the request (anonymous ⇒ Zen). - md := g.catalog.MetadataForTier(model, route.Tier) - entry := map[string]any{ - "id": model, "object": "model", "created": now, "owned_by": "opencode", - "metadata": md, - } - // Top-level OpenAI-standard fields: discovery clients (jcode, Pi, …) - // read context/reasoning at the top level of each model entry. - if md.ContextWindow > 0 { - entry["context_window"] = md.ContextWindow - entry["context_length"] = md.ContextWindow - } - if md.MaxInput > 0 { - entry["max_input"] = md.MaxInput - } - if md.MaxOutput > 0 { - entry["max_output"] = md.MaxOutput - } - if md.Reasoning { - entry["reasoning"] = true - entry["supports_reasoning"] = true - } - if md.ToolCall { - entry["tool_call"] = true - } - if md.StructuredOutput { - entry["structured_output"] = true - } - data = append(data, entry) - } - writeJSON(w, http.StatusOK, map[string]any{"object": "list", "data": data}) -} - func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBody)) @@ -275,12 +118,18 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { return } route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous) + if override, selected := debugKeyOverrideFrom(r.Context()); selected { + // A per-key diagnostic must not silently be served by another key, + // another tier or the anonymous lane. + 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") return } if meta != nil { meta.Tier = string(route.Tier) + meta.Protocol = route.Protocol } bodies, err := g.prepareRouteBodies(external, route, payload) if err != nil { @@ -302,12 +151,19 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { } 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) + return + } writeAPIError(w, external, http.StatusBadGateway, "all upstream attempts failed", "upstream_error", ids.Request) return } defer resp.Body.Close() if meta != nil { meta.Tier = string(upstreamRoute.Tier) + meta.Protocol = upstreamRoute.Protocol } w.Header().Set("x-request-id", ids.Request) if resp.StatusCode/100 != 2 { @@ -335,9 +191,15 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { } if meta != nil { meta.Usage, meta.UsageReported = usage, usageReported + if err != nil { + meta.Outcome = "stream_error" + if streamClientCancelled(r.Context(), err) { + meta.Outcome = "client_canceled" + } + } } if err != nil && !errors.Is(err, context.Canceled) { - g.logger.Debug("downstream stream ended with an error", "component", "stream", "event", "stream_failed", "request_id", ids.Request, "model", model, "tier", route.Tier, "error", err) + g.logger.Warn("downstream stream ended with an error", "component", "stream", "event", "stream_failed", "request_id", ids.Request, "model", model, "tier", upstreamRoute.Tier, "error", err) } return } @@ -407,678 +269,6 @@ func (g *Gateway) prepareRouteBodies(from Protocol, route modelRoute, input map[ return bodies, nil } -func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs) (*http.Response, modelRoute, error) { - resp, effectiveRoute, attempts, err := g.doUpstreamTiers(ctx, route, bodies, ids, 0) - if err != nil || resp == nil || resp.StatusCode != http.StatusBadRequest { - return resp, effectiveRoute, err - } - origBody := resp.Body - errBody, readErr := io.ReadAll(io.LimitReader(origBody, 1<<20)) - // 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) - if readErr != nil { - resp.Body = io.NopCloser(bytes.NewReader(errBody)) - return resp, effectiveRoute, nil - } - // Restore the body so downstream error handling still sees the original - // payload when no retry happens below. - resp.Body = io.NopCloser(bytes.NewReader(errBody)) - if !isStaleReasoningReference(errBody) { - return resp, effectiveRoute, nil - } - stripped, changed := stripStaleReasoningInputs(effectiveRoute, bodies) - if !changed { - return resp, effectiveRoute, nil - } - // The referenced reasoning items belong to an upstream chain this session - // can no longer address (e.g. an interrupted stream). Replay once without - // them under a fresh upstream session instead of failing the client - // request outright. Attempt numbering continues from the first round so - // monitoring never shows duplicate attempt numbers for one request. - retryIDs := ids - retryIDs.Session = randomID("ses", 12) - g.logger.Info("retrying upstream without stale reasoning references", "component", "upstream", "event", "reasoning_reference_retry", "request_id", ids.Request, "model", route.ID, "tier", effectiveRoute.Tier, "attempt_offset", attempts) - retryResp, retryRoute, _, retryErr := g.doUpstreamTiers(ctx, effectiveRoute, stripped, retryIDs, attempts) - if retryErr != nil || retryResp == nil || retryResp.StatusCode/100 != 2 { - retryStatus := 0 - if retryResp != nil { - retryStatus = retryResp.StatusCode - 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 - fallback.Body = io.NopCloser(bytes.NewReader(errBody)) - return &fallback, effectiveRoute, nil - } - return retryResp, retryRoute, nil -} - -// isStaleReasoningReference reports whether an upstream 400 body describes a -// reasoning item/reference the server no longer recognizes, such as -// "Referenced reasoning item 'rs_...' was not found or has expired". -// Generic validation errors that merely mention reasoning (e.g. "unknown -// reasoning field") must NOT match, so both the target phrase and the -// gone/expired marker are required. -func isStaleReasoningReference(body []byte) bool { - text := strings.ToLower(string(body)) - if !strings.Contains(text, "reasoning item") && !strings.Contains(text, "reasoning reference") { - return false - } - for _, marker := range []string{"not found", "expir", "does not exist", "no longer"} { - if strings.Contains(text, marker) { - return true - } - } - return false -} - -// stripStaleReasoningInputs removes server-issued reasoning references from -// 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) { - changed := false - out := make(map[Tier][]byte, len(bodies)) - for tier, body := range bodies { - if len(body) == 0 || route.ProtocolFor(tier) != ProtocolResponses { - out[tier] = body - continue - } - var payload map[string]any - if err := json.Unmarshal(body, &payload); err != nil { - out[tier] = body - continue - } - tierChanged := false - if _, ok := payload["previous_response_id"]; ok { - delete(payload, "previous_response_id") - tierChanged = true - } - 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" { - tierChanged = true - continue - } - kept = append(kept, item) - } - if tierChanged { - payload["input"] = kept - } - } - if !tierChanged { - out[tier] = body - continue - } - encoded, err := json.Marshal(payload) - if err != nil { - out[tier] = body - continue - } - out[tier] = encoded - changed = true - } - 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) { - var lastResponse *http.Response - var lastErr error - effectiveRoute := route - attempts := attemptOffset - if route.Anonymous { - resp, err, used := g.doAnonymousUpstream(ctx, route, bodies, ids, attempts) - attempts += used - if err == nil && resp != nil && resp.StatusCode/100 == 2 { - return resp, route, attempts, nil - } - lastResponse, lastErr = resp, err - if len(route.KeyTiers) > 0 { - g.logger.Debug("anonymous request did not succeed; entering preferred key tiers", "component", "upstream", "event", "anonymous_fallback", "request_id", ids.Request, "attempts", attempts, "key_tiers", route.KeyTiers) - } - } - - keyTiers := route.KeyTiers - if !route.Anonymous && len(keyTiers) == 0 && (route.Tier == TierZen || route.Tier == TierGo) { - keyTiers = []Tier{route.Tier} - } - for _, tier := range keyTiers { - if lastResponse != nil { - drainAndClose(lastResponse.Body) - lastResponse = nil - } - keyRoute := route - keyRoute.Tier = tier - keyRoute.Anonymous = false - keyRoute.Protocol = route.ProtocolFor(tier) - effectiveRoute = keyRoute - resp, err, used := g.doKeyUpstream(ctx, keyRoute, bodies, ids, attempts) - attempts += used - if err == nil && resp != nil && resp.StatusCode/100 == 2 { - return resp, keyRoute, attempts, nil - } - lastResponse, lastErr = resp, err - } - if lastResponse != nil { - return lastResponse, effectiveRoute, attempts, nil - } - if lastErr == nil { - lastErr = errors.New("no usable upstream route") - } - return nil, effectiveRoute, attempts, lastErr -} - -// doAnonymousUpstream tries every currently available proxy at most once. Any -// 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) { - var lastResponse *http.Response - var lastErr error - cursor := g.anonymous.CursorFor(ids.Session) - limit := g.anonymous.Len() - attempts := 0 - body := bodies[TierZen] - if len(body) == 0 { - return nil, errors.New("no prepared Zen request body"), 0 - } - for attempts < limit { - node := cursor.Next() - if node == nil { - break - } - attempts++ - if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil { - meta.Attempts = attemptOffset + attempts - meta.Tier = string(TierZen) - } - if lastResponse != nil { - 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) - started := time.Now() - resp, err := node.proxy.client.Do(req) - duration := time.Since(started) - status := 0 - if resp != nil { - status = resp.StatusCode - } - g.syncProxyResult(ctx, node.proxy, status, err) - g.recordUpstreamAttempt(route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, node.proxy, resp, err, duration) - if err == nil && resp.StatusCode/100 == 2 { - g.anonymous.MarkSuccess(node) - 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()) - return resp, nil, attempts - } - g.anonymous.MarkFailure(node, resp, err) - 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) - } 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()) - } - } - if lastResponse != nil { - return lastResponse, nil, attempts - } - if lastErr == nil { - lastErr = errors.New("no healthy anonymous proxies available") - } - return nil, lastErr, attempts -} - -func (g *Gateway) doKeyUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids 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 { - nodes = g.goNodes - baseURL = g.cfg.Upstream.Go - } - cursor := nodes.CursorFor(ids.Session) - if nodes.Len() == 0 { - return nil, fmt.Errorf("no %s nodes configured", route.Tier), 0 - } - attempts := 0 - body := bodies[route.Tier] - if len(body) == 0 { - return nil, fmt.Errorf("no prepared %s request body", route.Tier), 0 - } - for attempts < g.cfg.Retry.MaxAttempts { - node := cursor.Next() - if node == nil { - break - } - 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 { - meta.Attempts = attemptOffset + attempts - meta.Tier = string(route.Tier) - } - if lastResponse != nil { - drainAndClose(lastResponse.Body) - lastResponse = nil - } - req, err := newUpstreamRequest(ctx, baseURL, route.Protocol, body, ids, node.key) - if err != nil { - return nil, err, attempts - } - proxy := nodes.Proxy(node) - if proxy == nil { - lastErr = errors.New("upstream key has no proxy binding") - break - } - keyID := keyDisplayID(node.key) - setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy) - attemptStarted := time.Now() - resp, err := proxy.client.Do(req) - attemptDuration := time.Since(attemptStarted) - status := 0 - if resp != nil { - status = resp.StatusCode - } - proxyFailed := g.syncProxyResult(ctx, proxy, status, err) - g.recordUpstreamAttempt(route, ids, attemptOffset+attempts, keyID, "key", false, proxy, resp, err, attemptDuration) - if err == nil && resp.StatusCode/100 == 2 { - nodes.MarkSuccess(node) - 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()) - return resp, nil, attempts - } - // Request-shape errors are deterministic and must leave this tier without - // rotating through unrelated keys. The outer route may still try the next - // tier in prefer order. Authentication, throttling, server, and transport - // failures remain retryable inside this tier. - if isNonRetryableClientResponse(resp, err) { - nodes.MarkSuccess(node) - 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()) - return resp, nil, attempts - } - if proxyFailed { - if nodes.Proxy(node) == proxy { - nodes.MarkFailure(node, resp, err) - } - } else { - nodes.MarkFailure(node, resp, err) - } - 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) - } 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()) - } - } - if lastResponse != nil { - return lastResponse, nil, attempts - } - return nil, lastErr, attempts -} - -func setRequestCredential(ctx context.Context, tier Tier, keyID, channel string, anonymous bool, proxy *proxyTransport) { - meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta) - if meta == nil { - return - } - meta.Tier = string(tier) - meta.KeyID = keyID - meta.Channel = channel - meta.Anonymous = anonymous - meta.Proxy = "" - if proxy != nil { - meta.Proxy = redactURL(proxy.name) - } -} - -func requestCredential(ctx context.Context) (string, string, bool) { - meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta) - 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(route modelRoute, ids requestIDs, attempt int, keyID, channel string, anonymous bool, proxy *proxyTransport, resp *http.Response, err error, duration time.Duration) { - if g.monitor == nil { - return - } - status := 0 - if resp != nil { - status = resp.StatusCode - } - success := err == nil && status >= 200 && status < 300 - outcome := "retryable_failure" - if success { - outcome = "success" - } else if err != nil { - outcome = "transport_error" - } else if isNonRetryableClientResponse(resp, nil) { - outcome = "rejected" - } - proxyName := "unavailable" - if proxy != nil { - proxyName = redactURL(proxy.name) - } - g.monitor.RecordAttempt(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) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "application/json, text/event-stream") - req.Header.Set("User-Agent", opencodeUserAgent()) - req.Header.Set("x-opencode-client", "cli") - req.Header.Set("x-opencode-session", ids.Session) - // OpenCode 1.18.x sends these correlation headers to preserve provider-side - // prompt/session affinity. Keep the legacy x-opencode-session header too so - // older Zen deployments continue to recognize the request. - req.Header.Set("x-session-affinity", ids.Session) - req.Header.Set("X-Session-Id", ids.Session) - req.Header.Set("x-opencode-request", ids.Request) - req.Header.Set("x-opencode-project", ids.Project) - if ids.ParentSession != "" { - req.Header.Set("x-parent-session-id", ids.ParentSession) - } - if protocol == ProtocolAnthropic { - 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") - } else { - req.Header.Set("Authorization", "Bearer "+key) - } - return req, nil -} - -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 -} - -// syncProxyResult updates proxy health from real traffic. Only timeouts and -// connection refusals mark a proxy unavailable. Other errors and 4xx/5xx -// responses trigger a neutral URL check without being treated as proxy failure. -func (g *Gateway) syncProxyResult(ctx context.Context, proxy *proxyTransport, status int, err error) bool { - if proxy == nil { - return false - } - if isProxyFailure(err) { - g.rebindFailedProxy(proxy) - g.verifyProxyAfterError(ctx, proxy, status) - return true - } - if status >= 200 && status < 400 { - wasHealthy := proxy.healthy.Swap(true) - if !wasHealthy { - g.restoreProxy(proxy) - } - return false - } - if err != nil { - g.verifyProxyAfterError(ctx, proxy, status) - return false - } - if status >= 400 && status < 600 { - g.verifyProxyAfterError(ctx, proxy, status) - } - return false -} - -func (g *Gateway) verifyProxyAfterError(ctx context.Context, proxy *proxyTransport, status int) { - if !proxy.checking.CompareAndSwap(false, true) { - return - } - // The client request may finish or be cancelled while the verification is - // running. Keep its values but give the proxy check an independent timeout. - checkCtx := context.WithoutCancel(ctx) - go func() { - result := g.transports.checkClaimedProxy(checkCtx, proxy, proxyHealthCheckURL, proxyHealthCheckTimeout) - g.applyProxyHealthResult(result, "upstream HTTP response", status) - }() -} - -func (g *Gateway) rebindFailedProxy(proxy *proxyTransport) (zenMoved, goMoved int) { - if proxy == nil { - return 0, 0 - } - wasHealthy := proxy.healthy.Swap(false) - return g.rebindUnavailableProxy(proxy, wasHealthy) -} - -func (g *Gateway) rebindUnavailableProxy(proxy *proxyTransport, wasHealthy bool) (zenMoved, goMoved int) { - 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) - } - return zenMoved, goMoved -} - -func (g *Gateway) restoreProxy(proxy *proxyTransport) (zenMoved, goMoved int) { - if proxy == nil { - return 0, 0 - } - 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) - } - return zenMoved, goMoved -} - -func (g *Gateway) StartProxyHealthChecks(ctx context.Context) { - check := func() { - results := g.transports.CheckHealth(ctx, proxyHealthCheckURL, proxyHealthCheckTimeout) - for _, result := range results { - g.applyProxyHealthResult(result, "scheduled health check", 0) - } - } - go func() { - ticker := time.NewTicker(proxyHealthCheckInterval) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - check() - } - } - }() -} - -func (g *Gateway) applyProxyHealthResult(result proxyHealthResult, source string, upstreamStatus int) { - if result.err == nil { - 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)) - 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) - 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) - 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) -} - -func protocolPath(protocol Protocol) string { - switch protocol { - case ProtocolResponses: - return "/v1/responses" - case ProtocolAnthropic: - return "/v1/messages" - default: - return "/v1/chat/completions" - } -} - -func (g *Gateway) StartModelRefresh(ctx context.Context) { - refresh := func() { - var zen, goModels []string - var capabilities protocolCapabilities - var capabilitiesErr error - var wg sync.WaitGroup - wg.Add(3) - go func() { defer wg.Done(); zen = g.refreshZen(ctx) }() - go func() { defer wg.Done(); goModels = g.refreshTier(ctx, g.cfg.Upstream.Go, g.goNodes) }() - go func() { - defer wg.Done() - capabilityCtx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() - capabilities, capabilitiesErr = g.refreshProtocolCapabilities(capabilityCtx) - }() - wg.Wait() - if ctx.Err() != nil { - return - } - if capabilitiesErr != nil { - g.logger.Warn("OpenCode capability catalog refresh failed", "component", "models", "event", "capability_refresh_failed", "error", capabilitiesErr) - } - if zen != nil || goModels != nil { - g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata) - if ctx.Err() == nil { - if err := g.catalog.SaveCache(); err != nil { - g.logger.Warn("model catalog cache write failed", "component", "models", "event", "catalog_cache_write_failed", "error", err) - } - } - g.logger.Info("model catalog refreshed", "component", "models", "event", "catalog_refreshed", "models", len(g.catalog.List())) - } - } - go func() { - refresh() - ticker := time.NewTicker(time.Duration(g.cfg.Models.RefreshSeconds) * time.Second) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - refresh() - } - } - }() -} - -func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (protocolCapabilities, error) { - if g.transports == nil || len(g.transports.items) == 0 { - return fetchProtocolCapabilities(ctx, &http.Client{Timeout: 30 * time.Second}, openCodeCapabilitiesURL) - } - var lastErr error - for _, proxy := range g.transports.items { - if proxy == nil || !proxy.healthy.Load() { - continue - } - capabilities, err := fetchProtocolCapabilities(ctx, proxy.client, openCodeCapabilitiesURL) - if err == nil { - return capabilities, nil - } - lastErr = err - } - if lastErr == nil { - lastErr = errors.New("no healthy proxy available for OpenCode capability catalog") - } - return protocolCapabilities{}, lastErr -} - -func (g *Gateway) refreshZen(ctx context.Context) []string { - if models := g.refreshTier(ctx, g.cfg.Upstream.Zen, g.zenNodes); models != nil { - return models - } - if !g.cfg.Anonymous { - return nil - } - return g.refreshAnonymousTier(ctx, g.cfg.Upstream.Zen) -} - -func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []string { - cursor := g.anonymous.CursorFor("") - limit := g.anonymous.Len() - for attempt := 1; attempt <= limit; attempt++ { - node := cursor.Next() - if node == nil { - break - } - refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) - models, status, err := fetchModels(refreshCtx, node.proxy.client, base, anonymousZenKey) - g.syncProxyResult(refreshCtx, node.proxy, status, err) - cancel() - if err == nil { - g.anonymous.MarkSuccess(node) - 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.Warn("anonymous model catalog refresh failed", "component", "models", "event", "anonymous_refresh_failed", "upstream", redactURL(base)) - return nil -} - -func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool) []string { - cursor := nodes.Cursor() - for attempt := 0; attempt < g.cfg.Retry.MaxAttempts; attempt++ { - node := cursor.Next() - if node == nil { - return nil - } - refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) - proxy := nodes.Proxy(node) - if proxy == nil { - cancel() - return nil - } - models, status, err := fetchModels(refreshCtx, proxy.client, base, node.key) - g.syncProxyResult(refreshCtx, proxy, status, err) - cancel() - if err == nil { - nodes.MarkSuccess(node) - 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.Warn("model catalog refresh failed", "component", "models", "event", "refresh_failed", "upstream", redactURL(base)) - return nil -} - func copyErrorResponse(w http.ResponseWriter, protocol Protocol, resp *http.Response, requestID string) { body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" { diff --git a/gateway_health.go b/gateway_health.go new file mode 100644 index 0000000..ec7c49b --- /dev/null +++ b/gateway_health.go @@ -0,0 +1,153 @@ +package main + +import ( + "net/http" + "time" +) + +type healthResponse struct { + Status string `json:"status"` + Ready bool `json:"ready"` + Version string `json:"version"` + Models healthModels `json:"models"` + Keys healthKeys `json:"keys"` + Proxies healthProxies `json:"proxies"` + Issues []string `json:"issues,omitempty"` +} + +type healthModels struct { + Status string `json:"status"` + Total int `json:"total"` + Exposed int `json:"exposed"` + Zen int `json:"zen"` + Go int `json:"go"` + LastRefresh *time.Time `json:"last_refresh,omitempty"` + StaleAfterSeconds int `json:"stale_after_seconds"` + CacheSource string `json:"cache_source,omitempty"` + Stale bool `json:"stale"` +} + +type healthKeys struct { + Zen int `json:"zen"` + Go int `json:"go"` + Total int `json:"total"` + Anonymous bool `json:"anonymous"` +} + +type healthProxies struct { + Total int `json:"total"` + Healthy int `json:"healthy"` + Unhealthy int `json:"unhealthy"` +} + +func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { + _, models := g.availableModels() + proxyTotal, proxyHealthy := g.transports.healthCounts() + zenKeys, goKeys := g.zenNodes.Len(), g.goNodes.Len() + staleAfter := max(2*time.Duration(g.cfg.Models.RefreshSeconds)*time.Second, time.Minute) + + modelStatus := "ready" + var lastRefresh *time.Time + issues := make([]string, 0, 3) + if models.UpdatedAt.IsZero() { + modelStatus = "pending" + issues = append(issues, "model_catalog_pending") + } else { + updatedAt := models.UpdatedAt.UTC() + lastRefresh = &updatedAt + if models.Exposed == 0 { + modelStatus = "empty" + issues = append(issues, "model_catalog_empty") + } else if models.Stale || time.Since(models.UpdatedAt) > staleAfter { + modelStatus = "stale" + issues = append(issues, "model_catalog_stale") + } + } + if zenKeys+goKeys == 0 && !g.cfg.Anonymous { + issues = append(issues, "no_upstream_keys") + } + if proxyHealthy == 0 { + issues = append(issues, "no_healthy_proxies") + } + + status := "ok" + if len(issues) > 0 { + status = "degraded" + } + blocking := modelStatus == "pending" || modelStatus == "empty" || proxyHealthy == 0 + httpStatus := http.StatusOK + ready := !blocking + if blocking { + httpStatus = http.StatusServiceUnavailable + if modelStatus == "pending" { + status = "starting" + } + } + writeJSON(w, httpStatus, healthResponse{ + Status: status, + Ready: ready, + Version: version, + Models: healthModels{ + Status: modelStatus, + Total: models.Total, + Exposed: models.Exposed, + Zen: models.Zen, + Go: models.Go, + LastRefresh: lastRefresh, + StaleAfterSeconds: int(staleAfter / time.Second), + CacheSource: models.CacheSource, + Stale: models.Stale, + }, + Keys: healthKeys{Zen: zenKeys, Go: goKeys, Total: zenKeys + goKeys, Anonymous: g.cfg.Anonymous}, + Proxies: healthProxies{ + Total: proxyTotal, + Healthy: proxyHealthy, + Unhealthy: proxyTotal - proxyHealthy, + }, + Issues: issues, + }) +} + +func (g *Gateway) availableModels() ([]modelRoute, modelCatalogSnapshot) { + return g.catalog.AvailableModels(g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) +} + +func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { + now := time.Now().Unix() + routes, _ := g.availableModels() + data := make([]map[string]any, 0, len(routes)) + for _, route := range routes { + model := route.ID + // Tier-scoped metadata: the advertised context window must match + // the tier that will serve the request (anonymous ⇒ Zen). + md := g.catalog.MetadataForTier(model, route.Tier) + entry := map[string]any{ + "id": model, "object": "model", "created": now, "owned_by": "opencode", + "metadata": md, + } + // Top-level OpenAI-standard fields: discovery clients (jcode, Pi, …) + // read context/reasoning at the top level of each model entry. + if md.ContextWindow > 0 { + entry["context_window"] = md.ContextWindow + entry["context_length"] = md.ContextWindow + } + if md.MaxInput > 0 { + entry["max_input"] = md.MaxInput + } + if md.MaxOutput > 0 { + entry["max_output"] = md.MaxOutput + } + if md.Reasoning { + entry["reasoning"] = true + entry["supports_reasoning"] = true + } + if md.ToolCall { + entry["tool_call"] = true + } + if md.StructuredOutput { + entry["structured_output"] = true + } + data = append(data, entry) + } + writeJSON(w, http.StatusOK, map[string]any{"object": "list", "data": data}) +} diff --git a/gateway_health_test.go b/gateway_health_test.go new file mode 100644 index 0000000..3d62af2 --- /dev/null +++ b/gateway_health_test.go @@ -0,0 +1,76 @@ +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_refresh.go b/gateway_refresh.go new file mode 100644 index 0000000..e431fa7 --- /dev/null +++ b/gateway_refresh.go @@ -0,0 +1,257 @@ +package main + +import ( + "context" + "errors" + "net/http" + "sync" + "time" +) + +const ( + proxyHealthCheckURL = "https://cloudflare.com/cdn-cgi/trace" + proxyHealthCheckInterval = 15 * time.Minute + proxyHealthCheckTimeout = 10 * time.Second +) + +// syncProxyResult updates proxy health from real traffic. Only timeouts and +// connection refusals mark a proxy unavailable. Other errors and 4xx/5xx +// responses trigger a neutral URL check without being treated as proxy failure. +func (g *Gateway) syncProxyResult(ctx context.Context, proxy *proxyTransport, status int, err error) bool { + if proxy == nil { + return false + } + if isProxyFailure(err) { + g.rebindFailedProxy(proxy) + g.verifyProxyAfterError(ctx, proxy, status) + return true + } + if status >= 200 && status < 400 { + wasHealthy := proxy.healthy.Swap(true) + if !wasHealthy { + g.restoreProxy(proxy) + } + return false + } + if err != nil { + g.verifyProxyAfterError(ctx, proxy, status) + return false + } + if status >= 400 && status < 600 { + g.verifyProxyAfterError(ctx, proxy, status) + } + return false +} + +func (g *Gateway) verifyProxyAfterError(ctx context.Context, proxy *proxyTransport, status int) { + if !proxy.checking.CompareAndSwap(false, true) { + return + } + // The client request may finish or be cancelled while the verification is + // running. Keep its values but give the proxy check an independent timeout. + checkCtx := context.WithoutCancel(ctx) + go func() { + result := g.transports.checkClaimedProxy(checkCtx, proxy, proxyHealthCheckURL, proxyHealthCheckTimeout) + g.applyProxyHealthResult(result, "upstream HTTP response", status) + }() +} + +func (g *Gateway) rebindFailedProxy(proxy *proxyTransport) (zenMoved, goMoved int) { + if proxy == nil { + return 0, 0 + } + wasHealthy := proxy.healthy.Swap(false) + return g.rebindUnavailableProxy(proxy, wasHealthy) +} + +func (g *Gateway) rebindUnavailableProxy(proxy *proxyTransport, wasHealthy bool) (zenMoved, goMoved int) { + 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) + } + return zenMoved, goMoved +} + +func (g *Gateway) restoreProxy(proxy *proxyTransport) (zenMoved, goMoved int) { + if proxy == nil { + return 0, 0 + } + 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) + } + return zenMoved, goMoved +} + +func (g *Gateway) StartProxyHealthChecks(ctx context.Context) { + check := func() { + results := g.transports.CheckHealth(ctx, proxyHealthCheckURL, proxyHealthCheckTimeout) + for _, result := range results { + g.applyProxyHealthResult(result, "scheduled health check", 0) + } + } + go func() { + ticker := time.NewTicker(proxyHealthCheckInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + check() + } + } + }() +} + +func (g *Gateway) applyProxyHealthResult(result proxyHealthResult, source string, upstreamStatus int) { + if result.err == nil { + 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)) + 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) + 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) + 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) +} + +func (g *Gateway) StartModelRefresh(ctx context.Context) { + refresh := func() { + var zen, goModels []string + var capabilities protocolCapabilities + var capabilitiesErr error + var wg sync.WaitGroup + wg.Add(3) + go func() { defer wg.Done(); zen = g.refreshZen(ctx) }() + go func() { defer wg.Done(); goModels = g.refreshTier(ctx, g.cfg.Upstream.Go, g.goNodes) }() + go func() { + defer wg.Done() + capabilityCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + capabilities, capabilitiesErr = g.refreshProtocolCapabilities(capabilityCtx) + }() + wg.Wait() + if ctx.Err() != nil { + return + } + if capabilitiesErr != nil { + g.logger.Warn("OpenCode capability catalog refresh failed", "component", "models", "event", "capability_refresh_failed", "error", capabilitiesErr) + } + if zen != nil || goModels != nil { + g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata) + if ctx.Err() == nil { + if err := g.catalog.SaveCache(); err != nil { + g.logger.Warn("model catalog cache write failed", "component", "models", "event", "catalog_cache_write_failed", "error", err) + } + } + g.logger.Info("model catalog refreshed", "component", "models", "event", "catalog_refreshed", "models", len(g.catalog.List())) + } + } + go func() { + refresh() + ticker := time.NewTicker(time.Duration(g.cfg.Models.RefreshSeconds) * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + refresh() + } + } + }() +} + +func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (protocolCapabilities, error) { + if g.transports == nil || len(g.transports.items) == 0 { + return fetchProtocolCapabilities(ctx, &http.Client{Timeout: 30 * time.Second}, openCodeCapabilitiesURL) + } + var lastErr error + for _, proxy := range g.transports.items { + if proxy == nil || !proxy.healthy.Load() { + continue + } + capabilities, err := fetchProtocolCapabilities(ctx, proxy.client, openCodeCapabilitiesURL) + if err == nil { + return capabilities, nil + } + lastErr = err + } + if lastErr == nil { + lastErr = errors.New("no healthy proxy available for OpenCode capability catalog") + } + return protocolCapabilities{}, lastErr +} + +func (g *Gateway) refreshZen(ctx context.Context) []string { + if models := g.refreshTier(ctx, g.cfg.Upstream.Zen, g.zenNodes); models != nil { + return models + } + if !g.cfg.Anonymous { + return nil + } + return g.refreshAnonymousTier(ctx, g.cfg.Upstream.Zen) +} + +func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []string { + cursor := g.anonymous.CursorFor("") + limit := g.anonymous.Len() + for attempt := 1; attempt <= limit; attempt++ { + node := cursor.Next() + if node == nil { + break + } + refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + models, status, err := fetchModels(refreshCtx, node.proxy.client, base, anonymousZenKey) + g.syncProxyResult(refreshCtx, node.proxy, status, err) + cancel() + if err == nil { + g.anonymous.MarkSuccess(node) + 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.Warn("anonymous model catalog refresh failed", "component", "models", "event", "anonymous_refresh_failed", "upstream", redactURL(base)) + return nil +} + +func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool) []string { + cursor := nodes.Cursor() + for attempt := 0; attempt < g.cfg.Retry.MaxAttempts; attempt++ { + node := cursor.Next() + if node == nil { + return nil + } + refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + proxy := nodes.Proxy(node) + if proxy == nil { + cancel() + return nil + } + models, status, err := fetchModels(refreshCtx, proxy.client, base, node.key) + g.syncProxyResult(refreshCtx, proxy, status, err) + cancel() + if err == nil { + nodes.MarkSuccess(node) + 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.Warn("model catalog refresh failed", "component", "models", "event", "refresh_failed", "upstream", redactURL(base)) + return nil +} diff --git a/gateway_stream_test.go b/gateway_stream_test.go new file mode 100644 index 0000000..bc24299 --- /dev/null +++ b/gateway_stream_test.go @@ -0,0 +1,181 @@ +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 new file mode 100644 index 0000000..705461a --- /dev/null +++ b/gateway_test.go @@ -0,0 +1,148 @@ +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/logging.go b/logging.go new file mode 100644 index 0000000..b1b57d7 --- /dev/null +++ b/logging.go @@ -0,0 +1,299 @@ +package main + +import ( + "context" + "fmt" + "io" + "log/slog" + "net/url" + "os" + "sort" + "strings" + "sync" + "sync/atomic" + "time" +) + +type LogEvent struct { + Sequence uint64 `json:"sequence"` + Time time.Time `json:"time"` + Level string `json:"level"` + Message string `json:"message"` + Component string `json:"component,omitempty"` + Fields map[string]any `json:"fields,omitempty"` +} + +type logSubscriber struct { + ch chan LogEvent +} + +type LogHub struct { + mu sync.RWMutex + buffer []LogEvent + start int + count int + next uint64 + subscribers map[uint64]*logSubscriber + nextSub uint64 +} + +func NewLogHub(capacity int) *LogHub { + if capacity < 100 { + capacity = 100 + } + return &LogHub{buffer: make([]LogEvent, capacity), subscribers: make(map[uint64]*logSubscriber)} +} + +func (h *LogHub) Resize(capacity int) { + if capacity < 100 { + capacity = 100 + } + h.mu.Lock() + if capacity == len(h.buffer) { + h.mu.Unlock() + return + } + keep := min(h.count, capacity) + next := make([]LogEvent, capacity) + for i := 0; i < keep; i++ { + source := (h.start + h.count - keep + i) % len(h.buffer) + next[i] = h.buffer[source] + } + h.buffer, h.start, h.count = next, 0, keep + h.mu.Unlock() +} + +func (h *LogHub) Publish(event LogEvent) { + h.mu.Lock() + h.next++ + event.Sequence = h.next + if h.count < len(h.buffer) { + index := (h.start + h.count) % len(h.buffer) + h.buffer[index] = event + h.count++ + } else { + h.buffer[h.start] = event + h.start = (h.start + 1) % len(h.buffer) + } + for _, sub := range h.subscribers { + select { + case sub.ch <- event: + default: + // A slow browser must never block request processing. Its reconnect + // cursor will make the gap visible on the next subscription. + } + } + h.mu.Unlock() +} + +func (h *LogHub) Recent(after uint64, limit int) ([]LogEvent, bool) { + h.mu.RLock() + defer h.mu.RUnlock() + if limit < 1 || limit > len(h.buffer) { + limit = len(h.buffer) + } + oldest := uint64(0) + if h.count > 0 { + oldest = h.buffer[h.start].Sequence + } + gap := after > 0 && oldest > 0 && after+1 < oldest + out := make([]LogEvent, 0, min(limit, h.count)) + for i := 0; i < h.count; i++ { + event := h.buffer[(h.start+i)%len(h.buffer)] + if event.Sequence > after { + out = append(out, event) + } + } + if len(out) > limit { + out = out[len(out)-limit:] + } + return out, gap +} + +func (h *LogHub) Subscribe() (<-chan LogEvent, func()) { + h.mu.Lock() + h.nextSub++ + id := h.nextSub + sub := &logSubscriber{ch: make(chan LogEvent, 128)} + h.subscribers[id] = sub + h.mu.Unlock() + return sub.ch, func() { + h.mu.Lock() + delete(h.subscribers, id) + h.mu.Unlock() + } +} + +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 + attrs []slog.Attr + groups []string +} + +func NewStructuredLogger(level *slog.LevelVar, hub *LogHub, redactor *SecretRedactor) *slog.Logger { + return newStructuredLogger(os.Stdout, level, hub, redactor) +} + +func newStructuredLogger(output io.Writer, level *slog.LevelVar, hub *LogHub, redactor *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 { + 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") { + return slog.String(attr.Key, "***") + } + switch attr.Value.Kind() { + case slog.KindString: + attr.Value = slog.StringValue(redactor.String(attr.Value.String())) + case slog.KindAny: + if err, ok := attr.Value.Any().(error); ok { + attr.Value = slog.StringValue(redactor.String(err.Error())) + } + } + return attr +} + +func (h *hubHandler) Enabled(ctx context.Context, level slog.Level) bool { + return h.base.Enabled(ctx, level) +} + +func (h *hubHandler) Handle(ctx context.Context, record slog.Record) error { + if err := h.base.Handle(ctx, record); err != nil { + return err + } + fields := make(map[string]any, record.NumAttrs()+len(h.attrs)) + for _, attr := range h.attrs { + h.addAttr(fields, attr) + } + record.Attrs(func(attr slog.Attr) bool { + h.addAttr(fields, attr) + return true + }) + component, _ := fields["component"].(string) + delete(fields, "component") + h.hub.Publish(LogEvent{ + Time: record.Time.UTC(), + Level: strings.ToLower(record.Level.String()), + Message: h.redactor.String(record.Message), + Component: component, + Fields: fields, + }) + return nil +} + +func (h *hubHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + clone := *h + clone.base = h.base.WithAttrs(attrs) + clone.attrs = append(append([]slog.Attr(nil), h.attrs...), attrs...) + return &clone +} + +func (h *hubHandler) WithGroup(name string) slog.Handler { + clone := *h + clone.base = h.base.WithGroup(name) + clone.groups = append(append([]string(nil), h.groups...), name) + return &clone +} + +func (h *hubHandler) addAttr(fields map[string]any, attr slog.Attr) { + attr.Value = attr.Value.Resolve() + key := attr.Key + if len(h.groups) > 0 { + key = strings.Join(append(append([]string(nil), h.groups...), key), ".") + } + lower := strings.ToLower(key) + if strings.Contains(lower, "password") || strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "secret") { + fields[key] = "***" + return + } + var value any + switch attr.Value.Kind() { + case slog.KindString: + value = h.redactor.String(attr.Value.String()) + case slog.KindInt64: + value = attr.Value.Int64() + case slog.KindUint64: + value = attr.Value.Uint64() + case slog.KindFloat64: + value = attr.Value.Float64() + case slog.KindBool: + value = attr.Value.Bool() + case slog.KindDuration: + value = attr.Value.Duration().String() + case slog.KindTime: + value = attr.Value.Time().UTC() + default: + value = h.redactor.String(fmt.Sprint(attr.Value.Any())) + } + fields[key] = value +} + +func setLogLevel(level *slog.LevelVar, value string) { + switch value { + case "debug": + level.Set(slog.LevelDebug) + case "warn": + level.Set(slog.LevelWarn) + case "error": + level.Set(slog.LevelError) + default: + level.Set(slog.LevelInfo) + } +} diff --git a/metrics.go b/metrics.go new file mode 100644 index 0000000..7e494fb --- /dev/null +++ b/metrics.go @@ -0,0 +1,612 @@ +package main + +import ( + "fmt" + "sync" + "sync/atomic" + "time" +) + +type metricBucket struct { + minute int64 + total uint64 + success uint64 + errors uint64 + duration uint64 + histogram [11]uint64 + endpoints map[string]uint64 + models map[string]uint64 + tiers map[string]uint64 + statuses map[string]uint64 + usageRequests uint64 + usageReported uint64 + tokens TokenCounts + usageModels map[string]TokenCounts + usageTiers map[string]TokenCounts +} + +func (b *metricBucket) reset(minute int64) { + *b = metricBucket{ + minute: minute, endpoints: make(map[string]uint64), models: make(map[string]uint64), + tiers: make(map[string]uint64), statuses: make(map[string]uint64), + usageModels: make(map[string]TokenCounts), usageTiers: make(map[string]TokenCounts), + } +} + +type TokenCounts struct { + Input uint64 `json:"input_tokens"` + Output uint64 `json:"output_tokens"` + Cached uint64 `json:"cached_tokens"` + Reasoning uint64 `json:"reasoning_tokens"` + Total uint64 `json:"total_tokens"` +} + +type UsagePeriod struct { + Requests uint64 `json:"requests"` + Reported uint64 `json:"reported"` + Coverage float64 `json:"coverage"` + Tokens TokenCounts `json:"tokens"` + Models map[string]TokenCounts `json:"models"` + Tiers map[string]TokenCounts `json:"tiers"` +} + +type UsageSnapshot struct { + Lifetime UsagePeriod `json:"lifetime"` + Window UsagePeriod `json:"last_hour"` +} + +type AttemptCounts struct { + Total uint64 `json:"total"` + Success uint64 `json:"success"` + Failed uint64 `json:"failed"` +} + +type AttemptAggregate struct { + AttemptCounts + SuccessRate float64 `json:"success_rate"` + Tiers map[string]AttemptCounts `json:"tiers"` + Channels map[string]AttemptCounts `json:"channels"` + Keys map[string]AttemptCounts `json:"keys"` +} + +type UpstreamAttempt struct { + Time time.Time `json:"time"` + RequestID string `json:"request_id"` + Model string `json:"model"` + Tier string `json:"tier"` + Attempt int `json:"attempt"` + KeyID string `json:"key_id"` + Channel string `json:"channel"` + Anonymous bool `json:"anonymous"` + Proxy string `json:"proxy_node"` + Status int `json:"status,omitempty"` + DurationMS int64 `json:"duration_ms"` + Success bool `json:"success"` + Outcome string `json:"outcome"` +} + +// UpstreamRequest is the credential route that was actually used for one +// client inference request. It is kept separately from UpstreamAttempt, +// because a single request can try several keys before it succeeds. +type UpstreamRequest struct { + Time time.Time `json:"time"` + RequestID string `json:"request_id"` + Model string `json:"model"` + Tier string `json:"tier,omitempty"` + KeyID string `json:"key_id,omitempty"` + Channel string `json:"channel"` + Anonymous bool `json:"anonymous"` + Proxy string `json:"proxy_node,omitempty"` + Attempts int `json:"attempts"` + Status int `json:"status"` + DurationMS int64 `json:"duration_ms"` + Success bool `json:"success"` + Outcome string `json:"outcome"` +} + +type attemptBucket struct { + minute int64 + aggregate AttemptAggregate +} + +type UpstreamSnapshot struct { + Lifetime AttemptAggregate `json:"lifetime"` + Window AttemptAggregate `json:"last_hour"` + Requests []UpstreamRequest `json:"requests"` + Recent []UpstreamAttempt `json:"recent"` +} + +const ( + monitorRecentRequestCapacity = 10000 + monitorRecentAttemptCapacity = 20000 + monitorRecentOutputLimit = 500 +) + +type upstreamRequestRing struct { + items []UpstreamRequest + start int + count int +} + +func newUpstreamRequestRing() upstreamRequestRing { + return upstreamRequestRing{items: make([]UpstreamRequest, monitorRecentRequestCapacity)} +} + +func (ring *upstreamRequestRing) Add(value UpstreamRequest) { + if len(ring.items) == 0 { + ring.items = make([]UpstreamRequest, monitorRecentRequestCapacity) + } + index := (ring.start + ring.count) % len(ring.items) + if ring.count == len(ring.items) { + ring.items[index] = value + ring.start = (ring.start + 1) % len(ring.items) + return + } + ring.items[index] = value + ring.count++ +} + +func (ring *upstreamRequestRing) PruneBefore(cutoff time.Time) { + for ring.count > 0 && ring.items[ring.start].Time.Before(cutoff) { + ring.items[ring.start] = UpstreamRequest{} + ring.start = (ring.start + 1) % len(ring.items) + ring.count-- + } +} + +func (ring *upstreamRequestRing) Snapshot(cutoff time.Time, limit int) []UpstreamRequest { + if limit < 1 || ring.count == 0 { + return nil + } + result := make([]UpstreamRequest, 0, min(ring.count, limit)) + for offset := 0; offset < ring.count; offset++ { + value := ring.items[(ring.start+offset)%len(ring.items)] + if !value.Time.Before(cutoff) { + result = append(result, value) + } + } + if len(result) > limit { + result = result[len(result)-limit:] + } + return result +} + +type upstreamAttemptRing struct { + items []UpstreamAttempt + start int + count int +} + +func newUpstreamAttemptRing() upstreamAttemptRing { + return upstreamAttemptRing{items: make([]UpstreamAttempt, monitorRecentAttemptCapacity)} +} + +func (ring *upstreamAttemptRing) Add(value UpstreamAttempt) { + if len(ring.items) == 0 { + ring.items = make([]UpstreamAttempt, monitorRecentAttemptCapacity) + } + index := (ring.start + ring.count) % len(ring.items) + if ring.count == len(ring.items) { + ring.items[index] = value + ring.start = (ring.start + 1) % len(ring.items) + return + } + ring.items[index] = value + ring.count++ +} + +func (ring *upstreamAttemptRing) PruneBefore(cutoff time.Time) { + for ring.count > 0 && ring.items[ring.start].Time.Before(cutoff) { + ring.items[ring.start] = UpstreamAttempt{} + ring.start = (ring.start + 1) % len(ring.items) + ring.count-- + } +} + +func (ring *upstreamAttemptRing) Snapshot(cutoff time.Time, limit int) []UpstreamAttempt { + if limit < 1 || ring.count == 0 { + return nil + } + result := make([]UpstreamAttempt, 0, min(ring.count, limit)) + for offset := 0; offset < ring.count; offset++ { + value := ring.items[(ring.start+offset)%len(ring.items)] + if !value.Time.Before(cutoff) { + result = append(result, value) + } + } + if len(result) > limit { + result = result[len(result)-limit:] + } + return result +} + +type Monitor struct { + started time.Time + active atomic.Int64 + activeStreams atomic.Int64 + total atomic.Uint64 + success atomic.Uint64 + errors atomic.Uint64 + mu sync.Mutex + buckets [60]metricBucket + lifetimeUsage UsagePeriod + attemptLifetime AttemptAggregate + attemptBuckets [60]attemptBucket + recentRequests upstreamRequestRing + recentAttempts upstreamAttemptRing +} + +func NewMonitor() *Monitor { + return &Monitor{ + started: time.Now().UTC(), + lifetimeUsage: newUsagePeriod(), + attemptLifetime: newAttemptAggregate(), + recentRequests: newUpstreamRequestRing(), + recentAttempts: newUpstreamAttemptRing(), + } +} + +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) { + success := requestSucceeded(status, meta) + m.total.Add(1) + if success { + m.success.Add(1) + } else { + m.errors.Add(1) + } + minute := time.Now().Unix() / 60 + m.mu.Lock() + bucket := &m.buckets[minute%60] + if bucket.minute != minute { + bucket.reset(minute) + } + bucket.total++ + if success { + bucket.success++ + } else { + bucket.errors++ + } + milliseconds := uint64(max(duration.Milliseconds(), 0)) + bucket.duration += milliseconds + index := len(latencyBounds) + for i, bound := range latencyBounds { + if milliseconds <= bound { + index = i + break + } + } + bucket.histogram[index]++ + bucket.endpoints[endpoint]++ + bucket.statuses[fmt.Sprint(status)]++ + if meta != nil { + if meta.Model != "" { + bucket.models[meta.Model]++ + } + if meta.Tier != "" { + bucket.tiers[meta.Tier]++ + bucket.usageRequests++ + m.lifetimeUsage.Requests++ + if meta.UsageReported { + bucket.usageReported++ + m.lifetimeUsage.Reported++ + } + tokens := tokenCounts(meta.Usage) + addTokenCounts(&bucket.tokens, tokens) + addTokenCounts(&m.lifetimeUsage.Tokens, tokens) + addTokenMap(bucket.usageModels, meta.Model, tokens) + addTokenMap(bucket.usageTiers, meta.Tier, tokens) + addTokenMap(m.lifetimeUsage.Models, meta.Model, tokens) + addTokenMap(m.lifetimeUsage.Tiers, meta.Tier, tokens) + } + if meta.Request != "" && meta.Model != "" { + request := UpstreamRequest{ + Time: time.Now().UTC(), RequestID: meta.Request, Model: meta.Model, Tier: meta.Tier, + KeyID: meta.KeyID, Channel: meta.Channel, Anonymous: meta.Anonymous, Proxy: meta.Proxy, + Attempts: meta.Attempts, Status: status, DurationMS: max(duration.Milliseconds(), 0), + Success: success, + } + if request.Channel == "" { + request.Channel = "not_routed" + } + if request.Anonymous { + request.KeyID = "anonymous" + } + request.Outcome = requestOutcome(status, request.Channel) + if meta.Outcome != "" { + request.Outcome = meta.Outcome + } + m.recentRequests.PruneBefore(request.Time.Add(-time.Hour)) + m.recentRequests.Add(request) + } + } + m.mu.Unlock() +} + +// 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 { + return status >= 200 && status < 400 && (meta == nil || meta.Outcome == "") +} + +func requestOutcome(status int, channel string) string { + if channel == "" || channel == "not_routed" { + return "not_routed" + } + if status >= 200 && status < 400 { + return "success" + } + if status >= 400 && status < 500 { + return "client_error" + } + if status >= 500 { + return "server_error" + } + return "unknown" +} + +func (m *Monitor) RecordAttempt(attempt UpstreamAttempt) { + if attempt.Time.IsZero() { + attempt.Time = time.Now().UTC() + } else { + attempt.Time = attempt.Time.UTC() + } + minute := attempt.Time.Unix() / 60 + m.mu.Lock() + recordAttemptAggregate(&m.attemptLifetime, attempt) + bucket := &m.attemptBuckets[minute%60] + if bucket.minute != minute { + *bucket = attemptBucket{minute: minute, aggregate: newAttemptAggregate()} + } + recordAttemptAggregate(&bucket.aggregate, attempt) + m.recentAttempts.PruneBefore(attempt.Time.Add(-time.Hour)) + m.recentAttempts.Add(attempt) + m.mu.Unlock() +} + +type MonitorSnapshot struct { + StartedAt time.Time `json:"started_at"` + UptimeSeconds int64 `json:"uptime_seconds"` + Active int64 `json:"active_requests"` + ActiveStreams int64 `json:"active_streams"` + Lifetime MetricSummary `json:"lifetime"` + Window MetricSummary `json:"last_hour"` + Series []MetricSeries `json:"series"` + Endpoints map[string]uint64 `json:"endpoints"` + Models map[string]uint64 `json:"models"` + Tiers map[string]uint64 `json:"tiers"` + Statuses map[string]uint64 `json:"statuses"` + Usage UsageSnapshot `json:"usage"` + Upstream UpstreamSnapshot `json:"upstream"` +} + +type MetricSummary struct { + Total uint64 `json:"total"` + Success uint64 `json:"success"` + Errors uint64 `json:"errors"` + SuccessRate float64 `json:"success_rate"` + AverageMS float64 `json:"average_ms,omitempty"` + P50MS uint64 `json:"p50_ms,omitempty"` + P95MS uint64 `json:"p95_ms,omitempty"` + P99MS uint64 `json:"p99_ms,omitempty"` +} + +type MetricSeries struct { + Minute time.Time `json:"minute"` + Total uint64 `json:"total"` + Success uint64 `json:"success"` + Errors uint64 `json:"errors"` + InputTokens uint64 `json:"input_tokens"` + OutputTokens uint64 `json:"output_tokens"` + CachedTokens uint64 `json:"cached_tokens"` + ReasoningTokens uint64 `json:"reasoning_tokens"` + TotalTokens uint64 `json:"total_tokens"` + UsageReported uint64 `json:"usage_reported"` +} + +func (m *Monitor) Snapshot() MonitorSnapshot { + nowMinute := time.Now().Unix() / 60 + window := MetricSummary{} + var histogram [11]uint64 + endpoints, models, tiers, statuses := map[string]uint64{}, map[string]uint64{}, map[string]uint64{}, map[string]uint64{} + series := make([]MetricSeries, 0, 60) + usageWindow := newUsagePeriod() + upstreamWindow := newAttemptAggregate() + var recentRequests []UpstreamRequest + var recentAttempts []UpstreamAttempt + m.mu.Lock() + for offset := int64(59); offset >= 0; offset-- { + minute := nowMinute - offset + bucket := &m.buckets[minute%60] + entry := MetricSeries{Minute: time.Unix(minute*60, 0).UTC()} + if bucket.minute == minute { + entry.Total, entry.Success, entry.Errors = bucket.total, bucket.success, bucket.errors + entry.InputTokens, entry.OutputTokens = bucket.tokens.Input, bucket.tokens.Output + entry.CachedTokens, entry.ReasoningTokens, entry.TotalTokens = bucket.tokens.Cached, bucket.tokens.Reasoning, bucket.tokens.Total + entry.UsageReported = bucket.usageReported + window.Total += bucket.total + window.Success += bucket.success + window.Errors += bucket.errors + window.AverageMS += float64(bucket.duration) + for i := range histogram { + histogram[i] += bucket.histogram[i] + } + mergeCounts(endpoints, bucket.endpoints) + mergeCounts(models, bucket.models) + mergeCounts(tiers, bucket.tiers) + mergeCounts(statuses, bucket.statuses) + usageWindow.Requests += bucket.usageRequests + usageWindow.Reported += bucket.usageReported + addTokenCounts(&usageWindow.Tokens, bucket.tokens) + mergeTokenMaps(usageWindow.Models, bucket.usageModels) + mergeTokenMaps(usageWindow.Tiers, bucket.usageTiers) + } + attemptBucket := &m.attemptBuckets[minute%60] + if attemptBucket.minute == minute { + mergeAttemptAggregate(&upstreamWindow, attemptBucket.aggregate) + } + series = append(series, entry) + } + usageLifetime := cloneUsagePeriod(m.lifetimeUsage) + upstreamLifetime := cloneAttemptAggregate(m.attemptLifetime) + cutoff := time.Now().Add(-time.Hour) + m.recentRequests.PruneBefore(cutoff) + m.recentAttempts.PruneBefore(cutoff) + recentRequests = m.recentRequests.Snapshot(cutoff, monitorRecentOutputLimit) + recentAttempts = m.recentAttempts.Snapshot(cutoff, monitorRecentOutputLimit) + m.mu.Unlock() + finalizeUsagePeriod(&usageLifetime) + finalizeUsagePeriod(&usageWindow) + finalizeAttemptAggregate(&upstreamLifetime) + finalizeAttemptAggregate(&upstreamWindow) + if window.Total > 0 { + window.SuccessRate = float64(window.Success) / float64(window.Total) + window.AverageMS /= float64(window.Total) + window.P50MS = histogramPercentile(histogram, window.Total, 0.50) + window.P95MS = histogramPercentile(histogram, window.Total, 0.95) + window.P99MS = histogramPercentile(histogram, window.Total, 0.99) + } + lifetime := MetricSummary{Total: m.total.Load(), Success: m.success.Load(), Errors: m.errors.Load()} + if lifetime.Total > 0 { + lifetime.SuccessRate = float64(lifetime.Success) / float64(lifetime.Total) + } + return MonitorSnapshot{ + StartedAt: m.started, UptimeSeconds: int64(time.Since(m.started).Seconds()), Active: m.active.Load(), + ActiveStreams: m.activeStreams.Load(), Lifetime: lifetime, Window: window, Series: series, + Endpoints: endpoints, Models: models, Tiers: tiers, Statuses: statuses, + Usage: UsageSnapshot{Lifetime: usageLifetime, Window: usageWindow}, + Upstream: UpstreamSnapshot{Lifetime: upstreamLifetime, Window: upstreamWindow, Requests: recentRequests, Recent: recentAttempts}, + } +} + +func mergeCounts(target, source map[string]uint64) { + for key, value := range source { + target[key] += value + } +} + +func newUsagePeriod() UsagePeriod { + return UsagePeriod{Models: make(map[string]TokenCounts), Tiers: make(map[string]TokenCounts)} +} + +func tokenCounts(usage bridgeUsage) 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)), + } +} + +func addTokenCounts(target *TokenCounts, source TokenCounts) { + target.Input += source.Input + target.Output += source.Output + target.Cached += source.Cached + target.Reasoning += source.Reasoning + target.Total += source.Total +} + +func addTokenMap(target map[string]TokenCounts, key string, value TokenCounts) { + if key == "" { + return + } + current := target[key] + addTokenCounts(¤t, value) + target[key] = current +} + +func mergeTokenMaps(target, source map[string]TokenCounts) { + for key, value := range source { + addTokenMap(target, key, value) + } +} + +func cloneUsagePeriod(source UsagePeriod) UsagePeriod { + result := newUsagePeriod() + result.Requests, result.Reported, result.Tokens = source.Requests, source.Reported, source.Tokens + mergeTokenMaps(result.Models, source.Models) + mergeTokenMaps(result.Tiers, source.Tiers) + return result +} + +func finalizeUsagePeriod(period *UsagePeriod) { + if period.Requests > 0 { + period.Coverage = float64(period.Reported) / float64(period.Requests) + } +} + +func newAttemptAggregate() AttemptAggregate { + return AttemptAggregate{ + Tiers: make(map[string]AttemptCounts), Channels: make(map[string]AttemptCounts), Keys: make(map[string]AttemptCounts), + } +} + +func recordAttemptAggregate(target *AttemptAggregate, attempt UpstreamAttempt) { + recordAttemptCounts(&target.AttemptCounts, attempt.Success) + addAttemptMap(target.Tiers, attempt.Tier, attempt.Success) + addAttemptMap(target.Channels, attempt.Channel, attempt.Success) + addAttemptMap(target.Keys, attempt.KeyID, attempt.Success) +} + +func recordAttemptCounts(target *AttemptCounts, success bool) { + target.Total++ + if success { + target.Success++ + } else { + target.Failed++ + } +} + +func addAttemptMap(target map[string]AttemptCounts, key string, success bool) { + if key == "" { + return + } + current := target[key] + recordAttemptCounts(¤t, success) + target[key] = current +} + +func mergeAttemptAggregate(target *AttemptAggregate, source AttemptAggregate) { + target.Total += source.Total + target.Success += source.Success + target.Failed += source.Failed + mergeAttemptMaps(target.Tiers, source.Tiers) + mergeAttemptMaps(target.Channels, source.Channels) + mergeAttemptMaps(target.Keys, source.Keys) +} + +func mergeAttemptMaps(target, source map[string]AttemptCounts) { + for key, value := range source { + current := target[key] + current.Total += value.Total + current.Success += value.Success + current.Failed += value.Failed + target[key] = current + } +} + +func cloneAttemptAggregate(source AttemptAggregate) AttemptAggregate { + result := newAttemptAggregate() + mergeAttemptAggregate(&result, source) + return result +} + +func finalizeAttemptAggregate(aggregate *AttemptAggregate) { + if aggregate.Total > 0 { + aggregate.SuccessRate = float64(aggregate.Success) / float64(aggregate.Total) + } +} + +func histogramPercentile(histogram [11]uint64, total uint64, percentile float64) uint64 { + target := uint64(float64(total)*percentile + 0.999) + var count uint64 + for i, value := range histogram { + count += value + if count >= target { + if i < len(latencyBounds) { + return latencyBounds[i] + } + return latencyBounds[len(latencyBounds)-1] + 1 + } + } + return 0 +} diff --git a/model_cache.go b/model_cache.go new file mode 100644 index 0000000..fafacc4 --- /dev/null +++ b/model_cache.go @@ -0,0 +1,224 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "sort" + "strings" + "sync" + "time" +) + +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"` +} + +// 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 { + cache, err := loadModelCatalogCache(path) + if err != nil { + return err + } + c.mu.Lock() + c.zen = toSet(cache.Zen) + c.goModels = toSet(cache.Go) + c.nativeProtocols = cloneTierProtocols(cache.NativeProtocols) + c.unsupported = cloneTierBools(cache.Unsupported) + c.modelMeta = cloneModelMeta(cache.Metadata) + c.updatedAt = cache.UpdatedAt.UTC() + c.cacheSource = "disk" + c.stale = true + if c.cachePath == "" { + c.cachePath = path + } + c.mu.Unlock() + return nil +} + +// 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 { + c.mu.RLock() + path := c.cachePath + cache := modelCatalogCache{ + SchemaVersion: modelCatalogCacheSchemaVersion, + UpdatedAt: c.updatedAt.UTC(), + Zen: sortedSetKeys(c.zen), + Go: sortedSetKeys(c.goModels), + NativeProtocols: cloneTierProtocols(c.nativeProtocols), + Unsupported: cloneTierBools(c.unsupported), + Metadata: cloneModelMeta(c.modelMeta), + } + c.mu.RUnlock() + if path == "" { + return nil + } + return saveModelCatalogCache(path, cache) +} + +func modelCatalogCachePath(configPath string) string { + if configPath == "" { + return "" + } + return configPath + ".models.catalog.json" +} + +func loadModelCatalogCache(path string) (modelCatalogCache, error) { + if path == "" { + return modelCatalogCache{}, os.ErrNotExist + } + file, err := os.Open(path) + if err != nil { + return modelCatalogCache{}, err + } + defer file.Close() + var cache modelCatalogCache + decoder := json.NewDecoder(io.LimitReader(file, 32<<20)) + if err := decoder.Decode(&cache); err != nil { + return modelCatalogCache{}, err + } + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + if err == nil { + return modelCatalogCache{}, errors.New("model catalog cache contains multiple JSON values") + } + return modelCatalogCache{}, err + } + if cache.SchemaVersion != modelCatalogCacheSchemaVersion { + return modelCatalogCache{}, fmt.Errorf("unsupported model catalog cache schema version %d", cache.SchemaVersion) + } + if cache.UpdatedAt.IsZero() { + return modelCatalogCache{}, errors.New("model catalog cache is missing updated_at") + } + cache.Zen = normalizeModelIDs(cache.Zen) + cache.Go = normalizeModelIDs(cache.Go) + if len(cache.Zen) == 0 && len(cache.Go) == 0 { + return modelCatalogCache{}, errors.New("model catalog cache is empty") + } + if err := validateCatalogCapabilities(cache.NativeProtocols, cache.Unsupported); err != nil { + return modelCatalogCache{}, err + } + cache.NativeProtocols = cloneTierProtocols(cache.NativeProtocols) + cache.Unsupported = cloneTierBools(cache.Unsupported) + cache.UpdatedAt = cache.UpdatedAt.UTC() + return cache, nil +} + +func normalizeModelIDs(items []string) []string { + seen := make(map[string]struct{}, len(items)) + result := make([]string, 0, len(items)) + for _, item := range items { + item = strings.TrimSpace(item) + if item == "" { + continue + } + if _, ok := seen[item]; ok { + continue + } + seen[item] = struct{}{} + result = append(result, item) + } + sort.Strings(result) + return result +} + +func validateCatalogCapabilities(native map[Tier]map[string]Protocol, unsupported map[Tier]map[string]bool) error { + for tier, protocols := range native { + if tier != TierZen && tier != TierGo { + return fmt.Errorf("model catalog cache contains unknown tier %q", tier) + } + for model, protocol := range protocols { + if model == "" || !validProtocol(protocol) { + return fmt.Errorf("model catalog cache contains invalid protocol for %q", model) + } + } + } + for tier, models := range unsupported { + if tier != TierZen && tier != TierGo { + return fmt.Errorf("model catalog cache contains unknown tier %q", tier) + } + for model := range models { + if strings.TrimSpace(model) == "" { + return errors.New("model catalog cache contains an empty unsupported model") + } + } + } + return nil +} + +func saveModelCatalogCache(path string, cache modelCatalogCache) error { + if path == "" { + return nil + } + modelCatalogCacheWriteMu.Lock() + defer modelCatalogCacheWriteMu.Unlock() + data, err := json.MarshalIndent(cache, "", " ") + if err != nil { + return err + } + data = append(data, '\n') + dir := filepath.Dir(path) + temp, err := os.CreateTemp(dir, ".models-catalog-*.tmp") + if err != nil { + return err + } + tempPath := temp.Name() + defer os.Remove(tempPath) + if err = temp.Chmod(0600); err == nil { + _, err = temp.Write(data) + } + if err == nil { + err = temp.Sync() + } + if closeErr := temp.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + + if runtime.GOOS == "windows" { + backup := path + ".replace" + if err := os.Remove(backup); err != nil && !os.IsNotExist(err) { + return err + } + hadOld := false + if _, statErr := os.Stat(path); statErr == nil { + if err := os.Rename(path, backup); err != nil { + return err + } + hadOld = true + } else if !os.IsNotExist(statErr) { + return statErr + } + if err := os.Rename(tempPath, path); err != nil { + if hadOld { + _ = os.Rename(backup, path) + } + return err + } + if hadOld { + _ = os.Remove(backup) + } + return nil + } + return os.Rename(tempPath, path) +} diff --git a/model_discovery.go b/model_discovery.go new file mode 100644 index 0000000..88db1cb --- /dev/null +++ b/model_discovery.go @@ -0,0 +1,282 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "regexp" + "strings" +) + +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" +) + +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 capabilityProvider struct { + ID string `json:"id"` + API string `json:"api"` + NPM string `json:"npm"` + Models map[string]capabilityModel `json:"models"` +} + +type capabilityModel struct { + ID string `json:"id"` + Provider *capabilityModelProvider `json:"provider"` + Limit *capabilityModelLimit `json:"limit"` + Reasoning bool `json:"reasoning"` + ToolCall bool `json:"tool_call"` + StructuredOutput bool `json:"structured_output"` + Modalities *capabilityModelModalities `json:"modalities"` +} + +type capabilityModelModalities struct { + Input []string `json:"input"` + Output []string `json:"output"` +} + +type capabilityModelLimit struct { + Context int `json:"context"` + Input int `json:"input"` + Output int `json:"output"` +} + +// ModelMetadata 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 { + ContextWindow int `json:"context_window,omitempty"` + MaxInput int `json:"max_input,omitempty"` + MaxOutput int `json:"max_output,omitempty"` + Reasoning bool `json:"reasoning,omitempty"` + ToolCall bool `json:"tool_call,omitempty"` + StructuredOutput bool `json:"structured_output,omitempty"` + InputModalities []string `json:"input_modalities,omitempty"` + OutputModalities []string `json:"output_modalities,omitempty"` +} + +func (m *capabilityModel) metadata() ModelMetadata { + md := ModelMetadata{ + Reasoning: m.Reasoning, + ToolCall: m.ToolCall, + StructuredOutput: m.StructuredOutput, + } + if m.Modalities != nil { + md.InputModalities = m.Modalities.Input + md.OutputModalities = m.Modalities.Output + } + if m.Limit != nil { + md.ContextWindow = m.Limit.Context + md.MaxInput = m.Limit.Input + md.MaxOutput = m.Limit.Output + } + return md +} + +type capabilityModelProvider struct { + NPM string `json:"npm"` +} + +// fetchProtocolCapabilities reads OpenCode's machine-readable provider +// 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) { + if client == nil { + client = http.DefaultClient + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return protocolCapabilities{}, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", opencodeUserAgent()) + resp, err := client.Do(req) + if err != nil { + return protocolCapabilities{}, err + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + return protocolCapabilities{}, 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 + } + 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: {}}, + } + for providerID, provider := range providers { + tier, ok := capabilityTier(providerID, provider.API) + if !ok { + continue + } + for modelID, model := range provider.Models { + if model.ID != "" { + modelID = model.ID + } + npm := provider.NPM + if model.Provider != nil && model.Provider.NPM != "" { + npm = model.Provider.NPM + } + if protocol, ok := protocolForSDK(npm); ok { + result.Protocols[tier][modelID] = protocol + } else { + result.Unsupported[tier][modelID] = true + } + result.Metadata[tier][modelID] = model.metadata() + } + } + // The machine catalog is the primary source. The upstream endpoint tables + // are a supplemental source for models whose provider inherits a default SDK + // 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 + url string + }{ + {TierZen, openCodeZenDocsURL}, + {TierGo, openCodeGoDocsURL}, + } { + protocols, err := fetchProtocolDocs(ctx, client, doc.url) + if err != nil { + continue + } + for modelID, protocol := range protocols { + result.Protocols[doc.tier][modelID] = protocol + 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") + } + return result, nil +} + +func fetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string) (map[string]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()) + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + return nil, fmt.Errorf("OpenCode endpoint documentation returned HTTP %d", resp.StatusCode) + } + body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) + if err != nil { + return nil, err + } + result := make(map[string]Protocol) + for _, line := range strings.Split(string(body), "\n") { + match := protocolDocEndpointPattern.FindStringSubmatch(line) + if len(match) != 3 { + continue + } + modelID := strings.TrimSpace(match[1]) + if modelID == "" || strings.ContainsAny(modelID, " `|") { + continue + } + var protocol Protocol + switch match[2] { + case "chat/completions": + protocol = ProtocolChat + case "responses": + protocol = ProtocolResponses + case "messages": + protocol = ProtocolAnthropic + } + if protocol != "" { + result[modelID] = protocol + } + } + if len(result) == 0 { + return nil, errors.New("OpenCode endpoint documentation returned no protocol rows") + } + return result, nil +} + +func capabilityTier(providerID, api string) (Tier, bool) { + value := strings.ToLower(strings.TrimSpace(providerID + " " + api)) + if strings.Contains(value, "opencode-go") || strings.Contains(value, "/go/") { + return TierGo, true + } + if strings.Contains(value, "opencode") || strings.Contains(value, "/zen/") { + return TierZen, true + } + return "", false +} + +func protocolForSDK(npm string) (Protocol, bool) { + value := strings.ToLower(strings.TrimSpace(npm)) + switch { + case strings.Contains(value, "anthropic"): + return ProtocolAnthropic, true + case value == "@ai-sdk/openai" || strings.HasSuffix(value, "/openai"): + return ProtocolResponses, true + case strings.Contains(value, "openai-compatible"): + return ProtocolChat, true + default: + return "", false + } +} + +type modelsResponse struct { + Data []struct { + ID string `json:"id"` + } `json:"data"` +} + +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("x-opencode-client", "cli") + resp, err := client.Do(req) + if err != nil { + return nil, 0, err + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + return nil, resp.StatusCode, fmt.Errorf("models endpoint returned HTTP %d", resp.StatusCode) + } + var payload modelsResponse + dec := json.NewDecoder(io.LimitReader(resp.Body, 8<<20)) + if err := dec.Decode(&payload); err != nil { + return nil, resp.StatusCode, err + } + models := make([]string, 0, len(payload.Data)) + for _, item := range payload.Data { + if item.ID != "" { + models = append(models, item.ID) + } + } + if len(models) == 0 { + return nil, resp.StatusCode, errors.New("models endpoint returned an empty list") + } + return models, resp.StatusCode, nil +} diff --git a/models.go b/models.go index 37dfb34..4e3f995 100644 --- a/models.go +++ b/models.go @@ -1,16 +1,8 @@ package main import ( - "context" - "encoding/json" "errors" "fmt" - "io" - "net/http" - "os" - "path/filepath" - "regexp" - "runtime" "sort" "strings" "sync" @@ -25,14 +17,6 @@ const ( ProtocolAnthropic Protocol = "anthropic" ) -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" -) - -var protocolDocEndpointPattern = regexp.MustCompile("\\|[^|]+\\|\\s*`?([^|`\\s]+)`?\\s*\\|\\s*`[^`]+/v1/(chat/completions|responses|messages)`") - func validProtocol(p Protocol) bool { return p == ProtocolChat || p == ProtocolResponses || p == ProtocolAnthropic } @@ -108,20 +92,6 @@ type modelCatalogSnapshot struct { Stale bool `json:"stale"` } -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"` -} - func newModelCatalog(prefer Tier, overrides map[string]string) *modelCatalog { protocols := make(map[string]Protocol, len(overrides)) for model, protocol := range overrides { @@ -217,55 +187,13 @@ func (c *modelCatalog) CopyState(source *modelCatalog) { c.mu.Unlock() } -// 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 { - cache, err := loadModelCatalogCache(path) - if err != nil { - return err - } - c.mu.Lock() - c.zen = toSet(cache.Zen) - c.goModels = toSet(cache.Go) - c.nativeProtocols = cloneTierProtocols(cache.NativeProtocols) - c.unsupported = cloneTierBools(cache.Unsupported) - c.modelMeta = cloneModelMeta(cache.Metadata) - c.updatedAt = cache.UpdatedAt.UTC() - c.cacheSource = "disk" - c.stale = true - if c.cachePath == "" { - c.cachePath = path - } - c.mu.Unlock() - return nil -} - -// 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 { - c.mu.RLock() - path := c.cachePath - cache := modelCatalogCache{ - SchemaVersion: modelCatalogCacheSchemaVersion, - UpdatedAt: c.updatedAt.UTC(), - Zen: sortedSetKeys(c.zen), - Go: sortedSetKeys(c.goModels), - NativeProtocols: cloneTierProtocols(c.nativeProtocols), - Unsupported: cloneTierBools(c.unsupported), - Metadata: cloneModelMeta(c.modelMeta), - } - c.mu.RUnlock() - if path == "" { - return nil - } - return saveModelCatalogCache(path, cache) -} - func (c *modelCatalog) Route(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (modelRoute, 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) { 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 @@ -343,6 +271,42 @@ func (c *modelCatalog) keyTierOrderLocked(model string, hasZenKeys, hasGoKeys bo return result } +// RouteForTier builds a route pinned to one tier, used by the Playground's +// 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") + } + hasKeys := hasZenKeys + if tier == TierGo { + hasKeys = hasGoKeys + } + if !hasKeys { + return modelRoute{}, 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 { + advertised = c.goModels[model] + } + if !catalogPending && !advertised { + return modelRoute{}, 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) + } + protocol := c.protocolForLocked(model, tier) + return modelRoute{ + ID: model, Tier: tier, Protocol: protocol, + Protocols: map[Tier]Protocol{tier: protocol}, + KeyTiers: []Tier{tier}, + }, nil +} + func (c *modelCatalog) anonymousDecision(model string) AnonymousDecision { if c.metadata != nil { return c.metadata.Decide(model) @@ -400,6 +364,17 @@ func isFreeModel(model string) bool { func (c *modelCatalog) List() []string { c.mu.RLock() defer c.mu.RUnlock() + ids := c.modelIDsLocked() + models := ids[:0] + for _, model := range ids { + if c.supportedLocked(model) { + models = append(models, model) + } + } + return models +} + +func (c *modelCatalog) modelIDsLocked() []string { seen := make(map[string]bool, len(c.zen)+len(c.goModels)) for model := range c.zen { seen[model] = true @@ -407,28 +382,38 @@ func (c *modelCatalog) List() []string { for model := range c.goModels { seen[model] = true } - models := make([]string, 0, len(seen)) - for model := range seen { - if c.supportedLocked(model) { - models = append(models, model) - } - } - sort.Strings(models) - return models + return sortedSetKeys(seen) } func (c *modelCatalog) Snapshot() modelCatalogSnapshot { c.mu.RLock() defer c.mu.RUnlock() - seen := make(map[string]bool, len(c.zen)+len(c.goModels)) - for model := range c.zen { - seen[model] = true - } - for model := range c.goModels { - seen[model] = true + return c.snapshotLocked(c.modelIDsLocked()) +} + +// 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) { + c.mu.RLock() + defer c.mu.RUnlock() + ids := c.modelIDsLocked() + routes := make([]modelRoute, 0, len(ids)) + for _, model := range ids { + if !c.supportedLocked(model) { + continue + } + if route, err := c.routeLocked(model, hasZenKeys, hasGoKeys, hasAnonymous); err == nil { + routes = append(routes, route) + } } + snapshot := c.snapshotLocked(ids) + snapshot.Exposed = len(routes) + return routes, snapshot +} + +func (c *modelCatalog) snapshotLocked(ids []string) modelCatalogSnapshot { exposed := 0 - for model := range seen { + for _, model := range ids { if c.supportedLocked(model) { exposed++ } @@ -438,7 +423,7 @@ func (c *modelCatalog) Snapshot() modelCatalogSnapshot { stale = stale || time.Since(c.updatedAt) > max(2*c.refreshAfter, time.Minute) } return modelCatalogSnapshot{ - Zen: len(c.zen), Go: len(c.goModels), Total: len(seen), Exposed: exposed, + Zen: len(c.zen), Go: len(c.goModels), Total: len(ids), Exposed: exposed, UpdatedAt: c.updatedAt, CacheSource: c.cacheSource, Stale: stale, } } @@ -554,414 +539,3 @@ func cloneTierBools(source map[Tier]map[string]bool) map[Tier]map[string]bool { } return result } - -func modelCatalogCachePath(configPath string) string { - if configPath == "" { - return "" - } - return configPath + ".models.catalog.json" -} - -func loadModelCatalogCache(path string) (modelCatalogCache, error) { - if path == "" { - return modelCatalogCache{}, os.ErrNotExist - } - file, err := os.Open(path) - if err != nil { - return modelCatalogCache{}, err - } - defer file.Close() - var cache modelCatalogCache - decoder := json.NewDecoder(io.LimitReader(file, 32<<20)) - if err := decoder.Decode(&cache); err != nil { - return modelCatalogCache{}, err - } - var extra any - if err := decoder.Decode(&extra); err != io.EOF { - if err == nil { - return modelCatalogCache{}, errors.New("model catalog cache contains multiple JSON values") - } - return modelCatalogCache{}, err - } - if cache.SchemaVersion != modelCatalogCacheSchemaVersion { - return modelCatalogCache{}, fmt.Errorf("unsupported model catalog cache schema version %d", cache.SchemaVersion) - } - if cache.UpdatedAt.IsZero() { - return modelCatalogCache{}, errors.New("model catalog cache is missing updated_at") - } - cache.Zen = normalizeModelIDs(cache.Zen) - cache.Go = normalizeModelIDs(cache.Go) - if len(cache.Zen) == 0 && len(cache.Go) == 0 { - return modelCatalogCache{}, errors.New("model catalog cache is empty") - } - if err := validateCatalogCapabilities(cache.NativeProtocols, cache.Unsupported); err != nil { - return modelCatalogCache{}, err - } - cache.NativeProtocols = cloneTierProtocols(cache.NativeProtocols) - cache.Unsupported = cloneTierBools(cache.Unsupported) - cache.UpdatedAt = cache.UpdatedAt.UTC() - return cache, nil -} - -func normalizeModelIDs(items []string) []string { - seen := make(map[string]struct{}, len(items)) - result := make([]string, 0, len(items)) - for _, item := range items { - item = strings.TrimSpace(item) - if item == "" { - continue - } - if _, ok := seen[item]; ok { - continue - } - seen[item] = struct{}{} - result = append(result, item) - } - sort.Strings(result) - return result -} - -func validateCatalogCapabilities(native map[Tier]map[string]Protocol, unsupported map[Tier]map[string]bool) error { - for tier, protocols := range native { - if tier != TierZen && tier != TierGo { - return fmt.Errorf("model catalog cache contains unknown tier %q", tier) - } - for model, protocol := range protocols { - if model == "" || !validProtocol(protocol) { - return fmt.Errorf("model catalog cache contains invalid protocol for %q", model) - } - } - } - for tier, models := range unsupported { - if tier != TierZen && tier != TierGo { - return fmt.Errorf("model catalog cache contains unknown tier %q", tier) - } - for model := range models { - if strings.TrimSpace(model) == "" { - return errors.New("model catalog cache contains an empty unsupported model") - } - } - } - return nil -} - -func saveModelCatalogCache(path string, cache modelCatalogCache) error { - if path == "" { - return nil - } - modelCatalogCacheWriteMu.Lock() - defer modelCatalogCacheWriteMu.Unlock() - data, err := json.MarshalIndent(cache, "", " ") - if err != nil { - return err - } - data = append(data, '\n') - dir := filepath.Dir(path) - temp, err := os.CreateTemp(dir, ".models-catalog-*.tmp") - if err != nil { - return err - } - tempPath := temp.Name() - defer os.Remove(tempPath) - if err = temp.Chmod(0600); err == nil { - _, err = temp.Write(data) - } - if err == nil { - err = temp.Sync() - } - if closeErr := temp.Close(); err == nil { - err = closeErr - } - if err != nil { - return err - } - - if runtime.GOOS == "windows" { - backup := path + ".replace" - if err := os.Remove(backup); err != nil && !os.IsNotExist(err) { - return err - } - hadOld := false - if _, statErr := os.Stat(path); statErr == nil { - if err := os.Rename(path, backup); err != nil { - return err - } - hadOld = true - } else if !os.IsNotExist(statErr) { - return statErr - } - if err := os.Rename(tempPath, path); err != nil { - if hadOld { - _ = os.Rename(backup, path) - } - return err - } - if hadOld { - _ = os.Remove(backup) - } - return nil - } - return os.Rename(tempPath, path) -} - -type protocolCapabilities struct { - Protocols map[Tier]map[string]Protocol - Unsupported map[Tier]map[string]bool - Metadata map[Tier]map[string]ModelMetadata -} - -type capabilityProvider struct { - ID string `json:"id"` - API string `json:"api"` - NPM string `json:"npm"` - Models map[string]capabilityModel `json:"models"` -} - -type capabilityModel struct { - ID string `json:"id"` - Provider *capabilityModelProvider `json:"provider"` - Limit *capabilityModelLimit `json:"limit"` - Reasoning bool `json:"reasoning"` - ToolCall bool `json:"tool_call"` - StructuredOutput bool `json:"structured_output"` - Modalities *capabilityModelModalities `json:"modalities"` -} - -type capabilityModelModalities struct { - Input []string `json:"input"` - Output []string `json:"output"` -} - -type capabilityModelLimit struct { - Context int `json:"context"` - Input int `json:"input"` - Output int `json:"output"` -} - -// ModelMetadata 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 { - ContextWindow int `json:"context_window,omitempty"` - MaxInput int `json:"max_input,omitempty"` - MaxOutput int `json:"max_output,omitempty"` - Reasoning bool `json:"reasoning,omitempty"` - ToolCall bool `json:"tool_call,omitempty"` - StructuredOutput bool `json:"structured_output,omitempty"` - InputModalities []string `json:"input_modalities,omitempty"` - OutputModalities []string `json:"output_modalities,omitempty"` -} - -func (m *capabilityModel) metadata() ModelMetadata { - md := ModelMetadata{ - Reasoning: m.Reasoning, - ToolCall: m.ToolCall, - StructuredOutput: m.StructuredOutput, - } - if m.Modalities != nil { - md.InputModalities = m.Modalities.Input - md.OutputModalities = m.Modalities.Output - } - if m.Limit != nil { - md.ContextWindow = m.Limit.Context - md.MaxInput = m.Limit.Input - md.MaxOutput = m.Limit.Output - } - return md -} - -type capabilityModelProvider struct { - NPM string `json:"npm"` -} - -// fetchProtocolCapabilities reads OpenCode's machine-readable provider -// 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) { - if client == nil { - client = http.DefaultClient - } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) - if err != nil { - return protocolCapabilities{}, err - } - req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", opencodeUserAgent()) - resp, err := client.Do(req) - if err != nil { - return protocolCapabilities{}, err - } - defer resp.Body.Close() - if resp.StatusCode/100 != 2 { - return protocolCapabilities{}, 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 - } - 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: {}}, - } - for providerID, provider := range providers { - tier, ok := capabilityTier(providerID, provider.API) - if !ok { - continue - } - for modelID, model := range provider.Models { - if model.ID != "" { - modelID = model.ID - } - npm := provider.NPM - if model.Provider != nil && model.Provider.NPM != "" { - npm = model.Provider.NPM - } - if protocol, ok := protocolForSDK(npm); ok { - result.Protocols[tier][modelID] = protocol - } else { - result.Unsupported[tier][modelID] = true - } - result.Metadata[tier][modelID] = model.metadata() - } - } - // The machine catalog is the primary source. The upstream endpoint tables - // are a supplemental source for models whose provider inherits a default SDK - // 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 - url string - }{ - {TierZen, openCodeZenDocsURL}, - {TierGo, openCodeGoDocsURL}, - } { - protocols, err := fetchProtocolDocs(ctx, client, doc.url) - if err != nil { - continue - } - for modelID, protocol := range protocols { - result.Protocols[doc.tier][modelID] = protocol - 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") - } - return result, nil -} - -func fetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string) (map[string]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()) - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - if resp.StatusCode/100 != 2 { - return nil, fmt.Errorf("OpenCode endpoint documentation returned HTTP %d", resp.StatusCode) - } - body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) - if err != nil { - return nil, err - } - result := make(map[string]Protocol) - for _, line := range strings.Split(string(body), "\n") { - match := protocolDocEndpointPattern.FindStringSubmatch(line) - if len(match) != 3 { - continue - } - modelID := strings.TrimSpace(match[1]) - if modelID == "" || strings.ContainsAny(modelID, " `|") { - continue - } - var protocol Protocol - switch match[2] { - case "chat/completions": - protocol = ProtocolChat - case "responses": - protocol = ProtocolResponses - case "messages": - protocol = ProtocolAnthropic - } - if protocol != "" { - result[modelID] = protocol - } - } - if len(result) == 0 { - return nil, errors.New("OpenCode endpoint documentation returned no protocol rows") - } - return result, nil -} - -func capabilityTier(providerID, api string) (Tier, bool) { - value := strings.ToLower(strings.TrimSpace(providerID + " " + api)) - if strings.Contains(value, "opencode-go") || strings.Contains(value, "/go/") { - return TierGo, true - } - if strings.Contains(value, "opencode") || strings.Contains(value, "/zen/") { - return TierZen, true - } - return "", false -} - -func protocolForSDK(npm string) (Protocol, bool) { - value := strings.ToLower(strings.TrimSpace(npm)) - switch { - case strings.Contains(value, "anthropic"): - return ProtocolAnthropic, true - case value == "@ai-sdk/openai" || strings.HasSuffix(value, "/openai"): - return ProtocolResponses, true - case strings.Contains(value, "openai-compatible"): - return ProtocolChat, true - default: - return "", false - } -} - -type modelsResponse struct { - Data []struct { - ID string `json:"id"` - } `json:"data"` -} - -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("x-opencode-client", "cli") - resp, err := client.Do(req) - if err != nil { - return nil, 0, err - } - defer resp.Body.Close() - if resp.StatusCode/100 != 2 { - return nil, resp.StatusCode, fmt.Errorf("models endpoint returned HTTP %d", resp.StatusCode) - } - var payload modelsResponse - dec := json.NewDecoder(io.LimitReader(resp.Body, 8<<20)) - if err := dec.Decode(&payload); err != nil { - return nil, resp.StatusCode, err - } - models := make([]string, 0, len(payload.Data)) - for _, item := range payload.Data { - if item.ID != "" { - models = append(models, item.ID) - } - } - if len(models) == 0 { - return nil, resp.StatusCode, errors.New("models endpoint returned an empty list") - } - return models, resp.StatusCode, nil -} diff --git a/observability.go b/observability.go index 41a39d6..8871e47 100644 --- a/observability.go +++ b/observability.go @@ -4,301 +4,26 @@ import ( "context" "encoding/json" "fmt" - "io" "log/slog" "net/http" - "net/url" - "os" - "sort" - "strings" - "sync" - "sync/atomic" "time" ) -type LogEvent struct { - Sequence uint64 `json:"sequence"` - Time time.Time `json:"time"` - Level string `json:"level"` - Message string `json:"message"` - Component string `json:"component,omitempty"` - Fields map[string]any `json:"fields,omitempty"` -} - -type logSubscriber struct { - ch chan LogEvent -} - -type LogHub struct { - mu sync.RWMutex - buffer []LogEvent - start int - count int - next uint64 - subscribers map[uint64]*logSubscriber - nextSub uint64 -} - -func NewLogHub(capacity int) *LogHub { - if capacity < 100 { - capacity = 100 - } - return &LogHub{buffer: make([]LogEvent, capacity), subscribers: make(map[uint64]*logSubscriber)} -} - -func (h *LogHub) Resize(capacity int) { - if capacity < 100 { - capacity = 100 - } - h.mu.Lock() - if capacity == len(h.buffer) { - h.mu.Unlock() - return - } - keep := min(h.count, capacity) - next := make([]LogEvent, capacity) - for i := 0; i < keep; i++ { - source := (h.start + h.count - keep + i) % len(h.buffer) - next[i] = h.buffer[source] - } - h.buffer, h.start, h.count = next, 0, keep - h.mu.Unlock() -} - -func (h *LogHub) Publish(event LogEvent) { - h.mu.Lock() - h.next++ - event.Sequence = h.next - if h.count < len(h.buffer) { - index := (h.start + h.count) % len(h.buffer) - h.buffer[index] = event - h.count++ - } else { - h.buffer[h.start] = event - h.start = (h.start + 1) % len(h.buffer) - } - for _, sub := range h.subscribers { - select { - case sub.ch <- event: - default: - // A slow browser must never block request processing. Its reconnect - // cursor will make the gap visible on the next subscription. - } - } - h.mu.Unlock() -} - -func (h *LogHub) Recent(after uint64, limit int) ([]LogEvent, bool) { - h.mu.RLock() - defer h.mu.RUnlock() - if limit < 1 || limit > len(h.buffer) { - limit = len(h.buffer) - } - oldest := uint64(0) - if h.count > 0 { - oldest = h.buffer[h.start].Sequence - } - gap := after > 0 && oldest > 0 && after+1 < oldest - out := make([]LogEvent, 0, min(limit, h.count)) - for i := 0; i < h.count; i++ { - event := h.buffer[(h.start+i)%len(h.buffer)] - if event.Sequence > after { - out = append(out, event) - } - } - if len(out) > limit { - out = out[len(out)-limit:] - } - return out, gap -} - -func (h *LogHub) Subscribe() (<-chan LogEvent, func()) { - h.mu.Lock() - h.nextSub++ - id := h.nextSub - sub := &logSubscriber{ch: make(chan LogEvent, 128)} - h.subscribers[id] = sub - h.mu.Unlock() - return sub.ch, func() { - h.mu.Lock() - delete(h.subscribers, id) - h.mu.Unlock() - } -} - -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 - attrs []slog.Attr - groups []string -} - -func NewStructuredLogger(level *slog.LevelVar, hub *LogHub, redactor *SecretRedactor) *slog.Logger { - return newStructuredLogger(os.Stdout, level, hub, redactor) -} - -func newStructuredLogger(output io.Writer, level *slog.LevelVar, hub *LogHub, redactor *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 { - 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") { - return slog.String(attr.Key, "***") - } - switch attr.Value.Kind() { - case slog.KindString: - attr.Value = slog.StringValue(redactor.String(attr.Value.String())) - case slog.KindAny: - if err, ok := attr.Value.Any().(error); ok { - attr.Value = slog.StringValue(redactor.String(err.Error())) - } - } - return attr -} - -func (h *hubHandler) Enabled(ctx context.Context, level slog.Level) bool { - return h.base.Enabled(ctx, level) -} - -func (h *hubHandler) Handle(ctx context.Context, record slog.Record) error { - if err := h.base.Handle(ctx, record); err != nil { - return err - } - fields := make(map[string]any, record.NumAttrs()+len(h.attrs)) - for _, attr := range h.attrs { - h.addAttr(fields, attr) - } - record.Attrs(func(attr slog.Attr) bool { - h.addAttr(fields, attr) - return true - }) - component, _ := fields["component"].(string) - delete(fields, "component") - h.hub.Publish(LogEvent{ - Time: record.Time.UTC(), - Level: strings.ToLower(record.Level.String()), - Message: h.redactor.String(record.Message), - Component: component, - Fields: fields, - }) - return nil -} - -func (h *hubHandler) WithAttrs(attrs []slog.Attr) slog.Handler { - clone := *h - clone.base = h.base.WithAttrs(attrs) - clone.attrs = append(append([]slog.Attr(nil), h.attrs...), attrs...) - return &clone -} - -func (h *hubHandler) WithGroup(name string) slog.Handler { - clone := *h - clone.base = h.base.WithGroup(name) - clone.groups = append(append([]string(nil), h.groups...), name) - return &clone -} - -func (h *hubHandler) addAttr(fields map[string]any, attr slog.Attr) { - attr.Value = attr.Value.Resolve() - key := attr.Key - if len(h.groups) > 0 { - key = strings.Join(append(append([]string(nil), h.groups...), key), ".") - } - lower := strings.ToLower(key) - if strings.Contains(lower, "password") || strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "secret") { - fields[key] = "***" - return - } - var value any - switch attr.Value.Kind() { - case slog.KindString: - value = h.redactor.String(attr.Value.String()) - case slog.KindInt64: - value = attr.Value.Int64() - case slog.KindUint64: - value = attr.Value.Uint64() - case slog.KindFloat64: - value = attr.Value.Float64() - case slog.KindBool: - value = attr.Value.Bool() - case slog.KindDuration: - value = attr.Value.Duration().String() - case slog.KindTime: - value = attr.Value.Time().UTC() - default: - value = h.redactor.String(fmt.Sprint(attr.Value.Any())) - } - fields[key] = value -} - type requestMeta struct { - Model string - Tier string - Request string - KeyID string - Channel string - Anonymous bool - Proxy string - Attempts int - Stream bool - Usage bridgeUsage - UsageReported bool + Model string + Tier string + Protocol Protocol + Request string + KeyID string + Channel string + Anonymous bool + Proxy string + Attempts int + Stream bool + Usage bridgeUsage + UsageReported bool + AttemptOutcome string + Outcome string } type requestMetaKey struct{} @@ -308,600 +33,6 @@ func metaFromRequest(r *http.Request) *requestMeta { return meta } -type metricBucket struct { - minute int64 - total uint64 - success uint64 - errors uint64 - duration uint64 - histogram [11]uint64 - endpoints map[string]uint64 - models map[string]uint64 - tiers map[string]uint64 - statuses map[string]uint64 - usageRequests uint64 - usageReported uint64 - tokens TokenCounts - usageModels map[string]TokenCounts - usageTiers map[string]TokenCounts -} - -func (b *metricBucket) reset(minute int64) { - *b = metricBucket{ - minute: minute, endpoints: make(map[string]uint64), models: make(map[string]uint64), - tiers: make(map[string]uint64), statuses: make(map[string]uint64), - usageModels: make(map[string]TokenCounts), usageTiers: make(map[string]TokenCounts), - } -} - -type TokenCounts struct { - Input uint64 `json:"input_tokens"` - Output uint64 `json:"output_tokens"` - Cached uint64 `json:"cached_tokens"` - Reasoning uint64 `json:"reasoning_tokens"` - Total uint64 `json:"total_tokens"` -} - -type UsagePeriod struct { - Requests uint64 `json:"requests"` - Reported uint64 `json:"reported"` - Coverage float64 `json:"coverage"` - Tokens TokenCounts `json:"tokens"` - Models map[string]TokenCounts `json:"models"` - Tiers map[string]TokenCounts `json:"tiers"` -} - -type UsageSnapshot struct { - Lifetime UsagePeriod `json:"lifetime"` - Window UsagePeriod `json:"last_hour"` -} - -type AttemptCounts struct { - Total uint64 `json:"total"` - Success uint64 `json:"success"` - Failed uint64 `json:"failed"` -} - -type AttemptAggregate struct { - AttemptCounts - SuccessRate float64 `json:"success_rate"` - Tiers map[string]AttemptCounts `json:"tiers"` - Channels map[string]AttemptCounts `json:"channels"` - Keys map[string]AttemptCounts `json:"keys"` -} - -type UpstreamAttempt struct { - Time time.Time `json:"time"` - RequestID string `json:"request_id"` - Model string `json:"model"` - Tier string `json:"tier"` - Attempt int `json:"attempt"` - KeyID string `json:"key_id"` - Channel string `json:"channel"` - Anonymous bool `json:"anonymous"` - Proxy string `json:"proxy_node"` - Status int `json:"status,omitempty"` - DurationMS int64 `json:"duration_ms"` - Success bool `json:"success"` - Outcome string `json:"outcome"` -} - -// UpstreamRequest is the credential route that was actually used for one -// client inference request. It is kept separately from UpstreamAttempt, -// because a single request can try several keys before it succeeds. -type UpstreamRequest struct { - Time time.Time `json:"time"` - RequestID string `json:"request_id"` - Model string `json:"model"` - Tier string `json:"tier,omitempty"` - KeyID string `json:"key_id,omitempty"` - Channel string `json:"channel"` - Anonymous bool `json:"anonymous"` - Proxy string `json:"proxy_node,omitempty"` - Attempts int `json:"attempts"` - Status int `json:"status"` - DurationMS int64 `json:"duration_ms"` - Success bool `json:"success"` - Outcome string `json:"outcome"` -} - -type attemptBucket struct { - minute int64 - aggregate AttemptAggregate -} - -type UpstreamSnapshot struct { - Lifetime AttemptAggregate `json:"lifetime"` - Window AttemptAggregate `json:"last_hour"` - Requests []UpstreamRequest `json:"requests"` - Recent []UpstreamAttempt `json:"recent"` -} - -const ( - monitorRecentRequestCapacity = 10000 - monitorRecentAttemptCapacity = 20000 - monitorRecentOutputLimit = 500 -) - -type upstreamRequestRing struct { - items []UpstreamRequest - start int - count int -} - -func newUpstreamRequestRing() upstreamRequestRing { - return upstreamRequestRing{items: make([]UpstreamRequest, monitorRecentRequestCapacity)} -} - -func (ring *upstreamRequestRing) Add(value UpstreamRequest) { - if len(ring.items) == 0 { - ring.items = make([]UpstreamRequest, monitorRecentRequestCapacity) - } - index := (ring.start + ring.count) % len(ring.items) - if ring.count == len(ring.items) { - ring.items[index] = value - ring.start = (ring.start + 1) % len(ring.items) - return - } - ring.items[index] = value - ring.count++ -} - -func (ring *upstreamRequestRing) PruneBefore(cutoff time.Time) { - for ring.count > 0 && ring.items[ring.start].Time.Before(cutoff) { - ring.items[ring.start] = UpstreamRequest{} - ring.start = (ring.start + 1) % len(ring.items) - ring.count-- - } -} - -func (ring *upstreamRequestRing) Snapshot(cutoff time.Time, limit int) []UpstreamRequest { - if limit < 1 || ring.count == 0 { - return nil - } - result := make([]UpstreamRequest, 0, min(ring.count, limit)) - for offset := 0; offset < ring.count; offset++ { - value := ring.items[(ring.start+offset)%len(ring.items)] - if !value.Time.Before(cutoff) { - result = append(result, value) - } - } - if len(result) > limit { - result = result[len(result)-limit:] - } - return result -} - -type upstreamAttemptRing struct { - items []UpstreamAttempt - start int - count int -} - -func newUpstreamAttemptRing() upstreamAttemptRing { - return upstreamAttemptRing{items: make([]UpstreamAttempt, monitorRecentAttemptCapacity)} -} - -func (ring *upstreamAttemptRing) Add(value UpstreamAttempt) { - if len(ring.items) == 0 { - ring.items = make([]UpstreamAttempt, monitorRecentAttemptCapacity) - } - index := (ring.start + ring.count) % len(ring.items) - if ring.count == len(ring.items) { - ring.items[index] = value - ring.start = (ring.start + 1) % len(ring.items) - return - } - ring.items[index] = value - ring.count++ -} - -func (ring *upstreamAttemptRing) PruneBefore(cutoff time.Time) { - for ring.count > 0 && ring.items[ring.start].Time.Before(cutoff) { - ring.items[ring.start] = UpstreamAttempt{} - ring.start = (ring.start + 1) % len(ring.items) - ring.count-- - } -} - -func (ring *upstreamAttemptRing) Snapshot(cutoff time.Time, limit int) []UpstreamAttempt { - if limit < 1 || ring.count == 0 { - return nil - } - result := make([]UpstreamAttempt, 0, min(ring.count, limit)) - for offset := 0; offset < ring.count; offset++ { - value := ring.items[(ring.start+offset)%len(ring.items)] - if !value.Time.Before(cutoff) { - result = append(result, value) - } - } - if len(result) > limit { - result = result[len(result)-limit:] - } - return result -} - -type Monitor struct { - started time.Time - active atomic.Int64 - activeStreams atomic.Int64 - total atomic.Uint64 - success atomic.Uint64 - errors atomic.Uint64 - mu sync.Mutex - buckets [60]metricBucket - lifetimeUsage UsagePeriod - attemptLifetime AttemptAggregate - attemptBuckets [60]attemptBucket - recentRequests upstreamRequestRing - recentAttempts upstreamAttemptRing -} - -func NewMonitor() *Monitor { - return &Monitor{ - started: time.Now().UTC(), - lifetimeUsage: newUsagePeriod(), - attemptLifetime: newAttemptAggregate(), - recentRequests: newUpstreamRequestRing(), - recentAttempts: newUpstreamAttemptRing(), - } -} - -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) { - m.total.Add(1) - if status >= 200 && status < 400 { - m.success.Add(1) - } else { - m.errors.Add(1) - } - minute := time.Now().Unix() / 60 - m.mu.Lock() - bucket := &m.buckets[minute%60] - if bucket.minute != minute { - bucket.reset(minute) - } - bucket.total++ - if status >= 200 && status < 400 { - bucket.success++ - } else { - bucket.errors++ - } - milliseconds := uint64(max(duration.Milliseconds(), 0)) - bucket.duration += milliseconds - index := len(latencyBounds) - for i, bound := range latencyBounds { - if milliseconds <= bound { - index = i - break - } - } - bucket.histogram[index]++ - bucket.endpoints[endpoint]++ - bucket.statuses[fmt.Sprint(status)]++ - if meta != nil { - if meta.Model != "" { - bucket.models[meta.Model]++ - } - if meta.Tier != "" { - bucket.tiers[meta.Tier]++ - bucket.usageRequests++ - m.lifetimeUsage.Requests++ - if meta.UsageReported { - bucket.usageReported++ - m.lifetimeUsage.Reported++ - } - tokens := tokenCounts(meta.Usage) - addTokenCounts(&bucket.tokens, tokens) - addTokenCounts(&m.lifetimeUsage.Tokens, tokens) - addTokenMap(bucket.usageModels, meta.Model, tokens) - addTokenMap(bucket.usageTiers, meta.Tier, tokens) - addTokenMap(m.lifetimeUsage.Models, meta.Model, tokens) - addTokenMap(m.lifetimeUsage.Tiers, meta.Tier, tokens) - } - if meta.Request != "" && meta.Model != "" { - request := UpstreamRequest{ - Time: time.Now().UTC(), RequestID: meta.Request, Model: meta.Model, Tier: meta.Tier, - KeyID: meta.KeyID, Channel: meta.Channel, Anonymous: meta.Anonymous, Proxy: meta.Proxy, - Attempts: meta.Attempts, Status: status, DurationMS: max(duration.Milliseconds(), 0), - Success: status >= 200 && status < 400, - } - if request.Channel == "" { - request.Channel = "not_routed" - } - if request.Anonymous { - request.KeyID = "anonymous" - } - request.Outcome = requestOutcome(status, request.Channel) - m.recentRequests.PruneBefore(request.Time.Add(-time.Hour)) - m.recentRequests.Add(request) - } - } - m.mu.Unlock() -} - -func requestOutcome(status int, channel string) string { - if channel == "" || channel == "not_routed" { - return "not_routed" - } - if status >= 200 && status < 400 { - return "success" - } - if status >= 400 && status < 500 { - return "client_error" - } - if status >= 500 { - return "server_error" - } - return "unknown" -} - -func (m *Monitor) RecordAttempt(attempt UpstreamAttempt) { - if attempt.Time.IsZero() { - attempt.Time = time.Now().UTC() - } else { - attempt.Time = attempt.Time.UTC() - } - minute := attempt.Time.Unix() / 60 - m.mu.Lock() - recordAttemptAggregate(&m.attemptLifetime, attempt) - bucket := &m.attemptBuckets[minute%60] - if bucket.minute != minute { - *bucket = attemptBucket{minute: minute, aggregate: newAttemptAggregate()} - } - recordAttemptAggregate(&bucket.aggregate, attempt) - m.recentAttempts.PruneBefore(attempt.Time.Add(-time.Hour)) - m.recentAttempts.Add(attempt) - m.mu.Unlock() -} - -type MonitorSnapshot struct { - StartedAt time.Time `json:"started_at"` - UptimeSeconds int64 `json:"uptime_seconds"` - Active int64 `json:"active_requests"` - ActiveStreams int64 `json:"active_streams"` - Lifetime MetricSummary `json:"lifetime"` - Window MetricSummary `json:"last_hour"` - Series []MetricSeries `json:"series"` - Endpoints map[string]uint64 `json:"endpoints"` - Models map[string]uint64 `json:"models"` - Tiers map[string]uint64 `json:"tiers"` - Statuses map[string]uint64 `json:"statuses"` - Usage UsageSnapshot `json:"usage"` - Upstream UpstreamSnapshot `json:"upstream"` -} - -type MetricSummary struct { - Total uint64 `json:"total"` - Success uint64 `json:"success"` - Errors uint64 `json:"errors"` - SuccessRate float64 `json:"success_rate"` - AverageMS float64 `json:"average_ms,omitempty"` - P50MS uint64 `json:"p50_ms,omitempty"` - P95MS uint64 `json:"p95_ms,omitempty"` - P99MS uint64 `json:"p99_ms,omitempty"` -} - -type MetricSeries struct { - Minute time.Time `json:"minute"` - Total uint64 `json:"total"` - Success uint64 `json:"success"` - Errors uint64 `json:"errors"` - InputTokens uint64 `json:"input_tokens"` - OutputTokens uint64 `json:"output_tokens"` - CachedTokens uint64 `json:"cached_tokens"` - ReasoningTokens uint64 `json:"reasoning_tokens"` - TotalTokens uint64 `json:"total_tokens"` - UsageReported uint64 `json:"usage_reported"` -} - -func (m *Monitor) Snapshot() MonitorSnapshot { - nowMinute := time.Now().Unix() / 60 - window := MetricSummary{} - var histogram [11]uint64 - endpoints, models, tiers, statuses := map[string]uint64{}, map[string]uint64{}, map[string]uint64{}, map[string]uint64{} - series := make([]MetricSeries, 0, 60) - usageWindow := newUsagePeriod() - upstreamWindow := newAttemptAggregate() - var recentRequests []UpstreamRequest - var recentAttempts []UpstreamAttempt - m.mu.Lock() - for offset := int64(59); offset >= 0; offset-- { - minute := nowMinute - offset - bucket := &m.buckets[minute%60] - entry := MetricSeries{Minute: time.Unix(minute*60, 0).UTC()} - if bucket.minute == minute { - entry.Total, entry.Success, entry.Errors = bucket.total, bucket.success, bucket.errors - entry.InputTokens, entry.OutputTokens = bucket.tokens.Input, bucket.tokens.Output - entry.CachedTokens, entry.ReasoningTokens, entry.TotalTokens = bucket.tokens.Cached, bucket.tokens.Reasoning, bucket.tokens.Total - entry.UsageReported = bucket.usageReported - window.Total += bucket.total - window.Success += bucket.success - window.Errors += bucket.errors - window.AverageMS += float64(bucket.duration) - for i := range histogram { - histogram[i] += bucket.histogram[i] - } - mergeCounts(endpoints, bucket.endpoints) - mergeCounts(models, bucket.models) - mergeCounts(tiers, bucket.tiers) - mergeCounts(statuses, bucket.statuses) - usageWindow.Requests += bucket.usageRequests - usageWindow.Reported += bucket.usageReported - addTokenCounts(&usageWindow.Tokens, bucket.tokens) - mergeTokenMaps(usageWindow.Models, bucket.usageModels) - mergeTokenMaps(usageWindow.Tiers, bucket.usageTiers) - } - attemptBucket := &m.attemptBuckets[minute%60] - if attemptBucket.minute == minute { - mergeAttemptAggregate(&upstreamWindow, attemptBucket.aggregate) - } - series = append(series, entry) - } - usageLifetime := cloneUsagePeriod(m.lifetimeUsage) - upstreamLifetime := cloneAttemptAggregate(m.attemptLifetime) - cutoff := time.Now().Add(-time.Hour) - m.recentRequests.PruneBefore(cutoff) - m.recentAttempts.PruneBefore(cutoff) - recentRequests = m.recentRequests.Snapshot(cutoff, monitorRecentOutputLimit) - recentAttempts = m.recentAttempts.Snapshot(cutoff, monitorRecentOutputLimit) - m.mu.Unlock() - finalizeUsagePeriod(&usageLifetime) - finalizeUsagePeriod(&usageWindow) - finalizeAttemptAggregate(&upstreamLifetime) - finalizeAttemptAggregate(&upstreamWindow) - if window.Total > 0 { - window.SuccessRate = float64(window.Success) / float64(window.Total) - window.AverageMS /= float64(window.Total) - window.P50MS = histogramPercentile(histogram, window.Total, 0.50) - window.P95MS = histogramPercentile(histogram, window.Total, 0.95) - window.P99MS = histogramPercentile(histogram, window.Total, 0.99) - } - lifetime := MetricSummary{Total: m.total.Load(), Success: m.success.Load(), Errors: m.errors.Load()} - if lifetime.Total > 0 { - lifetime.SuccessRate = float64(lifetime.Success) / float64(lifetime.Total) - } - return MonitorSnapshot{ - StartedAt: m.started, UptimeSeconds: int64(time.Since(m.started).Seconds()), Active: m.active.Load(), - ActiveStreams: m.activeStreams.Load(), Lifetime: lifetime, Window: window, Series: series, - Endpoints: endpoints, Models: models, Tiers: tiers, Statuses: statuses, - Usage: UsageSnapshot{Lifetime: usageLifetime, Window: usageWindow}, - Upstream: UpstreamSnapshot{Lifetime: upstreamLifetime, Window: upstreamWindow, Requests: recentRequests, Recent: recentAttempts}, - } -} - -func mergeCounts(target, source map[string]uint64) { - for key, value := range source { - target[key] += value - } -} - -func newUsagePeriod() UsagePeriod { - return UsagePeriod{Models: make(map[string]TokenCounts), Tiers: make(map[string]TokenCounts)} -} - -func tokenCounts(usage bridgeUsage) 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)), - } -} - -func addTokenCounts(target *TokenCounts, source TokenCounts) { - target.Input += source.Input - target.Output += source.Output - target.Cached += source.Cached - target.Reasoning += source.Reasoning - target.Total += source.Total -} - -func addTokenMap(target map[string]TokenCounts, key string, value TokenCounts) { - if key == "" { - return - } - current := target[key] - addTokenCounts(¤t, value) - target[key] = current -} - -func mergeTokenMaps(target, source map[string]TokenCounts) { - for key, value := range source { - addTokenMap(target, key, value) - } -} - -func cloneUsagePeriod(source UsagePeriod) UsagePeriod { - result := newUsagePeriod() - result.Requests, result.Reported, result.Tokens = source.Requests, source.Reported, source.Tokens - mergeTokenMaps(result.Models, source.Models) - mergeTokenMaps(result.Tiers, source.Tiers) - return result -} - -func finalizeUsagePeriod(period *UsagePeriod) { - if period.Requests > 0 { - period.Coverage = float64(period.Reported) / float64(period.Requests) - } -} - -func newAttemptAggregate() AttemptAggregate { - return AttemptAggregate{ - Tiers: make(map[string]AttemptCounts), Channels: make(map[string]AttemptCounts), Keys: make(map[string]AttemptCounts), - } -} - -func recordAttemptAggregate(target *AttemptAggregate, attempt UpstreamAttempt) { - recordAttemptCounts(&target.AttemptCounts, attempt.Success) - addAttemptMap(target.Tiers, attempt.Tier, attempt.Success) - addAttemptMap(target.Channels, attempt.Channel, attempt.Success) - addAttemptMap(target.Keys, attempt.KeyID, attempt.Success) -} - -func recordAttemptCounts(target *AttemptCounts, success bool) { - target.Total++ - if success { - target.Success++ - } else { - target.Failed++ - } -} - -func addAttemptMap(target map[string]AttemptCounts, key string, success bool) { - if key == "" { - return - } - current := target[key] - recordAttemptCounts(¤t, success) - target[key] = current -} - -func mergeAttemptAggregate(target *AttemptAggregate, source AttemptAggregate) { - target.Total += source.Total - target.Success += source.Success - target.Failed += source.Failed - mergeAttemptMaps(target.Tiers, source.Tiers) - mergeAttemptMaps(target.Channels, source.Channels) - mergeAttemptMaps(target.Keys, source.Keys) -} - -func mergeAttemptMaps(target, source map[string]AttemptCounts) { - for key, value := range source { - current := target[key] - current.Total += value.Total - current.Success += value.Success - current.Failed += value.Failed - target[key] = current - } -} - -func cloneAttemptAggregate(source AttemptAggregate) AttemptAggregate { - result := newAttemptAggregate() - mergeAttemptAggregate(&result, source) - return result -} - -func finalizeAttemptAggregate(aggregate *AttemptAggregate) { - if aggregate.Total > 0 { - aggregate.SuccessRate = float64(aggregate.Success) / float64(aggregate.Total) - } -} - -func histogramPercentile(histogram [11]uint64, total uint64, percentile float64) uint64 { - target := uint64(float64(total)*percentile + 0.999) - var count uint64 - for i, value := range histogram { - count += value - if count >= target { - if i < len(latencyBounds) { - return latencyBounds[i] - } - return latencyBounds[len(latencyBounds)-1] + 1 - } - } - return 0 -} - type statusWriter struct { http.ResponseWriter status int @@ -938,8 +69,11 @@ func monitorMiddleware(monitor *Monitor, logger *slog.Logger, next http.Handler) return } started := time.Now() - meta := &requestMeta{} - r = r.WithContext(context.WithValue(r.Context(), requestMetaKey{}, meta)) + meta := metaFromRequest(r) + if meta == nil { + meta = &requestMeta{} + r = r.WithContext(context.WithValue(r.Context(), requestMetaKey{}, meta)) + } writer := &statusWriter{ResponseWriter: w} monitor.active.Add(1) defer func() { @@ -950,34 +84,25 @@ func monitorMiddleware(monitor *Monitor, logger *slog.Logger, next http.Handler) } duration := time.Since(started) monitor.Record(r.URL.Path, status, duration, meta) + outcome := meta.Outcome + if outcome == "" { + outcome = requestOutcome(status, meta.Channel) + } if meta.Channel != "" { logger.Info("request routed", "component", "http", "event", "request_routed", "method", r.Method, "path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "request_id", meta.Request, "model", meta.Model, "tier", meta.Tier, "key_id", meta.KeyID, "channel", meta.Channel, - "anonymous", meta.Anonymous, "attempts", meta.Attempts, "stream", meta.Stream) + "anonymous", meta.Anonymous, "attempts", meta.Attempts, "stream", meta.Stream, "outcome", outcome) } logger.Debug("request completed", "component", "http", "event", "request_complete", "method", r.Method, "path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "bytes", writer.bytes, "request_id", meta.Request, "model", meta.Model, "tier", meta.Tier, "key_id", meta.KeyID, - "channel", meta.Channel, "anonymous", meta.Anonymous, "attempts", meta.Attempts, "stream", meta.Stream) + "channel", meta.Channel, "anonymous", meta.Anonymous, "attempts", meta.Attempts, "stream", meta.Stream, "outcome", outcome) }() next.ServeHTTP(writer, r) }) } -func setLogLevel(level *slog.LevelVar, value string) { - switch value { - case "debug": - level.Set(slog.LevelDebug) - case "warn": - level.Set(slog.LevelWarn) - case "error": - level.Set(slog.LevelError) - default: - level.Set(slog.LevelInfo) - } -} - func encodeSSE(w http.ResponseWriter, event string, id uint64, value any) error { data, err := json.Marshal(value) if err != nil { diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..1792dd0 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,29 @@ +{ + "name": "opencode2api-dev", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "opencode2api-dev", + "devDependencies": { + "prettier": "3.9.6" + } + }, + "node_modules/prettier": { + "version": "3.9.6", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.6.tgz", + "integrity": "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..c603cde --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "opencode2api-dev", + "private": true, + "scripts": { + "format": "prettier --write .", + "format:check": "prettier --check .", + "check:web": "node --check webui/app.js" + }, + "devDependencies": { + "prettier": "3.9.6" + } +} diff --git a/pool.go b/pool.go index 91ada8e..d757b7a 100644 --- a/pool.go +++ b/pool.go @@ -328,6 +328,20 @@ func (p *nodePool) RestoreProxy(recoveredProxy int) int { func (p *nodePool) Len() int { return len(p.nodes) } +// NodeByID resolves a node by its stable fingerprint. Callers only ever hold +// the fingerprint, never the key value, so the lookup cannot leak a secret. +func (p *nodePool) NodeByID(id string) *upstreamNode { + if p == nil || id == "" { + return nil + } + for _, node := range p.nodes { + if secretFingerprint(node.key) == id { + return node + } + } + return nil +} + func (p *nodePool) Proxy(node *upstreamNode) *proxyTransport { if p == nil || node == nil || p.transports == nil { return nil diff --git a/runtime.go b/runtime.go index b6a041d..b0ba957 100644 --- a/runtime.go +++ b/runtime.go @@ -277,7 +277,8 @@ func (m *RuntimeManager) Resources() ResourceSnapshot { return ResourceSnapshot{} } gateway := runtime.gateway - result := ResourceSnapshot{Models: gateway.catalog.Snapshot(), Anonymous: gateway.cfg.Anonymous} + _, models := gateway.availableModels() + result := ResourceSnapshot{Models: models, Anonymous: gateway.cfg.Anonymous} if gateway.catalog.metadata != nil { result.Metadata = gateway.catalog.metadata.Snapshot() } @@ -329,6 +330,74 @@ func (m *RuntimeManager) DebugRoute(model string, requested Protocol) ModelRoute return gateway.catalog.Diagnostic(model, requested, len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0, gateway.cfg.Anonymous) } +// 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"` +} + +// DebugKeys lists every configured upstream key per tier so the Playground can +// offer an explicit per-key test target. +func (m *RuntimeManager) DebugKeys() map[string][]DebugKeyView { + result := map[string][]DebugKeyView{"zen": {}, "go": {}} + runtime := m.current.Load() + if runtime == nil { + return result + } + appendKeys := func(tier Tier, nodes []*upstreamNode) { + for _, node := range nodes { + view := DebugKeyView{ + ID: secretFingerprint(node.key), Tier: tier, Display: maskValue(node.key), + Index: node.index, Failures: node.failures.Load(), + } + if until := node.cooldownUntil.Load(); until > time.Now().UnixNano() { + value := time.Unix(0, until).UTC() + view.CooldownUntil = &value + } + result[string(tier)] = append(result[string(tier)], view) + } + } + appendKeys(TierZen, runtime.gateway.zenNodes.nodes) + appendKeys(TierGo, runtime.gateway.goNodes.nodes) + return result +} + +func (m *RuntimeManager) DebugKey(tier Tier, id string) *DebugKeyView { + for _, view := range m.DebugKeys()[string(tier)] { + if view.ID == id { + selected := view + return &selected + } + } + return nil +} + +// DebugRouteForTier reports the route a diagnostic against one tier would take. +func (m *RuntimeManager) DebugRouteForTier(model string, tier Tier) (ModelRouteDiagnostic, error) { + runtime := m.current.Load() + if runtime == nil { + return ModelRouteDiagnostic{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 + diagnostic := gateway.catalog.Diagnostic(model, "", hasZen, hasGo, false) + route, err := gateway.catalog.RouteForTier(model, tier, hasZen, hasGo) + if err != nil { + diagnostic.RouteError = err.Error() + return diagnostic, err + } + diagnostic.RouteError = "" + diagnostic.Tier, diagnostic.Anonymous = route.Tier, false + diagnostic.KeyTiers = []Tier{tier} + diagnostic.NativeProtocol, diagnostic.NativeProtocols = route.Protocol, route.Protocols + return diagnostic, nil +} + func keyStatuses(tier string, pool *nodePool) []KeyStatus { result := make([]KeyStatus, 0, len(pool.nodes)) for _, node := range pool.nodes { diff --git a/selected_key_test.go b/selected_key_test.go new file mode 100644 index 0000000..3060072 --- /dev/null +++ b/selected_key_test.go @@ -0,0 +1,206 @@ +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.go b/stream.go index 7db24b4..fc8c34f 100644 --- a/stream.go +++ b/stream.go @@ -4,17 +4,17 @@ import ( "bufio" "bytes" "context" - "encoding/json" "errors" "fmt" "io" "net/http" "strings" - "time" ) var errStreamUpstreamFailure = errors.New("upstream stream failure delivered") + var errStreamNormalTermination = errors.New("upstream stream terminated normally") + var errSSEUnexpectedEOF = errors.New("unexpected end of SSE stream") type streamTermination uint8 @@ -41,17 +41,6 @@ type bridgeStreamEvent struct { Usage *bridgeUsage } -type bridgeStreamParser struct { - protocol Protocol - started bool - tools map[string]bool - toolIDs map[string]string - toolNames map[string]string - toolOrder []string - responseArgs map[string]bool - responseReasoning map[string]bool -} - func transcodeStream(w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) error { _, _, err := transcodeStreamWithUsage(w, reader, from, to, model) return err @@ -105,7 +94,7 @@ func transcodeStreamWithUsageContext(ctx context.Context, w http.ResponseWriter, return nil }) if readErr != nil { - if errors.Is(readErr, errStreamNormalTermination) || errors.Is(readErr, errStreamUpstreamFailure) { + if errors.Is(readErr, errStreamNormalTermination) { return emitter.usage, emitter.usageReported, nil } if streamClientCancelled(ctx, readErr) { @@ -118,16 +107,19 @@ func transcodeStreamWithUsageContext(ctx context.Context, w http.ResponseWriter, } return emitter.usage, emitter.usageReported, readErr } - if termination == streamNormalTermination || termination == streamErrorTermination { + if termination == streamNormalTermination { return emitter.usage, emitter.usageReported, nil } + if termination == streamErrorTermination { + return emitter.usage, emitter.usageReported, errStreamUpstreamFailure + } if streamClientCancelled(ctx, nil) { return emitter.usage, emitter.usageReported, ctx.Err() } if err := emitUnexpectedStreamError(emitter, errSSEUnexpectedEOF); err != nil { return emitter.usage, emitter.usageReported, err } - return emitter.usage, emitter.usageReported, nil + return emitter.usage, emitter.usageReported, errSSEUnexpectedEOF } func emitUnexpectedStreamError(emitter *bridgeStreamEmitter, cause error) error { @@ -178,10 +170,19 @@ func forwardSSEWithUsageContext(ctx context.Context, w http.ResponseWriter, read observer := newStreamUsageObserver(protocol) _, copyErr := io.Copy(&sseFlushWriter{writer: w, flusher: flusher}, io.TeeReader(reader, observer)) usage := observer.Finish() - if observer.ErrorTermination() || observer.NormalTermination() && observer.ParseError() == nil { + if observer.ErrorTermination() { + if copyErr != nil { + return usage, observer.Reported(), copyErr + } + return usage, observer.Reported(), errStreamUpstreamFailure + } + if observer.NormalTermination() && observer.ParseError() == nil { return usage, observer.Reported(), copyErr } if streamClientCancelled(ctx, copyErr) { + if copyErr == nil { + copyErr = ctx.Err() + } return usage, observer.Reported(), copyErr } cause := observer.ParseError() @@ -195,7 +196,7 @@ func forwardSSEWithUsageContext(ctx context.Context, w http.ResponseWriter, read if err := emitUnexpectedStreamError(emitter, cause); err != nil { return usage, observer.Reported(), err } - return usage, observer.Reported(), copyErr + return usage, observer.Reported(), cause } type streamUsageObserver struct { @@ -329,976 +330,3 @@ func readSSE(reader io.Reader, handler func(eventName, data string) error) error } return nil } - -func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamEvent, error) { - if data == "[DONE]" { - if parser.protocol != ProtocolChat { - return nil, fmt.Errorf("unexpected [DONE] terminator for %s stream", parser.protocol) - } - return []bridgeStreamEvent{{Kind: "done"}}, nil - } - var value map[string]any - if err := json.Unmarshal([]byte(data), &value); err != nil { - return nil, fmt.Errorf("invalid upstream SSE JSON: %w", err) - } - switch parser.protocol { - case ProtocolChat: - return parser.parseChatEvent(eventName, value), nil - case ProtocolAnthropic: - return parser.parseAnthropicEvent(eventName, value) - case ProtocolResponses: - return parser.parseResponses(eventName, value), nil - default: - return nil, fmt.Errorf("unsupported stream protocol %q", parser.protocol) - } -} - -func (parser *bridgeStreamParser) parseChat(value map[string]any) []bridgeStreamEvent { - return parser.parseChatEvent("", value) -} - -func (parser *bridgeStreamParser) parseChatEvent(eventName string, value map[string]any) []bridgeStreamEvent { - events := make([]bridgeStreamEvent, 0, 4) - if eventName == "error" { - return []bridgeStreamEvent{{Kind: "error", Error: streamErrorMessage(value, "upstream Chat stream error"), ErrorType: streamErrorType(value)}} - } - if rawError, exists := value["error"]; exists && rawError != nil { - return []bridgeStreamEvent{{Kind: "error", Error: streamErrorMessage(value, "upstream Chat stream error"), ErrorType: streamErrorType(value)}} - } - if !parser.started { - if id := stringAt(value, "id"); id != "" { - parser.started = true - events = append(events, bridgeStreamEvent{Kind: "start", ResponseID: id, Model: stringAt(value, "model")}) - } - } - if usageMap := mapAt(value, "usage"); len(usageMap) > 0 { - usage := decodeOpenAIUsage(usageMap) - events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) - } - for _, raw := range sliceAt(value, "choices") { - choice, _ := raw.(map[string]any) - delta := mapAt(choice, "delta") - if reasoning := firstString(stringAt(delta, "reasoning_content"), stringAt(delta, "reasoning")); reasoning != "" { - events = append(events, bridgeStreamEvent{Kind: "reasoning", Text: reasoning}) - } - if text := stringAt(delta, "content"); text != "" { - events = append(events, bridgeStreamEvent{Kind: "text", Text: text}) - } - for _, rawCall := range sliceAt(delta, "tool_calls") { - call, _ := rawCall.(map[string]any) - key := fmt.Sprint(firstAny(call["index"], stringAt(call, "id"))) - function := mapAt(call, "function") - id := stringAt(call, "id") - if _, seen := parser.tools[key]; !seen { - parser.tools[key] = false - parser.toolOrder = append(parser.toolOrder, key) - } - if id != "" { - parser.toolIDs[key] = id - } - if name := stringAt(function, "name"); name != "" { - parser.toolNames[key] = mergeToolName(parser.toolNames[key], name) - } - if arguments := 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]}) - } - 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 isStreamErrorFinish(stop) { - events = append(events, bridgeStreamEvent{Kind: "error", Error: firstString(stringAt(choice, "error", "message"), "upstream Chat stream failed"), ErrorType: "upstream_error"}) - continue - } - for _, key := range parser.toolOrder { - 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]}) - } - } - events = append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}) - } - } - return events -} - -func (parser *bridgeStreamParser) parseAnthropic(value map[string]any) ([]bridgeStreamEvent, error) { - return parser.parseAnthropicEvent("", value) -} - -func (parser *bridgeStreamParser) parseAnthropicEvent(eventName string, value map[string]any) ([]bridgeStreamEvent, error) { - typeName := 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 { - usage := decodeAnthropicUsage(usageMap) - events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) - } - return events, nil - case "content_block_start": - block := mapAt(value, "content_block") - key := fmt.Sprint(value["index"]) - switch stringAt(block, "type") { - case "thinking": - events := make([]bridgeStreamEvent, 0, 2) - if thinking := stringAt(block, "thinking"); thinking != "" { - events = append(events, bridgeStreamEvent{Kind: "reasoning", Text: thinking}) - } - if signature := 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 - case "tool_use": - parser.tools[key] = true - return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: stringAt(block, "id"), ToolName: stringAt(block, "name")}}, nil - case "text": - if text := stringAt(block, "text"); text != "" { - return []bridgeStreamEvent{{Kind: "text", Text: text}}, nil - } - } - case "content_block_delta": - delta := mapAt(value, "delta") - key := fmt.Sprint(value["index"]) - switch stringAt(delta, "type") { - case "thinking_delta": - return []bridgeStreamEvent{{Kind: "reasoning", Text: stringAt(delta, "thinking")}}, nil - case "signature_delta": - return []bridgeStreamEvent{{Kind: "reasoning_signature", Signature: stringAt(delta, "signature")}}, nil - case "text_delta": - return []bridgeStreamEvent{{Kind: "text", Text: stringAt(delta, "text")}}, nil - case "input_json_delta": - return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, Text: stringAt(delta, "partial_json")}}, nil - } - case "message_delta": - events := make([]bridgeStreamEvent, 0, 2) - if usageMap := 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 isStreamErrorFinish(stop) { - events = append(events, bridgeStreamEvent{Kind: "error", Error: "upstream Anthropic stream failed", ErrorType: "upstream_error"}) - return events, nil - } - events = append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}) - } - return events, nil - 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 - } - return nil, nil -} - -func (parser *bridgeStreamParser) parseResponses(eventName string, value map[string]any) []bridgeStreamEvent { - typeName := stringAt(value, "type") - if typeName == "" { - typeName = eventName - } - switch typeName { - 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")}} - case "response.output_text.delta": - return []bridgeStreamEvent{{Kind: "text", Text: 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")}} - case "response.output_item.added": - item := mapAt(value, "item") - if stringAt(item, "type") == "function_call" { - key := responseToolKey(value, item) - parser.rememberTool(key, stringAt(item, "call_id"), 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]}} - } - } - 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")}} - 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")}} - } - case "response.output_item.done": - item := mapAt(value, "item") - if stringAt(item, "type") == "reasoning" { - key := responseToolKey(value, item) - if parser.responseReasoning[key] { - return nil - } - blocks := decodeResponsesReasoning(item) - if len(blocks) > 0 { - return []bridgeStreamEvent{{Kind: "reasoning", Text: blocks[0].Text, Encrypted: blocks[0].Encrypted}} - } - return nil - } - if stringAt(item, "type") == "function_call" { - key := responseToolKey(value, item) - parser.rememberTool(key, stringAt(item, "call_id"), 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 != "" { - 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")}} - if len(usageMap) > 0 { - usage := decodeOpenAIUsage(usageMap) - events = append([]bridgeStreamEvent{{Kind: "usage", Usage: &usage}}, events...) - } - return events - } - stop := "stop" - if typeName == "response.incomplete" { - stop = canonicalResponsesIncomplete(stringAt(response, "incomplete_details", "reason")) - } - events := make([]bridgeStreamEvent, 0, 3) - if len(usageMap) > 0 { - usage := decodeOpenAIUsage(usageMap) - events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) - } - return append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}, bridgeStreamEvent{Kind: "done"}) - } - return nil -} - -func streamErrorMessage(value map[string]any, fallback string) string { - if message := stringAt(value, "error", "message"); message != "" { - return message - } - if message := stringAt(value, "message"); message != "" { - return message - } - if message, ok := value["error"].(string); ok && message != "" { - return message - } - return fallback -} - -func streamErrorType(value map[string]any) string { - return firstString(stringAt(value, "error", "type"), stringAt(value, "error", "code"), "upstream_error") -} - -func isStreamErrorFinish(stop string) bool { - switch strings.ToLower(strings.TrimSpace(stop)) { - case "error", "network_error", "server_error": - return true - default: - return false - } -} - -func (parser *bridgeStreamParser) rememberTool(key, id, name string) { - if _, seen := parser.tools[key]; !seen { - parser.tools[key] = false - parser.toolOrder = append(parser.toolOrder, key) - } - if id != "" { - parser.toolIDs[key] = id - } - if name != "" { - parser.toolNames[key] = name - } -} - -func mergeToolName(current, fragment string) string { - if current == "" || fragment == current { - return fragment - } - if strings.HasPrefix(fragment, current) { - return fragment - } - return current + fragment -} - -func responseToolKey(event map[string]any, item map[string]any) string { - if item != nil { - if id := stringAt(item, "id"); id != "" { - return id - } - } - if id := stringAt(event, "item_id"); id != "" { - return id - } - return fmt.Sprint(event["output_index"]) -} - -type bridgeStreamTool struct { - Key string - ID string - ItemID string - Name string - Arguments strings.Builder - Index int - AnthropicIndex int - Started bool - EmittedArguments int -} - -type bridgeStreamEmitter struct { - w io.Writer - flush http.Flusher - target Protocol - model string - id string - created int64 - started bool - done bool - stop string - usage bridgeUsage - usageReported bool - reasoningEncrypted string - text strings.Builder - reasoning strings.Builder - reasoningSignature strings.Builder - - tools map[string]*bridgeStreamTool - order []string - - sequence int - nextOutput int - textOpen bool - reasoningOpen bool - reasoningClosed bool - reasoningItemID string - reasoningOutput int - reasoningIndex int - textIndex int - nextAnthropic int - textItemID string - textOutput int - responseOutput []any -} - -func newBridgeStreamEmitter(writer io.Writer, flusher http.Flusher, target Protocol, model string) *bridgeStreamEmitter { - return &bridgeStreamEmitter{ - w: writer, - flush: flusher, - target: target, - model: model, - created: time.Now().Unix(), - tools: map[string]*bridgeStreamTool{}, - } -} - -func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error { - if event.ResponseID != "" && emitter.id == "" { - emitter.id = event.ResponseID - } - if event.Model != "" { - emitter.model = event.Model - } - if !emitter.started && (event.Kind == "start" || event.Kind == "reasoning" || event.Kind == "reasoning_signature" || event.Kind == "text" || event.Kind == "tool_start" || event.Kind == "tool_delta") { - if err := emitter.start(); err != nil { - return err - } - } - switch event.Kind { - case "reasoning": - if event.Encrypted != "" { - emitter.reasoningEncrypted = event.Encrypted - if emitter.target != ProtocolResponses && event.Text == "" { - event.Text = anthropicRedactedThinkingPlaceholder - } - if emitter.target == ProtocolResponses && event.Text == "" { - return emitter.startReasoning() - } - } - if event.Text == "" { - return nil - } - emitter.reasoning.WriteString(event.Text) - return emitter.emitReasoning(event.Text) - case "reasoning_signature": - if event.Signature == "" { - return nil - } - emitter.reasoningSignature.WriteString(event.Signature) - return emitter.emitReasoningSignature(event.Signature) - case "text": - if event.Text == "" { - return nil - } - emitter.text.WriteString(event.Text) - return emitter.emitText(event.Text) - case "tool_start": - tool := emitter.tool(event.ToolKey) - if event.ToolID != "" { - tool.ID = event.ToolID - } - if event.ToolName != "" { - tool.Name = event.ToolName - } - if err := emitter.startTool(tool); err != nil { - return err - } - return emitter.emitPendingToolArguments(tool) - case "tool_delta": - tool := emitter.tool(event.ToolKey) - if event.ToolID != "" { - tool.ID = event.ToolID - } - if event.ToolName != "" { - tool.Name = event.ToolName - } - tool.Arguments.WriteString(event.Text) - if err := emitter.startTool(tool); err != nil { - return err - } - return emitter.emitPendingToolArguments(tool) - case "usage": - if event.Usage != nil { - emitter.usageReported = true - mergeBridgeUsage(&emitter.usage, *event.Usage) - } - case "finish": - 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 { - return err - } - return errStreamUpstreamFailure - case "done": - return emitter.Finish() - } - return nil -} - -func (emitter *bridgeStreamEmitter) emitError(message, errorType string) error { - switch emitter.target { - case ProtocolAnthropic: - return emitter.sse("error", map[string]any{ - "type": "error", - "error": map[string]any{"type": errorType, "message": message}, - }) - case ProtocolResponses: - response := emitter.responsesBase("failed", []any{}) - response["error"] = map[string]any{"code": errorType, "message": message} - return emitter.sse("response.failed", map[string]any{ - "type": "response.failed", - "response": response, - "sequence_number": emitter.nextSequence(), - }) - default: - if err := emitter.sse("", map[string]any{"error": map[string]any{ - "message": message, - "type": errorType, - "param": nil, - "code": nil, - }}); err != nil { - return err - } - return emitter.rawSSE("", "[DONE]") - } -} - -func (emitter *bridgeStreamEmitter) tool(key string) *bridgeStreamTool { - if key == "" { - key = fmt.Sprintf("tool-%d", len(emitter.order)) - } - if current := emitter.tools[key]; current != nil { - return current - } - tool := &bridgeStreamTool{ - Key: key, - ID: randomID("call", 12), - ItemID: randomID("fc", 12), - Index: len(emitter.order), - } - emitter.tools[key] = tool - emitter.order = append(emitter.order, key) - return tool -} - -func (emitter *bridgeStreamEmitter) start() error { - if emitter.started { - return nil - } - emitter.started = true - if emitter.id == "" { - emitter.id = randomID("resp", 12) - } - switch emitter.target { - case ProtocolChat: - return emitter.sse("", map[string]any{ - "id": asPrefix(emitter.id, "chatcmpl"), - "object": "chat.completion.chunk", - "created": emitter.created, - "model": emitter.model, - "choices": []any{map[string]any{ - "index": 0, - "delta": map[string]any{"role": "assistant", "content": ""}, - "finish_reason": nil, - }}, - }) - case ProtocolAnthropic: - return emitter.sse("message_start", map[string]any{ - "type": "message_start", - "message": map[string]any{ - "id": asPrefix(emitter.id, "msg"), - "type": "message", - "role": "assistant", - "model": emitter.model, - "content": []any{}, - "stop_reason": nil, - "stop_sequence": nil, - "usage": anthropicUsage(bridgeUsage{}), - }, - }) - case ProtocolResponses: - 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 - } - return emitter.sse("response.in_progress", map[string]any{"type": "response.in_progress", "response": response, "sequence_number": emitter.nextSequence()}) - default: - return fmt.Errorf("unsupported stream target %q", emitter.target) - } -} - -func (emitter *bridgeStreamEmitter) emitText(delta string) error { - if emitter.target == ProtocolAnthropic || emitter.target == ProtocolResponses { - if err := emitter.finishReasoning(); err != nil { - return err - } - } - switch emitter.target { - case ProtocolChat: - return emitter.chatChunk(map[string]any{"content": delta}, nil) - case ProtocolAnthropic: - if !emitter.textOpen { - emitter.textOpen = true - emitter.textIndex = emitter.nextAnthropic - emitter.nextAnthropic++ - if err := emitter.sse("content_block_start", map[string]any{ - "type": "content_block_start", - "index": emitter.textIndex, - "content_block": map[string]any{"type": "text", "text": ""}, - }); err != nil { - return err - } - } - return emitter.sse("content_block_delta", map[string]any{ - "type": "content_block_delta", - "index": emitter.textIndex, - "delta": map[string]any{"type": "text_delta", "text": delta}, - }) - case ProtocolResponses: - if !emitter.textOpen { - emitter.textOpen = true - emitter.textItemID = 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{}} - if err := emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": emitter.textOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { - return err - } - part := map[string]any{"type": "output_text", "text": "", "annotations": []any{}} - if err := emitter.sse("response.content_part.added", map[string]any{"type": "response.content_part.added", "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil { - return err - } - } - return emitter.sse("response.output_text.delta", map[string]any{"type": "response.output_text.delta", "delta": delta, "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "sequence_number": emitter.nextSequence()}) - } - return nil -} - -func (emitter *bridgeStreamEmitter) emitReasoning(delta string) error { - if err := emitter.startReasoning(); err != nil { - return err - } - switch emitter.target { - case ProtocolChat: - return emitter.chatChunk(map[string]any{"reasoning_content": delta}, nil) - case ProtocolAnthropic: - 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: - 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 -} - -func (emitter *bridgeStreamEmitter) emitReasoningSignature(signature string) error { - if err := emitter.startReasoning(); err != nil { - return err - } - switch emitter.target { - case ProtocolChat: - return emitter.chatChunk(map[string]any{"reasoning_signature": signature}, nil) - case ProtocolAnthropic: - return emitter.sse("content_block_delta", map[string]any{ - "type": "content_block_delta", - "index": emitter.reasoningIndex, - "delta": map[string]any{"type": "signature_delta", "signature": signature}, - }) - } - return nil -} - -func (emitter *bridgeStreamEmitter) startReasoning() error { - if emitter.reasoningOpen || emitter.reasoningClosed { - return nil - } - emitter.reasoningOpen = true - switch emitter.target { - case ProtocolAnthropic: - emitter.reasoningIndex = emitter.nextAnthropic - emitter.nextAnthropic++ - return emitter.sse("content_block_start", map[string]any{ - "type": "content_block_start", - "index": emitter.reasoningIndex, - "content_block": map[string]any{"type": "thinking", "thinking": "", "signature": ""}, - }) - case ProtocolResponses: - emitter.reasoningItemID = randomID("rs", 12) - emitter.reasoningOutput = emitter.nextOutput - emitter.nextOutput++ - item := map[string]any{"id": emitter.reasoningItemID, "type": "reasoning", "status": "in_progress", "summary": []any{}} - if err := emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": emitter.reasoningOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { - return err - } - part := map[string]any{"type": "summary_text", "text": ""} - return emitter.sse("response.reasoning_summary_part.added", map[string]any{"type": "response.reasoning_summary_part.added", "item_id": emitter.reasoningItemID, "output_index": emitter.reasoningOutput, "summary_index": 0, "part": part, "sequence_number": emitter.nextSequence()}) - } - return nil -} - -func (emitter *bridgeStreamEmitter) finishReasoning() error { - if !emitter.reasoningOpen || emitter.reasoningClosed { - return nil - } - emitter.reasoningClosed = true - text := emitter.reasoning.String() - switch emitter.target { - case ProtocolAnthropic: - return emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.reasoningIndex}) - case ProtocolResponses: - 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 - } - part := map[string]any{"type": "summary_text", "text": text} - if err := emitter.sse("response.reasoning_summary_part.done", map[string]any{"type": "response.reasoning_summary_part.done", "item_id": emitter.reasoningItemID, "output_index": emitter.reasoningOutput, "summary_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil { - return err - } - item := map[string]any{"id": emitter.reasoningItemID, "type": "reasoning", "status": "completed", "summary": []any{part}} - if emitter.reasoningEncrypted != "" { - item["encrypted_content"] = emitter.reasoningEncrypted - } - return emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": emitter.reasoningOutput, "item": item, "sequence_number": emitter.nextSequence()}) - } - return nil -} - -func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error { - if tool.Started || tool.Name == "" { - return nil - } - if emitter.target == ProtocolResponses || emitter.target == ProtocolAnthropic { - if err := emitter.finishReasoning(); err != nil { - return err - } - } - if emitter.target == ProtocolAnthropic && emitter.textOpen { - if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.textIndex}); err != nil { - return err - } - emitter.textOpen = false - } - tool.Started = true - switch emitter.target { - case ProtocolChat: - return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{ - "index": tool.Index, - "id": tool.ID, - "type": "function", - "function": map[string]any{ - "name": tool.Name, - "arguments": "", - }, - }}}, nil) - case ProtocolResponses: - 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: - tool.AnthropicIndex = emitter.nextAnthropic - emitter.nextAnthropic++ - return emitter.sse("content_block_start", map[string]any{ - "type": "content_block_start", "index": tool.AnthropicIndex, - "content_block": map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": map[string]any{}}, - }) - } - return nil -} - -func (emitter *bridgeStreamEmitter) emitToolDelta(tool *bridgeStreamTool, delta string) error { - if delta == "" { - return nil - } - switch emitter.target { - case ProtocolChat: - return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{ - "index": tool.Index, - "function": map[string]any{"arguments": delta}, - }}}, nil) - case ProtocolResponses: - 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: - 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 -} - -func (emitter *bridgeStreamEmitter) emitPendingToolArguments(tool *bridgeStreamTool) error { - if !tool.Started { - return nil - } - arguments := tool.Arguments.String() - if tool.EmittedArguments >= len(arguments) { - return nil - } - delta := arguments[tool.EmittedArguments:] - tool.EmittedArguments = len(arguments) - return emitter.emitToolDelta(tool, delta) -} - -func (emitter *bridgeStreamEmitter) Finish() error { - if emitter.done { - return nil - } - emitter.done = true - if !emitter.started { - if err := emitter.start(); err != nil { - return err - } - } - if emitter.stop == "" { - if len(emitter.order) > 0 { - emitter.stop = "tool_calls" - } else { - emitter.stop = "stop" - } - } - if err := emitter.finishReasoning(); err != nil { - return err - } - switch emitter.target { - case ProtocolChat: - if err := emitter.chatChunk(map[string]any{}, chatStop(emitter.stop)); err != nil { - return err - } - if err := emitter.sse("", map[string]any{ - "id": asPrefix(emitter.id, "chatcmpl"), - "object": "chat.completion.chunk", - "created": emitter.created, - "model": emitter.model, - "choices": []any{}, - "usage": openAIUsage(emitter.usage), - }); err != nil { - return err - } - return emitter.rawSSE("", "[DONE]") - - case ProtocolAnthropic: - if emitter.textOpen { - if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.textIndex}); err != nil { - return err - } - } - for _, key := range emitter.order { - tool := emitter.tools[key] - if err := emitter.startTool(tool); err != nil { - return err - } - if err := emitter.emitPendingToolArguments(tool); err != nil { - return err - } - if tool.Started { - if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": tool.AnthropicIndex}); err != nil { - return err - } - } - } - if err := emitter.sse("message_delta", map[string]any{ - "type": "message_delta", - "delta": map[string]any{"stop_reason": anthropicStop(emitter.stop), "stop_sequence": nil}, - "usage": anthropicUsage(emitter.usage), - }); err != nil { - return err - } - return emitter.sse("message_stop", map[string]any{"type": "message_stop"}) - - case ProtocolResponses: - if err := emitter.finishResponsesItems(); err != nil { - return err - } - response := bridgeResponse{ - ID: emitter.id, - Model: emitter.model, - Text: emitter.text.String(), - Reasoning: []bridgeBlock{{Kind: "reasoning", ID: emitter.reasoningItemID, Text: emitter.reasoning.String(), Signature: emitter.reasoningSignature.String()}}, - Stop: emitter.stop, - Usage: emitter.usage, - Created: emitter.created, - } - if emitter.reasoning.Len() == 0 && emitter.reasoningSignature.Len() == 0 { - response.Reasoning = nil - } - for _, key := range emitter.order { - 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) - return emitter.sse("response.completed", map[string]any{"type": "response.completed", "response": completed, "sequence_number": emitter.nextSequence()}) - } - return nil -} - -func (emitter *bridgeStreamEmitter) finishResponsesItems() error { - if emitter.textOpen { - text := emitter.text.String() - if err := emitter.sse("response.output_text.done", map[string]any{"type": "response.output_text.done", "text": text, "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "sequence_number": emitter.nextSequence()}); err != nil { - return err - } - part := map[string]any{"type": "output_text", "text": text, "annotations": []any{}} - if err := emitter.sse("response.content_part.done", map[string]any{"type": "response.content_part.done", "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil { - return err - } - item := map[string]any{"id": emitter.textItemID, "type": "message", "status": "completed", "role": "assistant", "content": []any{part}} - if err := emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": emitter.textOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { - return err - } - } - for _, key := range emitter.order { - tool := emitter.tools[key] - arguments := tool.Arguments.String() - if arguments == "" { - arguments = "{}" - } - if err := emitter.startTool(tool); err != nil { - return err - } - if err := emitter.emitPendingToolArguments(tool); err != nil { - return err - } - if err := emitter.sse("response.function_call_arguments.done", map[string]any{"type": "response.function_call_arguments.done", "arguments": arguments, "item_id": tool.ItemID, "output_index": tool.Index, "sequence_number": emitter.nextSequence()}); err != nil { - return err - } - item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "completed", "arguments": arguments, "call_id": tool.ID, "name": tool.Name} - if err := emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": tool.Index, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { - return err - } - } - return nil -} - -func (emitter *bridgeStreamEmitter) chatChunk(delta map[string]any, finish any) error { - return emitter.sse("", map[string]any{ - "id": asPrefix(emitter.id, "chatcmpl"), - "object": "chat.completion.chunk", - "created": emitter.created, - "model": emitter.model, - "choices": []any{map[string]any{ - "index": 0, - "delta": delta, - "finish_reason": finish, - }}, - }) -} - -func (emitter *bridgeStreamEmitter) responsesBase(status string, output []any) map[string]any { - return map[string]any{ - "id": asPrefix(emitter.id, "resp"), - "object": "response", - "created_at": emitter.created, - "status": status, - "model": emitter.model, - "output": output, - "error": nil, - } -} - -func (emitter *bridgeStreamEmitter) nextSequence() int { - sequence := emitter.sequence - emitter.sequence++ - return sequence -} - -func (emitter *bridgeStreamEmitter) sse(eventName string, value any) error { - data, err := json.Marshal(value) - if err != nil { - return err - } - return emitter.rawSSE(eventName, string(data)) -} - -func (emitter *bridgeStreamEmitter) rawSSE(eventName, data string) error { - if eventName != "" { - if _, err := fmt.Fprintf(emitter.w, "event: %s\n", eventName); err != nil { - return err - } - } - if _, err := fmt.Fprintf(emitter.w, "data: %s\n\n", data); err != nil { - return err - } - emitter.flush.Flush() - return nil -} - -func mergeBridgeUsage(destination *bridgeUsage, source bridgeUsage) { - if source.Input != 0 { - destination.Input = source.Input - } - if source.Output != 0 { - destination.Output = source.Output - } - if source.Total != 0 { - destination.Total = max(destination.Total, source.Total) - } - if source.Cached != 0 { - destination.Cached = source.Cached - } - if source.CacheCreation != 0 { - destination.CacheCreation = source.CacheCreation - } - if source.Reasoning != 0 { - destination.Reasoning = source.Reasoning - } - destination.Total = max(destination.Total, destination.Input+destination.Output) -} diff --git a/stream_emitter.go b/stream_emitter.go new file mode 100644 index 0000000..0ecd1d6 --- /dev/null +++ b/stream_emitter.go @@ -0,0 +1,660 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" +) + +type bridgeStreamTool struct { + Key string + ID string + ItemID string + Name string + Arguments strings.Builder + Index int + AnthropicIndex int + Started bool + EmittedArguments int +} + +type bridgeStreamEmitter struct { + w io.Writer + flush http.Flusher + target Protocol + model string + id string + created int64 + started bool + done bool + stop string + usage bridgeUsage + usageReported bool + reasoningEncrypted string + text strings.Builder + reasoning strings.Builder + reasoningSignature strings.Builder + + tools map[string]*bridgeStreamTool + order []string + + sequence int + nextOutput int + textOpen bool + reasoningOpen bool + reasoningClosed bool + reasoningItemID string + reasoningOutput int + reasoningIndex int + textIndex int + nextAnthropic int + textItemID string + textOutput int + responseOutput []any +} + +func newBridgeStreamEmitter(writer io.Writer, flusher http.Flusher, target Protocol, model string) *bridgeStreamEmitter { + return &bridgeStreamEmitter{ + w: writer, + flush: flusher, + target: target, + model: model, + created: time.Now().Unix(), + tools: map[string]*bridgeStreamTool{}, + } +} + +func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error { + if event.ResponseID != "" && emitter.id == "" { + emitter.id = event.ResponseID + } + if event.Model != "" { + emitter.model = event.Model + } + if !emitter.started && (event.Kind == "start" || event.Kind == "reasoning" || event.Kind == "reasoning_signature" || event.Kind == "text" || event.Kind == "tool_start" || event.Kind == "tool_delta") { + if err := emitter.start(); err != nil { + return err + } + } + switch event.Kind { + case "reasoning": + if event.Encrypted != "" { + emitter.reasoningEncrypted = event.Encrypted + if emitter.target != ProtocolResponses && event.Text == "" { + event.Text = anthropicRedactedThinkingPlaceholder + } + if emitter.target == ProtocolResponses && event.Text == "" { + return emitter.startReasoning() + } + } + if event.Text == "" { + return nil + } + emitter.reasoning.WriteString(event.Text) + return emitter.emitReasoning(event.Text) + case "reasoning_signature": + if event.Signature == "" { + return nil + } + emitter.reasoningSignature.WriteString(event.Signature) + return emitter.emitReasoningSignature(event.Signature) + case "text": + if event.Text == "" { + return nil + } + emitter.text.WriteString(event.Text) + return emitter.emitText(event.Text) + case "tool_start": + tool := emitter.tool(event.ToolKey) + if event.ToolID != "" { + tool.ID = event.ToolID + } + if event.ToolName != "" { + tool.Name = event.ToolName + } + if err := emitter.startTool(tool); err != nil { + return err + } + return emitter.emitPendingToolArguments(tool) + case "tool_delta": + tool := emitter.tool(event.ToolKey) + if event.ToolID != "" { + tool.ID = event.ToolID + } + if event.ToolName != "" { + tool.Name = event.ToolName + } + tool.Arguments.WriteString(event.Text) + if err := emitter.startTool(tool); err != nil { + return err + } + return emitter.emitPendingToolArguments(tool) + case "usage": + if event.Usage != nil { + emitter.usageReported = true + mergeBridgeUsage(&emitter.usage, *event.Usage) + } + case "finish": + 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 { + return err + } + return errStreamUpstreamFailure + case "done": + return emitter.Finish() + } + return nil +} + +func (emitter *bridgeStreamEmitter) emitError(message, errorType string) error { + switch emitter.target { + case ProtocolAnthropic: + return emitter.sse("error", map[string]any{ + "type": "error", + "error": map[string]any{"type": errorType, "message": message}, + }) + case ProtocolResponses: + response := emitter.responsesBase("failed", []any{}) + response["error"] = map[string]any{"code": errorType, "message": message} + return emitter.sse("response.failed", map[string]any{ + "type": "response.failed", + "response": response, + "sequence_number": emitter.nextSequence(), + }) + default: + if err := emitter.sse("", map[string]any{"error": map[string]any{ + "message": message, + "type": errorType, + "param": nil, + "code": nil, + }}); err != nil { + return err + } + return emitter.rawSSE("", "[DONE]") + } +} + +func (emitter *bridgeStreamEmitter) tool(key string) *bridgeStreamTool { + if key == "" { + key = fmt.Sprintf("tool-%d", len(emitter.order)) + } + if current := emitter.tools[key]; current != nil { + return current + } + tool := &bridgeStreamTool{ + Key: key, + ID: randomID("call", 12), + ItemID: randomID("fc", 12), + Index: len(emitter.order), + } + emitter.tools[key] = tool + emitter.order = append(emitter.order, key) + return tool +} + +func (emitter *bridgeStreamEmitter) start() error { + if emitter.started { + return nil + } + emitter.started = true + if emitter.id == "" { + emitter.id = randomID("resp", 12) + } + switch emitter.target { + case ProtocolChat: + return emitter.sse("", map[string]any{ + "id": asPrefix(emitter.id, "chatcmpl"), + "object": "chat.completion.chunk", + "created": emitter.created, + "model": emitter.model, + "choices": []any{map[string]any{ + "index": 0, + "delta": map[string]any{"role": "assistant", "content": ""}, + "finish_reason": nil, + }}, + }) + case ProtocolAnthropic: + return emitter.sse("message_start", map[string]any{ + "type": "message_start", + "message": map[string]any{ + "id": asPrefix(emitter.id, "msg"), + "type": "message", + "role": "assistant", + "model": emitter.model, + "content": []any{}, + "stop_reason": nil, + "stop_sequence": nil, + "usage": anthropicUsage(bridgeUsage{}), + }, + }) + case ProtocolResponses: + 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 + } + return emitter.sse("response.in_progress", map[string]any{"type": "response.in_progress", "response": response, "sequence_number": emitter.nextSequence()}) + default: + return fmt.Errorf("unsupported stream target %q", emitter.target) + } +} + +func (emitter *bridgeStreamEmitter) emitText(delta string) error { + if emitter.target == ProtocolAnthropic || emitter.target == ProtocolResponses { + if err := emitter.finishReasoning(); err != nil { + return err + } + } + switch emitter.target { + case ProtocolChat: + return emitter.chatChunk(map[string]any{"content": delta}, nil) + case ProtocolAnthropic: + if !emitter.textOpen { + emitter.textOpen = true + emitter.textIndex = emitter.nextAnthropic + emitter.nextAnthropic++ + if err := emitter.sse("content_block_start", map[string]any{ + "type": "content_block_start", + "index": emitter.textIndex, + "content_block": map[string]any{"type": "text", "text": ""}, + }); err != nil { + return err + } + } + return emitter.sse("content_block_delta", map[string]any{ + "type": "content_block_delta", + "index": emitter.textIndex, + "delta": map[string]any{"type": "text_delta", "text": delta}, + }) + case ProtocolResponses: + if !emitter.textOpen { + emitter.textOpen = true + emitter.textItemID = 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{}} + if err := emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": emitter.textOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + part := map[string]any{"type": "output_text", "text": "", "annotations": []any{}} + if err := emitter.sse("response.content_part.added", map[string]any{"type": "response.content_part.added", "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + } + return emitter.sse("response.output_text.delta", map[string]any{"type": "response.output_text.delta", "delta": delta, "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "sequence_number": emitter.nextSequence()}) + } + return nil +} + +func (emitter *bridgeStreamEmitter) emitReasoning(delta string) error { + if err := emitter.startReasoning(); err != nil { + return err + } + switch emitter.target { + case ProtocolChat: + return emitter.chatChunk(map[string]any{"reasoning_content": delta}, nil) + case ProtocolAnthropic: + 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: + 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 +} + +func (emitter *bridgeStreamEmitter) emitReasoningSignature(signature string) error { + if err := emitter.startReasoning(); err != nil { + return err + } + switch emitter.target { + case ProtocolChat: + return emitter.chatChunk(map[string]any{"reasoning_signature": signature}, nil) + case ProtocolAnthropic: + return emitter.sse("content_block_delta", map[string]any{ + "type": "content_block_delta", + "index": emitter.reasoningIndex, + "delta": map[string]any{"type": "signature_delta", "signature": signature}, + }) + } + return nil +} + +func (emitter *bridgeStreamEmitter) startReasoning() error { + if emitter.reasoningOpen || emitter.reasoningClosed { + return nil + } + emitter.reasoningOpen = true + switch emitter.target { + case ProtocolAnthropic: + emitter.reasoningIndex = emitter.nextAnthropic + emitter.nextAnthropic++ + return emitter.sse("content_block_start", map[string]any{ + "type": "content_block_start", + "index": emitter.reasoningIndex, + "content_block": map[string]any{"type": "thinking", "thinking": "", "signature": ""}, + }) + case ProtocolResponses: + emitter.reasoningItemID = randomID("rs", 12) + emitter.reasoningOutput = emitter.nextOutput + emitter.nextOutput++ + item := map[string]any{"id": emitter.reasoningItemID, "type": "reasoning", "status": "in_progress", "summary": []any{}} + if err := emitter.sse("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": emitter.reasoningOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + part := map[string]any{"type": "summary_text", "text": ""} + return emitter.sse("response.reasoning_summary_part.added", map[string]any{"type": "response.reasoning_summary_part.added", "item_id": emitter.reasoningItemID, "output_index": emitter.reasoningOutput, "summary_index": 0, "part": part, "sequence_number": emitter.nextSequence()}) + } + return nil +} + +func (emitter *bridgeStreamEmitter) finishReasoning() error { + if !emitter.reasoningOpen || emitter.reasoningClosed { + return nil + } + emitter.reasoningClosed = true + text := emitter.reasoning.String() + switch emitter.target { + case ProtocolAnthropic: + return emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.reasoningIndex}) + case ProtocolResponses: + 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 + } + part := map[string]any{"type": "summary_text", "text": text} + if err := emitter.sse("response.reasoning_summary_part.done", map[string]any{"type": "response.reasoning_summary_part.done", "item_id": emitter.reasoningItemID, "output_index": emitter.reasoningOutput, "summary_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + item := map[string]any{"id": emitter.reasoningItemID, "type": "reasoning", "status": "completed", "summary": []any{part}} + if emitter.reasoningEncrypted != "" { + item["encrypted_content"] = emitter.reasoningEncrypted + } + return emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": emitter.reasoningOutput, "item": item, "sequence_number": emitter.nextSequence()}) + } + return nil +} + +func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error { + if tool.Started || tool.Name == "" { + return nil + } + if emitter.target == ProtocolResponses || emitter.target == ProtocolAnthropic { + if err := emitter.finishReasoning(); err != nil { + return err + } + } + if emitter.target == ProtocolAnthropic && emitter.textOpen { + if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.textIndex}); err != nil { + return err + } + emitter.textOpen = false + } + tool.Started = true + switch emitter.target { + case ProtocolChat: + return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{ + "index": tool.Index, + "id": tool.ID, + "type": "function", + "function": map[string]any{ + "name": tool.Name, + "arguments": "", + }, + }}}, nil) + case ProtocolResponses: + 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: + tool.AnthropicIndex = emitter.nextAnthropic + emitter.nextAnthropic++ + return emitter.sse("content_block_start", map[string]any{ + "type": "content_block_start", "index": tool.AnthropicIndex, + "content_block": map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": map[string]any{}}, + }) + } + return nil +} + +func (emitter *bridgeStreamEmitter) emitToolDelta(tool *bridgeStreamTool, delta string) error { + if delta == "" { + return nil + } + switch emitter.target { + case ProtocolChat: + return emitter.chatChunk(map[string]any{"tool_calls": []any{map[string]any{ + "index": tool.Index, + "function": map[string]any{"arguments": delta}, + }}}, nil) + case ProtocolResponses: + 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: + 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 +} + +func (emitter *bridgeStreamEmitter) emitPendingToolArguments(tool *bridgeStreamTool) error { + if !tool.Started { + return nil + } + arguments := tool.Arguments.String() + if tool.EmittedArguments >= len(arguments) { + return nil + } + delta := arguments[tool.EmittedArguments:] + tool.EmittedArguments = len(arguments) + return emitter.emitToolDelta(tool, delta) +} + +func (emitter *bridgeStreamEmitter) Finish() error { + if emitter.done { + return nil + } + emitter.done = true + if !emitter.started { + if err := emitter.start(); err != nil { + return err + } + } + if emitter.stop == "" { + if len(emitter.order) > 0 { + emitter.stop = "tool_calls" + } else { + emitter.stop = "stop" + } + } + if err := emitter.finishReasoning(); err != nil { + return err + } + switch emitter.target { + case ProtocolChat: + if err := emitter.chatChunk(map[string]any{}, chatStop(emitter.stop)); err != nil { + return err + } + if err := emitter.sse("", map[string]any{ + "id": asPrefix(emitter.id, "chatcmpl"), + "object": "chat.completion.chunk", + "created": emitter.created, + "model": emitter.model, + "choices": []any{}, + "usage": openAIUsage(emitter.usage), + }); err != nil { + return err + } + return emitter.rawSSE("", "[DONE]") + + case ProtocolAnthropic: + if emitter.textOpen { + if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": emitter.textIndex}); err != nil { + return err + } + } + for _, key := range emitter.order { + tool := emitter.tools[key] + if err := emitter.startTool(tool); err != nil { + return err + } + if err := emitter.emitPendingToolArguments(tool); err != nil { + return err + } + if tool.Started { + if err := emitter.sse("content_block_stop", map[string]any{"type": "content_block_stop", "index": tool.AnthropicIndex}); err != nil { + return err + } + } + } + if err := emitter.sse("message_delta", map[string]any{ + "type": "message_delta", + "delta": map[string]any{"stop_reason": anthropicStop(emitter.stop), "stop_sequence": nil}, + "usage": anthropicUsage(emitter.usage), + }); err != nil { + return err + } + return emitter.sse("message_stop", map[string]any{"type": "message_stop"}) + + case ProtocolResponses: + if err := emitter.finishResponsesItems(); err != nil { + return err + } + response := bridgeResponse{ + ID: emitter.id, + Model: emitter.model, + Text: emitter.text.String(), + Reasoning: []bridgeBlock{{Kind: "reasoning", ID: emitter.reasoningItemID, Text: emitter.reasoning.String(), Signature: emitter.reasoningSignature.String()}}, + Stop: emitter.stop, + Usage: emitter.usage, + Created: emitter.created, + } + if emitter.reasoning.Len() == 0 && emitter.reasoningSignature.Len() == 0 { + response.Reasoning = nil + } + for _, key := range emitter.order { + 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) + return emitter.sse("response.completed", map[string]any{"type": "response.completed", "response": completed, "sequence_number": emitter.nextSequence()}) + } + return nil +} + +func (emitter *bridgeStreamEmitter) finishResponsesItems() error { + if emitter.textOpen { + text := emitter.text.String() + if err := emitter.sse("response.output_text.done", map[string]any{"type": "response.output_text.done", "text": text, "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + part := map[string]any{"type": "output_text", "text": text, "annotations": []any{}} + if err := emitter.sse("response.content_part.done", map[string]any{"type": "response.content_part.done", "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "part": part, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + item := map[string]any{"id": emitter.textItemID, "type": "message", "status": "completed", "role": "assistant", "content": []any{part}} + if err := emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": emitter.textOutput, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + } + for _, key := range emitter.order { + tool := emitter.tools[key] + arguments := tool.Arguments.String() + if arguments == "" { + arguments = "{}" + } + if err := emitter.startTool(tool); err != nil { + return err + } + if err := emitter.emitPendingToolArguments(tool); err != nil { + return err + } + if err := emitter.sse("response.function_call_arguments.done", map[string]any{"type": "response.function_call_arguments.done", "arguments": arguments, "item_id": tool.ItemID, "output_index": tool.Index, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + item := map[string]any{"id": tool.ItemID, "type": "function_call", "status": "completed", "arguments": arguments, "call_id": tool.ID, "name": tool.Name} + if err := emitter.sse("response.output_item.done", map[string]any{"type": "response.output_item.done", "output_index": tool.Index, "item": item, "sequence_number": emitter.nextSequence()}); err != nil { + return err + } + } + return nil +} + +func (emitter *bridgeStreamEmitter) chatChunk(delta map[string]any, finish any) error { + return emitter.sse("", map[string]any{ + "id": asPrefix(emitter.id, "chatcmpl"), + "object": "chat.completion.chunk", + "created": emitter.created, + "model": emitter.model, + "choices": []any{map[string]any{ + "index": 0, + "delta": delta, + "finish_reason": finish, + }}, + }) +} + +func (emitter *bridgeStreamEmitter) responsesBase(status string, output []any) map[string]any { + return map[string]any{ + "id": asPrefix(emitter.id, "resp"), + "object": "response", + "created_at": emitter.created, + "status": status, + "model": emitter.model, + "output": output, + "error": nil, + } +} + +func (emitter *bridgeStreamEmitter) nextSequence() int { + sequence := emitter.sequence + emitter.sequence++ + return sequence +} + +func (emitter *bridgeStreamEmitter) sse(eventName string, value any) error { + data, err := json.Marshal(value) + if err != nil { + return err + } + return emitter.rawSSE(eventName, string(data)) +} + +func (emitter *bridgeStreamEmitter) rawSSE(eventName, data string) error { + if eventName != "" { + if _, err := fmt.Fprintf(emitter.w, "event: %s\n", eventName); err != nil { + return err + } + } + if _, err := fmt.Fprintf(emitter.w, "data: %s\n\n", data); err != nil { + return err + } + emitter.flush.Flush() + return nil +} + +func mergeBridgeUsage(destination *bridgeUsage, source bridgeUsage) { + if source.Input != 0 { + destination.Input = source.Input + } + if source.Output != 0 { + destination.Output = source.Output + } + if source.Total != 0 { + destination.Total = max(destination.Total, source.Total) + } + if source.Cached != 0 { + destination.Cached = source.Cached + } + if source.CacheCreation != 0 { + destination.CacheCreation = source.CacheCreation + } + if source.Reasoning != 0 { + destination.Reasoning = source.Reasoning + } + destination.Total = max(destination.Total, destination.Input+destination.Output) +} diff --git a/stream_parser.go b/stream_parser.go new file mode 100644 index 0000000..c35ceaf --- /dev/null +++ b/stream_parser.go @@ -0,0 +1,362 @@ +package main + +import ( + "encoding/json" + "fmt" + "strings" +) + +type bridgeStreamParser struct { + protocol Protocol + started bool + tools map[string]bool + toolIDs map[string]string + toolNames map[string]string + toolOrder []string + responseArgs map[string]bool + responseReasoning map[string]bool +} + +func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamEvent, error) { + if data == "[DONE]" { + if parser.protocol != ProtocolChat { + return nil, fmt.Errorf("unexpected [DONE] terminator for %s stream", parser.protocol) + } + return []bridgeStreamEvent{{Kind: "done"}}, nil + } + var value map[string]any + if err := json.Unmarshal([]byte(data), &value); err != nil { + return nil, fmt.Errorf("invalid upstream SSE JSON: %w", err) + } + switch parser.protocol { + case ProtocolChat: + return parser.parseChatEvent(eventName, value), nil + case ProtocolAnthropic: + return parser.parseAnthropicEvent(eventName, value) + case ProtocolResponses: + return parser.parseResponses(eventName, value), nil + default: + return nil, fmt.Errorf("unsupported stream protocol %q", parser.protocol) + } +} + +func (parser *bridgeStreamParser) parseChat(value map[string]any) []bridgeStreamEvent { + return parser.parseChatEvent("", value) +} + +func (parser *bridgeStreamParser) parseChatEvent(eventName string, value map[string]any) []bridgeStreamEvent { + events := make([]bridgeStreamEvent, 0, 4) + if eventName == "error" { + return []bridgeStreamEvent{{Kind: "error", Error: streamErrorMessage(value, "upstream Chat stream error"), ErrorType: streamErrorType(value)}} + } + if rawError, exists := value["error"]; exists && rawError != nil { + return []bridgeStreamEvent{{Kind: "error", Error: streamErrorMessage(value, "upstream Chat stream error"), ErrorType: streamErrorType(value)}} + } + if !parser.started { + if id := stringAt(value, "id"); id != "" { + parser.started = true + events = append(events, bridgeStreamEvent{Kind: "start", ResponseID: id, Model: stringAt(value, "model")}) + } + } + if usageMap := mapAt(value, "usage"); len(usageMap) > 0 { + usage := decodeOpenAIUsage(usageMap) + events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) + } + for _, raw := range sliceAt(value, "choices") { + choice, _ := raw.(map[string]any) + delta := mapAt(choice, "delta") + if reasoning := firstString(stringAt(delta, "reasoning_content"), stringAt(delta, "reasoning")); reasoning != "" { + events = append(events, bridgeStreamEvent{Kind: "reasoning", Text: reasoning}) + } + if text := stringAt(delta, "content"); text != "" { + events = append(events, bridgeStreamEvent{Kind: "text", Text: text}) + } + for _, rawCall := range sliceAt(delta, "tool_calls") { + call, _ := rawCall.(map[string]any) + key := fmt.Sprint(firstAny(call["index"], stringAt(call, "id"))) + function := mapAt(call, "function") + id := stringAt(call, "id") + if _, seen := parser.tools[key]; !seen { + parser.tools[key] = false + parser.toolOrder = append(parser.toolOrder, key) + } + if id != "" { + parser.toolIDs[key] = id + } + if name := stringAt(function, "name"); name != "" { + parser.toolNames[key] = mergeToolName(parser.toolNames[key], name) + } + if arguments := 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]}) + } + 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 isStreamErrorFinish(stop) { + events = append(events, bridgeStreamEvent{Kind: "error", Error: firstString(stringAt(choice, "error", "message"), "upstream Chat stream failed"), ErrorType: "upstream_error"}) + continue + } + for _, key := range parser.toolOrder { + 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]}) + } + } + events = append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}) + } + } + return events +} + +func (parser *bridgeStreamParser) parseAnthropic(value map[string]any) ([]bridgeStreamEvent, error) { + return parser.parseAnthropicEvent("", value) +} + +func (parser *bridgeStreamParser) parseAnthropicEvent(eventName string, value map[string]any) ([]bridgeStreamEvent, error) { + typeName := 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 { + usage := decodeAnthropicUsage(usageMap) + events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) + } + return events, nil + case "content_block_start": + block := mapAt(value, "content_block") + key := fmt.Sprint(value["index"]) + switch stringAt(block, "type") { + case "thinking": + events := make([]bridgeStreamEvent, 0, 2) + if thinking := stringAt(block, "thinking"); thinking != "" { + events = append(events, bridgeStreamEvent{Kind: "reasoning", Text: thinking}) + } + if signature := 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 + case "tool_use": + parser.tools[key] = true + return []bridgeStreamEvent{{Kind: "tool_start", ToolKey: key, ToolID: stringAt(block, "id"), ToolName: stringAt(block, "name")}}, nil + case "text": + if text := stringAt(block, "text"); text != "" { + return []bridgeStreamEvent{{Kind: "text", Text: text}}, nil + } + } + case "content_block_delta": + delta := mapAt(value, "delta") + key := fmt.Sprint(value["index"]) + switch stringAt(delta, "type") { + case "thinking_delta": + return []bridgeStreamEvent{{Kind: "reasoning", Text: stringAt(delta, "thinking")}}, nil + case "signature_delta": + return []bridgeStreamEvent{{Kind: "reasoning_signature", Signature: stringAt(delta, "signature")}}, nil + case "text_delta": + return []bridgeStreamEvent{{Kind: "text", Text: stringAt(delta, "text")}}, nil + case "input_json_delta": + return []bridgeStreamEvent{{Kind: "tool_delta", ToolKey: key, Text: stringAt(delta, "partial_json")}}, nil + } + case "message_delta": + events := make([]bridgeStreamEvent, 0, 2) + if usageMap := 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 isStreamErrorFinish(stop) { + events = append(events, bridgeStreamEvent{Kind: "error", Error: "upstream Anthropic stream failed", ErrorType: "upstream_error"}) + return events, nil + } + events = append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}) + } + return events, nil + 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 + } + return nil, nil +} + +func (parser *bridgeStreamParser) parseResponses(eventName string, value map[string]any) []bridgeStreamEvent { + typeName := stringAt(value, "type") + if typeName == "" { + typeName = eventName + } + switch typeName { + 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")}} + case "response.output_text.delta": + return []bridgeStreamEvent{{Kind: "text", Text: 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")}} + case "response.output_item.added": + item := mapAt(value, "item") + if stringAt(item, "type") == "function_call" { + key := responseToolKey(value, item) + parser.rememberTool(key, stringAt(item, "call_id"), 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]}} + } + } + 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")}} + 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")}} + } + case "response.output_item.done": + item := mapAt(value, "item") + if stringAt(item, "type") == "reasoning" { + key := responseToolKey(value, item) + if parser.responseReasoning[key] { + return nil + } + blocks := decodeResponsesReasoning(item) + if len(blocks) > 0 { + return []bridgeStreamEvent{{Kind: "reasoning", Text: blocks[0].Text, Encrypted: blocks[0].Encrypted}} + } + return nil + } + if stringAt(item, "type") == "function_call" { + key := responseToolKey(value, item) + parser.rememberTool(key, stringAt(item, "call_id"), 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 != "" { + 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")}} + if len(usageMap) > 0 { + usage := decodeOpenAIUsage(usageMap) + events = append([]bridgeStreamEvent{{Kind: "usage", Usage: &usage}}, events...) + } + return events + } + stop := "stop" + if typeName == "response.incomplete" { + stop = canonicalResponsesIncomplete(stringAt(response, "incomplete_details", "reason")) + } else { + stop = parser.responsesCompletedStop(response) + } + events := make([]bridgeStreamEvent, 0, 3) + if len(usageMap) > 0 { + usage := decodeOpenAIUsage(usageMap) + events = append(events, bridgeStreamEvent{Kind: "usage", Usage: &usage}) + } + return append(events, bridgeStreamEvent{Kind: "finish", Stop: stop}, bridgeStreamEvent{Kind: "done"}) + } + return nil +} + +// responsesCompletedStop decides how a finished Responses turn is reported +// downstream. The completed event carries no stop reason, so the function_call +// items in its output — or the tool calls observed earlier on the stream — are +// the only signal that the turn ended waiting for tool results. Defaulting to +// "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") { + item, _ := raw.(map[string]any) + if stringAt(item, "type") == "function_call" { + return "tool_calls" + } + } + if len(parser.toolOrder) > 0 { + return "tool_calls" + } + return "stop" +} + +func streamErrorMessage(value map[string]any, fallback string) string { + if message := stringAt(value, "error", "message"); message != "" { + return message + } + if message := stringAt(value, "message"); message != "" { + return message + } + if message, ok := value["error"].(string); ok && message != "" { + return message + } + return fallback +} + +func streamErrorType(value map[string]any) string { + return firstString(stringAt(value, "error", "type"), stringAt(value, "error", "code"), "upstream_error") +} + +func isStreamErrorFinish(stop string) bool { + switch strings.ToLower(strings.TrimSpace(stop)) { + case "error", "network_error", "server_error": + return true + default: + return false + } +} + +func (parser *bridgeStreamParser) rememberTool(key, id, name string) { + if _, seen := parser.tools[key]; !seen { + parser.tools[key] = false + parser.toolOrder = append(parser.toolOrder, key) + } + if id != "" { + parser.toolIDs[key] = id + } + if name != "" { + parser.toolNames[key] = name + } +} + +func mergeToolName(current, fragment string) string { + if current == "" || fragment == current { + return fragment + } + if strings.HasPrefix(fragment, current) { + return fragment + } + return current + fragment +} + +func responseToolKey(event map[string]any, item map[string]any) string { + if item != nil { + if id := stringAt(item, "id"); id != "" { + return id + } + } + if id := stringAt(event, "item_id"); id != "" { + return id + } + return fmt.Sprint(event["output_index"]) +} diff --git a/stream_test.go b/stream_test.go new file mode 100644 index 0000000..eee7586 --- /dev/null +++ b/stream_test.go @@ -0,0 +1,74 @@ +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 new file mode 100644 index 0000000..47872b7 --- /dev/null +++ b/test_helpers_test.go @@ -0,0 +1,85 @@ +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/upstream.go b/upstream.go new file mode 100644 index 0000000..e29409c --- /dev/null +++ b/upstream.go @@ -0,0 +1,642 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "sort" + "strings" + "time" +) + +// 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 + KeyID string +} + +type debugKeyOverrideContextKey struct{} + +type diagnosticContextKey struct{} + +func withDiagnosticRequest(ctx context.Context) context.Context { + return context.WithValue(ctx, diagnosticContextKey{}, true) +} + +func isDiagnosticRequest(ctx context.Context) bool { + diagnostic, _ := ctx.Value(diagnosticContextKey{}).(bool) + return diagnostic +} + +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) + return override, ok && override.KeyID != "" +} + +func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs) (*http.Response, modelRoute, error) { + resp, effectiveRoute, attempts, err := g.doUpstreamTiers(ctx, route, bodies, ids, 0) + if _, selected := debugKeyOverrideFrom(ctx); selected { + return resp, effectiveRoute, err + } + if err != nil || resp == nil || resp.StatusCode != http.StatusBadRequest { + return resp, effectiveRoute, err + } + origBody := resp.Body + errBody, readErr := io.ReadAll(io.LimitReader(origBody, 1<<20)) + // 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) + if readErr != nil { + resp.Body = io.NopCloser(bytes.NewReader(errBody)) + return resp, effectiveRoute, nil + } + // Restore the body so downstream error handling still sees the original + // payload when no retry happens below. + resp.Body = io.NopCloser(bytes.NewReader(errBody)) + if !isStaleReasoningReference(errBody) { + return resp, effectiveRoute, nil + } + stripped, changed := stripStaleReasoningInputs(effectiveRoute, bodies) + if !changed { + return resp, effectiveRoute, nil + } + // The referenced reasoning items belong to an upstream chain this session + // can no longer address (e.g. an interrupted stream). Replay once without + // them instead of failing the client request outright. Attempt numbering + // continues from the first round so monitoring never shows duplicate attempt + // numbers for one request. + // + // The client's session is deliberately preserved: it carries key/proxy + // affinity and upstream session correlation. Minting a fresh session made + // the replay land on a different node with a cold prompt cache and detached + // the reply from the chain the client still holds; the stale references are + // already removed from the payload itself. + g.logger.Info("retrying upstream without stale reasoning references", "component", "upstream", "event", "reasoning_reference_retry", "request_id", ids.Request, "model", route.ID, "tier", effectiveRoute.Tier, "attempt_offset", attempts) + retryResp, retryRoute, _, retryErr := g.doUpstreamTiers(ctx, effectiveRoute, stripped, ids, attempts) + if retryErr != nil || retryResp == nil || retryResp.StatusCode/100 != 2 { + retryStatus := 0 + if retryResp != nil { + retryStatus = retryResp.StatusCode + 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 + fallback.Body = io.NopCloser(bytes.NewReader(errBody)) + return &fallback, effectiveRoute, nil + } + return retryResp, retryRoute, nil +} + +// isStaleReasoningReference reports whether an upstream 400 body describes a +// reasoning item/reference the server no longer recognizes, such as +// "Referenced reasoning item 'rs_...' was not found or has expired". +// Generic validation errors that merely mention reasoning (e.g. "unknown +// reasoning field") must NOT match, so both the target phrase and the +// gone/expired marker are required. +func isStaleReasoningReference(body []byte) bool { + text := strings.ToLower(string(body)) + if !strings.Contains(text, "reasoning item") && !strings.Contains(text, "reasoning reference") { + return false + } + for _, marker := range []string{"not found", "expir", "does not exist", "no longer"} { + if strings.Contains(text, marker) { + return true + } + } + return false +} + +// stripStaleReasoningInputs removes server-issued reasoning references from +// 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) { + changed := false + out := make(map[Tier][]byte, len(bodies)) + for tier, body := range bodies { + if len(body) == 0 || route.ProtocolFor(tier) != ProtocolResponses { + out[tier] = body + continue + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + out[tier] = body + continue + } + tierChanged := false + if _, ok := payload["previous_response_id"]; ok { + delete(payload, "previous_response_id") + tierChanged = true + } + 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" { + tierChanged = true + continue + } + kept = append(kept, item) + } + if tierChanged { + payload["input"] = kept + } + } + if !tierChanged { + out[tier] = body + continue + } + encoded, err := json.Marshal(payload) + if err != nil { + out[tier] = body + continue + } + out[tier] = encoded + changed = true + } + 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) { + var lastResponse *http.Response + var lastErr error + effectiveRoute := route + attempts := attemptOffset + g.dumpOutboundBodies(route, bodies, ids, attemptOffset) + if override, selected := debugKeyOverrideFrom(ctx); selected { + resp, err, used := g.doSelectedKeyUpstream(ctx, route, bodies, ids, override, attemptOffset) + return resp, route, used, err + } + if route.Anonymous { + resp, err, used := g.doAnonymousUpstream(ctx, route, bodies, ids, attempts) + attempts += used + if err == nil && resp != nil && resp.StatusCode/100 == 2 { + return resp, route, attempts, nil + } + lastResponse, lastErr = resp, err + if len(route.KeyTiers) > 0 { + g.logger.Debug("anonymous request did not succeed; entering preferred key tiers", "component", "upstream", "event", "anonymous_fallback", "request_id", ids.Request, "attempts", attempts, "key_tiers", route.KeyTiers) + } + } + if ctx.Err() != nil { + // The anonymous phase already consumed the request budget. Entering the + // authenticated tiers here would only fire instant attempts against a + // dead context, cooling keys that were never really tried. + if lastResponse != nil { + return lastResponse, effectiveRoute, attempts, nil + } + if lastErr == nil { + lastErr = ctx.Err() + } + return nil, effectiveRoute, attempts, lastErr + } + + keyTiers := route.KeyTiers + if !route.Anonymous && len(keyTiers) == 0 && (route.Tier == TierZen || route.Tier == TierGo) { + keyTiers = []Tier{route.Tier} + } + for _, tier := range keyTiers { + if lastResponse != nil { + drainAndClose(lastResponse.Body) + lastResponse = nil + } + keyRoute := route + keyRoute.Tier = tier + keyRoute.Anonymous = false + keyRoute.Protocol = route.ProtocolFor(tier) + effectiveRoute = keyRoute + resp, err, used := g.doKeyUpstream(ctx, keyRoute, bodies, ids, attempts) + attempts += used + if err == nil && resp != nil && resp.StatusCode/100 == 2 { + return resp, keyRoute, attempts, nil + } + lastResponse, lastErr = resp, err + } + if lastResponse != nil { + return lastResponse, effectiveRoute, attempts, nil + } + if lastErr == nil { + lastErr = errors.New("no usable upstream route") + } + return nil, effectiveRoute, attempts, lastErr +} + +// doAnonymousUpstream tries every currently available proxy at most once. Any +// 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) { + var lastResponse *http.Response + var lastErr error + cursor := g.anonymous.CursorFor(ids.Session) + limit := g.anonymous.Len() + attempts := 0 + body := bodies[TierZen] + if len(body) == 0 { + return nil, errors.New("no prepared Zen request body"), 0 + } + for attempts < limit { + if ctx.Err() != nil { + // The request-level budget is already gone. Stop scanning instead + // of firing attempts that cannot succeed and then recording them + // as failures against proxies that were never really tried. + if lastErr == nil { + lastErr = ctx.Err() + } + break + } + node := cursor.Next() + if node == nil { + break + } + attempts++ + if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil { + meta.Attempts = attemptOffset + attempts + meta.Tier = string(TierZen) + } + if lastResponse != nil { + 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) + started := time.Now() + resp, err := node.proxy.client.Do(req) + duration := time.Since(started) + if ctx.Err() != nil { + // The parent budget expired while this attempt was in flight. Its + // outcome says nothing about this proxy, so record nothing and stop + // scanning. + lastResponse, lastErr = resp, err + if lastErr == nil && lastResponse == nil { + lastErr = ctx.Err() + } + break + } + 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()) + 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) + } 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()) + } + } + if lastResponse != nil { + return lastResponse, nil, attempts + } + if lastErr == nil { + lastErr = errors.New("no healthy anonymous proxies available") + } + return nil, lastErr, attempts +} + +// requestBodyDumpLimit caps how much of an outbound body is written to the log. +const requestBodyDumpLimit = 64 << 10 + +// dumpOutboundBodies records the exact bytes about to be sent upstream when +// logging.dump_request_bodies is enabled. It exists so retry and translation +// problems (stale rs_* references, re-encoded history, tier re-encoding) can be +// 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) { + if !g.cfg.Logging.DumpRequestBodies || len(bodies) == 0 { + return + } + phase := "initial" + if attemptOffset > 0 { + phase = "retry" + } + tiers := make([]string, 0, len(bodies)) + for tier := range bodies { + tiers = append(tiers, string(tier)) + } + sort.Strings(tiers) + for _, name := range tiers { + tier := Tier(name) + body := bodies[tier] + if len(body) == 0 { + continue + } + sum := sha256.Sum256(body) + truncated := len(body) > requestBodyDumpLimit + payload := body + if truncated { + payload = body[:requestBodyDumpLimit] + } + g.logger.Debug("outbound upstream request body", "component", "upstream", "event", "upstream_request_body", + "request_id", ids.Request, "model", route.ID, "tier", tier, "protocol", route.ProtocolFor(tier), + "phase", phase, "bytes", len(body), "sha256", hex.EncodeToString(sum[:8]), + "truncated", truncated, "body", string(payload)) + } +} + +// doSelectedKeyUpstream sends exactly one attempt through the operator-selected +// key. It performs no failover at all — no anonymous lane, no other key and no +// other tier — so the outcome describes that one key. It also leaves pool state +// 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) { + nodes := g.zenNodes + baseURL := g.cfg.Upstream.Zen + if override.Tier == TierGo { + nodes = g.goNodes + baseURL = g.cfg.Upstream.Go + } + node := nodes.NodeByID(override.KeyID) + if node == nil { + return nil, fmt.Errorf("selected %s key is no longer configured", override.Tier), 0 + } + body := bodies[override.Tier] + if len(body) == 0 { + return nil, fmt.Errorf("no prepared %s request body", override.Tier), 0 + } + proxy := nodes.Proxy(node) + if proxy == nil { + return nil, errors.New("selected upstream key has no proxy binding"), 0 + } + if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil { + meta.Attempts = attemptOffset + 1 + meta.Tier = string(override.Tier) + } + keyID := 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 { + return nil, err, 0 + } + started := time.Now() + resp, err := proxy.client.Do(req) + duration := time.Since(started) + g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+1, keyID, "key", false, proxy, resp, err, duration) + if err != nil { + return nil, err, 1 + } + 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) { + var lastResponse *http.Response + var lastErr error + nodes := g.zenNodes + baseURL := g.cfg.Upstream.Zen + if route.Tier == TierGo { + nodes = g.goNodes + baseURL = g.cfg.Upstream.Go + } + cursor := nodes.CursorFor(ids.Session) + if nodes.Len() == 0 { + return nil, fmt.Errorf("no %s nodes configured", route.Tier), 0 + } + attempts := 0 + body := bodies[route.Tier] + if len(body) == 0 { + return nil, fmt.Errorf("no prepared %s request body", route.Tier), 0 + } + for attempts < g.cfg.Retry.MaxAttempts { + if ctx.Err() != nil { + // Same guard as the anonymous loop: an exhausted request budget + // must not be spent rotating keys that were never really tried. + if lastErr == nil { + lastErr = ctx.Err() + } + break + } + node := cursor.Next() + if node == nil { + break + } + 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 { + meta.Attempts = attemptOffset + attempts + meta.Tier = string(route.Tier) + } + if lastResponse != nil { + drainAndClose(lastResponse.Body) + lastResponse = nil + } + req, err := newUpstreamRequest(ctx, baseURL, route.Protocol, body, ids, node.key) + if err != nil { + return nil, err, attempts + } + proxy := nodes.Proxy(node) + if proxy == nil { + lastErr = errors.New("upstream key has no proxy binding") + break + } + keyID := keyDisplayID(node.key) + setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy) + attemptStarted := time.Now() + resp, err := proxy.client.Do(req) + attemptDuration := time.Since(attemptStarted) + if ctx.Err() != nil { + // The request budget expired while this attempt was in flight. A + // cancelled context says nothing about the key or the proxy: without + // this guard the instant DeadlineExceeded would cool a healthy key + // and evict a healthy proxy from the pool. + lastResponse, lastErr = resp, err + if lastErr == nil && lastResponse == nil { + lastErr = ctx.Err() + } + break + } + 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()) + return resp, nil, attempts + } + // Request-shape errors are deterministic and must leave this tier without + // rotating through unrelated keys. The outer route may still try the next + // 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()) + 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) + } 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()) + } + } + if lastResponse != nil { + return lastResponse, nil, attempts + } + return nil, lastErr, attempts +} + +// Diagnostics use the same routing and transports as production, but must not +// update cooldowns, health, or bindings, including after successful attempts. +func (g *Gateway) observeKeyResult(ctx context.Context, nodes *nodePool, node *upstreamNode, proxy *proxyTransport, resp *http.Response, err error) { + if isDiagnosticRequest(ctx) { + return + } + status := upstreamStatus(resp) + proxyFailed := g.syncProxyResult(ctx, proxy, status, err) + if err == nil && status/100 == 2 || isNonRetryableClientResponse(resp, err) { + nodes.MarkSuccess(node) + return + } + if !proxyFailed || nodes.Proxy(node) == proxy { + nodes.MarkFailure(node, resp, err) + } +} + +func (g *Gateway) observeAnonymousResult(ctx context.Context, node *anonymousNode, resp *http.Response, err error) { + if isDiagnosticRequest(ctx) { + return + } + status := upstreamStatus(resp) + g.syncProxyResult(ctx, node.proxy, status, err) + if err == nil && status/100 == 2 { + g.anonymous.MarkSuccess(node) + } else { + g.anonymous.MarkFailure(node, resp, err) + } +} + +func upstreamStatus(resp *http.Response) int { + if resp == nil { + return 0 + } + return resp.StatusCode +} + +func setRequestCredential(ctx context.Context, tier Tier, keyID, channel string, anonymous bool, proxy *proxyTransport) { + meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta) + if meta == nil { + return + } + meta.Tier = string(tier) + meta.KeyID = keyID + meta.Channel = channel + meta.Anonymous = anonymous + meta.Proxy = "" + if proxy != nil { + meta.Proxy = redactURL(proxy.name) + } +} + +func requestCredential(ctx context.Context) (string, string, bool) { + meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta) + 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) { + status := upstreamStatus(resp) + success := err == nil && status >= 200 && status < 300 + outcome := "retryable_failure" + if success { + outcome = "success" + } else if err != nil { + outcome = "transport_error" + } else if isNonRetryableClientResponse(resp, nil) { + outcome = "rejected" + } + if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil { + meta.AttemptOutcome = outcome + meta.Protocol = route.Protocol + } + if g.monitor == nil { + return + } + proxyName := "unavailable" + if proxy != nil { + proxyName = redactURL(proxy.name) + } + g.monitor.RecordAttempt(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) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("User-Agent", opencodeUserAgent()) + req.Header.Set("x-opencode-client", "cli") + req.Header.Set("x-opencode-session", ids.Session) + // OpenCode 1.18.x sends these correlation headers to preserve provider-side + // prompt/session affinity. Keep the legacy x-opencode-session header too so + // older Zen deployments continue to recognize the request. + req.Header.Set("x-session-affinity", ids.Session) + req.Header.Set("X-Session-Id", ids.Session) + req.Header.Set("x-opencode-request", ids.Request) + req.Header.Set("x-opencode-project", ids.Project) + if ids.ParentSession != "" { + req.Header.Set("x-parent-session-id", ids.ParentSession) + } + if protocol == ProtocolAnthropic { + 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") + } else { + req.Header.Set("Authorization", "Bearer "+key) + } + return req, nil +} + +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/webui/app.js b/webui/app.js new file mode 100644 index 0000000..49e26a2 --- /dev/null +++ b/webui/app.js @@ -0,0 +1,906 @@ +const $ = (selector) => document.querySelector(selector), + $$ = (selector) => [...document.querySelectorAll(selector)]; +let csrf = "", + config = null, + monitorData = null, + debugData = null, + lastPlayground = null, + logEvents = [], + eventSource = null, + paused = false, + monitorTimer = null, + logRenderPending = false, + toastTimer = null; +const pages = { + overview: ["01", "运行桌面", "最近一小时、进程累计与当前资源状态。"], + guide: ["02", "首次运行", "用六个检查点完成从配置到首个请求。"], + access: ["03", "接入手册", "Chat、Responses、Anthropic 与 SDK 示例。"], + usage: ["04", "Token 用量", "覆盖率、每分钟趋势、模型排行与 Tier 分布。"], + playground: ["05", "Playground", "三种入口协议共用真实 Gateway 路由与诊断。"], + diagnostics: ["06", "路由诊断", "Metadata、模型资格与每一次上游尝试。"], + config: ["07", "配置中心", "验证后原子保存,并热应用可变字段。"], + logs: ["08", "事件日志", "来自进程内 Ring Buffer 的结构化 SSE。"], + account: ["09", "账号安全", "更新后撤销全部管理 Session。"], +}; +async function api(path, options = {}) { + options.headers = { ...(options.headers || {}), Accept: "application/json" }; + if (options.body) options.headers["Content-Type"] = "application/json"; + if (csrf && !["GET", "HEAD"].includes(options.method || "GET")) + options.headers["X-CSRF-Token"] = csrf; + const response = await fetch(path, options); + if (response.status === 401) { + showLogin(); + throw new Error("登录已失效"); + } + if (response.status === 204) return null; + const data = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(data.error?.message || `HTTP ${response.status}`); + return data; +} +function toast(message, bad = false) { + const node = $("#toast"); + node.textContent = message; + node.classList.toggle("bad-toast", bad); + node.classList.remove("hidden"); + clearTimeout(toastTimer); + toastTimer = setTimeout(() => node.classList.add("hidden"), 3600); +} +function showLogin() { + csrf = ""; + $("#app").classList.add("hidden"); + $("#login").classList.remove("hidden"); + if (eventSource) eventSource.close(); + eventSource = null; + clearInterval(monitorTimer); +} +async function enterConsole(session) { + csrf = session.csrf_token; + $("#login").classList.add("hidden"); + $("#app").classList.remove("hidden"); + await loadConfig(); + await Promise.all([refreshMonitor(), loadDebugModels()]); + clearInterval(monitorTimer); + monitorTimer = setInterval(refreshMonitor, 3000); + connectLogs(); +} +async function boot() { + try { + await enterConsole(await api("/api/auth/session")); + } catch (_) { + showLogin(); + } +} +$("#login-form").addEventListener("submit", async (event) => { + event.preventDefault(); + $("#login-error").textContent = ""; + try { + const session = await api("/api/auth/login", { + method: "POST", + body: JSON.stringify({ username: $("#login-user").value, password: $("#login-pass").value }), + }); + $("#login-pass").value = ""; + await enterConsole(session); + } catch (error) { + $("#login-error").textContent = error.message; + } +}); +$("#logout").onclick = async () => { + try { + await api("/api/auth/logout", { method: "POST", body: "{}" }); + } finally { + showLogin(); + } +}; +function openPage(page) { + $$(".nav button").forEach((button) => + button.classList.toggle("active", button.dataset.page === page), + ); + $$(".page").forEach((node) => node.classList.toggle("hidden", node.id !== `page-${page}`)); + const meta = pages[page]; + $("#page-index").textContent = `Section ${meta[0]}`; + $("#page-title").textContent = meta[1]; + $("#page-sub").textContent = meta[2]; + if (page === "access") renderAccessExamples(); + if (page === "usage") renderUsage(); + if (page === "playground" && !debugData) loadDebugModels(); + if (page === "diagnostics") { + loadDebugModels(); + renderDiagnostics(); + } +} +$$(".nav button").forEach((button) => (button.onclick = () => openPage(button.dataset.page))); +async function loadConfig() { + config = await api("/api/config"); + fillConfig(config); + renderAccessExamples(); +} +function fillConfig(value) { + $("#c-listen").value = value.listen; + $("#c-prefer").value = value.prefer; + $("#c-web-listen").value = value.webui.listen; + $("#c-session").value = value.webui.session_ttl_minutes; + $("#c-web-enabled").checked = value.webui.enabled; + $("#c-anonymous").checked = !!value.anonymous; + $("#c-proxyfile").value = value.proxyfile; + $("#c-up-zen").value = value.upstream.zen; + $("#c-up-go").value = value.upstream.go; + $("#c-attempts").value = value.retry.max_attempts; + $("#c-timeout").value = value.retry.timeout_seconds; + $("#c-refresh").value = value.models.refresh_seconds; + $("#c-protocols").value = JSON.stringify(value.models.protocols || {}, null, 2); + $("#c-idle").value = value.performance.max_idle_conns; + $("#c-idle-host").value = value.performance.max_idle_conns_per_host; + $("#c-max-host").value = value.performance.max_conns_per_host; + $("#c-idle-timeout").value = value.performance.idle_conn_timeout_seconds; + $("#c-connect").value = value.performance.connect_timeout_seconds; + $("#c-cooldown").value = value.performance.failure_cooldown_seconds; + $("#c-attempt-timeout").value = value.performance.attempt_timeout_seconds; + $("#c-level").value = value.logging.level; + $("#c-ring").value = value.logging.ring_size; + $("#c-dump-bodies").checked = !!value.logging.dump_request_bodies; + ["server_keys", "zen_keys", "go_keys", "proxies"].forEach(renderChips); + const notice = $("#restart-notice"); + if (value.restart_required_fields?.length) { + notice.textContent = `已保存但尚未生效:${value.restart_required_fields.join(", ")}。当前 API ${value.effective.listen}、WebUI ${value.effective.webui_listen}。请重启进程。`; + notice.classList.remove("hidden"); + } else notice.classList.add("hidden"); +} +function renderChips(name) { + const host = $(`#${name}-chips`); + host.replaceChildren(); + (config[name] || []).forEach((item) => { + const chip = document.createElement("span"), + text = document.createElement("span"), + remove = document.createElement("button"); + chip.className = "chip"; + chip.dataset.id = item.id; + text.textContent = item.display; + remove.type = "button"; + remove.title = "移除"; + remove.textContent = "×"; + remove.onclick = () => chip.remove(); + chip.append(text, remove); + host.appendChild(chip); + }); +} +function secretInputs(name) { + const kept = [...$(`#${name}-chips`).children].map((node) => ({ id: node.dataset.id })); + const added = $(`#${name}-new`) + .value.split(/\r?\n/) + .map((value) => value.trim()) + .filter(Boolean) + .map((value) => ({ value })); + return kept.concat(added); +} +const number = (id) => Number($(id).value); +$("#config-form").addEventListener("submit", async (event) => { + event.preventDefault(); + try { + const update = { + listen: $("#c-listen").value, + server_keys: secretInputs("server_keys"), + zen_keys: secretInputs("zen_keys"), + go_keys: secretInputs("go_keys"), + anonymous: $("#c-anonymous").checked, + proxies: secretInputs("proxies"), + proxyfile: $("#c-proxyfile").value, + prefer: $("#c-prefer").value, + upstream: { zen: $("#c-up-zen").value, go: $("#c-up-go").value }, + retry: { max_attempts: number("#c-attempts"), timeout_seconds: number("#c-timeout") }, + models: { + refresh_seconds: number("#c-refresh"), + protocols: JSON.parse($("#c-protocols").value || "{}"), + }, + performance: { + max_idle_conns: number("#c-idle"), + max_idle_conns_per_host: number("#c-idle-host"), + max_conns_per_host: number("#c-max-host"), + idle_conn_timeout_seconds: number("#c-idle-timeout"), + connect_timeout_seconds: number("#c-connect"), + failure_cooldown_seconds: number("#c-cooldown"), + attempt_timeout_seconds: number("#c-attempt-timeout"), + }, + logging: { + level: $("#c-level").value, + ring_size: number("#c-ring"), + dump_request_bodies: $("#c-dump-bodies").checked, + }, + webui: { + enabled: $("#c-web-enabled").checked, + listen: $("#c-web-listen").value, + username: config.webui.username, + session_ttl_minutes: number("#c-session"), + }, + }; + const result = await api("/api/config", { method: "PUT", body: JSON.stringify(update) }); + config = result.config; + ["server_keys", "zen_keys", "go_keys", "proxies"].forEach( + (name) => ($(`#${name}-new`).value = ""), + ); + fillConfig(config); + await loadDebugModels(); + toast( + result.result.restart_required + ? `已应用;${result.result.restart_fields.join(", ")} 需重启` + : "配置已保存并立即应用", + ); + } catch (error) { + toast(error.message, true); + } +}); +$("#reload-config").onclick = async () => { + try { + const result = await api("/api/config/reload", { method: "POST", body: "{}" }); + await loadConfig(); + await loadDebugModels(); + toast(result.restart_required ? "磁盘配置已重载,监听字段需重启" : "磁盘配置已重载"); + } catch (error) { + toast(error.message, true); + } +}; +$("#reveal").onclick = async () => { + const password = prompt("请再次输入管理密码"); + if (password === null) return; + try { + const values = await api("/api/config/reveal", { + method: "POST", + body: JSON.stringify({ password }), + }); + $("#modal-content").textContent = JSON.stringify(values, null, 2); + $("#modal").classList.remove("hidden"); + } catch (error) { + toast(error.message, true); + } +}; +$("#modal-close").onclick = () => { + $("#modal").classList.add("hidden"); + $("#modal-content").textContent = ""; +}; +$("#account-form").addEventListener("submit", async (event) => { + event.preventDefault(); + try { + await api("/api/account", { + method: "PUT", + body: JSON.stringify({ + current_password: $("#a-current").value, + username: $("#a-user").value, + new_password: $("#a-new").value, + }), + }); + toast("账号已更新,请重新登录"); + setTimeout(showLogin, 800); + } catch (error) { + toast(error.message, true); + } +}); +function appendCell(row, value, className = "") { + const cell = document.createElement("td"); + cell.textContent = String(value); + if (className) cell.className = className; + row.appendChild(cell); +} +function emptyRow(host, columns, message = "暂无数据") { + const row = document.createElement("tr"), + cell = document.createElement("td"); + cell.colSpan = columns; + cell.className = "empty"; + cell.textContent = message; + row.appendChild(cell); + host.appendChild(row); +} +function renderResources(resources) { + const proxies = $("#proxy-table"); + proxies.replaceChildren(); + (resources.proxies || []).forEach((proxy) => { + const row = document.createElement("tr"); + appendCell(row, proxy.address); + appendCell(row, proxy.healthy ? "正常" : "不可用", `status ${proxy.healthy ? "ok" : "bad"}`); + appendCell( + row, + `Z ${proxy.zen_keys} · G ${proxy.go_keys} · A ${proxy.anonymous ? "开" : "关"}`, + ); + proxies.appendChild(row); + }); + if (!proxies.children.length) emptyRow(proxies, 3); + const keys = $("#key-table"); + keys.replaceChildren(); + if (resources.anonymous) { + const row = document.createElement("tr"); + appendCell(row, "anonymous"); + appendCell(row, "zen"); + appendCell(row, "已启用", "status ok"); + keys.appendChild(row); + } + (resources.keys || []).forEach((key) => { + const row = document.createElement("tr"); + appendCell(row, key.id); + appendCell(row, key.tier); + appendCell( + row, + key.cooldown_until ? "冷却中" : "可用", + `status ${key.cooldown_until ? "warn" : "ok"}`, + ); + keys.appendChild(row); + }); + if (!keys.children.length) emptyRow(keys, 3); +} +function renderBreakdowns(metrics) { + const host = $("#breakdowns"); + host.replaceChildren(); + [ + ["端点", metrics.endpoints], + ["状态码", metrics.statuses], + ["模型", metrics.models], + ["Tier", metrics.tiers], + ].forEach(([title, data]) => { + const block = document.createElement("div"), + heading = document.createElement("h3"), + table = document.createElement("table"), + body = document.createElement("tbody"); + heading.textContent = title; + table.className = "table"; + Object.entries(data || {}) + .sort((a, b) => b[1] - a[1]) + .slice(0, 10) + .forEach(([key, value]) => { + const row = document.createElement("tr"); + appendCell(row, key); + appendCell(row, value); + body.appendChild(row); + }); + if (!body.children.length) emptyRow(body, 2, "暂无请求"); + table.appendChild(body); + block.append(heading, table); + host.appendChild(block); + }); +} +function renderGuide() { + if (!config || !monitorData) return; + const resources = monitorData.resources, + models = resources.models || {}, + modelDescription = models.stale + ? "目录来自" + (models.cache_source || "磁盘") + "快取,等待背景刷新。" + : "上游目录已完成首次刷新且有可暴露模型。"; + const checks = [ + ["登录管理端", "当前 Session 已通过服务端验证。", true], + ["配置本地 Key", "客户端使用 Server Key 访问 Gateway。", (config.server_keys || []).length > 0], + [ + "选择上游通道", + "至少有 Zen / Go Key,或启用匿名通道。", + (config.zen_keys || []).length + (config.go_keys || []).length > 0 || config.anonymous, + ], + [ + "检查 Proxy", + "至少一个代理节点健康。", + (resources.proxies || []).some((proxy) => proxy.healthy), + ], + ["等待模型目录", modelDescription, models.exposed > 0 && !!models.updated_at], + ["复制接入示例", "进入接入手册,替换模型与 YOUR_API_KEY。", true], + ]; + const host = $("#guide-steps"); + host.replaceChildren(); + checks.forEach(([title, description, done]) => { + const node = document.createElement("article"), + heading = document.createElement("h3"), + copy = document.createElement("p"), + state = document.createElement("div"); + node.className = "guide-step"; + heading.textContent = title; + copy.textContent = description; + state.className = `step-state ${done ? "ok" : "warn"}`; + state.textContent = done ? "✓ 已就绪" : "○ 待处理"; + node.append(heading, copy, state); + host.appendChild(node); + }); +} +const formatTokens = (value) => Number(value || 0).toLocaleString(); +function renderUsage() { + if (!monitorData) return; + const usage = monitorData.usage?.last_hour || {}, + tokens = usage.tokens || {}; + $("#u-coverage").textContent = `${((usage.coverage || 0) * 100).toFixed(1)}%`; + $("#u-total").textContent = formatTokens(tokens.total_tokens); + $("#u-cached").textContent = formatTokens(tokens.cached_tokens); + $("#u-reasoning").textContent = formatTokens(tokens.reasoning_tokens); + const trend = $("#usage-trend"), + series = monitorData.metrics?.series || [], + maximum = Math.max(1, ...series.map((point) => point.total_tokens || 0)); + trend.replaceChildren(); + series.forEach((point) => { + const bar = document.createElement("div"); + bar.className = "trend-bar"; + bar.style.height = `${Math.max(2, Math.round(((point.total_tokens || 0) / maximum) * 100))}%`; + bar.title = `${new Date(point.minute).toLocaleTimeString()} · input ${formatTokens(point.input_tokens)} · output ${formatTokens(point.output_tokens)} · total ${formatTokens(point.total_tokens)}`; + trend.appendChild(bar); + }); + const models = $("#usage-models"); + models.replaceChildren(); + Object.entries(usage.models || {}) + .sort((a, b) => (b[1].total_tokens || 0) - (a[1].total_tokens || 0)) + .slice(0, 15) + .forEach(([model, value]) => { + const row = document.createElement("tr"); + appendCell(row, model); + appendCell(row, formatTokens(value.input_tokens)); + appendCell(row, formatTokens(value.output_tokens)); + appendCell(row, formatTokens(value.total_tokens)); + models.appendChild(row); + }); + if (!models.children.length) emptyRow(models, 4, "尚无 Token 用量"); + const tiers = $("#usage-tiers"), + tierEntries = Object.entries(usage.tiers || {}).sort( + (a, b) => (b[1].total_tokens || 0) - (a[1].total_tokens || 0), + ), + tierTotal = Math.max(1, ...tierEntries.map(([, value]) => value.total_tokens || 0)); + tiers.replaceChildren(); + tierEntries.forEach(([tier, value]) => { + const row = document.createElement("div"), + name = document.createElement("strong"), + track = document.createElement("div"), + fill = document.createElement("div"), + amount = document.createElement("span"); + row.className = "tier-row"; + name.textContent = tier; + track.className = "tier-track"; + fill.className = "tier-fill"; + fill.style.width = `${Math.round(((value.total_tokens || 0) / tierTotal) * 100)}%`; + amount.className = "mono"; + amount.textContent = formatTokens(value.total_tokens); + track.appendChild(fill); + row.append(name, track, amount); + tiers.appendChild(row); + }); + if (!tierEntries.length) { + const empty = document.createElement("div"); + empty.className = "empty"; + empty.textContent = "尚无 Tier 用量"; + tiers.appendChild(empty); + } +} +function renderFacts(selector, entries) { + const host = $(selector); + host.replaceChildren(); + entries.forEach(([label, value, tone]) => { + const fact = document.createElement("dl"), + term = document.createElement("dt"), + detail = document.createElement("dd"); + fact.className = "fact"; + term.textContent = label; + detail.textContent = value ?? "—"; + if (tone) detail.className = tone; + fact.append(term, detail); + host.appendChild(fact); + }); +} +function renderPlayKeys() { + const select = $("#play-key"); + if (!select) return; + const selected = select.value; + select.replaceChildren(); + const auto = document.createElement("option"); + auto.value = "auto"; + auto.textContent = "自动路由(匿名 / Tier 回退 / Key 轮询)"; + select.appendChild(auto); + const keys = debugData?.keys || {}; + [ + ["zen", "Zen Keys"], + ["go", "Go Keys"], + ].forEach(([tier, label]) => { + const items = keys[tier] || []; + if (!items.length) return; + const group = document.createElement("optgroup"); + group.label = label; + items.forEach((item) => { + const option = document.createElement("option"); + option.value = `${tier}:${item.id}`; + const cooling = item.cooldown_until + ? ` · 冷却至 ${new Date(item.cooldown_until).toLocaleTimeString()}` + : ""; + option.textContent = `${tier.toUpperCase()} · ${item.display} · ${item.id}${cooling}`; + group.appendChild(option); + }); + select.appendChild(group); + }); + if (selected && [...select.options].some((option) => option.value === selected)) + select.value = selected; + else select.value = "auto"; +} +async function loadDebugModels() { + try { + debugData = await api("/api/debug/models"); + if (debugData.last_inference) lastPlayground = debugData.last_inference; + const select = $("#play-model"), + selected = select.value; + select.replaceChildren(); + (debugData.models || []).forEach((item) => { + const option = document.createElement("option"); + option.value = item.model; + option.textContent = item.model; + select.appendChild(option); + }); + if (selected && [...select.options].some((option) => option.value === selected)) + select.value = selected; + renderPlayKeys(); + if (!$("#play-request").value.trim()) resetPlayTemplate(); + renderDiagnostics(); + } catch (error) { + toast(error.message, true); + } +} +function playgroundTemplate() { + const protocol = $("#play-protocol").value, + model = $("#play-model").value || "YOUR_MODEL"; + if (protocol === "responses") return { model, input: "用一句话说明这个模型的能力。" }; + if (protocol === "anthropic") + return { + model, + max_tokens: 512, + messages: [{ role: "user", content: "用一句话说明这个模型的能力。" }], + }; + return { model, messages: [{ role: "user", content: "用一句话说明这个模型的能力。" }] }; +} +function resetPlayTemplate() { + $("#play-request").value = JSON.stringify(playgroundTemplate(), null, 2); +} +$("#play-protocol").addEventListener("change", resetPlayTemplate); +$("#play-model").addEventListener("change", () => { + try { + const request = JSON.parse($("#play-request").value); + request.model = $("#play-model").value; + $("#play-request").value = JSON.stringify(request, null, 2); + } catch (_) { + resetPlayTemplate(); + } +}); +$("#play-reset").onclick = resetPlayTemplate; +function displayPlayground(result) { + lastPlayground = result; + const keyTest = result.key_test + ? { + usable: "Key 可用", + rejected: "Key 被拒绝", + rate_limited: "Key 已被接受但受到限流", + upstream_error: "上游异常,无法判定 Key", + transport_error: "网络或代理异常,无法判定 Key", + unavailable: "Key 或运行时不可用", + request_error: "请求未成功", + }[result.key_test] || result.key_test + : ""; + $("#play-state").textContent = result.ok + ? `请求成功 · HTTP ${result.http_status}` + : `请求失败 · HTTP ${result.http_status}`; + $("#play-state").className = `section-caption ${result.ok ? "ok" : "bad"}`; + const route = result.route || {}, + eligibility = route.anonymous_eligibility || {}, + selected = result.selected_key, + routeLabel = route.tier + ? `${route.tier} / ${route.anonymous ? "anonymous" : route.key_id || "key"}` + : "未路由"; + renderFacts("#play-facts", [ + ["HTTP 状态", result.http_status, result.ok ? "ok" : "bad"], + ["耗时", `${result.duration_ms} ms`], + ["Request ID", result.request_id || "—"], + ["测试模式", selected ? `指定 ${selected.tier.toUpperCase()} Key` : "自动路由"], + ["测试 Key", selected ? `${selected.display} · ${selected.id}` : "—"], + [ + "Key 判断", + keyTest || "自动路由未单独判定", + result.key_test === "usable" ? "ok" : result.key_test ? "bad" : "", + ], + ["实际路由", routeLabel], + ["原生协议", route.native_protocol || "—"], + [ + "匿名判断", + `${eligibility.allowed ? "允许" : "拒绝"} · ${eligibility.source || "—"}`, + eligibility.allowed ? "ok" : "warn", + ], + ]); + $("#play-output").textContent = JSON.stringify(result.response, null, 2); + renderDiagnostics(); +} +$("#play-form").addEventListener("submit", async (event) => { + event.preventDefault(); + let request; + try { + request = JSON.parse($("#play-request").value); + } catch (error) { + toast(`请求 JSON 无效:${error.message}`, true); + return; + } + const keyValue = $("#play-key").value, + key = + keyValue === "auto" + ? { mode: "auto" } + : { + mode: "selected", + tier: keyValue.split(":")[0], + id: keyValue.split(":").slice(1).join(":"), + }; + $("#play-run").disabled = true; + $("#play-state").textContent = + key.mode === "selected" ? "指定 Key 测试进行中…" : "Gateway 请求进行中…"; + try { + const result = await api("/api/debug/inference", { + method: "POST", + body: JSON.stringify({ protocol: $("#play-protocol").value, key, request }), + }); + displayPlayground(result); + } catch (error) { + toast(error.message, true); + $("#play-state").textContent = "诊断入口请求失败"; + } finally { + $("#play-run").disabled = false; + } +}); +$("#play-copy").onclick = async () => { + try { + await navigator.clipboard.writeText($("#play-output").textContent); + toast("原始响应已复制"); + } catch (_) { + toast("浏览器不允许剪贴板访问", true); + } +}; +function renderDiagnostics() { + if (!monitorData && !debugData) return; + const metadata = debugData?.metadata || monitorData?.resources?.metadata || {}, + last = lastPlayground || debugData?.last_inference; + renderFacts("#metadata-facts", [ + ["就绪", metadata.ready ? "是" : "否", metadata.ready ? "ok" : "warn"], + ["模型数", formatTokens(metadata.models)], + ["更新时间", metadata.updated_at ? new Date(metadata.updated_at).toLocaleString() : "尚未更新"], + ["是否过期", metadata.stale ? "是" : "否", metadata.stale ? "warn" : "ok"], + ["下次刷新", metadata.next_refresh ? new Date(metadata.next_refresh).toLocaleString() : "—"], + ["最近错误", metadata.last_error || "无", metadata.last_error ? "bad" : "ok"], + ]); + renderFacts( + "#last-playground", + last + ? [ + ["结果", last.ok ? "成功" : "失败", last.ok ? "ok" : "bad"], + ["HTTP", last.http_status], + ["耗时", `${last.duration_ms} ms`], + ["Request ID", last.request_id || "—"], + ["模型", last.route?.model || "—"], + [ + "路由", + last.route?.tier + ? `${last.route.tier} / ${last.route.anonymous ? "anonymous" : last.route.key_id || "key"}` + : "未路由", + ], + ] + : [["状态", "尚无 Playground 追踪"]], + ); + renderDiagnosticModels(); + const requests = $("#upstream-requests"); + requests.replaceChildren(); + (monitorData?.upstream?.requests || []) + .slice(-100) + .reverse() + .forEach((request) => { + const row = document.createElement("tr"); + appendCell(row, new Date(request.time).toLocaleTimeString()); + appendCell(row, request.request_id); + appendCell(row, request.model); + appendCell(row, request.tier || "—"); + appendCell(row, request.channel); + appendCell(row, request.key_id || "—"); + appendCell(row, request.attempts); + const terminalResults = { + stream_error: "流式响应失败", + client_canceled: "客户端已取消", + }; + const result = terminalResults[request.outcome] + ? `HTTP ${request.status} · ${terminalResults[request.outcome]}` + : request.status || request.outcome; + appendCell(row, result, request.success ? "ok" : "bad"); + appendCell(row, `${request.duration_ms} ms`); + requests.appendChild(row); + }); + if (!requests.children.length) emptyRow(requests, 9, "尚无请求路由"); + const attempts = $("#upstream-attempts"); + attempts.replaceChildren(); + (monitorData?.upstream?.recent || []) + .slice(-100) + .reverse() + .forEach((attempt) => { + const row = document.createElement("tr"); + appendCell(row, new Date(attempt.time).toLocaleTimeString()); + appendCell(row, attempt.request_id); + appendCell(row, attempt.model); + appendCell(row, `${attempt.tier} / ${attempt.channel}`); + appendCell(row, attempt.key_id); + appendCell(row, attempt.proxy_node); + appendCell(row, attempt.status || attempt.outcome, attempt.success ? "ok" : "bad"); + appendCell(row, `${attempt.duration_ms} ms`); + attempts.appendChild(row); + }); + if (!attempts.children.length) emptyRow(attempts, 8, "尚无上游尝试"); +} +function renderDiagnosticModels() { + const host = $("#diagnostic-models"); + if (!host || !debugData) return; + const query = $("#diagnostic-model-search").value.trim().toLowerCase(); + host.replaceChildren(); + (debugData.models || []) + .filter((item) => !query || item.model.toLowerCase().includes(query)) + .forEach((item) => { + const eligibility = item.anonymous_eligibility || {}, + row = document.createElement("tr"), + input = eligibility.input_cost, + output = eligibility.output_cost, + plan = [...(item.anonymous ? ["anonymous"] : []), ...(item.key_tiers || [])]; + appendCell(row, item.model); + appendCell(row, `${item.native_protocol} · ${item.protocol_source}`); + appendCell( + row, + item.route_error || (plan.length ? plan.join(" → ") : "—"), + item.route_error ? "bad" : "", + ); + appendCell(row, eligibility.allowed ? "允许" : "拒绝", eligibility.allowed ? "ok" : "warn"); + appendCell(row, eligibility.source || "—"); + appendCell(row, `${input == null ? "?" : input} / ${output == null ? "?" : output}`, "cost"); + host.appendChild(row); + }); + if (!host.children.length) emptyRow(host, 6, "没有匹配模型"); +} +$("#diagnostic-model-search").addEventListener("input", renderDiagnosticModels); +async function refreshMonitor() { + try { + monitorData = await api("/api/monitor"); + const metrics = monitorData.metrics; + $("#version").textContent = `version ${monitorData.version}`; + $("#m-total").textContent = Number(metrics.last_hour.total || 0).toLocaleString(); + $("#m-rate").textContent = `${((metrics.last_hour.success_rate || 0) * 100).toFixed(1)}%`; + $("#m-p95").textContent = `${metrics.last_hour.p95_ms || 0} ms`; + $("#m-active").textContent = `${metrics.active_requests || 0} / ${metrics.active_streams || 0}`; + renderResources(monitorData.resources); + renderBreakdowns(metrics); + renderGuide(); + renderUsage(); + renderDiagnostics(); + } catch (_) {} +} +$("#refresh-now").onclick = async () => { + await Promise.all([refreshMonitor(), loadConfig(), loadDebugModels()]); + toast("状态已刷新"); +}; +function derivedAPIBase() { + if (!config) return `${location.protocol}//${location.hostname}:8080`; + const listen = config.effective?.listen || config.listen || ":8080"; + const bracket = listen.match(/^\[.*\]:(\d+)$/), + plain = listen.match(/:(\d+)$/), + port = (bracket || plain)?.[1] || "8080"; + return `${location.protocol}//${location.hostname}:${port}`; +} +function codeCard(label, text) { + const card = document.createElement("div"), + head = document.createElement("div"), + title = document.createElement("span"), + copy = document.createElement("button"), + pre = document.createElement("pre"), + code = document.createElement("code"); + card.className = "code-card"; + head.className = "code-head"; + title.textContent = label; + copy.type = "button"; + copy.className = "copy"; + copy.textContent = "复制"; + copy.onclick = async () => { + try { + await navigator.clipboard.writeText(text); + toast("示例已复制"); + } catch (_) { + toast("浏览器不允许剪贴板访问", true); + } + }; + head.append(title, copy); + code.textContent = text; + pre.appendChild(code); + card.append(head, pre); + return card; +} +function renderAccessExamples() { + if (!config) return; + const base = derivedAPIBase(), + model = $("#access-model")?.value.trim() || "YOUR_MODEL"; + $("#access-base-value").value = base; + const protocols = $("#access-protocol-examples"), + sdks = $("#access-sdk-examples"); + protocols.replaceChildren(); + sdks.replaceChildren(); + const chat = `curl ${base}/v1/chat/completions \\\n -H "Authorization: Bearer YOUR_API_KEY" \\\n -H "Content-Type: application/json" \\\n -d '{"model":"${model}","messages":[{"role":"user","content":"Hello"}]}'`; + const responses = `curl ${base}/v1/responses \\\n -H "Authorization: Bearer YOUR_API_KEY" \\\n -H "Content-Type: application/json" \\\n -d '{"model":"${model}","input":"Hello"}'`; + const anthropic = `curl ${base}/v1/messages \\\n -H "x-api-key: YOUR_API_KEY" \\\n -H "anthropic-version: 2023-06-01" \\\n -H "Content-Type: application/json" \\\n -d '{"model":"${model}","max_tokens":512,"messages":[{"role":"user","content":"Hello"}]}'`; + protocols.append( + codeCard("Chat Completions", chat), + codeCard("Responses", responses), + codeCard("Anthropic Messages", anthropic), + ); + const python = `from openai import OpenAI\n\nclient = OpenAI(base_url="${base}/v1", api_key="YOUR_API_KEY")\nresponse = client.chat.completions.create(\n model="${model}",\n messages=[{"role": "user", "content": "Hello"}],\n)\nprint(response.choices[0].message.content)`; + const javascript = `import OpenAI from "openai";\n\nconst client = new OpenAI({\n baseURL: "${base}/v1",\n apiKey: "YOUR_API_KEY",\n});\nconst response = await client.responses.create({\n model: "${model}",\n input: "Hello",\n});\nconsole.log(response.output_text);`; + sdks.append( + codeCard("Python · OpenAI SDK", python), + codeCard("JavaScript · OpenAI SDK", javascript), + ); +} +$("#access-model").addEventListener("input", renderAccessExamples); +$$("[data-scroll]").forEach( + (button) => + (button.onclick = () => + document.getElementById(button.dataset.scroll).scrollIntoView({ behavior: "smooth" })), +); +function connectLogs() { + if (eventSource) eventSource.close(); + eventSource = new EventSource("/api/logs/stream"); + eventSource.addEventListener("log", (event) => { + const item = JSON.parse(event.data); + logEvents.push(item); + if (logEvents.length > 2000) logEvents.shift(); + if (!paused && !logRenderPending) { + logRenderPending = true; + requestAnimationFrame(() => { + logRenderPending = false; + renderLogs(); + }); + } + }); + eventSource.addEventListener("gap", () => toast("较早日志已从内存清除", true)); +} +function renderLogs() { + const level = $("#log-level").value, + component = $("#log-component").value.toLowerCase(), + query = $("#log-search").value.toLowerCase(), + rows = logEvents + .filter( + (item) => + (!level || item.level === level) && + (!component || (item.component || "").toLowerCase().includes(component)) && + (!query || JSON.stringify(item).toLowerCase().includes(query)), + ) + .slice(-500), + host = $("#log-list"); + host.replaceChildren(); + rows.forEach((item) => { + const row = document.createElement("div"); + row.className = "log"; + const timeNode = document.createElement("span"), + levelNode = document.createElement("span"), + componentNode = document.createElement("span"), + messageNode = document.createElement("span"), + fieldsNode = document.createElement("span"); + timeNode.className = "log-time"; + timeNode.textContent = new Date(item.time).toLocaleTimeString(); + levelNode.className = + item.level === "error" + ? "bad" + : item.level === "warn" + ? "warn" + : item.level === "info" + ? "ok" + : ""; + levelNode.textContent = item.level; + componentNode.className = "log-component"; + componentNode.textContent = item.component || "core"; + messageNode.textContent = item.message; + fieldsNode.className = "log-fields"; + fieldsNode.textContent = JSON.stringify(item.fields || {}); + row.append(timeNode, levelNode, componentNode, messageNode, fieldsNode); + host.appendChild(row); + }); + if (!rows.length) { + const empty = document.createElement("div"); + empty.className = "empty"; + empty.textContent = "等待日志事件…"; + host.appendChild(empty); + } + host.scrollTop = host.scrollHeight; +} +["#log-level", "#log-component", "#log-search"].forEach((id) => + $(id).addEventListener("input", renderLogs), +); +$("#log-pause").onclick = () => { + paused = !paused; + $("#log-pause").textContent = paused ? "继续" : "暂停"; + if (!paused) renderLogs(); +}; +boot(); diff --git a/webui/index.html b/webui/index.html index aa98e3d..9b3451f 100644 --- a/webui/index.html +++ b/webui/index.html @@ -1,120 +1,661 @@ - - - - opencode2api · Field Manual - - - - - - - - + + + + opencode2api · Field Manual + + + + + + + + + diff --git a/webui/styles.css b/webui/styles.css new file mode 100644 index 0000000..36d497b --- /dev/null +++ b/webui/styles.css @@ -0,0 +1,833 @@ +#diagnostic-model-search { + max-width: 260px; +} + +#account-form { + max-width: 660px; +} + +:root { + color-scheme: light; + --paper: #f2efe5; + --paper2: #e8e2d4; + --ink: #17231f; + --muted: #68716c; + --forest: #153c34; + --forest2: #204d43; + --orange: #ed5a2a; + --yellow: #e7b94f; + --line: #c9c3b5; + --white: #fffdf7; + --bad: #b6382f; + --ok: #237056; + --shadow: 0 12px 35px #17231f16; +} +* { + box-sizing: border-box; +} +html { + scroll-behavior: smooth; +} +body { + margin: 0; + background: var(--paper); + color: var(--ink); + font: + 14px/1.55 ui-sans-serif, + system-ui, + -apple-system, + "Segoe UI", + sans-serif; +} +button, +input, +textarea, +select { + font: inherit; +} +button { + cursor: pointer; +} +.hidden { + display: none !important; +} +.mono, +code, +pre, +.eyebrow, +.nav-no, +.metric, +.table th, +.log { + font-family: ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace; +} +.login { + min-height: 100vh; + display: grid; + grid-template-columns: minmax(280px, 1fr) minmax(360px, 520px); + background: var(--forest); +} +.login-intro { + padding: 9vw 7vw; + color: #f8f2e4; + display: flex; + flex-direction: column; + justify-content: space-between; + background-image: + linear-gradient(#ffffff0d 1px, transparent 1px), + linear-gradient(90deg, #ffffff0d 1px, transparent 1px); + background-size: 36px 36px; +} +.manual-mark { + display: flex; + align-items: center; + gap: 12px; + font-weight: 800; + letter-spacing: 0.03em; +} +.manual-mark i { + display: grid; + place-items: center; + width: 38px; + height: 38px; + background: var(--orange); + color: white; + font: + normal 900 17px ui-monospace, + monospace; +} +.login-intro h1 { + font: + 500 clamp(42px, 7vw, 84px)/0.95 Georgia, + serif; + letter-spacing: -0.055em; + margin: 60px 0 18px; + max-width: 700px; +} +.login-intro p { + max-width: 560px; + color: #d4ddd8; + font-size: 16px; +} +.login-panel { + background: var(--paper); + display: grid; + place-items: center; + padding: 32px; +} +.login-card { + width: min(390px, 100%); +} +.login-card h2 { + font: + 500 34px/1.1 Georgia, + serif; + margin: 10px 0; +} +.login-card .rule { + height: 4px; + width: 54px; + background: var(--orange); + margin: 20px 0 28px; +} +.layout { + display: grid; + grid-template-columns: 274px minmax(0, 1fr); + min-height: 100vh; +} +.sidebar { + position: sticky; + top: 0; + height: 100vh; + color: #f8f2e4; + background: var(--forest); + display: flex; + flex-direction: column; + padding: 24px 18px 20px; + border-right: 6px solid var(--orange); +} +.sidebar-head { + padding: 4px 10px 25px; + border-bottom: 1px solid #ffffff24; +} +.sidebar-kicker { + font: + 11px ui-monospace, + monospace; + color: #9fb7ae; + text-transform: uppercase; + letter-spacing: 0.18em; +} +.sidebar-title { + font: + 500 25px Georgia, + serif; + margin-top: 5px; +} +.nav { + display: grid; + margin-top: 18px; + gap: 3px; +} +.nav button { + display: grid; + grid-template-columns: 30px 1fr; + align-items: center; + border: 0; + background: transparent; + color: #b9cbc4; + text-align: left; + padding: 10px 11px; + border-left: 3px solid transparent; +} +.nav button:hover, +.nav button.active { + color: white; + background: #ffffff0c; + border-left-color: var(--orange); +} +.nav-no { + font-size: 10px; + color: #76958a; +} +.nav button.active .nav-no { + color: #ff926e; +} +.sidebar-foot { + margin-top: auto; + padding: 18px 10px 0; + border-top: 1px solid #ffffff24; + color: #9fb7ae; + font-size: 12px; +} +.live-line { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 7px; +} +.live-dot { + width: 8px; + height: 8px; + background: #5dd6a6; + border-radius: 50%; + box-shadow: 0 0 0 4px #5dd6a619; +} +.main { + min-width: 0; + padding: 30px clamp(20px, 4vw, 56px) 72px; +} +.topbar { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 20px; + padding-bottom: 22px; + border-bottom: 1px solid var(--line); + margin-bottom: 26px; +} +.eyebrow { + font-size: 10px; + text-transform: uppercase; + letter-spacing: 0.19em; + color: var(--orange); + font-weight: 800; +} +.topbar h1 { + font: + 500 clamp(30px, 4vw, 48px)/1 Georgia, + serif; + margin: 7px 0; +} +.subtitle { + color: var(--muted); + max-width: 680px; +} +.toolbar { + display: flex; + gap: 8px; + align-items: center; +} +.primary, +.ghost, +.danger, +.copy { + border: 1px solid var(--ink); + padding: 9px 14px; + font-weight: 750; + background: transparent; + color: var(--ink); +} +.primary { + background: var(--ink); + color: var(--white); +} +.primary:hover { + background: var(--orange); + border-color: var(--orange); +} +.ghost:hover, +.copy:hover { + background: var(--paper2); +} +.danger { + color: var(--bad); + border-color: var(--bad); +} +.wide { + width: 100%; +} +.notice { + border-left: 5px solid var(--yellow); + background: #f8eac4; + padding: 12px 15px; + margin: -8px 0 20px; +} +.metric-grid { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 1px; + background: var(--line); + border: 1px solid var(--line); +} +.metric-card { + background: var(--white); + padding: 21px; + min-height: 132px; +} +.label { + font: + 700 10px ui-monospace, + monospace; + text-transform: uppercase; + letter-spacing: 0.12em; + color: var(--muted); +} +.metric { + font-size: 31px; + font-weight: 800; + margin-top: 19px; + letter-spacing: -0.06em; +} +.metric-note { + color: var(--muted); + font-size: 11px; + margin-top: 4px; +} +.section { + background: var(--white); + border: 1px solid var(--line); + padding: 22px; + margin-top: 18px; + box-shadow: var(--shadow); +} +.section-head { + display: flex; + justify-content: space-between; + align-items: start; + gap: 16px; + margin-bottom: 16px; +} +.section h2, +.section h3 { + font: + 600 20px/1.2 Georgia, + serif; + margin: 0; +} +.section-caption { + color: var(--muted); + font-size: 12px; +} +.split { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 18px; +} +.table-wrap { + overflow: auto; +} +.table { + width: 100%; + border-collapse: collapse; +} +.table th, +.table td { + text-align: left; + padding: 10px 8px; + border-bottom: 1px solid #ded9cd; + vertical-align: top; +} +.table th { + font-size: 9px; + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--muted); +} +.table tr:last-child td { + border-bottom: 0; +} +.status { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; +} +.status:before { + content: ""; + width: 7px; + height: 7px; + border-radius: 50%; + background: currentColor; +} +.ok { + color: var(--ok); +} +.bad { + color: var(--bad); +} +.warn { + color: #9b6810; +} +.guide { + counter-reset: steps; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1px; + background: var(--line); + border: 1px solid var(--line); +} +.guide-step { + counter-increment: steps; + background: var(--white); + padding: 22px; + min-height: 150px; + position: relative; +} +.guide-step:before { + content: "0" counter(steps); + font: + 800 11px ui-monospace, + monospace; + color: var(--orange); + letter-spacing: 0.12em; +} +.guide-step h3 { + font: + 600 18px Georgia, + serif; + margin: 14px 0 7px; +} +.guide-step p { + color: var(--muted); + margin: 0 0 14px; +} +.step-state { + font: + 700 11px ui-monospace, + monospace; + text-transform: uppercase; +} +.access-grid { + display: grid; + grid-template-columns: 220px minmax(0, 1fr); + gap: 18px; +} +.toc { + position: sticky; + top: 20px; + align-self: start; + border-top: 4px solid var(--ink); + padding-top: 10px; +} +.toc button { + display: block; + width: 100%; + border: 0; + border-bottom: 1px solid var(--line); + background: transparent; + padding: 9px 4px; + text-align: left; + color: var(--muted); +} +.toc button:hover { + color: var(--orange); +} +.code-card { + margin: 14px 0; + border: 1px solid var(--line); + background: #17231f; + color: #dce6df; +} +.code-head { + display: flex; + justify-content: space-between; + align-items: center; + padding: 8px 12px; + border-bottom: 1px solid #ffffff1f; + color: #a9bcb4; + font: + 10px ui-monospace, + monospace; + text-transform: uppercase; + letter-spacing: 0.11em; +} +.code-card pre { + margin: 0; + padding: 16px; + white-space: pre-wrap; + overflow-wrap: anywhere; + font-size: 12px; + color: #edf3ef; +} +.copy { + color: #e8efe9; + border-color: #788d84; + padding: 5px 9px; + font-size: 10px; +} +.field { + display: grid; + gap: 6px; + margin: 13px 0; +} +.field label { + font: + 700 10px ui-monospace, + monospace; + text-transform: uppercase; + letter-spacing: 0.1em; + color: #56635e; +} +.input, +input, +textarea, +select { + width: 100%; + border: 1px solid #a9a397; + background: #fffef9; + color: var(--ink); + padding: 10px 11px; + border-radius: 0; + outline: none; +} +.input:focus, +input:focus, +textarea:focus, +select:focus { + border-color: var(--orange); + box-shadow: 0 0 0 2px #ed5a2a20; +} +textarea { + resize: vertical; + min-height: 92px; +} +.check-label { + display: flex !important; + align-items: center; + gap: 9px; + text-transform: none !important; + letter-spacing: 0 !important; + font-family: inherit !important; +} +.check-label input { + width: auto; +} +.form-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0 18px; +} +.full { + grid-column: 1/-1; +} +.chips { + display: flex; + gap: 6px; + flex-wrap: wrap; + margin: 4px 0 8px; +} +.chip { + display: flex; + align-items: center; + gap: 8px; + background: var(--paper2); + border: 1px solid var(--line); + padding: 5px 7px; + font: + 11px ui-monospace, + monospace; +} +.chip button { + border: 0; + background: transparent; + color: var(--bad); + font-weight: 900; + padding: 0; +} +.actions { + display: flex; + justify-content: flex-end; + gap: 9px; + margin-top: 18px; +} +.filters { + display: grid; + grid-template-columns: 140px 160px minmax(180px, 1fr) auto; + gap: 8px; + margin-bottom: 11px; +} +.logs { + height: 62vh; + overflow: auto; + background: #13201c; + color: #d7e2dc; + border: 1px solid #13201c; +} +.log { + display: grid; + grid-template-columns: 86px 55px 105px minmax(170px, 1fr); + gap: 10px; + padding: 8px 10px; + border-bottom: 1px solid #ffffff12; + font-size: 11px; +} +.log:hover { + background: #ffffff08; +} +.log-time, +.log-component, +.log-fields { + color: #89a097; +} +.log-fields { + grid-column: 4; + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.empty { + color: var(--muted); + padding: 14px 8px; +} +.error { + color: var(--bad); + min-height: 22px; +} +.modal { + position: fixed; + inset: 0; + background: #17231fcc; + display: grid; + place-items: center; + padding: 20px; + z-index: 10; +} +.modal-card { + width: min(720px, 100%); + max-height: 82vh; + overflow: auto; + background: var(--paper); + border-top: 7px solid var(--orange); + padding: 24px; + box-shadow: 0 30px 80px #0007; +} +.modal-card pre { + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.toast { + position: fixed; + right: 22px; + bottom: 22px; + z-index: 20; + background: var(--forest); + color: white; + border-left: 5px solid #5dd6a6; + padding: 12px 16px; + box-shadow: var(--shadow); +} +.toast.bad-toast { + border-left-color: #ff7062; +} +.tiny { + font-size: 11px; + color: var(--muted); +} +.trend-chart { + height: 230px; + display: flex; + align-items: flex-end; + gap: 3px; + padding: 18px 4px 0; + border-bottom: 1px solid var(--line); + overflow: hidden; +} +.trend-bar { + flex: 1; + min-width: 2px; + background: var(--forest2); + border-top: 3px solid var(--orange); + position: relative; +} +.trend-bar:hover { + background: var(--orange); +} +.tier-row { + display: grid; + grid-template-columns: 70px minmax(0, 1fr) 90px; + align-items: center; + gap: 10px; + margin: 14px 0; +} +.tier-track { + height: 12px; + background: var(--paper2); +} +.tier-fill { + height: 100%; + background: var(--orange); +} +.play-grid { + display: grid; + grid-template-columns: minmax(360px, 0.9fr) minmax(400px, 1.1fr); + gap: 18px; +} +.json-editor { + min-height: 430px; + background: #17231f; + color: #e7efe9; + border-color: #17231f; + font: + 12px/1.55 ui-monospace, + monospace; +} +.fact-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1px; + background: var(--line); + border: 1px solid var(--line); +} +.fact { + background: var(--white); + padding: 12px; +} +.fact dt { + font: + 700 9px ui-monospace, + monospace; + text-transform: uppercase; + letter-spacing: 0.1em; + color: var(--muted); +} +.fact dd { + margin: 5px 0 0; + overflow-wrap: anywhere; +} +.pill { + display: inline-block; + padding: 2px 6px; + border: 1px solid currentColor; + font: + 10px ui-monospace, + monospace; +} +.cost { + font: + 11px ui-monospace, + monospace; + white-space: nowrap; +} +@media (max-width: 1100px) { + .play-grid { + grid-template-columns: 1fr; + } +} +@media (max-width: 980px) { + .layout { + grid-template-columns: 1fr; + } + .sidebar { + position: relative; + height: auto; + border-right: 0; + border-bottom: 5px solid var(--orange); + padding: 15px; + } + .sidebar-head { + display: flex; + align-items: end; + justify-content: space-between; + padding: 0 5px 12px; + } + .nav { + display: flex; + overflow: auto; + margin-top: 10px; + } + .nav button { + min-width: max-content; + grid-template-columns: 24px 1fr; + } + .sidebar-foot { + display: none; + } + .main { + padding-top: 22px; + } + .metric-grid { + grid-template-columns: repeat(2, 1fr); + } + .login { + grid-template-columns: 1fr; + } + .login-intro { + display: none; + } +} +@media (max-width: 680px) { + .topbar { + flex-direction: column; + } + .metric-grid, + .split, + .guide, + .form-grid, + .fact-grid { + grid-template-columns: 1fr; + } + .full { + grid-column: auto; + } + .access-grid { + grid-template-columns: 1fr; + } + .toc { + position: static; + } + .filters { + grid-template-columns: 1fr 1fr; + } + .log { + grid-template-columns: 72px 48px minmax(0, 1fr); + } + .log-component { + display: none; + } + .log-fields { + grid-column: 1/-1; + } + .toolbar { + width: 100%; + justify-content: space-between; + } + .play-grid { + display: block; + } + .json-editor { + min-height: 320px; + } + .section-head { + flex-direction: column; + } +}